file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/include/carb/cpp/Bit.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief C++14-compatible implementation of select functionality from C++ `<bit>` library.
#pragma once
#include "TypeTraits.h"
#include "detail/ImplDummy.h"
#include "../extras/CpuInfo.h"
#ifndef DOXYGEN_SHOULD_SKIP_THIS
// CARB_POPCNT is 1 if the compiler is targeting a CPU with AVX instructions or GCC reports popcnt is available. It is
// undefined at the bottom of the file.
# if defined(__AVX__) /* MSC/GCC */ || defined(__POPCNT__) /* GCC */
# define CARB_POPCNT 1
# else
# define CARB_POPCNT 0
# endif
// CARB_LZCNT is 1 if the compiler is targeting a CPU with AVX2 instructions or GCC reports lzcnt is available. It is
// undefined at the bottom of the file.
# if defined(__AVX2__) /* MSC/GCC */ || defined(__LZCNT__) /* GCC */
# define CARB_LZCNT 1
# else
# define CARB_LZCNT 0
# endif
#endif
#if CARB_COMPILER_MSC
extern "C"
{
unsigned int __popcnt(unsigned int value);
unsigned __int64 __popcnt64(unsigned __int64 value);
unsigned char _BitScanReverse(unsigned long* _Index, unsigned long _Mask);
unsigned char _BitScanReverse64(unsigned long* _Index, unsigned __int64 _Mask);
unsigned char _BitScanForward(unsigned long* _Index, unsigned long _Mask);
unsigned char _BitScanForward64(unsigned long* _Index, unsigned __int64 _Mask);
# if CARB_LZCNT
unsigned int __lzcnt(unsigned int);
unsigned short __lzcnt16(unsigned short);
unsigned __int64 __lzcnt64(unsigned __int64);
# endif
}
# pragma intrinsic(__popcnt)
# pragma intrinsic(__popcnt64)
# pragma intrinsic(_BitScanReverse)
# pragma intrinsic(_BitScanReverse64)
# pragma intrinsic(_BitScanForward)
# pragma intrinsic(_BitScanForward64)
# if CARB_LZCNT
# pragma intrinsic(__lzcnt)
# pragma intrinsic(__lzcnt16)
# pragma intrinsic(__lzcnt64)
# endif
#elif CARB_COMPILER_GNUC
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
namespace carb
{
namespace cpp
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
// Naive implementation of popcnt for CPUs without built in instructions.
template <class T, std::enable_if_t<std::is_unsigned<T>::value, bool> = true>
constexpr int popCountImpl(T val) noexcept
{
int count = 0;
while (val != 0)
{
++count;
val = val & (val - 1);
}
return count;
}
// The Helper class is specialized by type and size since many intrinsics have different names for different sizes.
template <class T, size_t Size = sizeof(T)>
class Helper;
// Specialization for functions where sizeof(T) >= 1
template <class T>
class Helper<T, 1>
{
public:
static_assert(std::numeric_limits<T>::is_specialized, "Requires numeric type");
using Signed = typename std::make_signed_t<T>;
using Unsigned = typename std::make_unsigned_t<T>;
// popCount implementation for 1-4 bytes integers
static int popCount(const T& val)
{
# if CARB_COMPILER_MSC
# if !CARB_POPCNT // Skip the check if we know we have the instruction
// Only use the intrinsic if it's supported on the CPU
static extras::CpuInfo cpuInfo;
if (!cpuInfo.popcntSupported())
{
return popCountImpl((Unsigned)val);
}
else
# endif
{
return (int)__popcnt((unsigned long)(Unsigned)val);
}
# else
return __builtin_popcount((unsigned long)(Unsigned)val);
# endif
}
static constexpr void propagateHighBit(T& n)
{
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
}
static int countl_zero(T val)
{
# if CARB_LZCNT
# if CARB_COMPILER_MSC
return int(__lzcnt16((unsigned short)(Unsigned)val)) - (16 - std::numeric_limits<T>::digits);
# else
return int(__builtin_ia32_lzcnt_u16((unsigned short)(Unsigned)val)) - (16 - std::numeric_limits<T>::digits);
# endif
# else
# if CARB_COMPILER_MSC
unsigned long index;
constexpr static int diff = std::numeric_limits<unsigned long>::digits - std::numeric_limits<T>::digits;
return _BitScanReverse(&index, (unsigned long)(Unsigned)val) ?
(std::numeric_limits<unsigned long>::digits - 1 - index - diff) :
std::numeric_limits<T>::digits;
# else
// According to docs, undefined if val == 0
return val ? __builtin_clz((unsigned int)(Unsigned)val) - (32 - std::numeric_limits<T>::digits) :
std::numeric_limits<T>::digits;
# endif
# endif
}
static int countr_zero(T val)
{
if (val == 0)
{
return std::numeric_limits<T>::digits;
}
else
{
# if CARB_COMPILER_MSC
unsigned long result;
_BitScanForward(&result, (unsigned long)(Unsigned)val);
return (int)result;
# else
return __builtin_ctz((unsigned int)(Unsigned)val);
# endif
}
}
};
// Specialization for functions where sizeof(T) >= 2
template <class T>
class Helper<T, 2> : public Helper<T, 1>
{
public:
using Base = Helper<T, 1>;
using typename Base::Signed;
using typename Base::Unsigned;
static constexpr void propagateHighBit(T& n)
{
Base::propagateHighBit(n);
n |= (n >> 8);
}
};
// Specialization for functions where sizeof(T) >= 4
template <class T>
class Helper<T, 4> : public Helper<T, 2>
{
public:
using Base = Helper<T, 2>;
using typename Base::Signed;
using typename Base::Unsigned;
static constexpr void propagateHighBit(T& n)
{
Base::propagateHighBit(n);
n |= (n >> 16);
}
# if CARB_LZCNT
# if CARB_COMPILER_MSC
static int countl_zero(T val)
{
static_assert(std::numeric_limits<T>::digits == 32, "Invalid assumption");
return int(__lzcnt((unsigned int)(Unsigned)val));
}
# else
static int countl_zero(T val)
{
static_assert(std::numeric_limits<T>::digits == 32, "Invalid assumption");
return int(__builtin_ia32_lzcnt_u32((unsigned int)(Unsigned)val));
}
# endif
# endif
};
// Specialization for functions where sizeof(T) >= 8
template <class T>
class Helper<T, 8> : public Helper<T, 4>
{
public:
using Base = Helper<T, 4>;
using typename Base::Signed;
using typename Base::Unsigned;
// popCount implementation for 8 byte integers
static int popCount(const T& val)
{
static_assert(sizeof(T) == sizeof(uint64_t), "Unexpected size");
# if CARB_COMPILER_MSC
# if !CARB_POPCNT // Skip the check if we know we have the instruction
// Only use the intrinsic if it's supported on the CPU
static extras::CpuInfo cpuInfo;
if (!cpuInfo.popcntSupported())
{
return popCountImpl((Unsigned)val);
}
else
# endif
{
return (int)__popcnt64((Unsigned)val);
}
# else
return __builtin_popcountll((Unsigned)val);
# endif
}
static constexpr void propagateHighBit(T& n)
{
Base::propagateHighBit(n);
n |= (n >> 32);
}
static int countl_zero(T val)
{
# if CARB_LZCNT
# if CARB_COMPILER_MSC
return int(__lzcnt64((Unsigned)val));
# else
return int(__builtin_ia32_lzcnt_u64((Unsigned)val));
# endif
# else
# if CARB_COMPILER_MSC
unsigned long index;
static_assert(sizeof(val) == sizeof(unsigned __int64), "Invalid assumption");
return _BitScanReverse64(&index, val) ? std::numeric_limits<T>::digits - 1 - index :
std::numeric_limits<T>::digits;
# else
// According to docs, undefined if val == 0
return val ? __builtin_clzll((Unsigned)val) : std::numeric_limits<T>::digits;
# endif
# endif
}
static int countr_zero(T val)
{
if (val == 0)
{
return std::numeric_limits<T>::digits;
}
else
{
# if CARB_COMPILER_MSC
unsigned long result;
_BitScanForward64(&result, (Unsigned)val);
return (int)result;
# else
return __builtin_ctzll((Unsigned)val);
# endif
}
}
};
template <class U, class V>
struct SizeMatches : cpp::bool_constant<sizeof(U) == sizeof(V)>
{
};
} // namespace detail
#endif
/**
* Indicates the endianness of all scalar types for the current system.
*
* Endianness refers to byte ordering of scalar types larger than one byte. Take for example a 32-bit scalar with the
* value "1".
* On a little-endian system, the least-significant ("littlest") bytes are ordered first in memory. "1" would be
* represented as:
* @code{.txt}
* 01 00 00 00
* @endcode
*
* On a big-endian system, the most-significant ("biggest") bytes are ordered first in memory. "1" would be represented
* as:
* @code{.txt}
* 00 00 00 01
* @endcode
*/
enum class endian
{
#ifdef DOXYGEN_BUILD
little = 0, //!< An implementation-defined value representing little-endian scalar types.
big = 1, //!< An implementation-defined value representing big-endian scalar types.
native = -1 //!< Will be either @ref endian::little or @ref endian::big depending on the target platform.
#elif CARB_COMPILER_GNUC
little = __ORDER_LITTLE_ENDIAN__,
big = __ORDER_BIG_ENDIAN__,
native = __BYTE_ORDER__
#else
little = 0,
big = 1,
# if CARB_X86_64 || CARB_AARCH64
native = little
# else
CARB_UNSUPPORTED_PLATFORM();
# endif
#endif
};
/**
* Re-interprets the bits @p src as type `To`.
*
* @note The `To` and `From` types must exactly match size and both be trivially copyable.
*
* See: https://en.cppreference.com/w/cpp/numeric/bit_cast
* @tparam To The object type to convert to.
* @tparam From The (typically inferred) object type to convert from.
* @param src The source object to reinterpret.
* @returns The reinterpreted object.
*/
template <class To,
class From,
std::enable_if_t<detail::SizeMatches<To, From>::value && std::is_trivially_copyable<From>::value &&
std::is_trivially_copyable<To>::value,
bool> = false>
/* constexpr */ // Cannot be constexpr without compiler support
To bit_cast(const From& src) noexcept
{
// This union allows us to bypass `dest`'s constructor and just trivially copy into it.
union
{
detail::NontrivialDummyType dummy{};
To dest;
} u;
std::memcpy(&u.dest, &src, sizeof(From));
return u.dest;
}
/**
* Checks if a given value is an integral power of 2
* @see https://en.cppreference.com/w/cpp/numeric/has_single_bit
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns \c true if \p val is not zero and has a single bit set (integral power of two); \c false otherwise.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
constexpr bool has_single_bit(T val) noexcept
{
return val != T(0) && (val & (val - 1)) == T(0);
}
/**
* Finds the smallest integral power of two not less than the given value.
* @see https://en.cppreference.com/w/cpp/numeric/bit_ceil
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns The smallest integral power of two that is not smaller than \p val. Undefined if the resulting value is not
* representable in \c T.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
constexpr T bit_ceil(T val) noexcept
{
if (val <= 1)
return T(1);
// Yes, this could be implemented with a `nlz` instruction but cannot be constexpr without compiler support.
--val;
detail::Helper<T>::propagateHighBit(val);
++val;
return val;
}
/**
* Finds the largest integral power of two not greater than the given value.
* @see https://en.cppreference.com/w/cpp/numeric/bit_floor
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns The largest integral power of two not greater than \p val.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
constexpr T bit_floor(T val) noexcept
{
// Yes, this could be implemented with a `nlz` instruction but cannot be constexpr without compiler support.
detail::Helper<T>::propagateHighBit(val);
return val - (val >> 1);
}
/**
* Returns the number of 1 bits in the value of x.
*
* @note Unlike std::popcount, this function is not constexpr. This is because the compiler intrinsics used to
* implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to
* use compiler intrinsics. If a constexpr implementation is required, use \ref popcount_constexpr().
*
* @note (Intel/AMD CPUs) This function will check to see if the CPU supports the `popcnt` instruction (Intel Nehalem
* micro-architecture, 2008; AMD Jaguar micro-architecture, 2013), and if it is not supported, will use a fallback
* function that is ~85% slower than the `popcnt` instruction. If the compiler indicates that the target CPU has that
* instruction, the CPU support check can be skipped, saving about 20%. This is accomplished with command-line switches:
* `/arch:AVX` (or higher) for Visual Studio or `-march=sandybridge` (or several other `-march` options) for GCC.
*
* @param[in] val The unsigned integer value to test.
* @returns The number of 1 bits in the value of \p val.
*/
template <class T, std::enable_if_t<std::is_unsigned<T>::value, bool> = true>
int popcount(T val) noexcept
{
return detail::Helper<T>::popCount(val);
}
/**
* Returns the number of 1 bits in the value of x.
*
* @note Unlike \ref popcount(), this function is `constexpr` as it does not make use of intrinsics. Therefore, at
* runtime it is recommended to use \ref popcount() instead of this function.
*
* @param[in] val The unsigned integer value to test.
* @returns The number of 1 bits in the value of \p val.
*/
template <class T, std::enable_if_t<std::is_unsigned<T>::value, bool> = true>
constexpr int popcount_constexpr(T val) noexcept
{
return detail::popCountImpl(val);
}
/**
* Returns the number of consecutive 0 bits in the value of val, starting from the most significant bit ("left").
* @see https://en.cppreference.com/w/cpp/numeric/countl_zero
*
* @note Unlike std::countl_zero, this function is not constexpr. This is because the compiler intrinsics used to
* implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to
* use compiler intrinsics. If a constexpr implementation is required, use \ref countl_zero_constexpr().
*
* @note (Intel/AMD CPUs) To support backwards compatibility with older CPUs, by default this is implemented with a
* `bsr` instruction (i386+), that is slightly less performant (~3%) than the more modern `lzcnt` instruction. This
* function implementation will switch to using `lzcnt` if the compiler indicates that instruction is supported. On
* Visual Studio this is provided by passing `/arch:AVX2` command-line switch, or on GCC with `-march=haswell` (or
* several other
* `-march` options). The `lzcnt` instruction was
* <a href="https://en.wikipedia.org/wiki/X86_Bit_manipulation_instruction_set">introduced</a> on Intel's Haswell micro-
* architecture and AMD's Jaguar and Piledriver micro-architectures.
*
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns The number of consecutive 0 bits in the provided value, starting from the most significant bit.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
int countl_zero(T val) noexcept
{
return detail::Helper<T>::countl_zero(val);
}
/**
* Returns the number of consecutive 0 bits in the value of val, starting from the most significant bit ("left").
* @see https://en.cppreference.com/w/cpp/numeric/countl_zero
*
* @note Unlike \ref countl_zero(), this function is `constexpr` as it does not make use of intrinsics. Therefore, at
* runtime it is recommended to use \ref countl_zero() instead of this function.
*
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns The number of consecutive 0 bits in the provided value, starting from the most significant bit.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
constexpr int countl_zero_constexpr(T val) noexcept
{
if (val == 0)
return std::numeric_limits<T>::digits;
unsigned zeros = 0;
for (T shift = std::numeric_limits<T>::digits >> 1; shift; shift >>= 1)
{
T temp = val >> shift;
if (temp)
val = temp;
else
zeros |= shift;
}
return int(zeros);
}
/**
* Returns the number of consecutive 0 bits in the value of val, starting from the least significant bit ("right").
* @see https://en.cppreference.com/w/cpp/numeric/countr_zero
*
* @note Unlike std::countr_zero, this function is not constexpr. This is because the compiler intrinsics used to
* implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to
* use compiler intrinsics. If a constexpr implementation is required, use \ref countr_zero_constexpr().
*
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns The number of consecutive 0 bits in the provided value, starting from the least significant bit.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
int countr_zero(T val) noexcept
{
return detail::Helper<T>::countr_zero(val);
}
#pragma push_macro("max")
#undef max
/**
* Returns the number of consecutive 0 bits in the value of val, starting from the least significant bit ("right").
* @see https://en.cppreference.com/w/cpp/numeric/countr_zero
*
* @note Unlike \ref countr_zero(), this function is `constexpr` as it does not make use of intrinsics. Therefore, at
* runtime it is recommended to use \ref countr_zero() instead of this function.
*
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns The number of consecutive 0 bits in the provided value, starting from the least significant bit.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
constexpr int countr_zero_constexpr(T val) noexcept
{
if (val == 0)
return std::numeric_limits<T>::digits;
if (val & 1)
return 0;
int zeros = 0;
T shift = std::numeric_limits<T>::digits >> 1;
T mask = std::numeric_limits<T>::max() >> shift;
while (shift)
{
if (!(val & mask))
{
val >>= shift;
zeros |= shift;
}
shift >>= 1;
mask >>= shift;
}
return zeros;
}
#pragma pop_macro("max")
/**
* Returns the number of consecutive 1 bits in the value of val, starting from the most significant bit ("left").
* @see https://en.cppreference.com/w/cpp/numeric/countl_one
*
* @note Unlike std::countl_one, this function is not constexpr. This is because the compiler intrinsics used to
* implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to
* use compiler intrinsics. If a constexpr implementation is required, use \ref countl_one_constexpr().
*
* @note (Intel/AMD CPUs) To support backwards compatibility with older CPUs, by default this is implemented with a
* `bsr` instruction (i386+), that is slightly less performant (~3%) than the more modern `lzcnt` instruction. This
* function implementation will switch to using `lzcnt` if the compiler indicates that instruction is supported. On
* Visual Studio this is provided by passing `/arch:AVX2` command-line switch, or on GCC with `-march=haswell` (or
* several other
* `-march` options). The `lzcnt` instruction was
* <a href="https://en.wikipedia.org/wiki/X86_Bit_manipulation_instruction_set">introduced</a> on Intel's Haswell micro-
* architecture and AMD's Jaguar and Piledriver micro-architectures.
*
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns The number of consecutive 1 bits in the provided value, starting from the most significant bit.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
int countl_one(T val) noexcept
{
return detail::Helper<T>::countl_zero(T(~val));
}
/**
* Returns the number of consecutive 1 bits in the value of val, starting from the most significant bit ("left").
* @see https://en.cppreference.com/w/cpp/numeric/countl_zero
*
* @note Unlike \ref countl_one(), this function is `constexpr` as it does not make use of intrinsics. Therefore, at
* runtime it is recommended to use \ref countl_one() instead of this function.
*
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns The number of consecutive 0 bits in the provided value, starting from the most significant bit.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
constexpr int countl_one_constexpr(T val) noexcept
{
return countl_zero_constexpr(T(~val));
}
/**
* Returns the number of consecutive 1 bits in the value of val, starting from the least significant bit ("right").
* @see https://en.cppreference.com/w/cpp/numeric/countr_one
*
* @note Unlike std::countr_one, this function is not constexpr. This is because the compiler intrinsics used to
* implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to
* use compiler intrinsics. If a constexpr implementation is required, use \ref countr_one_constexpr().
*
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns The number of consecutive 1 bits in the provided value, starting from the least significant bit.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
int countr_one(T val) noexcept
{
return detail::Helper<T>::countr_zero(T(~val));
}
/**
* Returns the number of consecutive 1 bits in the value of val, starting from the least significant bit ("right").
* @see https://en.cppreference.com/w/cpp/numeric/countr_one
*
* @note Unlike \ref countr_one(), this function is `constexpr` as it does not make use of intrinsics. Therefore, at
* runtime it is recommended to use \ref countr_one() instead of this function.
*
* @tparam T An unsigned integral type
* @param val An unsigned integral value
* @returns The number of consecutive 1 bits in the provided value, starting from the least significant bit.
*/
template <class T, std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, bool> = false>
constexpr int countr_one_constexpr(T val) noexcept
{
return countr_zero_constexpr(T(~val));
}
} // namespace cpp
} // namespace carb
#undef CARB_LZCNT
#undef CARB_POPCNT
| 23,782 | C | 35.365443 | 120 | 0.668447 |
omniverse-code/kit/include/carb/cpp/Numeric.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! \brief C++14-compatible implementation of select functionality from C++ `<numeric>` library.
#pragma once
#include "../Defines.h"
#include "Bit.h"
namespace carb
{
namespace cpp
{
//! \cond DEV
namespace detail
{
template <class Signed, std::enable_if_t<std::is_signed<Signed>::value, bool> = false>
constexpr inline std::make_unsigned_t<Signed> abs(const Signed val) noexcept
{
using Unsigned = std::make_unsigned_t<Signed>;
if (val < 0)
return Unsigned(0) - Unsigned(val);
return Unsigned(val);
}
template <class Unsigned, std::enable_if_t<std::is_unsigned<Unsigned>::value, bool> = false>
constexpr inline Unsigned abs(const Unsigned val) noexcept
{
return val;
}
template <class Unsigned>
constexpr inline unsigned long bitscan_forward(Unsigned mask) noexcept
{
// Since carb::cpp::countr_zero isn't constexpr...
static_assert(std::is_unsigned<Unsigned>::value, "Must be an unsigned value");
unsigned long count = 0;
if (mask != 0)
{
while ((mask & 1u) == 0)
{
mask >>= 1;
++count;
}
}
return count;
}
template <class T>
using NotBoolIntegral =
::carb::cpp::bool_constant<std::is_integral<T>::value && !std::is_same<std::remove_cv_t<T>, bool>::value>;
} // namespace detail
//! \endcond
/**
* Computes the greatest common divisor of two integers.
*
* If either `M` or `N` is not an integer type, or if either is (possibly cv-qualified) `bool`, the program is ill-
* formed. If either `|m|` or `|n|` is not representable as a value of type `std::common_type_t<M, N>`, the behavior is
* undefined.
* @param m Integer value
* @param n Integer value
* @returns If both @p m and @p n are 0, returns 0; otherwise returns the greatest common divisor of `|m|` and `|n|`.
*/
template <class M, class N>
constexpr inline std::common_type_t<M, N> gcd(M m, N n) noexcept /*strengthened*/
{
static_assert(::carb::cpp::detail::NotBoolIntegral<M>::value && ::carb::cpp::detail::NotBoolIntegral<N>::value,
"Requires non-bool integral");
using Common = std::common_type_t<M, N>;
using Unsigned = std::make_unsigned_t<Common>;
Unsigned am = ::carb::cpp::detail::abs(m);
Unsigned an = ::carb::cpp::detail::abs(n);
if (am == 0)
return Common(an);
if (an == 0)
return Common(am);
const auto trailingZerosM = ::carb::cpp::detail::bitscan_forward(am);
const auto common2s = carb_min(trailingZerosM, ::carb::cpp::detail::bitscan_forward(an));
an >>= common2s;
am >>= trailingZerosM;
do
{
an >>= ::carb::cpp::detail::bitscan_forward(an);
if (am > an)
{
Unsigned temp = am;
am = an;
an = temp;
}
an -= am;
} while (an != 0u);
return Common(am << common2s);
}
} // namespace cpp
} // namespace carb
| 3,324 | C | 28.166666 | 119 | 0.640794 |
omniverse-code/kit/include/carb/cpp/Atomic.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// Implements the wait/notify functions from C++20-standard atomics for types that are 1, 2, 4 or 8 bytes. If this
// feature is not desired, or the type you're trying to atomic-wrap isn't supported, use std::atomic instead.
// See the following:
// https://en.cppreference.com/w/cpp/atomic/atomic/wait
// https://en.cppreference.com/w/cpp/atomic/atomic/notify_one
// https://en.cppreference.com/w/cpp/atomic/atomic/notify_all
//! \file
//! \brief C++14-compatible implementation of select functionality from C++ `<atomic>` library.
#pragma once
#include "../thread/Futex.h"
#include "../thread/Util.h"
#include <type_traits>
#include <algorithm>
namespace carb
{
namespace cpp
{
template <class T>
class atomic;
namespace detail
{
// C++20 adds fetch_add/fetch_sub and operator support for floating point types
template <class T>
class atomic_float_facade : public std::atomic<T>
{
using Base = std::atomic<T>;
static_assert(std::is_floating_point<T>::value, "");
public:
atomic_float_facade() noexcept = default;
constexpr atomic_float_facade(T desired) noexcept : Base(desired)
{
}
atomic_float_facade(const atomic_float_facade&) = delete;
using Base::operator=;
T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) noexcept
{
T temp = this->load(std::memory_order_relaxed);
while (!this->compare_exchange_strong(temp, temp + arg, order, std::memory_order_relaxed))
{
}
return temp;
}
T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) volatile noexcept
{
T temp = this->load(std::memory_order_relaxed);
while (!this->compare_exchange_strong(temp, temp + arg, order, std::memory_order_relaxed))
{
}
return temp;
}
T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) noexcept
{
T temp = this->load(std::memory_order_relaxed);
while (!this->compare_exchange_strong(temp, temp - arg, order, std::memory_order_relaxed))
{
}
return temp;
}
T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) volatile noexcept
{
T temp = this->load(std::memory_order_relaxed);
while (!this->compare_exchange_strong(temp, temp - arg, order, std::memory_order_relaxed))
{
}
return temp;
}
T operator+=(T arg) noexcept
{
return this->fetch_add(arg) + arg;
}
T operator+=(T arg) volatile noexcept
{
return this->fetch_add(arg) + arg;
}
T operator-=(T arg) noexcept
{
return this->fetch_sub(arg) - arg;
}
T operator-=(T arg) volatile noexcept
{
return this->fetch_sub(arg) - arg;
}
};
template <class T>
class atomic_ref_base
{
protected:
using AtomicType = ::carb::cpp::atomic<T>;
AtomicType& m_ref;
public:
using value_type = T;
static constexpr bool is_always_lock_free = AtomicType::is_always_lock_free;
static constexpr std::size_t required_alignment = alignof(T);
explicit atomic_ref_base(T& obj) : m_ref(reinterpret_cast<AtomicType&>(obj))
{
}
atomic_ref_base(const atomic_ref_base& ref) noexcept : m_ref(ref.m_ref)
{
}
T operator=(T desired) const noexcept
{
m_ref.store(desired);
return desired;
}
atomic_ref_base& operator=(const atomic_ref_base&) = delete;
bool is_lock_free() const noexcept
{
return m_ref.is_lock_free();
}
void store(T desired, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
m_ref.store(desired, order);
}
T load(std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return m_ref.load(order);
}
operator T() const noexcept
{
return load();
}
T exchange(T desired, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return m_ref.exchange(desired, order);
}
bool compare_exchange_weak(T& expected, T desired, std::memory_order success, std::memory_order failure) const noexcept
{
return m_ref.compare_exchange_weak(expected, desired, success, failure);
}
bool compare_exchange_weak(T& expected, T desired, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return m_ref.compare_exchange_weak(expected, desired, order);
}
bool compare_exchange_strong(T& expected, T desired, std::memory_order success, std::memory_order failure) const noexcept
{
return m_ref.compare_exchange_strong(expected, desired, success, failure);
}
bool compare_exchange_strong(T& expected, T desired, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return m_ref.compare_exchange_strong(expected, desired, order);
}
void wait(T old, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
m_ref.wait(old, order);
}
void wait(T old, std::memory_order order = std::memory_order_seq_cst) const volatile noexcept
{
m_ref.wait(old, order);
}
template <class Rep, class Period>
bool wait_for(T old,
std::chrono::duration<Rep, Period> duration,
std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return m_ref.wait_for(old, duration, order);
}
template <class Rep, class Period>
bool wait_for(T old,
std::chrono::duration<Rep, Period> duration,
std::memory_order order = std::memory_order_seq_cst) const volatile noexcept
{
return m_ref.wait_for(old, duration, order);
}
template <class Clock, class Duration>
bool wait_until(T old,
std::chrono::time_point<Clock, Duration> time_point,
std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return m_ref.wait_until(old, time_point, order);
}
template <class Clock, class Duration>
bool wait_until(T old,
std::chrono::time_point<Clock, Duration> time_point,
std::memory_order order = std::memory_order_seq_cst) const volatile noexcept
{
return m_ref.wait_until(old, time_point, order);
}
void notify_one() const noexcept
{
m_ref.notify_one();
}
void notify_one() const volatile noexcept
{
m_ref.notify_one();
}
void notify_all() const noexcept
{
m_ref.notify_all();
}
void notify_all() const volatile noexcept
{
m_ref.notify_all();
}
};
template <class T>
class atomic_ref_pointer_facade : public atomic_ref_base<T>
{
using Base = atomic_ref_base<T>;
static_assert(std::is_pointer<T>::value, "");
public:
using difference_type = std::ptrdiff_t;
explicit atomic_ref_pointer_facade(T& ref) : Base(ref)
{
}
atomic_ref_pointer_facade(const atomic_ref_pointer_facade& other) noexcept : Base(other)
{
}
using Base::operator=;
T fetch_add(std::ptrdiff_t arg, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return this->m_ref.fetch_add(arg, order);
}
T fetch_sub(std::ptrdiff_t arg, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return this->m_ref.fetch_sub(arg, order);
}
T operator++() const noexcept
{
return this->m_ref.fetch_add(1) + 1;
}
T operator++(int) const noexcept
{
return this->m_ref.fetch_add(1);
}
T operator--() const noexcept
{
return this->m_ref.fetch_sub(1) - 1;
}
T operator--(int) const noexcept
{
return this->m_ref.fetch_sub(1);
}
T operator+=(std::ptrdiff_t arg) const noexcept
{
return this->m_ref.fetch_add(arg) + arg;
}
T operator-=(std::ptrdiff_t arg) const noexcept
{
return this->m_ref.fetch_sub(arg) - arg;
}
};
template <class T>
class atomic_ref_numeric_facade : public atomic_ref_base<T>
{
using Base = atomic_ref_base<T>;
static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "");
public:
using difference_type = T;
explicit atomic_ref_numeric_facade(T& ref) : Base(ref)
{
}
atomic_ref_numeric_facade(const atomic_ref_numeric_facade& other) noexcept : Base(other)
{
}
using Base::operator=;
T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return this->m_ref.fetch_add(arg, order);
}
T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return this->m_ref.fetch_sub(arg, order);
}
T operator+=(T arg) const noexcept
{
return this->m_ref.fetch_add(arg) + arg;
}
T operator-=(T arg) const noexcept
{
return this->m_ref.fetch_sub(arg) - arg;
}
};
template <class T>
class atomic_ref_integer_facade : public atomic_ref_numeric_facade<T>
{
using Base = atomic_ref_numeric_facade<T>;
static_assert(std::is_integral<T>::value, "");
public:
explicit atomic_ref_integer_facade(T& ref) : Base(ref)
{
}
atomic_ref_integer_facade(const atomic_ref_integer_facade& other) noexcept : Base(other)
{
}
using Base::operator=;
T fetch_and(T arg, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return this->m_ref.fetch_and(arg, order);
}
T fetch_or(T arg, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return this->m_ref.fetch_or(arg, order);
}
T fetch_xor(T arg, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
return this->m_ref.fetch_xor(arg, order);
}
T operator++() const noexcept
{
return this->m_ref.fetch_add(T(1)) + T(1);
}
T operator++(int) const noexcept
{
return this->m_ref.fetch_add(T(1));
}
T operator--() const noexcept
{
return this->m_ref.fetch_sub(T(1)) - T(1);
}
T operator--(int) const noexcept
{
return this->m_ref.fetch_sub(T(1));
}
T operator&=(T arg) const noexcept
{
return this->m_ref.fetch_and(arg) & arg;
}
T operator|=(T arg) const noexcept
{
return this->m_ref.fetch_or(arg) | arg;
}
T operator^=(T arg) const noexcept
{
return this->m_ref.fetch_xor(arg) ^ arg;
}
};
template <class T>
using SelectAtomicRefBase = std::conditional_t<
std::is_pointer<T>::value,
atomic_ref_pointer_facade<T>,
std::conditional_t<std::is_integral<T>::value,
atomic_ref_integer_facade<T>,
std::conditional_t<std::is_floating_point<T>::value, atomic_ref_numeric_facade<T>, atomic_ref_base<T>>>>;
template <class T>
using SelectAtomicBase = std::conditional_t<std::is_floating_point<T>::value, atomic_float_facade<T>, std::atomic<T>>;
} // namespace detail
template <class T>
class atomic : public detail::SelectAtomicBase<T>
{
using Base = detail::SelectAtomicBase<T>;
public:
using value_type = T;
atomic() noexcept = default;
constexpr atomic(T desired) noexcept : Base(desired)
{
}
static constexpr bool is_always_lock_free = sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8;
using Base::operator=;
using Base::operator T;
CARB_PREVENT_COPY_AND_MOVE(atomic);
// See https://en.cppreference.com/w/cpp/atomic/atomic/wait
void wait(T old, std::memory_order order = std::memory_order_seq_cst) const noexcept
{
static_assert(is_always_lock_free, "Only supported for always-lock-free types");
using I = thread::detail::to_integral_t<T>;
for (;;)
{
if (this_thread::spinTryWait([&] {
return thread::detail::reinterpret_as<I>(this->load(order)) != thread::detail::reinterpret_as<I>(old);
}))
{
break;
}
thread::futex::wait(*this, old);
}
}
void wait(T old, std::memory_order order = std::memory_order_seq_cst) const volatile noexcept
{
static_assert(is_always_lock_free, "Only supported for always-lock-free types");
using I = thread::detail::to_integral_t<T>;
for (;;)
{
if (this_thread::spinTryWait([&] {
return thread::detail::reinterpret_as<I>(this->load(order)) != thread::detail::reinterpret_as<I>(old);
}))
{
break;
}
thread::futex::wait(const_cast<atomic<T>&>(*this), old);
}
}
// wait_for and wait_until are non-standard
template <class Rep, class Period>
bool wait_for(T old,
std::chrono::duration<Rep, Period> duration,
std::memory_order order = std::memory_order_seq_cst) const noexcept
{
// Since futex can spuriously wake up, calculate the end time so that we can handle the spurious wakeups without
// shortening our wait time potentially significantly.
return wait_until(old, std::chrono::steady_clock::now() + thread::detail::clampDuration(duration), order);
}
template <class Rep, class Period>
bool wait_for(T old,
std::chrono::duration<Rep, Period> duration,
std::memory_order order = std::memory_order_seq_cst) const volatile noexcept
{
// Since futex can spuriously wake up, calculate the end time so that we can handle the spurious wakeups without
// shortening our wait time potentially significantly.
return wait_until(old, std::chrono::steady_clock::now() + thread::detail::clampDuration(duration), order);
}
template <class Clock, class Duration>
bool wait_until(T old,
std::chrono::time_point<Clock, Duration> time_point,
std::memory_order order = std::memory_order_seq_cst) const noexcept
{
static_assert(is_always_lock_free, "Only supported for always-lock-free types");
using I = thread::detail::to_integral_t<T>;
for (;;)
{
if (this_thread::spinTryWait([&] {
return thread::detail::reinterpret_as<I>(this->load(order)) != thread::detail::reinterpret_as<I>(old);
}))
{
return true;
}
if (!thread::futex::wait_until(*this, old, time_point))
{
return false;
}
}
}
template <class Clock, class Duration>
bool wait_until(T old,
std::chrono::time_point<Clock, Duration> time_point,
std::memory_order order = std::memory_order_seq_cst) const volatile noexcept
{
static_assert(is_always_lock_free, "Only supported for always-lock-free types");
using I = thread::detail::to_integral_t<T>;
for (;;)
{
if (this_thread::spinTryWait([&] {
return thread::detail::reinterpret_as<I>(this->load(order)) != thread::detail::reinterpret_as<I>(old);
}))
{
return true;
}
if (!thread::futex::wait_until(const_cast<atomic<T>&>(*this), old, time_point))
{
return false;
}
}
}
// See https://en.cppreference.com/w/cpp/atomic/atomic/notify_one
void notify_one() noexcept
{
thread::futex::notify_one(*this);
}
void notify_one() volatile noexcept
{
thread::futex::notify_one(const_cast<atomic<T>&>(*this));
}
// See https://en.cppreference.com/w/cpp/atomic/atomic/notify_all
void notify_all() noexcept
{
thread::futex::notify_all(*this);
}
void notify_all() volatile noexcept
{
thread::futex::notify_all(const_cast<atomic<T>&>(*this));
}
};
template <class T>
class atomic_ref : public detail::SelectAtomicRefBase<T>
{
using Base = detail::SelectAtomicRefBase<T>;
public:
explicit atomic_ref(T& ref) : Base(ref)
{
}
atomic_ref(const atomic_ref& other) noexcept : Base(other)
{
}
using Base::operator=;
};
// Helper functions
// See https://en.cppreference.com/w/cpp/atomic/atomic_wait
template <class T>
inline void atomic_wait(const atomic<T>* object, typename atomic<T>::value_type old) noexcept
{
object->wait(old);
}
template <class T>
inline void atomic_wait_explicit(const atomic<T>* object, typename atomic<T>::value_type old, std::memory_order order) noexcept
{
object->wait(old, order);
}
// See https://en.cppreference.com/w/cpp/atomic/atomic_notify_one
template <class T>
inline void atomic_notify_one(atomic<T>* object)
{
object->notify_one();
}
// See https://en.cppreference.com/w/cpp/atomic/atomic_notify_all
template <class T>
inline void atomic_notify_all(atomic<T>* object)
{
object->notify_all();
}
using atomic_bool = atomic<bool>;
using atomic_char = atomic<char>;
using atomic_schar = atomic<signed char>;
using atomic_uchar = atomic<unsigned char>;
using atomic_short = atomic<short>;
using atomic_ushort = atomic<unsigned short>;
using atomic_int = atomic<int>;
using atomic_uint = atomic<unsigned int>;
using atomic_long = atomic<long>;
using atomic_ulong = atomic<unsigned long>;
using atomic_llong = atomic<long long>;
using atomic_ullong = atomic<unsigned long long>;
using atomic_char16_t = atomic<char16_t>;
using atomic_char32_t = atomic<char32_t>;
using atomic_wchar_t = atomic<wchar_t>;
using atomic_int8_t = atomic<int8_t>;
using atomic_uint8_t = atomic<uint8_t>;
using atomic_int16_t = atomic<int16_t>;
using atomic_uint16_t = atomic<uint16_t>;
using atomic_int32_t = atomic<int32_t>;
using atomic_uint32_t = atomic<uint32_t>;
using atomic_int64_t = atomic<int64_t>;
using atomic_uint64_t = atomic<uint64_t>;
using atomic_int_least8_t = atomic<int_least8_t>;
using atomic_uint_least8_t = atomic<uint_least8_t>;
using atomic_int_least16_t = atomic<int_least16_t>;
using atomic_uint_least16_t = atomic<uint_least16_t>;
using atomic_int_least32_t = atomic<int_least32_t>;
using atomic_uint_least32_t = atomic<uint_least32_t>;
using atomic_int_least64_t = atomic<int_least64_t>;
using atomic_uint_least64_t = atomic<uint_least64_t>;
using atomic_int_fast8_t = atomic<int_fast8_t>;
using atomic_uint_fast8_t = atomic<uint_fast8_t>;
using atomic_int_fast16_t = atomic<int_fast16_t>;
using atomic_uint_fast16_t = atomic<uint_fast16_t>;
using atomic_int_fast32_t = atomic<int_fast32_t>;
using atomic_uint_fast32_t = atomic<uint_fast32_t>;
using atomic_int_fast64_t = atomic<int_fast64_t>;
using atomic_uint_fast64_t = atomic<uint_fast64_t>;
using atomic_intptr_t = atomic<intptr_t>;
using atomic_uintptr_t = atomic<uintptr_t>;
using atomic_size_t = atomic<size_t>;
using atomic_ptrdiff_t = atomic<ptrdiff_t>;
using atomic_intmax_t = atomic<intmax_t>;
using atomic_uintmax_t = atomic<uintmax_t>;
} // namespace cpp
} // namespace carb
| 19,529 | C | 30.704545 | 128 | 0.623995 |
omniverse-code/kit/include/carb/cpp/detail/ImplData.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief C++14-compatible implementation of the C++ standard library `std::data` function.
#pragma once
#include <cstddef>
#include <initializer_list>
namespace carb
{
namespace cpp
{
//! Returns a pointer to the block of memory containing the elements of the range.
//! @tparam T The type of the array elements
//! @tparam N The size of the array
//! @param array An array
//! @returns array
template <class T, std::size_t N>
constexpr T* data(T (&array)[N]) noexcept
{
return array;
}
//! Returns a pointer to the block of memory containing the elements of the range.
//! @tparam C The container type
//! @param c A container
//! @returns `c.data()`
template <class C>
constexpr auto data(C& c) -> decltype(c.data())
{
return c.data();
}
//! Returns a pointer to the block of memory containing the elements of the range.
//! @tparam C The container type
//! @param c A container
//! @returns `c.data()`
template <class C>
constexpr auto data(const C& c) -> decltype(c.data())
{
return c.data();
}
//! Returns a pointer to the block of memory containing the elements of the range.
//! @tparam E The type contained in the `std::initializer_list`
//! @param il An `std::initializer_list` of type E
//! @returns `il.begin()`
template <class E>
constexpr const E* data(std::initializer_list<E> il) noexcept
{
return il.begin();
}
} // namespace cpp
} // namespace carb
| 1,836 | C | 27.261538 | 92 | 0.712418 |
omniverse-code/kit/include/carb/cpp/detail/ImplDummy.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Implementation details
#pragma once
#include <type_traits>
namespace carb
{
namespace cpp
{
//! \cond DEV
namespace detail
{
struct NontrivialDummyType
{
constexpr NontrivialDummyType() noexcept
{
}
};
static_assert(!std::is_trivially_default_constructible<NontrivialDummyType>::value, "Invalid assumption");
} // namespace detail
//! \endcond
} // namespace cpp
} // namespace carb
| 857 | C | 21.578947 | 106 | 0.752625 |
omniverse-code/kit/include/carb/cpp/detail/ImplInvoke.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Implementation details for `carb::cpp::invoke` and related functions.
#pragma once
#include "../../Defines.h"
#include "../../detail/NoexceptType.h"
#include <functional>
#include <type_traits>
#include <utility>
//! \file
//! Contains common utilities used by \c invoke (which lives in the \c functional header) and the \c invoke_result type
//! queries (which live in the \c type_traits header).
namespace carb
{
namespace cpp
{
//! \cond DEV
namespace detail
{
CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE()
template <typename T>
struct is_reference_wrapper : std::false_type
{
};
template <typename T>
struct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type
{
};
// The interface of invoke_impl are the `eval` and `uneval` functions, which have the correct return type and noexcept
// specifiers for an expression `INVOKE(f, args...)` (this comes from the C++ concept of "Callable"). The two functions
// are identical, save for the `eval` function having a body while the `uneval` function does not. This matters for
// functions with declared-but-undefined return types. It is legal to ask type transformation questions about a function
// `R (*)(Args...)` when `R` is undefined, but not legal to evaluate it in any way.
//
// Base template: T is directly invocable -- a function pointer or object with operator()
template <typename T>
struct invoke_impl
{
template <typename F, typename... TArgs>
static constexpr auto eval(F&& f,
TArgs&&... args) noexcept(noexcept(std::forward<F>(f)(std::forward<TArgs>(args)...)))
-> decltype(std::forward<F>(f)(std::forward<TArgs>(args)...))
{
return std::forward<F>(f)(std::forward<TArgs>(args)...);
}
template <typename F, typename... TArgs>
static constexpr auto uneval(F&& f,
TArgs&&... args) noexcept(noexcept(std::forward<F>(f)(std::forward<TArgs>(args)...)))
-> decltype(std::forward<F>(f)(std::forward<TArgs>(args)...));
};
// Match the case where we want to invoke a member function.
template <typename TObject, typename TReturn>
struct invoke_impl<TReturn TObject::*>
{
using Self = invoke_impl;
template <bool B>
using bool_constant = std::integral_constant<bool, B>;
#if CARB_COMPILER_GNUC == 1 && __cplusplus <= 201703L
// WORKAROUND for pre-C++20: Calling a `const&` member function on an `&&` object through invoke is a C++20
// extension. MSVC supports this, but GNUC-compatible compilers do not until C++20. To work around this, we change
// the object's ref qualifier from `&&` to `const&` if we are attempting to call a `const&` member function.
//
// Note `move(x).f()` has always been allowed if `f` is `const&` qualified, the issue is `std::move(x).*(&T::foo)()`
// is not allowed (this is a C++ specification bug, corrected in C++20). Further note that we can not do this for
// member data selectors, because the ref qualifier carries through since C++17. When this workaround is no longer
// needed (when C++20 is minimum), the `_is_cref_mem_fn` tests on the `_access` functions can be removed.
template <typename UReturn, typename UObject, typename... UArgs>
static std::true_type _test_is_cref_mem_fn(UReturn (UObject::*mem_fn)(UArgs...) const&);
static std::false_type _test_is_cref_mem_fn(...);
template <typename TRMem>
using _is_cref_mem_fn = decltype(_test_is_cref_mem_fn(std::declval<std::decay_t<TRMem>>()));
template <typename T, typename = std::enable_if_t<std::is_base_of<TObject, std::decay_t<T>>::value>>
static constexpr auto _access(T&& x, std::false_type) noexcept -> std::add_rvalue_reference_t<T>
{
return std::forward<T>(x);
}
template <typename T, typename = std::enable_if_t<std::is_base_of<TObject, std::decay_t<T>>::value>>
static constexpr auto _access(T const& x, std::true_type) noexcept -> T const&
{
return x;
}
#else
template <typename>
using _is_cref_mem_fn = std::false_type;
// Accessing the type should be done directly.
template <typename T, bool M, typename = std::enable_if_t<std::is_base_of<TObject, std::decay_t<T>>::value>>
static constexpr auto _access(T&& x, bool_constant<M>) noexcept -> std::add_rvalue_reference_t<T>
{
return std::forward<T>(x);
}
#endif
// T is a reference wrapper -- access goes through the `get` function.
template <typename T, bool M, typename = std::enable_if_t<is_reference_wrapper<std::decay_t<T>>::value>>
static constexpr auto _access(T&& x, bool_constant<M>) noexcept(noexcept(x.get())) -> decltype(x.get())
{
return x.get();
}
// Matches cases where a pointer or fancy pointer is passed in.
template <typename TOriginal,
bool M,
typename T = std::decay_t<TOriginal>,
typename = std::enable_if_t<!std::is_base_of<TObject, T>::value && !is_reference_wrapper<T>::value>>
static constexpr auto _access(TOriginal&& x, bool_constant<M>) noexcept(noexcept(*std::forward<TOriginal>(x)))
-> decltype(*std::forward<TOriginal>(x))
{
return *std::forward<TOriginal>(x);
}
template <typename T, typename... TArgs, typename TRMem, typename = std::enable_if_t<std::is_function<TRMem>::value>>
static constexpr auto eval(TRMem TObject::*pmem, T&& x, TArgs&&... args) noexcept(noexcept(
(Self::_access(std::forward<T>(x), _is_cref_mem_fn<decltype(pmem)>{}).*pmem)(std::forward<TArgs>(args)...)))
-> decltype((Self::_access(std::forward<T>(x), _is_cref_mem_fn<decltype(pmem)>{}).*
pmem)(std::forward<TArgs>(args)...))
{
return (Self::_access(std::forward<T>(x), _is_cref_mem_fn<decltype(pmem)>{}).*pmem)(std::forward<TArgs>(args)...);
}
template <typename T, typename... TArgs, typename TRMem, typename = std::enable_if_t<std::is_function<TRMem>::value>>
static constexpr auto uneval(TRMem TObject::*pmem, T&& x, TArgs&&... args) noexcept(noexcept(
(Self::_access(std::forward<T>(x), _is_cref_mem_fn<decltype(pmem)>{}).*pmem)(std::forward<TArgs>(args)...)))
-> decltype((Self::_access(std::forward<T>(x), _is_cref_mem_fn<decltype(pmem)>{}).*
pmem)(std::forward<TArgs>(args)...));
template <typename T>
static constexpr auto eval(TReturn TObject::*select,
T&& x) noexcept(noexcept(Self::_access(std::forward<T>(x), std::false_type{}).*select))
-> decltype(Self::_access(std::forward<T>(x), std::false_type{}).*select)
{
return Self::_access(std::forward<T>(x), std::false_type{}).*select;
}
template <typename T>
static constexpr auto uneval(TReturn TObject::*select,
T&& x) noexcept(noexcept(Self::_access(std::forward<T>(x), std::false_type{}).*select))
-> decltype(Self::_access(std::forward<T>(x), std::false_type{}).*select);
};
// Test invocation of `f(args...)` in an unevaluated context to get its return type. This is a SFINAE-safe error if the
// expression `f(args...)` is invalid.
template <typename F, typename... TArgs>
auto invoke_uneval(F&& f, TArgs&&... args) noexcept(
noexcept(invoke_impl<std::decay_t<F>>::uneval(std::forward<F>(f), std::forward<TArgs>(args)...)))
-> decltype(invoke_impl<std::decay_t<F>>::uneval(std::forward<F>(f), std::forward<TArgs>(args)...));
CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE()
} // namespace detail
//! \endcond
} // namespace cpp
} // namespace carb
| 8,010 | C | 44.005618 | 122 | 0.650687 |
omniverse-code/kit/include/carb/cpp/detail/ImplOptional.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Implementation details for `carb::cpp::optional<>`.
#pragma once
#ifndef CARB_IMPLOPTIONAL
# error This file should only be included from Optional.h
#endif
#include <utility>
#include "../TypeTraits.h"
#include "ImplDummy.h"
namespace carb
{
namespace cpp
{
namespace detail
{
// Default facade for trivial destruction of T
template <class T, bool = std::is_trivially_destructible<T>::value>
struct OptionalDestructor
{
union
{
NontrivialDummyType empty;
CARB_VIZ typename std::remove_const_t<T> value;
};
CARB_VIZ bool hasValue;
constexpr OptionalDestructor() noexcept : empty{}, hasValue{ false }
{
}
template <class... Args>
constexpr explicit OptionalDestructor(in_place_t, Args&&... args)
: value(std::forward<Args>(args)...), hasValue(true)
{
}
// Cannot access anonymous union member `value` until C++17, so expose access here
constexpr const T& val() const&
{
CARB_ASSERT(hasValue);
return value;
}
constexpr T& val() &
{
CARB_ASSERT(hasValue);
return value;
}
constexpr const T&& val() const&&
{
CARB_ASSERT(hasValue);
return std::move(value);
}
constexpr T&& val() &&
{
CARB_ASSERT(hasValue);
return std::move(value);
}
void reset() noexcept
{
// No need to destruct since trivially destructible
hasValue = false;
}
};
// Specialization for non-trivial destruction of T
template <class T>
struct OptionalDestructor<T, false>
{
union
{
NontrivialDummyType empty;
CARB_VIZ typename std::remove_const_t<T> value;
};
CARB_VIZ bool hasValue;
~OptionalDestructor() noexcept
{
if (hasValue)
{
value.~T();
}
}
constexpr OptionalDestructor() noexcept : empty{}, hasValue{ false }
{
}
template <class... Args>
constexpr explicit OptionalDestructor(in_place_t, Args&&... args)
: value(std::forward<Args>(args)...), hasValue(true)
{
}
OptionalDestructor(const OptionalDestructor&) = default;
OptionalDestructor(OptionalDestructor&&) = default;
OptionalDestructor& operator=(const OptionalDestructor&) = default;
OptionalDestructor& operator=(OptionalDestructor&&) = default;
// Cannot access anonymous union member `value` until C++17, so expose access here
const T& val() const&
{
CARB_ASSERT(hasValue);
return value;
}
T& val() &
{
CARB_ASSERT(hasValue);
return value;
}
constexpr const T&& val() const&&
{
CARB_ASSERT(hasValue);
return std::move(value);
}
constexpr T&& val() &&
{
CARB_ASSERT(hasValue);
return std::move(value);
}
void reset() noexcept
{
if (hasValue)
{
value.~T();
hasValue = false;
}
}
};
template <class T>
struct OptionalConstructor : OptionalDestructor<T>
{
using value_type = T;
using OptionalDestructor<T>::OptionalDestructor;
template <class... Args>
T& construct(Args&&... args)
{
CARB_ASSERT(!this->hasValue);
new (std::addressof(this->value)) decltype(this->value)(std::forward<Args>(args)...);
this->hasValue = true;
return this->value;
}
template <class U>
void assign(U&& rhs)
{
if (this->hasValue)
{
this->value = std::forward<U>(rhs);
}
else
{
construct(std::forward<U>(rhs));
}
}
template <class U>
void constructFrom(U&& rhs) noexcept(std::is_nothrow_constructible<T, decltype((std::forward<U>(rhs).value))>::value)
{
if (rhs.hasValue)
{
construct(std::forward<U>(rhs).value);
}
}
template <class U>
void assignFrom(U&& rhs) noexcept(std::is_nothrow_constructible<T, decltype((std::forward<U>(rhs).value))>::value&&
std::is_nothrow_assignable<T, decltype((std::forward<U>(rhs).value))>::value)
{
if (rhs.hasValue)
{
assign(std::forward<U>(rhs).value);
}
else
{
this->reset();
}
}
};
template <class Base>
struct NonTrivialCopy : Base
{
using Base::Base;
NonTrivialCopy() = default;
#if CARB_COMPILER_MSC // MSVC can evaluate the noexcept operator, but GCC errors when compiling it
NonTrivialCopy(const NonTrivialCopy& from) noexcept(noexcept(Base::constructFrom(static_cast<const Base&>(from))))
#else // for GCC, use the same clause as Base::constructFrom
NonTrivialCopy(const NonTrivialCopy& from) noexcept(
std::is_nothrow_constructible<typename Base::value_type, decltype(from.value)>::value)
#endif
{
Base::constructFrom(static_cast<const Base&>(from));
}
};
// If T is copy-constructible and not trivially copy-constructible, select NonTrivialCopy,
// otherwise use the base OptionalConstructor
template <class Base, class... Types>
using SelectCopy =
typename std::conditional_t<conjunction<std::is_copy_constructible<Types>...,
negation<conjunction<std::is_trivially_copy_constructible<Types>...>>>::value,
NonTrivialCopy<Base>,
Base>;
template <class Base, class... Types>
struct NonTrivialMove : SelectCopy<Base, Types...>
{
using BaseClass = SelectCopy<Base, Types...>;
using BaseClass::BaseClass;
NonTrivialMove() = default;
NonTrivialMove(const NonTrivialMove&) = default;
#if CARB_COMPILER_MSC // MSVC can evaluate the noexcept operator, but GCC errors when compiling it
NonTrivialMove(NonTrivialMove&& from) noexcept(noexcept(BaseClass::constructFrom(static_cast<Base&&>(from))))
#else // for GCC, use the same clause as Base::constructFrom
NonTrivialMove(NonTrivialMove&& from) noexcept(
std::is_nothrow_constructible<typename Base::value_type, decltype(static_cast<Base&&>(from).value)>::value)
#endif
{
BaseClass::constructFrom(static_cast<Base&&>(from));
}
NonTrivialMove& operator=(const NonTrivialMove&) = default;
NonTrivialMove& operator=(NonTrivialMove&&) = default;
};
// If T is move-constructible and not trivially move-constructible, select NonTrivialMove,
// otherwise use the selected Copy struct.
template <class Base, class... Types>
using SelectMove =
typename std::conditional_t<conjunction<std::is_move_constructible<Types>...,
negation<conjunction<std::is_trivially_move_constructible<Types>...>>>::value,
NonTrivialMove<Base, Types...>,
SelectCopy<Base, Types...>>;
template <class Base, class... Types>
struct NonTrivialCopyAssign : SelectMove<Base, Types...>
{
using BaseClass = SelectMove<Base, Types...>;
using BaseClass::BaseClass;
NonTrivialCopyAssign() = default;
NonTrivialCopyAssign(const NonTrivialCopyAssign&) = default;
NonTrivialCopyAssign(NonTrivialCopyAssign&&) = default;
NonTrivialCopyAssign& operator=(const NonTrivialCopyAssign& from) noexcept(
noexcept(BaseClass::assignFrom(static_cast<const Base&>(from))))
{
BaseClass::assignFrom(static_cast<const Base&>(from));
return *this;
}
NonTrivialCopyAssign& operator=(NonTrivialCopyAssign&&) = default;
};
template <class Base, class... Types>
struct DeletedCopyAssign : SelectMove<Base, Types...>
{
using BaseClass = SelectMove<Base, Types...>;
using BaseClass::BaseClass;
DeletedCopyAssign() = default;
DeletedCopyAssign(const DeletedCopyAssign&) = default;
DeletedCopyAssign(DeletedCopyAssign&&) = default;
DeletedCopyAssign& operator=(const DeletedCopyAssign&) = delete;
DeletedCopyAssign& operator=(DeletedCopyAssign&&) = default;
};
// For selecting the proper copy-assign class, things get a bit more complicated:
// - If T is trivially destructible and trivially copy-constructible and trivially copy-assignable:
// * We use the Move struct selected above
// - Otherwise, if T is copy-constructible and copy-assignable:
// * We select the NonTrivialCopyAssign struct
// - If all else fails, the class is not copy-assignable, so select DeletedCopyAssign
template <class Base, class... Types>
using SelectCopyAssign = typename std::conditional_t<
conjunction<std::is_trivially_destructible<Types>...,
std::is_trivially_copy_constructible<Types>...,
std::is_trivially_copy_assignable<Types>...>::value,
SelectMove<Base, Types...>,
typename std::conditional_t<conjunction<std::is_copy_constructible<Types>..., std::is_copy_assignable<Types>...>::value,
NonTrivialCopyAssign<Base, Types...>,
DeletedCopyAssign<Base, Types...>>>;
template <class Base, class... Types>
struct NonTrivialMoveAssign : SelectCopyAssign<Base, Types...>
{
using BaseClass = SelectCopyAssign<Base, Types...>;
using BaseClass::BaseClass;
NonTrivialMoveAssign() = default;
NonTrivialMoveAssign(const NonTrivialMoveAssign&) = default;
NonTrivialMoveAssign(NonTrivialMoveAssign&&) = default;
NonTrivialMoveAssign& operator=(const NonTrivialMoveAssign&) = default;
NonTrivialMoveAssign& operator=(NonTrivialMoveAssign&& from) noexcept(
noexcept(BaseClass::assignFrom(static_cast<const Base&&>(from))))
{
BaseClass::assignFrom(static_cast<Base&&>(from));
return *this;
}
};
template <class Base, class... Types>
struct DeletedMoveAssign : SelectCopyAssign<Base, Types...>
{
using BaseClass = SelectCopyAssign<Base, Types...>;
using BaseClass::BaseClass;
DeletedMoveAssign() = default;
DeletedMoveAssign(const DeletedMoveAssign&) = default;
DeletedMoveAssign(DeletedMoveAssign&&) = default;
DeletedMoveAssign& operator=(const DeletedMoveAssign&) = default;
DeletedMoveAssign& operator=(DeletedMoveAssign&&) = delete;
};
// Selecting the proper move-assign struct is equally complicated:
// - If T is trivially destructible, trivially move-constructible and trivially move-assignable:
// * We use the CopyAssign struct selected above
// - If T is move-constructible and move-assignable:
// * We select the NonTrivialMoveAssign struct
// - If all else fails, T is not move-assignable, so select DeletedMoveAssign
template <class Base, class... Types>
using SelectMoveAssign = typename std::conditional_t<
conjunction<std::is_trivially_destructible<Types>...,
std::is_trivially_move_constructible<Types>...,
std::is_trivially_move_assignable<Types>...>::value,
SelectCopyAssign<Base, Types...>,
typename std::conditional_t<conjunction<std::is_move_constructible<Types>..., std::is_move_assignable<Types>...>::value,
NonTrivialMoveAssign<Base, Types...>,
DeletedMoveAssign<Base, Types...>>>;
// An alias for constructing our struct hierarchy to wrap T
template <class Base, class... Types>
using SelectHierarchy = SelectMoveAssign<Base, Types...>;
// Helpers for determining which operators can be enabled
template <class T>
using EnableIfBoolConvertible = typename std::enable_if_t<std::is_convertible<T, bool>::value, int>;
template <class L, class R>
using EnableIfComparableWithEqual =
EnableIfBoolConvertible<decltype(std::declval<const L&>() == std::declval<const R&>())>;
template <class L, class R>
using EnableIfComparableWithNotEqual =
EnableIfBoolConvertible<decltype(std::declval<const L&>() != std::declval<const R&>())>;
template <class L, class R>
using EnableIfComparableWithLess =
EnableIfBoolConvertible<decltype(std::declval<const L&>() < std::declval<const R&>())>;
template <class L, class R>
using EnableIfComparableWithGreater =
EnableIfBoolConvertible<decltype(std::declval<const L&>() > std::declval<const R&>())>;
template <class L, class R>
using EnableIfComparableWithLessEqual =
EnableIfBoolConvertible<decltype(std::declval<const L&>() <= std::declval<const R&>())>;
template <class L, class R>
using EnableIfComparableWithGreaterEqual =
EnableIfBoolConvertible<decltype(std::declval<const L&>() >= std::declval<const R&>())>;
} // namespace detail
} // namespace cpp
} // namespace carb
| 12,932 | C | 32.076726 | 124 | 0.658367 |
omniverse-code/kit/include/carb/tokens/TokensBindingsPython.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../BindingsPythonUtils.h"
#include "../Framework.h"
#include "TokensUtils.h"
#include <memory>
#include <string>
#include <vector>
namespace carb
{
namespace tokens
{
namespace
{
inline void definePythonModule(py::module& m)
{
using namespace carb::tokens;
m.attr("RESOLVE_FLAG_NONE") = py::int_(kResolveFlagNone);
m.attr("RESOLVE_FLAG_LEAVE_TOKEN_IF_NOT_FOUND") = py::int_(kResolveFlagLeaveTokenIfNotFound);
defineInterfaceClass<ITokens>(m, "ITokens", "acquire_tokens_interface")
.def("set_value", wrapInterfaceFunction(&ITokens::setValue), py::call_guard<py::gil_scoped_release>())
.def("set_initial_value", &ITokens::setInitialValue, py::call_guard<py::gil_scoped_release>())
.def("remove_token", &ITokens::removeToken, py::call_guard<py::gil_scoped_release>())
.def("exists", wrapInterfaceFunction(&ITokens::exists), py::call_guard<py::gil_scoped_release>())
.def("resolve",
[](ITokens* self, const std::string& str, ResolveFlags flags) -> py::str {
carb::tokens::ResolveResult result;
std::string resolvedString;
{
py::gil_scoped_release nogil;
resolvedString = carb::tokens::resolveString(self, str.c_str(), flags, &result);
}
if (result == ResolveResult::eSuccess)
return resolvedString;
else
return py::none();
},
py::arg("str"), py::arg("flags") = kResolveFlagNone)
;
}
} // namespace
} // namespace tokens
} // namespace carb
| 2,097 | C | 33.393442 | 110 | 0.638531 |
omniverse-code/kit/include/carb/tokens/TokensUtils.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Implementation of utilities for \ref carb::tokens::ITokens.
#pragma once
#include "../InterfaceUtils.h"
#include "../logging/Log.h"
#include "ITokens.h"
#include <string>
#include <algorithm>
namespace carb
{
namespace tokens
{
/**
* Helper for resolving a token string. The resolve result (resolve code) is placed in the optional parameter.
*
* @param tokens tokens interface (passing a null pointer will result in an error)
* @param str string for token resolution (passing a null pointer will result in an error)
* @param resolveFlags flags that modify token resolution process
* @param resolveResult optional parameter for receiving resulting resolve code
*
* @return true if the operation was successful false otherwise
*/
inline std::string resolveString(const ITokens* tokens,
const char* str,
ResolveFlags resolveFlags = kResolveFlagNone,
ResolveResult* resolveResult = nullptr)
{
// Defaulting to an error result thus it's possible to just log an error message and return an empty string if
// anything goes wrong
if (resolveResult)
{
*resolveResult = ResolveResult::eFailure;
}
if (!tokens)
{
CARB_LOG_ERROR("Couldn't acquire ITokens interface.");
return std::string();
}
if (!str)
{
CARB_LOG_ERROR("Can't resolve a null token string.");
return std::string();
}
const size_t strLen = std::strlen(str);
ResolveResult resResult;
size_t resolvedStringSize = tokens->calculateDestinationBufferSize(
str, strLen, StringEndingMode::eNoNullTerminator, resolveFlags, &resResult);
if (resResult == ResolveResult::eFailure)
{
CARB_LOG_ERROR("Couldn't calculate required buffer size for token resolution of string: %s", str);
return std::string();
}
// Successful resolution to an empty string
if (resolvedStringSize == 0)
{
if (resolveResult)
{
*resolveResult = ResolveResult::eSuccess;
}
return std::string();
}
// C++11 guarantees that strings are continuous in memory
std::string resolvedString;
resolvedString.resize(resolvedStringSize);
const ResolveResult resolveResultLocal =
tokens->resolveString(str, strLen, &resolvedString.front(), resolvedString.size(),
StringEndingMode::eNoNullTerminator, resolveFlags, nullptr);
if (resolveResultLocal != ResolveResult::eSuccess)
{
CARB_LOG_ERROR("Couldn't successfully resolve provided string: %s", str);
return std::string();
}
if (resolveResult)
{
*resolveResult = ResolveResult::eSuccess;
}
return resolvedString;
}
/**
* A helper function that escapes necessary symbols in the provided string so that they won't be recognized as related
* to token parsing
* @param str a string that requires preprocessing to evade the token resolution (a string provided by a user or some
* other data that must not be a part of token resolution)
* @return a string with necessary modification so it won't participate in token resolution
*/
inline std::string escapeString(const std::string& str)
{
constexpr char kSpecialChar = '$';
const size_t countSpecials = std::count(str.begin(), str.end(), kSpecialChar);
if (!countSpecials)
{
return str;
}
std::string result;
result.reserve(str.length() + countSpecials);
for (char curChar : str)
{
result.push_back(curChar);
if (curChar == kSpecialChar)
{
result.push_back(kSpecialChar);
}
}
return result;
}
} // namespace tokens
} // namespace carb
| 4,219 | C | 30.259259 | 118 | 0.671012 |
omniverse-code/kit/include/carb/tokens/ITokens.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Implementation of `ITokens` interface
#pragma once
#include "../Interface.h"
namespace carb
{
//! Namespace for `ITokens`.
namespace tokens
{
/**
* Possible result of resolving tokens.
*/
enum class ResolveResult
{
eSuccess, //!< Result indicating success.
eTruncated, //!< Result that indicates success, but the output was truncated.
eFailure, //!< Result that indicates failure.
};
/**
* Possible options for ending of the resolved string
*/
enum class StringEndingMode
{
eNullTerminator, //!< Indicates that the resolved string is NUL-terminated.
eNoNullTerminator //!< Indicates that the resolved string is not NUL-terminated.
};
/**
* Flags for token resolution algorithm
*/
using ResolveFlags = uint32_t;
const ResolveFlags kResolveFlagNone = 0; //!< Default token resolution process
const ResolveFlags kResolveFlagLeaveTokenIfNotFound = 1; //!< If cannot resolve token in a string then leave it as is.
/**
* Interface for storing tokens and resolving strings containing them. Tokens are string pairs {name, value} that can be
* referenced in a string as `"some text ${token_name} some other text"`, where the token name starts with a sequence
* `"${"` and end with a first closing `"}"`.
*
* If a token with the name \<token_name\> has a defined value, then it will be substituted with its value.
* If the token does not have a defined value, an empty string will be used for the replacement. This interface will use
* the ISetting interface, if available, as storage and in such case tokens will be stored under the '/app/tokens' node.
*
* Note: The "$" symbol is considered to be special by the tokenizer and should be escaped by doubling it ("$" -> "$$")
* in order to be processed as just a symbol "$"
* Ex: "some text with $ sign" -> "some text with $$ sign"
*
* Single unescaped "$" signs are considered to be a bad practice to be used for token resolution but they are
* acceptable and will be resolved into single "$" signs and no warning will be given about it.
*
* Ex:
* "$" -> "$",
* "$$" -> "$",
* "$$$" -> "$$"
*
* It's better to use the helper function "escapeString" from the "TokensUtils.h" to produce a string
* that doesn't have any parts that could participate in tokenization. As a token name start with "${" and ends with the
* first encountered "}" it can contain "$" (same rules about escaping it apply) and "{" characters, however such cases
* will result in a warning being output to the log.
* Ex: for the string "${bar$${}" the token resolution process will consider the token name to be "bar${"
* (note that "$$" is reduced into a single "$") and a warning will be outputted into the log.
*
* Environment variables are automatically available as tokens, if defined. These are specified with the text
* `${env:<var name>}` where `<var name>` is the name of the environment variable. The `env:` prefix is a reserved name,
* so any call to \ref ITokens::setValue() or \ref ITokens::setInitialValue() with a name that starts with `env:` will
* be rejected. The environment variable is read when needed and not cached in any way. An undefined environment
* variable behaves as an undefined token.
*
* @thread_safety the interface's functions are not thread safe. It is responsibility of the user to use all necessary
* synchronization mechanisms if needed. All data passed into a plugin's function must be valid for the duration of the
* function call.
*/
struct ITokens
{
CARB_PLUGIN_INTERFACE("carb::tokens::ITokens", 1, 0)
/**
* Sets a new value for the specified token, if the token didn't exist it will be created.
*
* Note: if the value is null then the token will be removed (see also: "removeToken" function). In this case true
* is returned if the token was successfully deleted or didn't exist.
*
* @param name token name not enclosed in "${" and "}". Passing a null pointer results in an error
* @param value new value for the token. Passing a null pointer deletes the token
*
* @return true if the operation was successful, false if the token name was null or an error occurred during the
* operation
*/
bool(CARB_ABI* setValue)(const char* name, const char* value);
/**
* Creates a token with the given name and value if it was non-existent. Otherwise does nothing.
*
* @param name Name of a token. Passing a null pointer results in an error
* @param value Value of a token. Passing a null pointer does nothing.
*/
void setInitialValue(const char* name, const char* value) const;
/**
* A function to delete a token.
*
* @param name token name not enclosed in "${" and "}". Passing a null pointer results in an error
*
* @return true if the operation was successful or token with such name didn't exist, false if the name is null or
* an error occurred
*/
bool removeToken(const char* name) const;
/**
* Tries to resolve all tokens in the source string buffer and places the result into the destination buffer.
* If the destBufLen isn't enough to contain the result then the result will be truncated.
*
* @param sourceBuf the source string buffer. Passing a null pointer results in an error
* @param sourceBufLen the length of the source string buffer
* @param destBuf the destination buffer. Passing a null pointer results in an error
* @param destBufLen the size of the destination buffer
* @param endingMode sets if the result will have a null-terminator (in this case passing a zero
* destBufLen will result in an error) or not
* @param resolveFlags flags that modify token resolution process
* @param[out] resolvedSize optional parameter. If the provided buffer were enough for the operation and it
* succeeded then resolvedSize <= destBufLen and equals to the number of written bytes to the buffer, if the
* operation were successful but the output were truncated then resolvedSize > destBufLen and equals to the minimum
* buffer size that can hold the fully resolved string, if the operation failed then the value of the resolvedSize
* is undetermined
*
* @retval ResolveResult::eTruncated if the destination buffer was too small to contain the result (note that if the
* StringEndingMode::eNullTerminator was used the result truncated string will end with a null-terminator)
* @retval ResolveResult::eFailure if an error occurred.
* @retval ResolveResult::eSuccess will be returned if the function successfully wrote the whole resolve result into
* the \p destBuf.
*/
ResolveResult(CARB_ABI* resolveString)(const char* sourceBuf,
size_t sourceBufLen,
char* destBuf,
size_t destBufLen,
StringEndingMode endingMode,
ResolveFlags resolveFlags,
size_t* resolvedSize);
/**
* Calculates the minimum buffer size required to hold the result of resolving of the input string buffer.
*
* @param sourceBuf the source string buffer. Passing a null pointer results in an error
* @param sourceBufLen the length of the source string buffer
* @param endingMode sets if the result will have a null-terminator or not
* @param resolveFlags flags that modify token resolution process
* @param[out] resolveResult optional parameter that will contain the result of the attempted resolution to
* calculate the necessary size
*
* @returns The calculated minimum size. In case of any error the function will return 0.
*/
size_t(CARB_ABI* calculateDestinationBufferSize)(const char* sourceBuf,
size_t sourceBufLen,
StringEndingMode endingMode,
ResolveFlags resolveFlags,
ResolveResult* resolveResult);
/**
* Check the existence of a token
*
* @param tokenName the name of a token that will be checked for existence. Passing a null pointer results in an
* error
*
* @return true if the token with the specified name exists, false is returned if an error occurs or there is no
* token with such name
*/
bool(CARB_ABI* exists)(const char* tokenName);
};
inline void ITokens::setInitialValue(const char* name, const char* value) const
{
if (!exists(name) && value)
{
setValue(name, value);
}
}
inline bool ITokens::removeToken(const char* name) const
{
return setValue(name, nullptr);
}
} // namespace tokens
} // namespace carb
| 9,369 | C | 46.563452 | 120 | 0.678834 |
omniverse-code/kit/include/carb/tasking/ThreadPoolUtils.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief ThreadPoolWrapper definition file.
#pragma once
#include "../cpp/Tuple.h"
#include "../logging/Log.h"
#include "IThreadPool.h"
#include <future>
namespace carb
{
namespace tasking
{
#ifndef DOXYGEN_BUILD
namespace detail
{
template <class ReturnType>
struct ApplyWithPromise
{
template <class Callable, class Tuple>
void operator()(std::promise<ReturnType>& promise, Callable&& f, Tuple&& t)
{
promise.set_value(std::forward<ReturnType>(cpp::apply(std::forward<Callable>(f), std::forward<Tuple>(t))));
}
};
template <>
struct ApplyWithPromise<void>
{
template <class Callable, class Tuple>
void operator()(std::promise<void>& promise, Callable& f, Tuple&& t)
{
cpp::apply(std::forward<Callable>(f), std::forward<Tuple>(t));
promise.set_value();
}
};
} // namespace detail
#endif
/**
* Helper class for using IThreadPool API
*/
class ThreadPoolWrapper
{
public:
/**
* Constructor
*
* @param poolInterface The acquired IThreadPool interface.
* @param workerCount (optional) The number of worker threads to create. If 0 (default) is specified, the value
* returned from IThreadPool::getDefaultWorkerCount() is used.
*/
ThreadPoolWrapper(IThreadPool* poolInterface, size_t workerCount = 0) : m_interface(poolInterface)
{
if (m_interface == nullptr)
{
CARB_LOG_ERROR("IThreadPool interface used to create a thread pool wrapper is null.");
return;
}
if (workerCount == 0)
{
workerCount = m_interface->getDefaultWorkerCount();
}
m_pool = m_interface->createEx(workerCount);
if (m_pool == nullptr)
{
CARB_LOG_ERROR("Couldn't create a new thread pool.");
}
}
/**
* Returns the number of worker threads in the thread pool.
* @returns The number of worker threads.
*/
size_t getWorkerCount() const
{
if (!isValid())
{
CARB_LOG_ERROR("Attempt to call the 'getWorkerCount' method of an invalid thread pool wrapper.");
return 0;
}
return m_interface->getWorkerCount(m_pool);
}
/**
* Enqueues a <a href="https://en.cppreference.com/w/cpp/named_req/Callable">Callable</a> to run on a worker thread.
*
* @param task The callable object. May be a lambda, [member] function, functor, etc.
* @param args Optional <a href="https://en.cppreference.com/w/cpp/utility/functional/bind">std::bind</a>-style
* arguments to pass to the callable object.
* @returns A <a href="https://en.cppreference.com/w/cpp/thread/future">std::future</a> based on the return-type of
* the callable object. If enqueuing failed, `valid()` on the returned future will be false.
*/
template <class Callable, class... Args>
auto enqueueJob(Callable&& task, Args&&... args)
{
using ReturnType = typename cpp::invoke_result_t<Callable, Args...>;
using Future = std::future<ReturnType>;
using Tuple = std::tuple<std::decay_t<Args>...>;
struct Data
{
std::promise<ReturnType> promise{};
Callable f;
Tuple args;
Data(Callable&& f_, Args&&... args_) : f(std::forward<Callable>(f_)), args(std::forward<Args>(args_)...)
{
}
void callAndDelete()
{
detail::ApplyWithPromise<ReturnType>{}(promise, f, args);
delete this;
}
};
if (!isValid())
{
CARB_LOG_ERROR("Attempt to call the 'enqueueJob' method of an invalid thread pool wrapper.");
return Future{};
}
Data* pData = new (std::nothrow) Data{ std::forward<Callable>(task), std::forward<Args>(args)... };
if (!pData)
{
CARB_LOG_ERROR("ThreadPoolWrapper: No memory for job");
return Future{};
}
Future result = pData->promise.get_future();
if (CARB_LIKELY(m_interface->enqueueJob(
m_pool, [](void* userData) { static_cast<Data*>(userData)->callAndDelete(); }, pData)))
{
return result;
}
CARB_LOG_ERROR("ThreadPoolWrapper: failed to enqueue job");
delete pData;
return Future{};
}
/**
* Returns the number of jobs currently enqueued or executing in the ThreadPool.
*
* enqueueJob() increments this value and the value is decremented as jobs finish.
*
* @note This value changes by other threads and cannot be read atomically.
*
* @returns The number of jobs currently executing in the ThreadPool.
*/
size_t getCurrentlyRunningJobCount() const
{
if (!isValid())
{
CARB_LOG_ERROR("Attempt to call the 'getCurrentlyRunningJobCount' method of an invalid thread pool wrapper.");
return 0;
}
return m_interface->getCurrentlyRunningJobCount(m_pool);
}
/**
* Blocks the calling thread until all enqueued tasks have completed.
*/
void waitUntilFinished() const
{
if (!isValid())
{
CARB_LOG_ERROR("Attempt to call the 'waitUntilFinished' method of an invalid thread pool wrapper.");
return;
}
m_interface->waitUntilFinished(m_pool);
}
/**
* Returns true if the underlying ThreadPool is valid.
*
* @returns `true` if the underlying ThreadPool is valid; `false` otherwise.
*/
bool isValid() const
{
return m_pool != nullptr;
}
/**
* Destructor
*/
~ThreadPoolWrapper()
{
if (isValid())
{
m_interface->destroy(m_pool);
}
}
CARB_PREVENT_COPY_AND_MOVE(ThreadPoolWrapper);
private:
// ThreadPoolWrapper private members and functions
IThreadPool* m_interface = nullptr;
ThreadPool* m_pool = nullptr;
};
} // namespace tasking
} // namespace carb
| 6,482 | C | 28.202703 | 122 | 0.607066 |
omniverse-code/kit/include/carb/tasking/IThreadPool.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief IThreadPool definition file.
#pragma once
#include "../Interface.h"
namespace carb
{
namespace tasking
{
/**
* Opaque handle for a thread pool.
*/
class ThreadPool DOXYGEN_EMPTY_CLASS;
/**
* Defines the function for performing a user-provided job.
*
* @param jobData User provided data for the job, the memory must not be released until it no longer needed by the
* task.
*/
typedef void (*JobFn)(void* jobData);
/**
* Optional plugin providing helpful facilities for utilizing a pool of threads to perform basic small tasks.
*
* @warning It is not recommended to use IThreadPool in conjunction with ITasking; the latter is a much richer feature
* set and generally preferred over IThreadPool. IThreadPool is a simple thread pool with the ability to run individual
* tasks.
*
* @warning If multiple ThreadPool objects are used, caution must be taken to not overburden the system with too many
* threads.
*
* @note Prefer using ThreadPoolWrapper.
*/
struct IThreadPool
{
CARB_PLUGIN_INTERFACE("carb::tasking::IThreadPool", 1, 0)
/**
* Creates a new thread pool where the number of worker equals to the number specified by the user.
*
* @param workerCount Required number of worker threads.
*
* @return A newly created thread pool.
*/
ThreadPool*(CARB_ABI* createEx)(size_t workerCount);
/**
* Creates a new thread pool where the number of worker equals to a value
* returned by the "getDefaultWorkerCount" function.
*
* @return A newly created thread pool.
*/
ThreadPool* create() const;
/**
* Destroys previously created thread pool.
*
* @param threadPool Previously created thread pool.
*/
void(CARB_ABI* destroy)(ThreadPool* threadPool);
/**
* Returns default number of workers used for creation of a new thread pool.
*
* @return The default number of workers.
*/
size_t(CARB_ABI* getDefaultWorkerCount)();
/**
* Returns the number of worker threads in the thread pool.
*
* @param threadPool ThreadPool previously created with create().
* @returns The number of worker threads.
*/
size_t(CARB_ABI* getWorkerCount)(ThreadPool* threadPool);
/**
* Adds a new task to be executed by the thread pool.
*
* @param threadPool Thread pool for execution of the job.
* @param jobFunction User provided function to be executed by a worker.
* @param jobData User provided data for the job, the memory must not be released until it no longer needed by the
* task.
*
* @return Returns true if the task was successfully added into the thread pool.
*/
bool(CARB_ABI* enqueueJob)(ThreadPool* threadPool, JobFn jobFunction, void* jobData);
/**
* Returns the number of currently executed tasks in the thread pool.
*
* @param threadPool Thread pool to be inspected.
*
* @return The number of currently executed tasks in the thread pool.
*/
size_t(CARB_ABI* getCurrentlyRunningJobCount)(ThreadPool* threadPool);
/**
* Blocks execution of the current thread until the thread pool finishes all queued jobs.
*
* @param threadPool Thread pool to wait on.
*/
void(CARB_ABI* waitUntilFinished)(ThreadPool* threadPool);
};
inline ThreadPool* IThreadPool::create() const
{
return createEx(getDefaultWorkerCount());
}
} // namespace tasking
} // namespace carb
| 3,918 | C | 29.858267 | 119 | 0.696274 |
omniverse-code/kit/include/carb/tasking/ITasking.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief carb.tasking interface definition file.
#pragma once
#include "../Interface.h"
#include "../InterfaceUtils.h"
#include "TaskingHelpers.h"
namespace carb
{
//! Namespace for *carb.tasking.plugin* and related utilities.
namespace tasking
{
/**
* Default TaskingDesc plugin starts with.
*/
inline TaskingDesc getDefaultTaskingDesc()
{
return TaskingDesc{};
}
/**
* Defines a tasking plugin interface, acquired with carb::Framework::acquireInterface() when *carb.tasking.plugin* is
* loaded.
*
* ITasking is started automatically on plugin startup. It uses default TaskingDesc, see getDefaultTaskingDesc().
*
* Several @rstref{ISettings keys <tasking_settings>} exist to provide debug behavior and to override default startup
* behavior (but do not override a TaskingDesc provided to ITasking::changeParameters()).
*
* @thread_safety Unless otherwise specified, all functions in this interface can be called from multiple threads
* simultaneously.
*/
struct ITasking
{
// 0.1 - Initial version
// 0.2 - Thread pinning, sleep, suspending/waking (not ABI compatible with 0.1)
// 0.3 - Semaphore support, SharedMutex support
// 0.4 - ConditionVariable support
// 1.0 - Wait timeouts (git hash e13289c5a5)
// 1.1 - changeTaskPriority() / executeMainTasks()
// 1.2 - restart() -> changeParameters(); don't lose tasks when changing parameters
// 1.3 - Respect task priority when resuming tasks that have slept, waited, or unsuspended (not an API change)
// 1.4 - Stuck checking (not an API change)
// 1.5 - internalGroupCounters()
// 1.6 - createRecursiveMutex()
// 2.0 - ITasking 2.0 (git hash f68ae95da7)
// 2.1 - allocTaskStorage() / freeTaskStorage() / setTaskStorage() / getTaskStorage()
// 2.2 - beginTracking() / endTracking()
// 2.3 - internalNameTask()
// 2.4 - reloadFiberEvents()
CARB_PLUGIN_INTERFACE("carb::tasking::ITasking", 2, 4)
/**
* Changes the parameters under which the ITasking interface functions. This may stop and start threads, but will
* not lose any tasks in progress or queued.
*
* @note This function reloads all registered @ref IFiberEvents interfaces so they will start receiving
* notifications. However, if this is the only change desired it is recommended to use @ref reloadFiberEvents()
* instead.
*
* @thread_safety It is unsafe to add any additional tasks while calling this function. The caller must ensure that
* no new tasks are added until this function returns.
*
* @warning Calling this function from within a task context causes undefined behavior.
*
* @param desc The tasking plugin descriptor.
*/
void(CARB_ABI* changeParameters)(TaskingDesc desc);
/**
* Get TaskingDesc the plugin currently running with.
*
* @return The tasking plugin descriptor.
*/
const TaskingDesc&(CARB_ABI* getDesc)();
/**
* Creates a Counter with target value of zero.
*
* @warning Prefer using CounterWrapper instead.
*
* @return The counter created.
*/
Counter*(CARB_ABI* createCounter)();
/**
* Creates a counter with a specific target value.
*
* @warning Prefer using CounterWrapper instead.
*
* @param target The target value of the counter. Yielding on this counter will wait for this target.
* @return The counter created.
*/
Counter*(CARB_ABI* createCounterWithTarget)(uint32_t target);
/**
* Destroys the counter.
*
* @param counter A counter.
*/
void(CARB_ABI* destroyCounter)(Counter* counter);
/**
* Adds a task to the internal queue. Do not call this function directly; instead, use one of the helper functions
* such as addTask(), addSubTask() or addThrottledTask().
*
* @param task The task to queue.
* @param counter A counter to associate with this task. It will be incremented by 1.
* When the task completes, it will be decremented.
* @return A TaskContext that can be used to refer to this task
*/
//! @private
TaskContext(CARB_ABI* internalAddTask)(TaskDesc task, Counter* counter);
/**
* Adds a group of tasks to the internal queue
*
* @param tasks The tasks to queue.
* @param taskCount The number of tasks.
* @param counter A counter to associate with the task group as a whole.
* Initially it incremented by taskCount. When each task completes, it will be decremented by 1.
*/
void(CARB_ABI* addTasks)(TaskDesc* tasks, size_t taskCount, Counter* counter);
//! @private
TaskContext(CARB_ABI* internalAddDelayedTask)(uint64_t delayNs, TaskDesc desc, Counter* counter);
//! @private
void(CARB_ABI* internalApplyRange)(size_t range, ApplyFn fn, void* context);
/**
* Yields execution to another task until counter reaches its target value.
*
* Tasks invoking this call can resume on different thread. If the task must resume on the same thread, use
* PinGuard.
*
* @note deprecated Use wait() instead.
*
* @param counter The counter to check.
*/
CARB_DEPRECATED("Use wait() instead") void yieldUntilCounter(RequiredObject counter);
/**
* Yields execution to another task until counter reaches its target value or the timeout period elapses.
*
* Tasks invoking this call can resume on different thread. If the task must resume on the same thread, use
* PinGuard.
*
* @note Deprecated: Use wait_for() or wait_until() instead.
*
* @param counter The counter to check.
* @param timeoutNs The number of nanoseconds to wait. Pass kInfinite to wait forever or 0 to try immediately
* without waiting.
* @return true if the counter period has completed; false if the timeout period elapses.
*/
CARB_DEPRECATED("Use wait_for() or wait_until() instead.")
bool timedYieldUntilCounter(RequiredObject counter, uint64_t timeoutNs);
//! @private
bool(CARB_ABI* internalCheckCounter)(Counter* counter);
//! @private
uint32_t(CARB_ABI* internalGetCounterValue)(Counter* counter);
//! @private
uint32_t(CARB_ABI* internalGetCounterTarget)(Counter* counter);
//! @private
uint32_t(CARB_ABI* internalFetchAddCounter)(Counter* counter, uint32_t value);
//! @private
uint32_t(CARB_ABI* internalFetchSubCounter)(Counter* counter, uint32_t value);
//! @private
void(CARB_ABI* internalStoreCounter)(Counter* counter, uint32_t value);
/**
* Checks if counter is at the counter's target value
*
* @note Deprecated: The Counter interface is deprecated.
*
* @param c The counter to check.
* @return `true` if the counter is at the target value; `false` otherwise.
*/
CARB_DEPRECATED("The Counter interface is deprecated.") bool checkCounter(Counter* c)
{
return internalCheckCounter(c);
}
/**
* Retrieves the current value of the target. Note! Because of the threaded nature of counters, this
* value may have changed by another thread before the function returns.
*
* @note Deprecated: The Counter interface is deprecated.
*
* @param counter The counter.
* @return The current value of the counter.
*/
CARB_DEPRECATED("The Counter interface is deprecated.") uint32_t getCounterValue(Counter* counter)
{
return internalGetCounterValue(counter);
}
/**
* Gets the target value for the Counter
*
* @note Deprecated: The Counter interface is deprecated.
*
* @param counter The counter to check.
* @return The target value of the counter.
*/
CARB_DEPRECATED("The Counter interface is deprecated.") uint32_t getCounterTarget(Counter* counter)
{
return internalGetCounterTarget(counter);
}
/**
* Atomically adds a value to the counter and returns the value held previously.
*
* The fetchAdd operation on the counter will be atomic, but this function as a whole is not atomic.
*
* @note Deprecated: The Counter interface is deprecated.
*
* @param counter The counter.
* @param value The value to add to the counter.
* @return The value of the counter before the addition.
*/
CARB_DEPRECATED("The Counter interface is deprecated.") uint32_t fetchAddCounter(Counter* counter, uint32_t value)
{
return internalFetchAddCounter(counter, value);
}
/**
* Atomically subtracts a value from the counter and returns the value held previously.
*
* The fetchSub operation on the counter will be atomic, but this function as a whole is not atomic.
*
* @note Deprecated: The Counter interface is deprecated.
*
* @param counter The counter.
* @param value The value to subtract from the counter.
* @return The value of the counter before the addition.
*/
CARB_DEPRECATED("The Counter interface is deprecated.") uint32_t fetchSubCounter(Counter* counter, uint32_t value)
{
return internalFetchSubCounter(counter, value);
}
/**
* Atomically replaces the current value with desired on a counter.
*
* The store operation on the counter will be atomic, but this function as a whole is not atomic.
*
* @note Deprecated: The Counter interface is deprecated.
*
* @param counter The counter.
* @param value The value to load into to the counter.
*/
CARB_DEPRECATED("The Counter interface is deprecated.") void storeCounter(Counter* counter, uint32_t value)
{
return internalStoreCounter(counter, value);
}
/**
* Yields execution. Task invoking this call will be put in the very end of task queue, priority is ignored.
*/
void(CARB_ABI* yield)();
/**
* Causes the currently executing TaskContext to be "pinned" to the thread it is currently running on.
*
* @warning Do not call this function directly; instead use PinGuard.
*
* This function causes the current thread to be the only task thread that can run the current task. This is
* necessary in some cases where thread specificity is required (those these situations are NOT recommended for
* tasks): holding a mutex, or using thread-specific data, etc. Thread pinning is not efficient (the pinned thread
* could be running a different task causing delays for the current task to be resumed, and wakeTask() must wait to
* return until the pinned thread has been notified) and should therefore be avoided.
*
* Call unpinFromCurrentThread() to remove the pin, allowing the task to run on any thread.
*
* @note %All calls to pin a thread will issue a warning log message.
*
* @note It is assumed that the task is allowed to move to another thread during the pinning process, though this
* may not always be the case. Only after pinToCurrentThread() returns will a task be pinned. Therefore, make sure
* to call pinToCurrentThread() *before* any operation that requires pinning.
*
* @return true if the task was already pinned; false if the task was not pinned or if not called from Task Context
* (i.e. getTaskContext() would return kInvalidTaskContext)
*/
bool(CARB_ABI* pinToCurrentThread)();
/**
* Un-pins the currently executing TaskContext from the thread it is currently running on.
*
* @warning Do not call this function directly; instead use PinGuard.
*
* @return true if the task was successfully un-pinned; false if the task was not pinned or if not called from Task
* Context (i.e. getTaskContext() would return kInvalidTaskContext)
*/
bool(CARB_ABI* unpinFromCurrentThread)();
/**
* Creates a non-recursive mutex.
*
* @warning Prefer using MutexWrapper instead.
*
* @note Both createMutex() and createRecursiveMutex() return a Mutex object; it is up to the creator to ensure that
* the Mutex object is used properly. A Mutex created with createMutex() will call `std::terminate()` if recursively
* locked.
*
* @return The created non-recursive mutex.
*/
Mutex*(CARB_ABI* createMutex)();
/**
* Destroys a mutex.
*
* @param The mutex to destroy.
*/
void(CARB_ABI* destroyMutex)(Mutex* mutex);
/**
* Locks a mutex
*
* @param mutex The mutex to lock.
*/
void lockMutex(Mutex* mutex);
/**
* Locks a mutex or waits for the timeout period to expire.
*
* @note Attempting to recursively lock a mutex created with createMutex() will abort. Use a mutex created with
* createRecursiveMutex() to support recursive locking.
*
* @param mutex The mutex to lock.
* @param timeoutNs The relative timeout in nanoseconds. Specify kInfinite to wait forever or 0 to try locking
* without waiting.
* @returns true if the calling thread/fiber now has ownership of the mutex; false if the timeout period expired.
*/
bool(CARB_ABI* timedLockMutex)(Mutex* mutex, uint64_t timeoutNs);
/**
* Unlock a mutex
*
* @param The mutex to unlock.
*/
void(CARB_ABI* unlockMutex)(Mutex* mutex);
/**
* Sleeps for the given number of nanoseconds. Prefer using sleep_for() or sleep_until()
*
* @note This function is fiber-aware. If currently executing in a fiber, the fiber will be yielded until the
* requested amount of time has passed. If a thread is currently executing, then the thread will sleep.
*
* @param nanoseconds The amount of time to yield/sleep, in nanoseconds.
*/
void(CARB_ABI* sleepNs)(uint64_t nanoseconds);
/**
* If the calling thread is running in "task context", that is, a fiber executing a task previously queued with
* addTask(), this function returns a handle that can be used with suspendTask() and wakeTask().
*
* @return kInvalidTaskContext if the calling thread is not running within "task context"; otherwise, a TaskContext
* handle is returned that can be used with suspendTask() and wakeTask(), as well as anywhere a RequiredObject is
* used.
*/
TaskContext(CARB_ABI* getTaskContext)();
/**
* Suspends the current task. Does not return until wakeTask() is called with the task's TaskContext (see
* getTaskContext()).
*
* @note to avoid race-conditions between wakeTask() and suspendTask(), a wakeTask() that occurs before
* suspendTask() has been called will cause suspendTask() to return true immediately without waiting.
*
* @return true when wakeTask() is called. If the current thread is not running in "task context" (i.e.
* getTaskContext() would return kInvalidTaskContext), then this function returns false immediately.
*/
bool(CARB_ABI* suspendTask)();
/**
* Wakes a task previously suspended with suspendTask().
*
* @note to avoid race-conditions between wakeTask() and suspendTask(), a wakeTask() that occurs before
* suspendTask() has been called will cause suspendTask() to return true immediately without waiting. The wakeTask()
* function returns immediately and does not wait for the suspended task to resume.
*
* wakeTask() cannot be called on the current task context (false will be returned). Additional situations that will
* log (as a warning) and return false:
* - The task context given already has a pending wake
* - The task has finished
* - The task context given is sleeping or otherwise waiting on an event (cannot be woken)
* - The given TaskContext is not valid
*
* @param task The TaskContext (returned by getTaskContext()) for the task suspended with suspendTask().
* @return true if the task was woken properly. false if a situation listed above occurs.
*/
bool(CARB_ABI* wakeTask)(TaskContext task);
/**
* Blocks the current thread/task until the given Task has completed.
*
* Similar to yieldUntilCounter() but does not require a Counter object.
*
* @note Deprecated: Use wait() instead.
*
* @param task The TaskContext to wait on
* @return true if the wait was successful; false if the TaskContext has already expired or was invalid.
*/
CARB_DEPRECATED("Use wait() instead") bool waitForTask(TaskContext task);
//! @private
bool(CARB_ABI* internalTimedWait)(Object obj, uint64_t timeoutNs);
/**
* Checks the object specified in @p req to see if it is signaled.
*
* @param req The RequiredObject object to check.
* @returns `true` if the object is signaled; `false` if the object is invalid or not signaled.
*/
bool try_wait(RequiredObject req);
/**
* Blocks the calling thread or task until @p req is signaled.
*
* @param req The RequiredObject object to check.
*/
void wait(RequiredObject req);
/**
* Blocks the calling thread or task until @p req is signaled or @p dur has elapsed.
*
* @param dur The duration to wait for.
* @param req The RequiredObject object to check.
* @returns `true` if the object is signaled; `false` if the object is invalid or not signaled, or @p dur elapses.
*/
template <class Rep, class Period>
bool wait_for(std::chrono::duration<Rep, Period> dur, RequiredObject req);
/**
* Blocks the calling thread or task until @p req is signaled or the clock reaches @p when.
*
* @param when The time_point to wait until.
* @param req The RequiredObject object to check.
* @returns `true` if the object is signaled; `false` if the object is invalid or not signaled, or @p when is
* reached.
*/
template <class Clock, class Duration>
bool wait_until(std::chrono::time_point<Clock, Duration> when, RequiredObject req);
/**
* Creates a fiber-aware semaphore primitive.
*
* A semaphore is a gate that lets a certain number of tasks/threads through. This can also be used to throttle
* tasks (see addThrottledTask()). When the count of a semaphore goes negative tasks/threads will wait on the
* semaphore.
*
* @param value The starting value of the semaphore. Limited to INT_MAX. 0 means that any attempt to wait on the
* semaphore will block until the semaphore is released.
* @return A Semaphore object. When finished, dispose of the semaphore with destroySemaphore().
*
* @warning Prefer using SemaphoreWrapper instead.
*
* @note Semaphore can be used for @rstref{Throttling <tasking-throttling-label>} tasks.
*/
Semaphore*(CARB_ABI* createSemaphore)(unsigned value);
/**
* Destroys a semaphore object created by createSemaphore()
*
* @param sema The semaphore to destroy.
*/
void(CARB_ABI* destroySemaphore)(Semaphore* sema);
/**
* Releases (or posts, or signals) a semaphore.
*
* If a task/thread is waiting on the semaphore when it is released,
* the task/thread is un-blocked and will be resumed. If no tasks/threads are waiting on the semaphore, the next
* task/thread that attempts to wait will resume immediately.
*
* @param sema The semaphore to release.
* @param count The number of tasks/threads to release.
*/
void(CARB_ABI* releaseSemaphore)(Semaphore* sema, unsigned count);
/**
* Waits on a semaphore until it has been signaled.
*
* If the semaphore has already been signaled, this function returns immediately.
*
* @param sema The semaphore to wait on.
*/
void waitSemaphore(Semaphore* sema);
/**
* Waits on a semaphore until it has been signaled or the timeout period expires.
*
* If the semaphore has already been signaled, this function returns immediately.
*
* @param sema The semaphore to wait on.
* @param timeoutNs The relative timeout period in nanoseconds. Specify kInfinite to wait forever, or 0 to test
* immediately without waiting.
* @returns true if the semaphore count was decremented; false if the timeout period expired.
*/
bool(CARB_ABI* timedWaitSemaphore)(Semaphore* sema, uint64_t timeoutNs);
/**
* Creates a fiber-aware SharedMutex primitive.
*
* @warning Prefer using SharedMutexWrapper instead.
*
* A SharedMutex (also known as a read/write mutex) allows either multiple threads/tasks to share the primitive, or
* a single thread/task to own the primitive exclusively. Threads/tasks that request ownership of the primitive,
* whether shared or exclusive, will be blocked until they can be granted the access level requested. SharedMutex
* gives priority to exclusive access, but will not block additional shared access requests when exclusive access
* is requested.
*
* @return A SharedMutex object. When finished, dispose of the SharedMutex with destroySharedMutex().
*/
SharedMutex*(CARB_ABI* createSharedMutex)();
/**
* Requests shared access on a SharedMutex object.
*
* Use unlockSharedMutex() to release the shared lock. SharedMutex is not recursive.
*
* @param mutex The SharedMutex object.
*/
void lockSharedMutex(SharedMutex* mutex);
/**
* Requests shared access on a SharedMutex object with a timeout period.
*
* Use unlockSharedMutex() to release the shared lock. SharedMutex is not recursive.
*
* @param mutex The SharedMutex object.
* @param timeoutNs The relative timeout period in nanoseconds. Specify kInfinite to wait forever or 0 to test
* immediately without waiting.
* @returns true if the shared lock succeeded; false if timed out.
*/
bool(CARB_ABI* timedLockSharedMutex)(SharedMutex* mutex, uint64_t timeoutNs);
/**
* Requests exclusive access on a SharedMutex object.
*
* Use unlockSharedMutex() to release the exclusive lock. SharedMutex is not recursive.
*
* @param mutex The SharedMutex object.
*/
void lockSharedMutexExclusive(SharedMutex* mutex);
/**
* Requests exclusive access on a SharedMutex object with a timeout period.
*
* Use unlockSharedMutex() to release the exclusive lock. SharedMutex is not recursive.
*
* @param mutex The SharedMutex object.
* @param timeoutNs The relative timeout period in nanoseconds. Specify kInfinite to wait forever or 0 to test
* immediately without waiting.
* @returns true if the exclusive lock succeeded; false if timed out.
*/
bool(CARB_ABI* timedLockSharedMutexExclusive)(SharedMutex* mutex, uint64_t timeoutNs);
/**
* Releases a shared or an exclusive lock on a SharedMutex object.
*
* @param mutex The SharedMutex object.
*/
void(CARB_ABI* unlockSharedMutex)(SharedMutex* mutex);
/**
* Destroys a SharedMutex previously created with createSharedMutex().
*
* @param mutex The SharedMutex object to destroy.
*/
void(CARB_ABI* destroySharedMutex)(SharedMutex* mutex);
/**
* Creates a fiber-aware ConditionVariable primitive.
*
* @warning Prefer using ConditionVariableWrapper instead.
*
* ConditionVariable is a synchronization primitive that, together with a Mutex, blocks one or more threads or tasks
* until a condition becomes true.
*
* @return The ConditionVariable object. Destroy with destroyConditionVariable() when finished.
*/
ConditionVariable*(CARB_ABI* createConditionVariable)();
/**
* Destroys a previously-created ConditionVariable object.
*
* @param cv The ConditionVariable to destroy
*/
void(CARB_ABI* destroyConditionVariable)(ConditionVariable* cv);
/**
* Waits on a ConditionVariable object until it is notified. Prefer using the helper function,
* waitConditionVariablePred().
*
* The given Mutex must match the Mutex passed in by all other threads/tasks waiting on the ConditionVariable, and
* must be locked by the current thread/task. While waiting, the Mutex is unlocked. When the thread/task is notified
* the Mutex is re-locked before returning to the caller. ConditionVariables are allowed to spuriously wake up, so
* best practice is to check the variable in a loop and sleep if the variable still does not match desired.
*
* @param cv The ConditionVariable to wait on.
* @param m The Mutex that is locked by the current thread/task.
*/
void waitConditionVariable(ConditionVariable* cv, Mutex* m);
/**
* Waits on a ConditionVariable object until it is notified or the timeout period expires. Prefer using the helper
* function, timedWaitConditionVariablePred().
*
* The given Mutex must match the Mutex passed in by all other threads/tasks waiting on the ConditionVariable, and
* must be locked by the current thread/task. While waiting, the Mutex is unlocked. When the thread/task is notified
* the Mutex is re-locked before returning to the caller. ConditionVariables are allowed to spuriously wake up, so
* best practice is to check the variable in a loop and sleep if the variable still does not match desired.
*
* @param cv The ConditionVariable to wait on.
* @param m The Mutex that is locked by the current thread/task.
* @param timeoutNs The relative timeout period in nanoseconds. Specify kInfinite to wait forever or 0 to test
* immediately without waiting.
* @returns true if the condition variable was notified; false if the timeout period expired.
*/
bool(CARB_ABI* timedWaitConditionVariable)(ConditionVariable* cv, Mutex* m, uint64_t timeoutNs);
/**
* Wakes one thread/task currently waiting on the ConditionVariable.
*
* @note Having the Mutex provided to waitConditionVariable() locked while calling this function is recommended
* but not required.
*
* @param cv The condition variable to notify
*/
void(CARB_ABI* notifyConditionVariableOne)(ConditionVariable* cv);
/**
* Wakes all threads/tasks currently waiting on the ConditionVariable.
*
* @note Having the Mutex provided to waitConditionVariable() locked while calling this function is recommended
* but not required.
*
* @param cv The condition variable to notify
*/
void(CARB_ABI* notifyConditionVariableAll)(ConditionVariable* cv);
/**
* Changes a tasks priority.
*
* @note This can be used to change a task to execute on the main thread when it next resumes when using
* Priority::eMain. If called from within the context of the running task, the task immediately suspends itself
* until resumed on the main thread with the next call to executeMainTasks(), at which point this function will
* return.
*
* @param ctx The \ref TaskContext returned by \ref getTaskContext() or \ref Future::task_if().
* @param newPrio The Priority to change the task to.
* @returns `true` if the priority change took effect; `false` if the TaskContext is invalid.
*/
bool(CARB_ABI* changeTaskPriority)(TaskContext ctx, Priority newPrio);
/**
* Executes all tasks that have been queued with Priority::eMain until they finish or yield.
*
* @note Scheduled tasks (addTaskIn() / addTaskAt()) with Priority::eMain will only be executed during the next
* executeMainTasks() call after the requisite time has elapsed.
*/
void(CARB_ABI* executeMainTasks)();
// Intended for internal use only; only for the RequiredObject object.
// NOTE: The Counter returned from this function is a one-shot counter that is only intended to be passed as a
// RequiredObject. It is immediately released.
//! @private
enum GroupType
{
eAny,
eAll,
};
//! @private
Counter*(CARB_ABI* internalGroupObjects)(GroupType type, Object const* counters, size_t count);
/**
* Creates a recursive mutex.
*
* @warning Prefer using RecursiveMutexWrapper instead.
*
* @note Both createMutex() and createRecursiveMutex() return a Mutex object; it is up to the creator to ensure that
* the Mutex object is used properly. A Mutex created with createMutex() will call `std::terminate()` if recursively
* locked.
*
* @return The created recursive mutex.
*/
Mutex*(CARB_ABI* createRecursiveMutex)();
/**
* Attempts to cancel an outstanding task.
*
* If the task has already been started, has already been canceled or has completed, `false` is returned.
*
* If `true` is returned, then the task is guaranteed to never start, but every other side effect is as if the task
* completed. That is, any Counter objects that were passed to addTask() will be decremented; any blocking calls to
* waitForTask() will return `true`. The Future object for this task will no longer wait, but any attempt to read a
* non-`void` value from it will call `std::terminate()`. If the addTask() call provided a TaskDesc::cancel member,
* it will be called in the context of the calling thread and will finish before tryCancelTask() returns true.
*
* @param task The \ref TaskContext returned by \ref getTaskContext() or \ref Future::task_if().
* @returns `true` if the task was successfully canceled and state reset as described above. `false` if the task has
* cannot be canceled because it has already started, already been canceled or has already finished.
*/
bool(CARB_ABI* tryCancelTask)(TaskContext task);
//! @private
bool(CARB_ABI* internalFutexWait)(const void* addr, const void* compare, size_t size, uint64_t timeoutNs);
//! @private
unsigned(CARB_ABI* internalFutexWakeup)(const void* addr, unsigned count);
/**
* Attempts to allocate task storage, which is similar to thread-local storage but specific to a task.
*
* Allocates a "key" for Task Storage. A value can be stored at this key location ("slot") that is specific to each
* task. When the task finishes, @p fn is executed for any non-`nullptr` value stored in that slot.
*
* Values can be stored in the Task Storage slot with setTaskStorage() and getTaskStorage().
*
* When Task Storage is no longer needed, use freeTaskStorage() to return the slot to the system.
*
* @warning The number of slots are very limited. If no slots are available, kInvalidTaskStorageKey is returned.
*
* @param fn (Optional) A destructor function called when a task finishes with a non-`nullptr` value in the
* allocated slot. The value stored with setTaskStorage() is passed to the destructor. If a destructor is not
* desired, `nullptr` can be passed.
* @returns An opaque TaskStorageKey representing the slot for the requested Task Storage data. If no slots are
* available, kInvalidTaskStorageKey is returned.
*/
TaskStorageKey(CARB_ABI* allocTaskStorage)(TaskStorageDestructorFn fn);
/**
* Frees a Task Storage slot.
*
* @note Any associated destructor function registered with allocTaskStorage() will not be called for any data
* present in currently running tasks. Once freeTaskStorage() returns, the destructor function registered with
* allocTaskStorage() will not be called for any data on any tasks.
*
* @param key The Task Storage key previously allocated with allocTaskStorage().
*/
void(CARB_ABI* freeTaskStorage)(TaskStorageKey key);
/**
* Stores a value at a slot in Task Storage for the current task.
*
* The destructor function passed to allocTaskStorage() will be called with any non-`nullptr` values remaining in
* Task Storage at the associated @p key when the task finishes.
*
* @warning This function can only be called from task context, otherwise `false` is returned.
* @param key The Task Storage key previously allocated with allocTaskStorage().
* @param value A value to store at the Task Storage slot described by @p key for the current task only.
* @return `true` if the value was stored; `false` otherwise.
*/
bool(CARB_ABI* setTaskStorage)(TaskStorageKey key, void* value);
/**
* Retrieves a value at a slot in Task Storage for the current task.
*
* The destructor function passed to allocTaskStorage() will be called with any non-`nullptr` values remaining in
* Task Storage at the associated @p key when the task finishes.
*
* @warning This function can only be called from task context, otherwise `nullptr` is returned.
* @param key The Task Storage key previously allocated with allocTaskStorage().
* @returns The value previously passed to setTaskStorage(), or `nullptr` if not running in task context or a value
* was not previously passed to setTaskStorage() for the current task.
*/
void*(CARB_ABI* getTaskStorage)(TaskStorageKey key);
// Do not call directly; use ScopedTracking instead.
// Returns a special tracking object that MUST be passed to endTracking().
//! @private
Object(CARB_ABI* beginTracking)(Object const* trackers, size_t numTrackers);
// Do not call directly; use ScopedTracking instead.
//! @private
void(CARB_ABI* endTracking)(Object tracker);
/**
* Retrieves debug information about a specific task.
*
* @note This information is intended for debug only and should not affect application state or decisions in the
* application.
*
* @warning Since carb.tasking is an inherently multi-threaded API, the values presented as task debug information
* may have changed in a worker thread in the short amount of time between when they were generated and when they
* were read by the application. As such, the debug information was true at a previous point in time and should not
* be considered necessarily up-to-date.
*
* @param task The TaskContext to retrieve information about.
* @param[out] out A structure to fill with debug information about @p task. The TaskDebugInfo::sizeOf field must be
* pre-filled by the caller. May be `nullptr` to determine if @p task is valid.
* @returns `true` if the TaskContext was valid and @p out (if non-`nullptr`) was filled with known information
* about @p task. `false` if @p out specified an unknown size or @p task does not refer to a valid task.
*/
bool(CARB_ABI* getTaskDebugInfo)(TaskContext task, TaskDebugInfo* out);
/**
* Walks all current tasks and calls a callback function with debug info for each.
*
* @note This information is intended for debug only and should not affect application state or decisions in the
* application.
*
* @warning Since carb.tasking is an inherently multi-threaded API, the values presented as task debug information
* may have changed in a worker thread in the short amount of time between when they were generated and when they
* were read by the application. As such, the debug information was true at a previous point in time and should not
* be considered necessarily up-to-date.
*
* @param info A structure to fill with debug information about tasks encountered during the walk. The
* TaskDebugInfo::sizeOf field must be pre-filled by the caller.
* @param fn A function to call for each task encountered. The function is called repeatedly with a different task
* each time, until all tasks have been visited or the callback function returns `false`.
* @param context Application-specific context information that is passed directly to each invocation of @p fn.
*/
bool(CARB_ABI* walkTaskDebugInfo)(TaskDebugInfo& info, TaskDebugInfoFn fn, void* context);
//! @private
void(CARB_ABI* internalApplyRangeBatch)(size_t range, size_t batchHint, ApplyBatchFn fn, void* context);
//! @private
void(CARB_ABI* internalBindTrackers)(Object required, Object const* ptrackes, size_t numTrackers);
//! @private
void(CARB_ABI* internalNameTask)(TaskContext task, const char* name, bool dynamic);
/**
* Instructs ITasking to reload all IFiberEvents interfaces.
*
* The @ref IFiberEvents interface is used by @ref ITasking to notify listeners that are interested in fiber-switch
* events. All @ref IFiberEvents interfaces are queried from the @ref carb::Framework by @ref ITasking only at
* startup, or when @ref changeParameters() is called, or when `reloadFiberEvents()` is called.
*
* Unlike @ref changeParameters(), this function is safe to call from within a task, or from multiple threads
* simultaneously, and tasks can be added while this function is executing.
*
* @note This function is a task system synchronization point, requiring all task threads to synchronize and pause
* before reloading @ref IFiberEvents interfaces. Generally this happens rapidly, but if a task thread is busy, the
* entire tasking system will wait for the task to finish or enter a wait state before reloading @ref IFiberEvents
* interfaces.
*/
void(CARB_ABI* reloadFiberEvents)();
///////////////////////////////////////////////////////////////////////////
// Helper functions
/**
* Yields execution to another task until `counter == value`.
*
* Task invoking this call will resume on the same thread due to thread pinning. Thread pinning is not efficient.
* See pinToCurrentThread() for details.
*
* @param counter The counter to check.
*/
void yieldUntilCounterPinThread(RequiredObject counter);
/**
* Checks @p pred in a loop until it returns true, and waits on a ConditionVariable if @p pred returns false.
*
* @param cv The ConditionVariable to wait on
* @param m The Mutex associated with the ConditionVariable. Must be locked by the calling thread/task.
* @param pred A function-like predicate object in the form `bool(void)`. waitConditionVariablePred() returns when
* @p pred returns true.
*/
template <class Pred>
void waitConditionVariablePred(ConditionVariable* cv, Mutex* m, Pred&& pred)
{
while (!pred())
{
this->waitConditionVariable(cv, m);
}
}
/**
* Checks @p pred in a loop until it returns true or the timeout period expires, and waits on a ConditionVariable
* if @p pred returns false.
*
* @param cv The ConditionVariable to wait on
* @param m The Mutex associated with the ConditionVariable. Must be locked by the calling thread/task.
* @param timeoutNs The relative timeout period in nanoseconds. Specify @ref kInfinite to wait forever or 0 to test
* immediately without waiting.
* @param pred A function-like predicate object in the form `bool(void)`. waitConditionVariablePred() returns when
* @p pred returns true.
* @returns `true` if the predicate returned `true`; `false` if the timeout period expired
*/
template <class Pred>
bool timedWaitConditionVariablePred(ConditionVariable* cv, Mutex* m, uint64_t timeoutNs, Pred&& pred)
{
while (!pred())
if (!this->timedWaitConditionVariable(cv, m, timeoutNs))
return false;
return true;
}
/**
* Executes a task synchronously.
*
* @note To ensure that the task executes in task context, the function is called directly if already in task
* context. If called from non-task context, @p f is executed by a call to addTask() but this function does not
* return until the subtask is complete.
*
* @param priority The priority of the task to execute. Only used if not called in task context.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value.
* @param args Arguments to pass to @p f.
* @return The return value of @p f.
*/
template <class Callable, class... Args>
auto awaitSyncTask(Priority priority, Callable&& f, Args&&... args);
/**
* Runs the given function-like object as a task.
*
* @param priority The priority of the task to execute.
* @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a
* temporary object. The Tracker objects can be used to determine task completion or to provide input/output
* parameters to the task system.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value
* @param args Arguments to pass to @p f
* @return A Future based on the return type of @p f
*/
template <class Callable, class... Args>
auto addTask(Priority priority, Trackers&& trackers, Callable&& f, Args&&... args);
/**
* Adds a task to the internal queue.
*
* @note Deprecated: The other addTask() (and variant) functions accept lambdas and function-like objects, and are
* designed to simplify adding tasks and add tasks succinctly. Prefer using those functions.
*
* @param desc The TaskDesc describing the task.
* @param counter A counter to associate with this task. It will be incremented by 1.
* When the task completes, it will be decremented.
* @return A TaskContext that can be used to refer to this task
*/
CARB_DEPRECATED("Use a C++ addTask() function") TaskContext addTask(TaskDesc desc, Counter* counter)
{
return this->internalAddTask(desc, counter);
}
/**
* Runs the given function-like object as a task when a Semaphore is signaled.
*
* @param throttler (optional) A Semaphore used to throttle the number of tasks that can run concurrently. The task
* waits until the semaphore is signaled (released) before starting, and then signals the semaphore after the task
* has executed.
* @param priority The priority of the task to execute.
* @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a
* temporary object. The Tracker objects can be used to determine task completion or to provide input/output
* parameters to the task system.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value
* @param args Arguments to pass to @p f
* @return A Future based on the return type of @p f
*/
template <class Callable, class... Args>
auto addThrottledTask(Semaphore* throttler, Priority priority, Trackers&& trackers, Callable&& f, Args&&... args);
/**
* Runs the given function-like object as a task once a Counter reaches its target.
*
* @param requiredObject (optional) An object convertible to RequiredObject (such as a task or Future).
* that will, upon completing, trigger the execution of this task.
* @param priority The priority of the task to execute.
* @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a
* temporary object. The Tracker objects can be used to determine task completion or to provide input/output
* parameters to the task system.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value
* @param args Arguments to pass to @p f
* @return A Future based on the return type of @p f
*/
template <class Callable, class... Args>
auto addSubTask(RequiredObject requiredObject, Priority priority, Trackers&& trackers, Callable&& f, Args&&... args);
/**
* Runs the given function-like object as a task once a Counter reaches its target and when a Semaphore is signaled.
*
* @param requiredObject (optional) An object convertible to RequiredObject (such as a task or Future).
* that will, upon completing, trigger the execution of this task.
* @param throttler (optional) A semaphore used to throttle the number of tasks that can run concurrently. Once
* requiredObject becomes signaled, the task waits until the semaphore is signaled (released) before starting, and
* then signals the semaphore after the task has executed.
* @param priority The priority of the task to execute.
* @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a
* temporary object. The Tracker objects can be used to determine task completion or to provide input/output
* parameters to the task system.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value
* @param args Arguments to pass to @p f
* @return A Future based on the return type of @p f
*/
template <class Callable, class... Args>
auto addThrottledSubTask(RequiredObject requiredObject,
Semaphore* throttler,
Priority priority,
Trackers&& trackers,
Callable&& f,
Args&&... args);
/**
* Adds a task to occur after a specific duration has passed.
*
* @param dur The duration to wait for. The task is not started until this duration elapses.
* @param priority The priority of the task to execute
* @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a
* temporary object. The Tracker objects can be used to determine task completion or to provide input/output
* parameters to the task system.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value
* @param args Arguments to pass to @p f
* @return A Future based on the return type of @p f
*/
template <class Callable, class Rep, class Period, class... Args>
auto addTaskIn(const std::chrono::duration<Rep, Period>& dur,
Priority priority,
Trackers&& trackers,
Callable&& f,
Args&&... args);
/**
* Adds a task to occur at a specific point in time
*
* @param when The point in time at which to begin the task
* @param priority The priority of the task to execute
* @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a
* temporary object. The Tracker objects can be used to determine task completion or to provide input/output
* parameters to the task system.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value
* @param args Arguments to pass to @p f
* @return A Future based on the return type of @p f
*/
template <class Callable, class Clock, class Duration, class... Args>
auto addTaskAt(const std::chrono::time_point<Clock, Duration>& when,
Priority priority,
Trackers&& trackers,
Callable&& f,
Args&&... args);
/**
* Processes a range from `[0..range)` calling a functor for each index, potentially from different threads.
*
* @note This function does not return until @p f has been called (and returned) on every index from [0..
* @p range)
* @warning Since @p f can be called from multiple threads simultaneously, all operations it performs must
* be thread-safe. Additional consideration must be taken since mutable captures of any lambdas or passed in
* @p args will be accessed simultaneously by multiple threads so care must be taken to ensure thread safety.
* @note Calling this function recursively will automatically scale down the parallelism in order to not overburden
* the system.
* @note As there is overhead to calling \p f repeatedly, it is more efficient to use \ref applyRangeBatch() with
* `batchHint = 0` and a `f` that handles multiple indexes on one invocation.
*
* See the @rstref{additional documentation <tasking-parallel-for>} for `applyRange`.
*
* @param range The number of times to call @p f.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that is repeatedly called until
* all indexes in `[0..range)` have been processed, potentially from different threads. It is invoked with
* parameters `f(args..., index)` where `index` is within the range `[0..range)`.
* @param args Arguments to pass to @p f
*/
template <class Callable, class... Args>
void applyRange(size_t range, Callable f, Args&&... args);
/**
* Processes a range from `[0..range)` calling a functor for batches of indexes, potentially from different threads.
*
* @note This function does not return until @p f has been called (and returned) for every index from
* `[0..range)`
* @warning Since @p f can be called from multiple threads simultaneously, all operations it performs must
* be thread-safe. Additional consideration must be taken since mutable captures of any lambdas or passed in
* @p args will be accessed simultaneously by multiple threads so care must be taken to ensure thread safety.
* @note Calling this function recursively will automatically scale down the parallelism in order to not overburden
* the system.
*
* See the @rstref{additional documentation <tasking-parallel-for>} for `applyRange`.
*
* @param range The number of times to call @p f.
* @param batchHint A recommendation of batch size to determine the range of indexes to pass to @p f for processing.
* A value of 0 uses an internal heuristic to divide work, which is recommended in most cases. This value is a hint
* to the internal heuristic and therefore \p f may be invoked with a different range size.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that is repeatedly called until
* all indexes in `[0..range)` have been processed, potentially from different threads. It is invoked with
* parameters `f(args..., startIndex, endIndex)` where `[startIndex..endIndex)` is the range of indexes that must be
* processed by that invocation of `f`. Note that `endIndex` is a past-the-end index and must not actually be
* processed by that invocation of `f`.
* @param args Arguments to pass to @p f
*/
template <class Callable, class... Args>
void applyRangeBatch(size_t range, size_t batchHint, Callable f, Args&&... args);
/**
* Processes a range from [begin..end) calling a functor for each index, potentially from different threads.
*
* @note This function does not return until @p f has been called (and returned) on every index from [begin..
* @p end)
* @warning Since @p f can be called from multiple threads simultaneously, all operations it performs must
* be thread-safe. Additional consideration must be taken since mutable captures of any lambdas or passed in
* @p args will be accessed simultaneously by multiple threads so care must be taken to ensure thread safety.
* @note Calling this function recursively will automatically scale down the parallelism in order to not overburden
* the system.
*
* @param begin The starting value passed to @p f
* @param end The ending value. Every T(1) step in [begin, end) is passed to @p f
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value.
* The index value from [begin..end) is passed as the last parameter (after any passed @p args).
* @param args Arguments to pass to @p f
*/
template <class T, class Callable, class... Args>
void parallelFor(T begin, T end, Callable f, Args&&... args);
/**
* Processes a stepped range from [begin..end) calling a functor for each step, potentially from different threads.
*
* @note This function does not return until @p f has been called (and returned) on every index from [begin..
* @p end)
* @warning Since @p f can be called from multiple threads simultaneously, all operations it performs must
* be thread-safe. Additional consideration must be taken since mutable captures of any lambdas or passed in
* @p args will be accessed simultaneously by multiple threads so care must be taken to ensure thread safety.
* @note Calling this function recursively will automatically scale down the parallelism in order to not overburden
* the system.
*
* @param begin The starting value passed to @p f
* @param end The ending value. Every @p step in [begin, end) is passed to @p f
* @param step The step size to determine every value passed to @p f
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value.
* The stepped value from [begin..end) is passed as the last parameter (after any passed @p args).
* @param args Arguments to pass to @p f
*/
template <class T, class Callable, class... Args>
void parallelFor(T begin, T end, T step, Callable f, Args&&... args);
/**
* Causes the current thread or task to sleep for the specified time.
*
* @note This function is fiber-aware. If currently executing in a fiber, the fiber will be yielded until the
* requested amount of time has passed. If a thread is currently executing, then the thread will sleep.
*
* @param dur The duration to sleep for
*/
template <class Rep, class Period>
void sleep_for(const std::chrono::duration<Rep, Period>& dur)
{
sleepNs(detail::convertDuration(dur));
}
/**
* Causes the current thread or task to sleep until the specified time.
*
* @note This function is fiber-aware. If currently executing in a fiber, the fiber will be yielded until the
* requested amount of time has passed. If a thread is currently executing, then the thread will sleep.
*
* @param tp The absolute time point to sleep until
*/
template <class Clock, class Duration>
void sleep_until(const std::chrono::time_point<Clock, Duration>& tp)
{
sleepNs(detail::convertAbsTime(tp));
}
/**
* A fiber-safe futex implementation: if @p val equals @p compare, the thread or task sleeps until woken.
*
* @warning Futexes are complicated and error-prone. Prefer using higher-level synchronization primitives.
*
* @param val The atomic value to check.
* @param compare The value to compare against. If @p val matches this, then the calling thread or task sleeps until
* futexWakeup() is called.
*/
template <class T>
void futexWait(const std::atomic<T>& val, T compare)
{
bool b = internalFutexWait(&val, &compare, sizeof(T), kInfinite);
CARB_ASSERT(b);
CARB_UNUSED(b);
}
/**
* A fiber-safe futex implementation: if @p val equals @p compare, the thread or task sleeps until woken or the
* timeout period expires.
*
* @warning Futexes are complicated and error-prone. Prefer using higher-level synchronization primitives.
*
* @param val The atomic value to check.
* @param compare The value to compare against. If @p val matches this, then the calling thread or task sleeps until
* futexWakeup() is called.
* @param dur The maximum duration to wait.
* @returns `true` if @p val doesn't match @p compare or if futexWakeup() was called; `false` if the timeout period
* expires.
*/
template <class T, class Rep, class Period>
bool futexWaitFor(const std::atomic<T>& val, T compare, std::chrono::duration<Rep, Period> dur)
{
return internalFutexWait(&val, &compare, sizeof(T), detail::convertDuration(dur));
}
/**
* A fiber-safe futex implementation: if @p val equals @p compare, the thread or task sleeps until woken or the
* specific time is reached.
*
* @warning Futexes are complicated and error-prone. Prefer using higher-level synchronization primitives.
*
* @param val The atomic value to check.
* @param compare The value to compare against. If @p val matches this, then the calling thread or task sleeps until
* futexWakeup() is called.
* @param when The clock time to wait until.
* @returns `true` if @p val doesn't match @p compare or if futexWakeup() was called; `false` if the clock time is
* reached.
*/
template <class T, class Clock, class Duration>
bool futexWaitUntil(const std::atomic<T>& val, T compare, std::chrono::time_point<Clock, Duration> when)
{
return internalFutexWait(&val, &compare, sizeof(T), detail::convertAbsTime(when));
}
/**
* Wakes threads or tasks waiting in futexWait(), futexWaitFor() or futexWaitUntil().
*
* @warning Futexes are complicated and error-prone. Prefer using higher-level synchronization primitives.
*
* @param val The same `val` passed to futexWait(), futexWaitFor() or futexWaitUntil().
* @param count The number of threads or tasks to wakeup. To wake all waiters use `UINT_MAX`.
* @returns The number of threads or tasks that were waiting and are now woken.
*/
template <class T>
unsigned futexWakeup(const std::atomic<T>& val, unsigned count)
{
return internalFutexWakeup(&val, count);
}
/**
* Binds any number of \ref Tracker objects to the given \ref RequiredObject. Effectively allows adding trackers to
* a given object.
*
* Previously this was only achievable through a temporary task:
* ```cpp
* // Old way: a task that would bind `taskGroup` to `requiredObject`
* tasking->addSubTask(requiredObject, Priority::eDefault, { taskGroup }, []{});
* // New way: direct binding:
* tasking->bindTrackers(requiredObject, { taskGroup });
* ```
* The previous method wasted time in that one of the task threads would eventually have to pop the task from the
* queue and run an empty function. Calling `bindTrackers()` does not waste this time.
*
* However, there are some "disadvantages." The `addSubTask()` method would allocate a \ref TaskContext, return a
* \ref Future, and could be canceled. These features were seldom needed, hence this function.
*
* @param requiredObject An object convertible to RequiredObject (such as a task or Future). The given \p trackers
* will be bound to this required object.
* @param trackers A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a
* temporary object. The Tracker objects can be used to determine task completion or to provide input/output
* parameters to the task system.
*/
void bindTrackers(RequiredObject requiredObject, Trackers&& trackers);
/**
* Sets a name for a task for debugging purposes, similar to how threads can be named.
*
* This function is optimized for a literal string: passing a literal string as @p name does not copy the string but
* instead retains the pointer as it is guaranteed to never change. Passing a non-literal string will result in a
* copy.
*
* The task name is visible in the debugger as @rstref{debug information <showing-all-tasks>} for a task.
*
* Retrieving the task name can be accomplished through @ref getTaskDebugInfo().
*
* @note It is often easier to name the task as it's created by passing a task name as a @ref Tracker object to
* @ref addTask() or the other task creation functions.
*
* @thread_safety It is safe to set a task name from multiple threads, though inadvisable. Reading the task name via
* @ref getTaskDebugInfo() while it is being changed in a different thread is not strongly ordered and may
* result in an empty string being read, or random bytes as the name string, but will not result in a crash.
* @tparam T A type that is convertible to `const char*`. See @p name below.
* @param task The @ref TaskContext to name. If this is not a valid task, or the task has already completed or has
* been cancelled, nothing happens.
* @param name Either a `const char*` (dynamic string) or a `const char (&)[N]` (literal string) as the string name.
* May be `nullptr` to un-set a task name. Dynamic strings will be copied before the call returns. Literal
* strings will be retained by pointer value.
*/
template <class T, std::enable_if_t<std::is_convertible<T, const char*>::value, bool> = false>
void nameTask(TaskContext task, T&& name)
{
internalNameTask(task, name, !detail::is_literal_string<T>::value);
}
};
/**
* Causes the currently executing TaskContext to be "pinned" to the thread it is currently running on until PinGuard is
* destroyed.
*
* Appropriately handles recursive pinning. This class causes the current thread to be the only task thread that can run
* the current task. This is necessary in some cases where thread specificity is required (those these situations are
* NOT recommended for tasks): holding a mutex, or using thread-specific data, etc. Thread pinning is not efficient (the
* pinned thread could be running a different task causing delays for the current task to be resumed, and wakeTask()
* must wait to return until the pinned thread has been notified) and should therefore be avoided.
*
* @note It is assumed that the task is allowed to move to another thread during the pinning process, though this may
* not always be the case. Only after the PinGuard is constructed will a task be pinned. Therefore, make sure to
* construct PinGuard *before* any operation that requires pinning.
*/
class PinGuard
{
public:
/**
* Constructs a PinGuard and enters the "pinned" scope.
*/
PinGuard() : m_wasPinned(carb::getCachedInterface<ITasking>()->pinToCurrentThread())
{
}
/**
* Constructs a PinGuard and enters the "pinned" scope.
* @note Deprecated: ITasking no longer needed.
*/
CARB_DEPRECATED("ITasking no longer needed.")
PinGuard(ITasking*) : m_wasPinned(carb::getCachedInterface<ITasking>()->pinToCurrentThread())
{
}
/**
* Destructs a PinGuard and leaves the "pinned" scope.
*/
~PinGuard()
{
if (!m_wasPinned)
carb::getCachedInterface<ITasking>()->unpinFromCurrentThread();
}
private:
bool m_wasPinned;
};
} // namespace tasking
} // namespace carb
#include "ITasking.inl"
| 63,576 | C | 46.304315 | 121 | 0.68378 |
omniverse-code/kit/include/carb/tasking/TaskingTypes.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief carb.tasking type definitions
#pragma once
#include "../Defines.h"
namespace carb
{
namespace tasking
{
/**
* Used to create dependencies between tasks and to wait for a set of tasks to finish.
*
* @note Prefer using CounterWrapper.
*
* @see ITasking::createCounter(), ITasking::createCounterWithTarget(), ITasking::destroyCounter(),
* ITasking::yieldUntilCounter(), ITasking::timedYieldUntilCounter(), ITasking::checkCounter(),
* ITasking::getCounterValue(), ITasking::getCounterTarget(), ITasking::fetchAddCounter(), ITasking::fetchSubCounter(),
* ITasking::storeCounter()
*/
class Counter DOXYGEN_EMPTY_CLASS;
/**
* A fiber-aware mutex: a synchronization primitive for mutual exclusion. Only one thread/fiber can "own" the mutex at
* a time.
*
* @note Prefer using MutexWrapper.
*
* @see ITasking::createMutex(), ITasking::destroyMutex(), ITasking::lockMutex(), ITasking::timedLockMutex(),
* ITasking::unlockMutex(), ITasking::createRecursiveMutex()
*/
class Mutex DOXYGEN_EMPTY_CLASS;
/**
* A fiber-aware semaphore: a synchronization primitive that limits to N threads/fibers.
*
* @note Prefer using SemaphoreWrapper.
*
* @see ITasking::createSemaphore(), ITasking::destroySemaphore(), ITasking::releaseSemaphore(),
* ITasking::waitSemaphore(), ITasking::timedWaitSemaphore()
*/
class Semaphore DOXYGEN_EMPTY_CLASS;
/**
* A fiber-aware shared_mutex: a synchronization primitive that functions as a multiple-reader/single-writer lock.
*
* @note Prefer using SharedMutexWrapper.
*
* @see ITasking::createSharedMutex(), ITasking::lockSharedMutex(), ITasking::timedLockSharedMutex(),
* ITasking::lockSharedMutexExclusive(), ITasking::timedLockSharedMutexExclusive(), ITasking::unlockSharedMutex(),
* ITasking::destroySharedMutex()
*/
class SharedMutex DOXYGEN_EMPTY_CLASS;
/**
* A fiber-aware condition_variable: a synchronization primitive that, together with a Mutex, blocks one or more threads
* or tasks until a condition becomes true.
*
* @note Prefer using ConditionVariableWwrapper.
*
* @see ITasking::createConditionVariable(), ITasking::destroyConditionVariable(), ITasking::waitConditionVariable(),
* ITasking::timedWaitConditionVariable(), ITasking::notifyConditionVariableOne(),
* ITasking::notifyConditionVariableAll()
*/
class ConditionVariable DOXYGEN_EMPTY_CLASS;
struct ITasking;
/**
* A constant for ITasking wait functions indicating "infinite" timeout
*/
constexpr uint64_t kInfinite = uint64_t(-1);
/**
* Defines a task priority.
*/
enum class Priority
{
eLow, //!< Low priority. Tasks will be executed after higher priority tasks.
eMedium, //!< Medium priority.
eHigh, //!< High priority. Tasks will be executed before lower priority tasks.
eMain, //!< A special priority for tasks that are only executed during ITasking::executeMainTasks()
eCount, //!< The number of Priority classes
// Aliases
eDefault = eMedium, //!< Alias for eMedium priority.
};
/**
* Object type for Object.
*
* @note These are intended to be used only by helper classes such as RequiredObject.
*/
enum class ObjectType
{
eNone, //!< Null/no object.
eCounter, //!< Object::data refers to a Counter*.
eTaskContext, //!< Object::data refers to a TaskContext.
ePtrTaskContext, //!< Object::data refers to a TaskContext*.
eTaskGroup, //!< Object::data is a pointer to a std::atomic_size_t. @see TaskGroup
eSharedState, //!< Object::data is a pointer to a detail::SharedState. Not used internally by carb.tasking.
eFutex1, //!< Object::data is a pointer to a std::atomic_uint8_t. Signaled on zero.
eFutex2, //!< Object::data is a pointer to a std::atomic_uint16_t. Signaled on zero.
eFutex4, //!< Object::data is a pointer to a std::atomic_uint32_t. Signaled on zero.
eFutex8, //!< Object::data is a pointer to a std::atomic_uint64_t. Signaled on zero.
eTrackerGroup, //!< Object::data is a pointer to an internal tracking object.
eTaskName, //!< Object::data is a `const char*` to be copied and used as a task name.
eTaskNameLiteral, //!< Object::data is a `const char*` that can be retained because it is a literal.
};
/**
* The function to execute as a task.
*
* @param taskArg The argument passed to ITasking::addTask() variants.
*/
using OnTaskFn = void (*)(void* taskArg);
/**
* The function executed by ITasking::applyRange()
*
* @param index The ApplyFn is called once for every integer @p index value from 0 to the range provided to
* ITasking::applyRange().
* @param taskArg The argument passed to ITasking::applyRange().
*/
using ApplyFn = void (*)(size_t index, void* taskArg);
/**
* The function executed by ITasking::applyRangeBatch()
*
* @note This function differs from \ref ApplyFn in that it must handle a contiguous range of indexes determined by
* `[startIndex, endIndex)`.
* @warning The item at index \p endIndex is \b not to be processed by this function. In other words, the range handled
* by this function is:
* ```cpp
* for (size_t i = startIndex; i != endIndex; ++i)
* array[i]->process();
* ```
* @param startIndex The initial index that must be handled by this function call.
* @param endIndex The after-the-end index representing the range of indexes that must be handled by this function call.
* The item at this index is after-the-end of the assigned range and <strong>must not be processed</strong>.
* @param taskArg The argument passed to ITasking::applyRangeBatch().
*/
using ApplyBatchFn = void (*)(size_t startIndex, size_t endIndex, void* taskArg);
/**
* A destructor function for a Task Storage slot.
*
* This function is called when a task completes with a non-`nullptr` value in the respective Task Storage slot.
* @see ITasking::allocTaskStorage()
* @param arg The non-`nullptr` value stored in a task storage slot.
*/
using TaskStorageDestructorFn = void (*)(void* arg);
/**
* An opaque handle representing a Task Storage slot.
*/
using TaskStorageKey = size_t;
/**
* Represents an invalid TaskStorageKey.
*/
constexpr TaskStorageKey kInvalidTaskStorageKey = size_t(-1);
/**
* An opaque handle that is used with getTaskContext(), suspendTask() and wakeTask().
*/
using TaskContext = size_t;
/**
* A specific value for TaskContext that indicates a non-valid TaskContext.
*/
constexpr TaskContext kInvalidTaskContext = 0;
/**
* The absolute maximum number of fibers that ITasking will create.
*/
constexpr uint32_t kMaxFibers = 1048575;
/**
* A generic @rstref{ABI-safe <abi-compatibility>} representation of multiple types.
*/
struct Object
{
ObjectType type; //!< The ObjectType of the represented type.
void* data; //!< Interpreted based on the ObjectType provided.
};
/**
* Defines a task descriptor.
*/
struct TaskDesc
{
/// Must be set to sizeof(TaskDesc).
size_t size{ sizeof(TaskDesc) };
/// The task function to execute
OnTaskFn task;
/// The argument passed to the task function
void* taskArg;
/// The priority assigned to the task
Priority priority;
/// If not nullptr, then the task will only start when this counter reaches its target value. Specifying the counter
/// here is more efficient than having the task function yieldUntilCounter().
Object requiredObject;
/// If waitSemaphore is not nullptr, then the task will wait on the semaphore before starting. This can be used to
/// throttle tasks. If requiredObject is also specified, then the semaphore is not waited on until requiredObject
/// has reached its target value. Specifying the semaphore here is more efficient than having the task function
/// wait on the semaphore.
Semaphore* waitSemaphore;
/// Optional. An OnTaskFn that is executed only when ITasking::tryCancelTask() successfully cancels the task. Called
/// in the context of ITasking::tryCancelTask(). Typically provided to destroy taskArg.
OnTaskFn cancel;
// Internal only
//! @private
Object const* trackers{ nullptr };
//! @private
size_t numTrackers{ 0 };
/// Constructor.
constexpr TaskDesc(OnTaskFn task_ = nullptr,
void* taskArg_ = nullptr,
Priority priority_ = Priority::eLow,
Counter* requiredCounter_ = nullptr,
Semaphore* waitSemaphore_ = nullptr,
OnTaskFn cancel_ = nullptr)
: task(task_),
taskArg(taskArg_),
priority(priority_),
requiredObject{ ObjectType::eCounter, requiredCounter_ },
waitSemaphore(waitSemaphore_),
cancel(cancel_)
{
}
};
/**
* Defines a tasking plugin descriptor.
*/
struct TaskingDesc
{
/**
* The size of the fiber pool, limited to kMaxFibers.
*
* Every task must be assigned a fiber before it can execute. A fiber is like a thread stack, but carb.tasking can
* choose when the fibers run, as opposed to threads where the OS schedules them.
*
* A value of 0 means to use kMaxFibers.
*/
uint32_t fiberCount;
/**
* The number of worker threads.
*
* A value of 0 means to use \ref carb::thread::hardware_concurrency().
*/
uint32_t threadCount;
/**
* The optional array of affinity values for every thread.
*
* If set to `nullptr`, affinity is not set. Otherwise it must contain `threadCount` number of elements. Each
* affinity value is a CPU index in the range [0 - `carb::thread::hardware_concurrency()`)
*/
uint32_t* threadAffinity;
/**
* The stack size per fiber. 0 indicates to use the system default.
*/
uint64_t stackSize;
};
/**
* Debug state of a task.
*/
enum class TaskDebugState
{
Pending, //!< The task has unmet pre-requisites and cannot be started yet.
New, //!< The task has passed all pre-requisites and is waiting to be assigned to a task thread.
Running, //!< The task is actively running on a task thread.
Waiting, //!< The task has been started but is currently waiting and is not running on a task thread.
Finished, //!< The task has finished or has been canceled.
};
/**
* Defines debug information about a task retrieved by ITasking::getTaskDebugInfo() or ITasking::walkTaskDebugInfo().
*
* @note This information is intended for debug only and should not affect application state or decisions in the
* application.
*
* @warning Since carb.tasking is an inherently multi-threaded API, the values presented as task debug information
* may have changed in a worker thread in the short amount of time between when they were generated and when they were
* read by the application. As such, the debug information was true at a previous point in time and should not be
* considered necessarily up-to-date.
*/
struct TaskDebugInfo
{
//! Size of this struct, used for versioning.
size_t sizeOf{ sizeof(TaskDebugInfo) };
//! The TaskContext handle for the task.
TaskContext context{};
//! The state of the task.
TaskDebugState state{};
//! The task function for this task that was submitted to ITasking::addTask() (or variant function), if known. May
//! be `nullptr` if the task has finished or was canceled.
OnTaskFn task{};
//! The task argument for this task that was submitted to ITasking::addTask() (or variant function), if known. May
//! be `nullptr` if the task has finished or was canceled.
void* taskArg{};
//! Input: the maximum number of frames that can be stored in the memory pointed to by the `creationCallstack`
//! member.
//! Output: the number of frames that were stored in the memory pointed to by the `creationCallstack` member.
size_t numCreationFrames{ 0 };
//! The callstack that called ITasking::addTask() (or variant function). The callstack is only available if
//! carb.tasking is configured to capture callstacks with setting */plugins/carb.tasking.plugin/debugTaskBacktrace*.
//!
//! @note If this value is desired, prior to calling ITasking::getTaskDebugInfo() set this member to a buffer that
//! will be filled by the ITasking::getTaskDebugInfo() function. Set `numCreationFrames` to the number of frames
//! that can be contained in the buffer. After calling ITasking::getTaskDebugInfo(), this member will contain the
//! available creation callstack frames and `numCreationFrames` will be set to the number of frames that could be
//! written.
void** creationCallstack{ nullptr };
//! Input: the maximum number of frames that can be stored in the memory pointed to by the `waitingCallstack`
//! member.
//! Output: the number of frames that were stored in the memory pointed to by the `waitingCallstack` member.
size_t numWaitingFrames{ 0 };
//! The callstack of the task when waiting. This is only captured if carb.tasking is configured to capture
//! callstacks with setting */plugins/carb.tasking.plugin/debugTaskBacktrace* and if `state` is
//! TaskDebugState::Waiting.
//!
//! @warning Capturing this value is somewhat unsafe as debug information is not stored in a way that will impede
//! task execution whatsoever (i.e. with synchronization), therefore information is gathered from a running task
//! without stopping it. As such, reading the waiting callstack may produce bad data and in extremely rare cases
//! cause a crash. If the state changes while gathering info, `state` may report TaskDebugState::Waiting but
//! `numWaitingFrames` may be `0` even though some data was written to the buffer pointed to by `waitingCallstack`.
//!
//! @note If this value is desired, prior to calling ITasking::getTaskDebugInfo() set this member to a buffer that
//! will be filled by the ITasking::getTaskDebugInfo() function. Set `numWaitingFrames` to the number of frames that
//! can be contained in the buffer. After calling ITasking::getTaskDebugInfo(), this member will contain the
//! available waiting callstack frames and `numWaitingFrames` will be set to the number of frames that could be
//! written.
void** waitingCallstack{ nullptr };
//! Input: the maximum number of characters that can be stored in the memory pointed to by the `taskName` member.
//! Output: the number of characters written (including the NUL terminator) to the memory pointed to by the
//! `taskName` member.
size_t taskNameSize{ 0 };
//! A optional buffer that will be filled with the task name if provided.
//!
//! @note If this value is desired, prior to calling ITasking::getTaskDebugInfo() set this member to a buffer that
//! will be filled by the ITasking::getTaskDebugInfo() function. Set `taskNameSize` to the number of characters that
//! can be contained in the buffer. After calling ITasking::getTaskDebugInfo(), this member will contain the
//! NUL-terminated task name and `taskNameSize` will be set to the number of characters that could be written
//! (including the NUL-terminator).
char* taskName{ nullptr };
};
//! Callback function for ITasking::walkTaskDebugInfo().
//! @param info The TaskDebugInfo structure passed to ITasking::walkTaskDebugInfo(), filled with information about a
//! task.
//! @param context The `context` field passed to ITasking::walkTaskDebugInfo().
//! @return `true` if walking tasks should continue; `false` to terminate walking tasks.
using TaskDebugInfoFn = bool (*)(const TaskDebugInfo& info, void* context);
#ifndef DOXYGEN_BUILD
namespace detail
{
template <class T>
struct GenerateFuture;
template <class T>
class SharedState;
} // namespace detail
struct Trackers;
struct RequiredObject;
template <class T>
class Promise;
template <class T>
class SharedFuture;
#endif
/**
* A Future is a counterpart to a Promise. It is the receiving end of a one-way, one-time asynchronous communication
* channel for transmitting the result of an asynchronous operation.
*
* Future is very similar to <a href="https://en.cppreference.com/w/cpp/thread/future">std::future</a>
*
* Communication starts by creating a Promise. The Promise has an associated Future that can be retrieved once via
* Promise::get_future(). The Promise and the Future both reference a "shared state" that is used to communicate the
* result. When the result is available, it is set through Promise::set_value() (or the promise can be broken through
* Promise::setCanceled()), at which point the shared state becomes Ready and the Future will be able to retrieve the
* value through Future::get() (or determine cancellation via Future::isCanceled()).
*
* Task functions like ITasking::addTask() return a Future where the Promise side is the return value from the callable
* passed when the task is created.
*
* Future is inherently a "read-once" object. Once Future::get() is called, the Future becomes invalid. However,
* SharedFuture can be used (created via Future::share()) to retain the value. Many threads can wait on a SharedFuture
* and access the result simultaneously through SharedFuture::get().
*
* There are three specializations of Future:
* * Future<T>: The base specialization, used to communicate objects between tasks/threads.
* * Future<T&>: Reference specialization, used to communicate references between tasks/threads.
* * Future<void>: Void specialization, used to communicate stateless events between tasks/threads.
*
* The `void` specialization of Future is slightly different:
* * Future<void> does not have Future::isCanceled(); cancellation state cannot be determined.
*/
template <class T = void>
class Future
{
public:
/**
* Creates a future in an invalid state (valid() would return false).
*/
constexpr Future() noexcept = default;
/**
* Destructor.
*/
~Future();
/**
* Futures are movable.
*/
Future(Future&& rhs) noexcept;
/**
* Futures are movable.
*/
Future& operator=(Future&& rhs) noexcept;
/**
* Tests to see if this Future is valid.
*
* @returns true if get() and wait() are supported; false otherwise
*/
bool valid() const noexcept;
/**
* Checks to see if a value can be read from this Future
*
* @warning Undefined behavior to call this if valid() == `false`.
* @returns true if a value can be read from this Future; false if the value is not yet ready
*/
bool try_wait() const;
/**
* Waits until a value can be read from this Future
* @warning Undefined behavior to call this if valid() == `false`.
*/
void wait() const;
/**
* Waits until a value can be read from this Future, or the timeout period expires.
*
* @warning Undefined behavior to call this if valid() == `false`.
* @param dur The relative timeout period.
* @returns true if a value can be read from this Future; false if the timeout period expires before the value can
* be read
*/
template <class Rep, class Period>
bool wait_for(const std::chrono::duration<Rep, Period>& dur) const;
/**
* Waits until a value can be read from this Future, or the timeout period expires.
*
* @warning Undefined behavior to call this if valid() == `false`.
* @param when The absolute timeout period.
* @returns true if a value can be read from this Future; false if the timeout period expires before the value can
* be read
*/
template <class Clock, class Duration>
bool wait_until(const std::chrono::time_point<Clock, Duration>& when) const;
/**
* Waits until the future value is ready and returns the value. Resets the Future to an invalid state.
*
* @warning This function will call `std::terminate()` if the underlying task has been canceled with
* ITasking::tryCancelTask() or the Promise was broken. Use isCanceled() to determine if the value is safe to read.
*
* @returns The value passed to Promise::set_value().
*/
T get();
/**
* Returns whether the Promise has been broken (or if this Future represents a task, the task has been canceled).
*
* @warning Undefined behavior to call this if valid() == `false`.
* @note The `void` specialization of Future does not have this function.
* @returns `true` if the task has been canceled; `false` if the task is still pending or has a valid value to read.
*/
bool isCanceled() const;
/**
* Transfers the Future's shared state (if any) to a SharedFuture and leaves `*this` invalid (valid() == `false`).
* @returns A SharedFuture with the same shared state as `*this`.
*/
SharedFuture<T> share();
/**
* Returns a valid TaskContext if this Future represents a task.
*
* @note Futures can be returned from \ref ITasking::addTask() and related functions or from
* \ref Promise::get_future(). Only Future objects returned from \ref ITasking::addTask() will return a valid
* pointer from task_if().
*
* @returns A pointer to a TaskContext if this Future was created from \ref ITasking::addTask() or related
* functions; `nullptr` otherwise. The pointer is valid as long as the Future exists and the result from
* \ref valid() is `true`.
*/
const TaskContext* task_if() const;
/**
* Convertible to RequiredObject.
*/
operator RequiredObject() const;
/**
* Syntactic sugar around ITasking::addSubTask() that automatically passes the value from get() into `Callable` and
* resets the Future to an invalid state.
*
* @warning This resets the Future to an invalid state since the value is being consumed by the sub-task.
*
* @note This can be used to "chain" tasks together.
*
* @warning If the dependent task is canceled then the sub-task will call `std::terminate()`. When canceling the
* dependent task you must first cancel the sub-task.
*
* @warning For non-`void` specializations, it is undefined behavior to call this if valid() == `false`.
*
* @param prio The priority of the task to execute.
* @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a
* temporary object. The Tracker objects can be used to determine task completion or to provide input/output
* parameters to the task system.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value.
* The Callable object must take the Future's `T` type as its last parameter.
* @param args Arguments to pass to @p f
* @return A Future based on the return type of @p f
*/
template <class Callable, class... Args>
auto then(Priority prio, Trackers&& trackers, Callable&& f, Args&&... args);
private:
template <class U>
friend struct detail::GenerateFuture;
template <class U>
friend class Promise;
template <class U>
friend class SharedFuture;
CARB_PREVENT_COPY(Future);
constexpr Future(detail::SharedState<T>* state) noexcept;
Future(TaskContext task, detail::SharedState<T>* state) noexcept;
detail::SharedState<T>* m_state{ nullptr };
};
#ifndef DOXYGEN_BUILD
template <>
class Future<void>
{
public:
constexpr Future() noexcept = default;
~Future();
Future(Future&& rhs) noexcept;
Future& operator=(Future&& rhs) noexcept;
bool valid() const noexcept;
bool try_wait() const;
void wait() const;
template <class Rep, class Period>
bool wait_for(const std::chrono::duration<Rep, Period>& dur) const;
template <class Clock, class Duration>
bool wait_until(const std::chrono::time_point<Clock, Duration>& when) const;
void get();
SharedFuture<void> share();
const TaskContext* task_if() const;
operator RequiredObject() const;
template <class Callable, class... Args>
auto then(Priority prio, Trackers&& trackers, Callable&& f, Args&&... args);
private:
template <class U>
friend struct detail::GenerateFuture;
template <class U>
friend class Future;
template <class U>
friend class Promise;
template <class U>
friend class SharedFuture;
friend struct Tracker;
TaskContext* ptask();
detail::SharedState<void>* state() const noexcept;
Future(TaskContext task);
Future(detail::SharedState<void>* state);
Object m_obj{ ObjectType::eNone, nullptr };
};
#endif
/**
* SharedFuture is a shareable version of Future. Instead of Future::get() invalidating the Future and returning the
* value one time, multiple SharedFuture objects can reference the same shared state and allow multiple threads to
* wait and access the result value simultaneously.
*
* SharedFuture is similar to <a href="https://en.cppreference.com/w/cpp/thread/shared_future">std::shared_future</a>
*
* The same specializations (and their limitations) exist as with Future.
*/
template <class T = void>
class SharedFuture
{
public:
/**
* Default constructor. Constructs a SharedFuture where valid() == `false`.
*/
SharedFuture() noexcept = default;
/**
* Copy constructor. Holds the same state (if any) as @p other.
* @param other A SharedFuture to copy state from.
*/
SharedFuture(const SharedFuture<T>& other) noexcept;
/**
* Move constructor. Moves the shared state (if any) from @p other.
*
* After this call, @p other will report valid() == `false`.
* @param other A SharedFuture to move state from.
*/
SharedFuture(SharedFuture<T>&& other) noexcept;
/**
* Transfers the shared state (if any) from @p fut.
*
* After construction, @p fut will report valid() == `false`.
* @param fut A Future to move state from.
*/
SharedFuture(Future<T>&& fut) noexcept;
/**
* Destructor.
*/
~SharedFuture();
/**
* Copy-assign operator. Holds the same state (if any) as @p other after releasing any shared state previously held.
* @param other A SharedFuture to copy state from.
* @returns `*this`
*/
SharedFuture<T>& operator=(const SharedFuture<T>& other);
/**
* Move-assign operator. Swaps shared states with @p other.
* @param other A SharedFuture to swap states with.
* @returns `*this`
*/
SharedFuture<T>& operator=(SharedFuture<T>&& other) noexcept;
/**
* Waits until the shared state is Ready and retrieves the value stored.
* @warning Undefined behavior if valid() == `false`.
* @returns A const reference to the stored value.
*/
const T& get() const;
/**
* Checks if the SharedFuture references a shared state.
*
* This is only `true` for default-constructed SharedFuture or when moved from. Unlike Future, SharedFuture does not
* invalidate once the value is read with Future::get().
* @returns `true` if this SharedFuture references a shared state; `false` otherwise.
*/
bool valid() const noexcept;
/**
* Checks to see if the shared state is Ready without waiting.
*
* @warning Undefined behavior to call this if valid() == `false`.
* @returns `true` if the shared state is Ready; `false` otherwise.
*/
bool try_wait() const;
/**
* Blocks the task or thread and waits for the shared state to become Ready. try_wait() == `true` after this call
* and get() will immediately return a value.
*
* @warning Undefined behavior to call this if valid() == `false`.
*/
void wait() const;
/**
* Blocks the task or thread until @p dur has elapsed or the shared state becomes Ready.
*
* If `true` is returned, get() will return a value immediately.
* @warning Undefined behavior to call this if valid() == `false`.
* @param dur The duration to wait for.
* @returns `true` If the shared state is Ready; `false` if the timeout period elapsed.
*/
template <class Rep, class Period>
bool wait_for(const std::chrono::duration<Rep, Period>& dur) const;
/**
* Blocks the task or thread until @p when is reached or the shared state becomes Ready.
*
* If `true` is returned, get() will return a value immediately.
* @warning Undefined behavior to call this if valid() == `false`.
* @param when The clock time to wait until.
* @returns `true` If the shared state is Ready; `false` if the timeout period elapsed.
*/
template <class Clock, class Duration>
bool wait_until(const std::chrono::time_point<Clock, Duration>& when) const;
/**
* Returns whether the task promising a value to this Future has been canceled.
*
* @warning Undefined behavior to call this if valid() == `false`.
* @note The `void` specialization of SharedFuture does not have this function.
* @returns `true` if the task has been canceled or promise broken; `false` if the task is still pending, promise
* not yet fulfilled, or has a valid value to read.
*/
bool isCanceled() const;
/**
* Convertible to RequiredObject.
*/
operator RequiredObject() const;
/**
* Returns a valid TaskContext if this SharedFuture represents a task.
*
* @note Futures can be returned from addTask() and related functions or from Promise::get_future(). Only Future
* objects returned from addTask() and transferred to SharedFuture will return a valid pointer from task_if().
*
* @returns A pointer to a TaskContext if this SharedFuture was created from addTask() or related functions;
* `nullptr` otherwise. The pointer is valid as long as the SharedFuture exists and the response from valid() would
* be consistent.
*/
const TaskContext* task_if() const;
/**
* Syntactic sugar around ITasking::addSubTask() that automatically passes the value from get() into `Callable`.
* Unlike Future::then(), the SharedFuture is not reset to an invalid state.
*
* @note This can be used to "chain" tasks together.
*
* @warning If the dependent task is canceled then the sub-task will call `std::terminate()`. When canceling the
* dependent task you must first cancel the sub-task.
*
* @param prio The priority of the task to execute.
* @param trackers (optional) A `std::initializer_list` of zero or more Tracker objects. Note that this *must* be a
* temporary object. The Tracker objects can be used to determine task completion or to provide input/output
* parameters to the task system.
* @param f A C++ "Callable" object (i.e. functor, lambda, [member] function ptr) that optionally returns a value.
* The Callable object must take `const T&` as its last parameter.
* @param args Arguments to pass to @p f
* @return A Future based on the return type of @p f
*/
template <class Callable, class... Args>
auto then(Priority prio, Trackers&& trackers, Callable&& f, Args&&... args);
private:
detail::SharedState<T>* m_state{ nullptr };
};
#ifndef DOXYGEN_BUILD
template <class T>
class SharedFuture<T&>
{
public:
constexpr SharedFuture() noexcept = default;
SharedFuture(const SharedFuture& other) noexcept;
SharedFuture(SharedFuture&& other) noexcept;
SharedFuture(Future<T&>&& fut) noexcept;
~SharedFuture();
SharedFuture& operator=(const SharedFuture& other);
SharedFuture& operator=(SharedFuture&& other) noexcept;
T& get() const;
bool valid() const noexcept;
bool try_wait() const;
void wait() const;
template <class Rep, class Period>
bool wait_for(const std::chrono::duration<Rep, Period>& dur) const;
template <class Clock, class Duration>
bool wait_until(const std::chrono::time_point<Clock, Duration>& when) const;
bool isCanceled() const;
operator RequiredObject() const;
const TaskContext* task_if() const;
template <class Callable, class... Args>
auto then(Priority prio, Trackers&& trackers, Callable&& f, Args&&... args);
private:
detail::SharedState<T&>* m_state{ nullptr };
};
template <>
class SharedFuture<void>
{
public:
constexpr SharedFuture() noexcept = default;
SharedFuture(const SharedFuture<void>& other) noexcept;
SharedFuture(SharedFuture<void>&& other) noexcept;
SharedFuture(Future<void>&& fut) noexcept;
~SharedFuture();
SharedFuture<void>& operator=(const SharedFuture<void>& other);
SharedFuture<void>& operator=(SharedFuture<void>&& other) noexcept;
void get() const;
bool valid() const noexcept;
bool try_wait() const;
void wait() const;
template <class Rep, class Period>
bool wait_for(const std::chrono::duration<Rep, Period>& dur) const;
template <class Clock, class Duration>
bool wait_until(const std::chrono::time_point<Clock, Duration>& when) const;
operator RequiredObject() const;
const TaskContext* task_if() const;
template <class Callable, class... Args>
auto then(Priority prio, Trackers&& trackers, Callable&& f, Args&&... args);
private:
friend struct Tracker;
TaskContext* ptask();
detail::SharedState<void>* state() const;
Object m_obj{ ObjectType::eNone, nullptr };
};
#endif
/**
* A facility to store a value that is later acquired asynchronously via a Future created via Promise::get_future().
*
* The carb.tasking implementation is very similar to the C++11 <a
* href="https://en.cppreference.com/w/cpp/thread/promise">std::promise</a>.
*
* A promise has a "shared state" that is shared with the Future that it creates through Promise::get_future().
*
* A promise is a single-use object. The get_future() function may only be called once, and either set_value() or
* setCanceled() may only be called once.
*
* A promise that is destroyed without ever having called set_value() or setCanceled() is consider a broken promise and
* automatically calls setCanceled().
*
* There are three specializations of Promise:
* * Promise<T>: The base specialization, used to communicate objects between tasks/threads.
* * Promise<T&>: Reference specialization, used to communicate references between tasks/threads.
* * Promise<void>: Void specialization, used to communicate stateless events between tasks/threads.
*
* The `void` specialization of Promise is slightly different:
* * Promise<void> does not have Promise::setCanceled(); cancellation state cannot be determined.
*/
template <class T = void>
class Promise
{
CARB_PREVENT_COPY(Promise);
public:
/**
* Default constructor.
*
* Initializes the shared state.
*/
Promise();
/**
* Can be move-constructed.
*/
Promise(Promise&& other) noexcept;
/**
* Destructor.
*
* If the shared state has not yet received a value with set_value(), then it is canceled and made Ready similarly
* to setCanceled().
*/
~Promise();
/**
* Can be move-assigned.
*/
Promise& operator=(Promise&& other) noexcept;
/**
* Swaps the shared state with @p other's.
*
* @param other A Promise to swap shared states with.
*/
void swap(Promise& other) noexcept;
/**
* Atomically retrieves and clears the Future from this Promise that shares the same state.
*
* A Future::wait() call will wait until the shared state becomes Ready.
*
* @warning `std::terminate()` will be called if this function is called more than once.
*
* @returns A Future with the same shared state as this Promise.
*/
Future<T> get_future();
/**
* Atomically stores the value in the shared state and makes the state Ready.
*
* @warning Only one call of set_value() or setCanceled() is allowed. Subsequent calls will result in a call to
* `std::terminate()`.
*
* @param value The value to atomically set into the shared state.
*/
void set_value(const T& value);
/**
* Atomically stores the value in the shared state and makes the state Ready.
*
* @warning Only one call of set_value() or setCanceled() is allowed. Subsequent calls will result in a call to
* `std::terminate()`.
*
* @param value The value to atomically set into the shared state.
*/
void set_value(T&& value);
/**
* Atomically sets the shared state to canceled and makes the state Ready. This is a broken promise.
*
* @warning Calling Future::get() will result in a call to `std::terminate()`; Future::isCanceled() will return
* `true`.
*/
void setCanceled();
private:
using State = detail::SharedState<T>;
State* m_state{ nullptr };
};
#ifndef DOXYGEN_BUILD
template <class T>
class Promise<T&>
{
CARB_PREVENT_COPY(Promise);
public:
Promise();
Promise(Promise&& other) noexcept;
~Promise();
Promise& operator=(Promise&& other) noexcept;
void swap(Promise& other) noexcept;
Future<T&> get_future();
void set_value(T& value);
void setCanceled();
private:
using State = detail::SharedState<T&>;
State* m_state{ nullptr };
};
template <>
class Promise<void>
{
CARB_PREVENT_COPY(Promise);
public:
Promise();
Promise(Promise&& other) noexcept;
~Promise();
Promise& operator=(Promise&& other) noexcept;
void swap(Promise& other) noexcept;
Future<void> get_future();
void set_value();
private:
using State = detail::SharedState<void>;
State* m_state{ nullptr };
};
#endif
} // namespace tasking
} // namespace carb
| 38,072 | C | 35.643888 | 120 | 0.6862 |
omniverse-code/kit/include/carb/tasking/TaskingHelpers.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief carb.tasking helper functions
#pragma once
#include "TaskingTypes.h"
#include "../thread/Futex.h"
#include "../cpp/Functional.h"
#include "../cpp/Optional.h"
#include "../cpp/Variant.h"
#include "../Memory.h"
#include <atomic>
#include <chrono>
#include <iterator>
#include <vector>
namespace carb
{
namespace tasking
{
#ifndef DOXYGEN_BUILD
namespace detail
{
template <class T>
struct CarbDeleter
{
void operator()(T* p) noexcept
{
p->~T();
carb::deallocate(p);
}
};
template <class T, class U = std::remove_cv_t<T>>
inline void carbDelete(T* p) noexcept
{
if (p)
{
p->~T();
carb::deallocate(const_cast<U*>(p));
}
}
template <class T>
struct is_literal_string
{
constexpr static bool value = false;
};
template <size_t N>
struct is_literal_string<const char (&)[N]>
{
constexpr static bool value = true;
};
Counter* const kListOfCounters{ (Counter*)(size_t)-1 };
template <class Rep, class Period>
uint64_t convertDuration(const std::chrono::duration<Rep, Period>& dur)
{
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(thread::detail::clampDuration(dur)).count();
return uint64_t(::carb_max(std::chrono::nanoseconds::rep(0), ns));
}
template <class Clock, class Duration>
uint64_t convertAbsTime(const std::chrono::time_point<Clock, Duration>& tp)
{
return convertDuration(tp - Clock::now());
}
template <class F, class Tuple, size_t... I, class... Args>
decltype(auto) applyExtraImpl(F&& f, Tuple&& t, std::index_sequence<I...>, Args&&... args)
{
CARB_UNUSED(t); // Can get C4100: unreferenced formal parameter on MSVC when Tuple is empty.
return cpp::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))..., std::forward<Args>(args)...);
}
template <class F, class Tuple, class... Args>
decltype(auto) applyExtra(F&& f, Tuple&& t, Args&&... args)
{
return applyExtraImpl(std::forward<F>(f), std::forward<Tuple>(t),
std::make_index_sequence<std::tuple_size<std::remove_reference_t<Tuple>>::value>{},
std::forward<Args>(args)...);
}
// U looks like an iterator convertible to V when dereferenced
template <class U, class V>
using IsForwardIter = carb::cpp::conjunction<
carb::cpp::negation<
typename std::is_convertible<typename std::iterator_traits<U>::iterator_category, std::random_access_iterator_tag>>,
typename std::is_convertible<typename std::iterator_traits<U>::iterator_category, std::forward_iterator_tag>,
std::is_convertible<decltype(*std::declval<U&>()), V>>;
template <class U, class V>
using IsRandomAccessIter = carb::cpp::conjunction<
typename std::is_convertible<typename std::iterator_traits<U>::iterator_category, std::random_access_iterator_tag>,
std::is_convertible<decltype(*std::declval<U&>()), V>>;
// Must fit within a pointer, be trivially move constructible and trivially destructible.
template <class Functor>
using FitsWithinPointerTrivially =
carb::cpp::conjunction<carb::cpp::bool_constant<sizeof(typename std::decay_t<Functor>) <= sizeof(void*)>,
std::is_trivially_move_constructible<typename std::decay_t<Functor>>,
std::is_trivially_destructible<typename std::decay_t<Functor>>>;
template <class Functor, std::enable_if_t<FitsWithinPointerTrivially<Functor>::value, bool> = false>
inline void generateTaskFunc(TaskDesc& desc, Functor&& func)
{
// Use SFINAE to have this version of generateTaskFunc() contribute to resolution only if Functor will fit within a
// void*, so that we can use the taskArg as the instance. On my machine, this is about a tenth of the time for the
// below specialization, and happens more frequently.
using Func = typename std::decay_t<Functor>;
union
{
Func f;
void* v;
} u{ std::forward<Functor>(func) };
desc.taskArg = u.v;
desc.task = [](void* arg) {
union CARB_ATTRIBUTE(visibility("hidden"))
{
void* v;
Func f;
} u{ arg };
u.f();
};
// Func is trivially destructible so we don't need a cancel func
}
template <class Functor, std::enable_if_t<!FitsWithinPointerTrivially<Functor>::value, bool> = false>
inline void generateTaskFunc(TaskDesc& desc, Functor&& func)
{
// Use SFINAE to have this version of generateTaskFunc() contribute to resolution only if Functor will NOT fit
// within a void*, so that the heap can be used only if necessary
using Func = typename std::decay_t<Functor>;
// Need to allocate
desc.taskArg = new (carb::allocate(sizeof(Func))) Func(std::forward<Functor>(func));
desc.task = [](void* arg) {
std::unique_ptr<Func, detail::CarbDeleter<Func>> p(static_cast<Func*>(arg));
(*p)();
};
desc.cancel = [](void* arg) { detail::carbDelete(static_cast<Func*>(arg)); };
}
template <class T>
class SharedState;
template <>
class SharedState<void>
{
std::atomic_size_t m_refs;
public:
SharedState(bool futureRetrieved) noexcept : m_refs(1 + futureRetrieved), m_futureRetrieved(futureRetrieved)
{
}
virtual ~SharedState() = default;
void addRef() noexcept
{
m_refs.fetch_add(1, std::memory_order_relaxed);
}
void release()
{
if (m_refs.fetch_sub(1, std::memory_order_release) == 1)
{
std::atomic_thread_fence(std::memory_order_acquire);
detail::carbDelete(this);
}
}
void set()
{
CARB_FATAL_UNLESS(m_futex.exchange(isTask() ? eTaskPending : eReady, std::memory_order_acq_rel) == eUnset,
"Value already set");
}
void get()
{
}
void notify();
void markReady()
{
m_futex.store(eReady, std::memory_order_release);
}
bool ready() const
{
return m_futex.load(std::memory_order_relaxed) == eReady;
}
bool isTask() const
{
return m_object.type == ObjectType::eTaskContext;
}
enum State : uint8_t
{
eReady = 0,
eUnset,
eInProgress,
eTaskPending,
};
std::atomic<State> m_futex{ eUnset };
std::atomic_bool m_futureRetrieved{ false };
Object m_object{ ObjectType::eFutex1, &m_futex };
};
template <class T>
class SharedState<T&> final : public SharedState<void>
{
public:
SharedState(bool futureRetrieved) noexcept : SharedState<void>(futureRetrieved)
{
}
bool isSet() const noexcept
{
return m_value != nullptr;
}
T& get() const
{
CARB_FATAL_UNLESS(m_value, "Attempting to retrieve value from broken promise");
return *m_value;
}
void set(T& val)
{
CARB_FATAL_UNLESS(m_futex.exchange(eInProgress, std::memory_order_acquire) == 1, "Value already set");
m_value = std::addressof(val);
m_futex.store(this->isTask() ? eTaskPending : eReady, std::memory_order_release);
}
T* m_value{ nullptr };
};
template <class T>
class SharedState final : public SharedState<void>
{
public:
using Type = typename std::decay<T>::type;
SharedState(bool futureRetrieved) noexcept : SharedState<void>(futureRetrieved)
{
}
bool isSet() const noexcept
{
return m_type.has_value();
}
const T& get_ref() const
{
CARB_FATAL_UNLESS(m_type, "Attempting to retrieve value from broken promise");
return m_type.value();
}
T get()
{
CARB_FATAL_UNLESS(m_type, "Attempting to retrieve value from broken promise");
return std::move(m_type.value());
}
void set(const T& value)
{
CARB_FATAL_UNLESS(m_futex.exchange(eInProgress, std::memory_order_acquire) == 1, "Value already set");
m_type.emplace(value);
m_futex.store(this->isTask() ? eTaskPending : eReady, std::memory_order_release);
}
void set(T&& value)
{
CARB_FATAL_UNLESS(m_futex.exchange(eInProgress, std::memory_order_acquire) == 1, "Value already set");
m_type.emplace(std::move(value));
m_futex.store(this->isTask() ? eTaskPending : eReady, std::memory_order_release);
}
carb::cpp::optional<Type> m_type;
};
} // namespace detail
#endif
class TaskGroup;
/**
* Helper class to ensure correct compliance with the requiredObject parameter of ITasking::add[Throttled]SubTask() and
* wait() functions.
*
* The following may be converted into a RequiredObject: TaskContext, Future, Any, All, Counter*, or CounterWrapper.
*/
struct RequiredObject final : public Object
{
/**
* Constructor that accepts a `std::nullptr_t`.
*/
constexpr RequiredObject(std::nullptr_t) : Object{ ObjectType::eNone, nullptr }
{
}
/**
* Constructor that accepts an object that can be converted to Counter*.
*
* @param c An object convertible to Counter*. This can be Any, All, Counter* or CounterWrapper.
*/
template <class T, std::enable_if_t<std::is_convertible<T, Counter*>::value, bool> = false>
constexpr RequiredObject(T&& c) : Object{ ObjectType::eCounter, static_cast<Counter*>(c) }
{
}
/**
* Constructor that accepts an object that can be converted to TaskContext.
*
* @param tc A TaskContext or object convertible to TaskContext, such as a Future.
*/
template <class T, std::enable_if_t<std::is_convertible<T, TaskContext>::value, bool> = true>
constexpr RequiredObject(T&& tc)
: Object{ ObjectType::eTaskContext, reinterpret_cast<void*>(static_cast<TaskContext>(tc)) }
{
}
/**
* Constructor that accepts a TaskGroup&.
*/
constexpr RequiredObject(const TaskGroup& tg);
/**
* Constructor that accepts a TaskGroup*. `nullptr` may be provided.
*/
constexpr RequiredObject(const TaskGroup* tg);
private:
friend struct ITasking;
template <class U>
friend class Future;
template <class U>
friend class SharedFuture;
constexpr RequiredObject(const Object& o) : Object(o)
{
}
void get(TaskDesc& desc);
};
/**
* Specifies an "all" grouping of RequiredObject(s).
*
* @note *ALL* RequiredObject(s) given in the constructor must become signaled before the All object will be considered
* signaled.
*
* All and Any objects can be nested as they are convertible to RequiredObject.
*/
struct All final
{
/**
* Constructor that accepts an initializer_list of RequiredObject(s).
* @param il The `initializer_list` of RequiredObject(s).
*/
All(std::initializer_list<RequiredObject> il);
/**
* Constructor that accepts begin and end iterators that produce RequiredObject objects.
* @param begin The beginning iterator.
* @param end An off-the-end iterator just beyond the end of the list.
*/
template <class InputIt, std::enable_if_t<detail::IsForwardIter<InputIt, RequiredObject>::value, bool> = false>
All(InputIt begin, InputIt end);
//! @private
template <class InputIt, std::enable_if_t<detail::IsRandomAccessIter<InputIt, RequiredObject>::value, bool> = false>
All(InputIt begin, InputIt end);
/**
* Convertible to RequiredObject.
*/
operator RequiredObject() const
{
return RequiredObject(m_counter);
}
private:
friend struct RequiredObject;
Counter* m_counter;
operator Counter*() const
{
return m_counter;
}
};
/**
* Specifies an "any" grouping of RequiredObject(s).
*
* @note *ANY* RequiredObject given in the constructor that is or becomes signaled will cause the Any object to become
* signaled.
*
* All and Any objects can be nested as they are convertible to RequiredObject.
*/
struct Any final
{
/**
* Constructor that accepts an initializer_list of RequiredObject objects.
* @param il The initializer_list of RequiredObject objects.
*/
Any(std::initializer_list<RequiredObject> il);
/**
* Constructor that accepts begin and end iterators that produce RequiredObject objects.
* @param begin The beginning iterator.
* @param end An off-the-end iterator just beyond the end of the list.
*/
template <class InputIt, std::enable_if_t<detail::IsForwardIter<InputIt, RequiredObject>::value, bool> = false>
Any(InputIt begin, InputIt end);
//! @private
template <class InputIt, std::enable_if_t<detail::IsRandomAccessIter<InputIt, RequiredObject>::value, bool> = false>
Any(InputIt begin, InputIt end);
/**
* Convertible to RequiredObject.
*/
operator RequiredObject() const
{
return RequiredObject(m_counter);
}
private:
friend struct RequiredObject;
Counter* m_counter;
operator Counter*() const
{
return m_counter;
}
};
/**
* Helper class to provide correct types to the Trackers class.
*
* The following types are valid trackers:
* - Anything convertible to Counter*, such as CounterWrapper. Counters are deprecated however. The Counter is
* incremented before the task can possibly begin executing and decremented when the task finishes.
* - Future<void>&: This can be used to atomically populate a Future<void> before the task could possibly start
* executing.
* - Future<void>*: Can be `nullptr`, but if not, can be used to atomically populate a Future<void> before the task
* could possibly start executing.
* - TaskContext&: By providing a reference to a TaskContext it will be atomically filled before the task could possibly
* begin executing.
* - TaskContext*: By providing a pointer to a TaskContext (that can be `nullptr`), it will be atomically filled before
* the task could possibly begin executing, if valid.
*/
struct Tracker final : Object
{
/**
* Constructor that accepts a `std::nullptr_t`.
*/
constexpr Tracker(std::nullptr_t) : Object{ ObjectType::eNone, nullptr }
{
}
/**
* Constructor that accepts a Counter* or an object convertible to Counter*, such as CounterWrapper.
*
* @param c The object convertible to Counter*.
*/
template <class T, std::enable_if_t<std::is_convertible<T, Counter*>::value, bool> = false>
constexpr Tracker(T&& c) : Object{ ObjectType::eCounter, reinterpret_cast<void*>(static_cast<Counter*>(c)) }
{
}
/**
* Constructor that accepts a task name.
*
* @note This is not a Tracker per se; this is syntactic sugar to name a task as it is created.
* @tparam T A type that is convertible to `const char*`.
* @param name Either a `const char*` (dynamic string) or a `const char (&)[N]` (literal string) as the string name
* for a task.
* @see ITasking::nameTask()
*/
template <class T, std::enable_if_t<std::is_convertible<T, const char*>::value, bool> = false>
constexpr Tracker(T&& name)
: Object{ detail::is_literal_string<T>::value ? ObjectType::eTaskNameLiteral : ObjectType::eTaskName,
const_cast<void*>(reinterpret_cast<const void*>(name)) }
{
}
/**
* Constructor that accepts a Future<void>&. The Future will be initialized before the task can begin.
*/
Tracker(Future<>& fut) : Object{ ObjectType::ePtrTaskContext, fut.ptask() }
{
}
/**
* Constructor that accepts a Future<void>*. The Future<void> will be initialized before the task can begin.
* The Future<void> pointer can be `nullptr`.
*/
Tracker(Future<>* fut) : Object{ ObjectType::ePtrTaskContext, fut ? fut->ptask() : nullptr }
{
}
/**
* Constructor that accepts a SharedFuture<void>&. The SharedFuture will be initialized before the task can begin.
*/
Tracker(SharedFuture<>& fut) : Object{ ObjectType::ePtrTaskContext, fut.ptask() }
{
}
/**
* Constructor that accepts a SharedFuture<void>*. The SharedFuture<void> will be initialized before the task can
* begin. The SharedFuture<void> pointer can be `nullptr`.
*/
Tracker(SharedFuture<>* fut) : Object{ ObjectType::ePtrTaskContext, fut ? fut->ptask() : nullptr }
{
}
/**
* Constructor that accepts a TaskContext&. The value will be atomically written before the task can begin.
*/
constexpr Tracker(TaskContext& ctx) : Object{ ObjectType::ePtrTaskContext, &ctx }
{
}
/**
* Constructor that accepts a TaskContext*. The value will be atomically written before the task can begin.
* The TaskContext* can be `nullptr`.
*/
constexpr Tracker(TaskContext* ctx) : Object{ ObjectType::ePtrTaskContext, ctx }
{
}
/**
* Constructor that accepts a TaskGroup&. The TaskGroup will be entered immediately and left when the task finishes.
* The TaskGroup must exist until the task completes.
*/
Tracker(TaskGroup& grp);
/**
* Constructor that accepts a TaskGroup*. The TaskGroup will be entered immediately and left when the task finishes.
* The TaskGroup* can be `nullptr` in which case nothing happens. The TaskGroup must exist until the task completes.
*/
Tracker(TaskGroup* grp);
private:
friend struct Trackers;
};
/**
* Helper class to ensure correct compliance with trackers parameter of ITasking::addTask() variants
*/
struct Trackers final
{
/**
* Default constructor.
*/
constexpr Trackers() : m_variant{}
{
}
/**
* Constructor that accepts a single Tracker.
*
* @param t The type passed to the Tracker constructor.
*/
template <class T, std::enable_if_t<std::is_constructible<Tracker, T>::value, bool> = false>
constexpr Trackers(T&& t) : m_variant(Tracker(t))
{
}
/**
* Constructor that accepts an initializer_list of Tracker objects.
*
* @param il The `std::initializer_list` of Tracker objects.
*/
constexpr Trackers(std::initializer_list<Tracker> il)
{
switch (il.size())
{
case 0:
break;
case 1:
m_variant.emplace<Tracker>(*il.begin());
break;
default:
m_variant.emplace<std::vector<Tracker>>(std::move(il));
}
}
/**
* Constructor that accepts an initializer_list of Tracker objects and additional Tracker objects.
*
* @param il The `std::initializer_list` of Tracker objects.
* @param p A pointer to additional Tracker objects; size specified by @p count.
* @param count The number of additional Tracker objects in the list specified by @p p.
*/
Trackers(std::initializer_list<Tracker> il, Tracker const* p, size_t count)
: m_variant(carb::cpp::in_place_index<2>)
{
switch (il.size() + count)
{
case 0:
break;
case 1:
m_variant.emplace<Tracker>(il.size() == 0 ? *p : *il.begin());
break;
default:
{
auto& vec = m_variant.emplace<std::vector<Tracker>>();
vec.reserve(il.size() + count);
vec.insert(vec.end(), il.begin(), il.end());
vec.insert(vec.end(), p, p + count);
}
}
}
/**
* Retrieves a list of Tracker objects managed by this helper object.
*
* @param trackers Receives a pointer to a list of Tracker objects.
* @param count Receives the count of Tracker objects.
*/
void output(Tracker const*& trackers, size_t& count) const
{
static_assert(sizeof(Object) == sizeof(Tracker), "");
fill(reinterpret_cast<Object const*&>(trackers), count);
}
CARB_PREVENT_COPY(Trackers);
/**
* Trackers is move-constructible.
*/
Trackers(Trackers&&) = default;
/**
* Trackers is move-assignable.
*/
Trackers& operator=(Trackers&&) = default;
private:
friend struct ITasking;
using TrackerVec = std::vector<Tracker>;
using Variant = carb::cpp::variant<carb::cpp::monostate, Tracker, TrackerVec>;
Variant m_variant;
Counter* fill(carb::tasking::Object const*& trackers, size_t& count) const
{
if (m_variant.index() == 0)
{
trackers = nullptr;
count = 0;
return nullptr;
}
if (auto* vec = carb::cpp::get_if<TrackerVec>(&m_variant))
{
trackers = vec->data();
count = vec->size();
}
else
{
const Tracker& t = carb::cpp::get<Tracker>(m_variant);
trackers = &t;
count = 1;
}
return detail::kListOfCounters;
}
};
//! A macro that can be used to mark a function as async, that is, it always executes in the context of a task.
//!
//! Generally the body of the function has one of @ref CARB_ASSERT_ASYNC, @ref CARB_CHECK_ASYNC, or
//! @ref CARB_FATAL_UNLESS_ASYNC.
//!
//! @code{.cpp}
//! void CARB_ASYNC Context::loadTask();
//! @endcode
#define CARB_ASYNC
//! A macro that can be used to mark a function as possibly async, that is, it may execute in the context of a task.
//! @code{.cpp}
//! void CARB_MAYBE_ASYNC Context::loadTask();
//! @endcode
#define CARB_MAYBE_ASYNC
//! Helper macro that results in a boolean expression which is `true` if the current thread is running in task context.
#define CARB_IS_ASYNC \
(::carb::getCachedInterface<carb::tasking::ITasking>()->getTaskContext() != ::carb::tasking::kInvalidTaskContext)
//! A macro that is used to assert that a scope is running in task context in debug builds only.
#define CARB_ASSERT_ASYNC CARB_ASSERT(CARB_IS_ASYNC)
//! A macro that is used to assert that a scope is running in task context in debug and checked builds.
#define CARB_CHECK_ASYNC CARB_CHECK(CARB_IS_ASYNC)
//! A macro that is used to assert that a scope is running in task context.
#define CARB_FATAL_UNLESS_ASYNC CARB_FATAL_UNLESS(CARB_IS_ASYNC, "Not running in task context!")
} // namespace tasking
} // namespace carb
| 22,528 | C | 30.597475 | 124 | 0.640137 |
omniverse-code/kit/include/carb/tasking/IFiberEvents.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief IFiberEvents definition file.
#pragma once
#include "../Framework.h"
#include "../Interface.h"
namespace carb
{
namespace tasking
{
/**
* Defines the fiber events interface that receives fiber-related notifications.
*
* This is a \a reverse interface. It is not implemented by *carb.tasking.plugin*. Instead, *carb.tasking.plugin* looks
* for all instances of this interface and will call the functions to inform other plugins of fiber events. This can be
* used, for example, by a profiler that wants to keep track of which fiber is running on a thread.
*
* Once \ref IFiberEvents::notifyFiberStart() has been called, this is a signal to the receiver that a task is executing
* on the current thread, and will be executing on the current thread until \ref IFiberEvents::notifyFiberStop() is
* called on the same thread. Between these two calls, the thread is executing in *Task context*, that is, within a task
* submitted to *carb.tasking.plugin*. As such, it is possible to query information about the task, such as the context
* handle ( \ref ITasking::getTaskContext()) or access task-local storage ( \ref ITasking::getTaskStorage() /
* \ref ITasking::setTaskStorage()). However, **anything that could cause a task to yield is strictly prohibited**
* in these functions and will produce undefined behavior. This includes but is not limited to yielding, waiting on any
* task-aware synchronization primitive (i.e. locking a \ref Mutex), sleeping in a task-aware manner, suspending a task,
* etc.
*
* @warning *carb.tasking.plugin* queries for all IFiberEvents interfaces only during startup, during
* @ref ITasking::changeParameters() and @ref ITasking::reloadFiberEvents(). If a plugin is loaded which exports
* \c IFiberEvents then you **must** perform one of these methods to receive notifications about fiber events.
*
* @warning **DO NOT EVER** call the functions; only *carb.tasking.plugin* should be calling these functions. Receiving
* one of these function calls implies that *carb.tasking.plugin* is loaded, and these function calls can be coordinated
* with certain *carb.tasking.plugin* actions (reading task-specific data, for instance).
*
* @note Notification functions are called in the context of the thread which caused the fiber event.
*/
struct IFiberEvents
{
CARB_PLUGIN_INTERFACE("carb::tasking::IFiberEvents", 1, 0)
/**
* Specifies that a fiber started or resumed execution on the calling thread.
*
* Specifies that the calling thread is now running fiber with ID @p fiberId until notifyFiberStop() is called on
* the same thread.
*
* @note A thread switching fibers will always call notifyFiberStop() before calling notifyFiberStart() with the new
* fiber ID.
*
* @param fiberId A unique identifier for a fiber.
*/
void(CARB_ABI* notifyFiberStart)(const uint64_t fiberId);
/**
* Specifies that a fiber yielded execution on the calling thread. It may or may not restart again at some later
* point, on the same thread or a different one.
*
* Specifies that the calling thread has yielded fiber with ID @p fiberId and is now running its own context.
*
* @param fiberId A unique identifier for a fiber.
*/
void(CARB_ABI* notifyFiberStop)(const uint64_t fiberId);
};
} // namespace tasking
} // namespace carb
| 3,835 | C | 48.179487 | 120 | 0.739505 |
omniverse-code/kit/include/carb/tasking/TaskingUtils.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief carb.tasking utilities.
#pragma once
#include "ITasking.h"
#include "../thread/Util.h"
#include <atomic>
#include <condition_variable> // for std::cv_status
#include <functional>
namespace carb
{
namespace tasking
{
class RecursiveSharedMutex;
/**
* This atomic spin lock conforms to C++ Named Requirements of <a
* href="https://en.cppreference.com/w/cpp/named_req/Lockable">Lockable</a> which makes it compatible with
* std::lock_guard.
*/
struct SpinMutex
{
public:
/**
* Constructs the SpinMutex.
*/
constexpr SpinMutex() noexcept = default;
CARB_PREVENT_COPY_AND_MOVE(SpinMutex);
/**
* Spins until the lock is acquired.
*
* See § 30.4.1.2.1 in the C++11 standard.
*/
void lock() noexcept
{
this_thread::spinWaitWithBackoff([&] { return try_lock(); });
}
/**
* Attempts to acquire the lock, on try, returns true if the lock was acquired.
*/
bool try_lock() noexcept
{
return (!mtx.load(std::memory_order_relaxed) && !mtx.exchange(true, std::memory_order_acquire));
}
/**
* Unlocks, wait-free.
*
* See § 30.4.1.2.1 in the C++11 standard.
*/
void unlock() noexcept
{
mtx.store(false, std::memory_order_release);
}
private:
std::atomic_bool mtx{};
};
/**
* Spin lock conforming to C++ named requirements of <a
* href="https://en.cppreference.com/w/cpp/named_req/SharedMutex">SharedMutex</a>.
*
* @warning This implementation is non-recursive.
*/
struct SpinSharedMutex
{
public:
/**
* Constructor.
*/
constexpr SpinSharedMutex() = default;
CARB_PREVENT_COPY_AND_MOVE(SpinSharedMutex);
/**
* Spins until the shared mutex is exclusive-locked
*
* @warning It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
*/
void lock()
{
while (!try_lock())
{
CARB_HARDWARE_PAUSE();
}
}
/**
* Attempts to exclusive-lock the shared mutex immediately without spinning.
*
* @warning It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
* @returns true if the mutex was exclusive-locked; false if no exclusive lock could be obtained.
*/
bool try_lock()
{
int expected = 0;
return counter.compare_exchange_strong(expected, -1, std::memory_order_acquire, std::memory_order_relaxed);
}
/**
* Unlocks the mutex previously exclusive-locked by this thread/task.
*
* @warning It is undefined behavior to unlock a mutex that is not owned by the current thread or task.
*/
void unlock()
{
CARB_ASSERT(counter == -1);
counter.store(0, std::memory_order_release);
}
/**
* Attempts to shared-lock the shared mutex immediately without spinning.
*
* @warning It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
* @returns true if the mutex was shared-locked; false if no shared lock could be obtained.
*/
bool try_lock_shared()
{
auto ctr = counter.load(std::memory_order_relaxed);
if (ctr >= 0)
{
return counter.compare_exchange_strong(ctr, ctr + 1, std::memory_order_acquire, std::memory_order_relaxed);
}
return false;
}
/**
* Spins until the shared mutex is shared-locked
*
* @warning It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
*/
void lock_shared()
{
auto ctr = counter.load(std::memory_order_relaxed);
for (;;)
{
if (ctr < 0)
{
CARB_HARDWARE_PAUSE();
ctr = counter.load(std::memory_order_relaxed);
}
else if (counter.compare_exchange_strong(ctr, ctr + 1, std::memory_order_acquire, std::memory_order_relaxed))
{
return;
}
}
}
/**
* Unlocks the mutex previously shared-locked by this thread/task.
*
* @warning It is undefined behavior to unlock a mutex that is not owned by the current thread or task.
*/
void unlock_shared()
{
int ctr = counter.fetch_sub(1, std::memory_order_release);
CARB_ASSERT(ctr > 0);
CARB_UNUSED(ctr);
}
private:
// 0 - unlocked
// > 0 - Shared lock count
// -1 - Exclusive lock
std::atomic<int> counter{ 0 };
};
/**
* Wrapper for a carb::tasking::Counter
*/
class CounterWrapper
{
public:
/**
* Constructs a new CounterWrapper.
*
* @param target An optional (default:0) target value for the Counter to become signaled.
*/
CounterWrapper(uint32_t target = 0)
: m_counter(carb::getCachedInterface<ITasking>()->createCounterWithTarget(target))
{
}
/**
* Constructs a new CounterWrapper.
*
* @note Deprecated: The ITasking* parameter is no longer needed in this call.
* @param tasking The acquired ITasking interface.
* @param target An optional (default:0) target value for the Counter to become signaled.
*/
CARB_DEPRECATED("ITasking no longer needed.")
CounterWrapper(ITasking* tasking, uint32_t target = 0)
: m_counter(carb::getCachedInterface<ITasking>()->createCounterWithTarget(target))
{
CARB_UNUSED(tasking);
}
/**
* Destrutor
*
* @warning Destroying a Counter that is not signaled will assert in debug builds.
*/
~CounterWrapper()
{
carb::getCachedInterface<ITasking>()->destroyCounter(m_counter);
}
/**
* @returns true if the Counter is signaled; false otherwise
*/
CARB_DEPRECATED("The Counter interface is deprecated.") bool check() const
{
return try_wait();
}
/**
* @returns true if the Counter is signaled; false otherwise
*/
bool try_wait() const
{
return carb::getCachedInterface<ITasking>()->try_wait(m_counter);
}
/**
* Blocks the current thread or task in a fiber-safe way until the Counter becomes signaled.
*/
void wait() const
{
carb::getCachedInterface<ITasking>()->wait(m_counter);
}
/**
* Blocks the current thread or task in a fiber-safe way until the Counter becomes signaled or a period of time has
* elapsed.
*
* @param dur The amount of time to wait for.
* @returns true if the Counter is signaled; false if the time period elapsed.
*/
template <class Rep, class Period>
bool wait_for(const std::chrono::duration<Rep, Period>& dur) const
{
return carb::getCachedInterface<ITasking>()->wait_for(dur, m_counter);
}
/**
* Blocks the current thread or task in a fiber-safe way until the Counter becomes signaled or the clock reaches the
* given time point.
*
* @param tp The time point to wait until.
* @returns true if the Counter is signaled; false if the clock time is reached.
*/
template <class Clock, class Duration>
bool wait_until(const std::chrono::time_point<Clock, Duration>& tp) const
{
return carb::getCachedInterface<ITasking>()->wait_until(tp, m_counter);
}
/**
* Convertible to Counter*.
*/
operator Counter*() const
{
return m_counter;
}
/**
* Returns the acquired ITasking interface that was used to construct this object.
* @note Deprecated: Use carb::getCachedInterface instead.
*/
CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const
{
return carb::getCachedInterface<ITasking>();
}
CARB_PREVENT_COPY_AND_MOVE(CounterWrapper);
private:
Counter* m_counter;
};
/**
* TaskGroup is a small and fast counter for tasks.
*
* TaskGroup blocks when tasks have "entered" the TaskGroup. It becomes signaled when all tasks have left the TaskGroup.
*/
class TaskGroup
{
public:
CARB_PREVENT_COPY_AND_MOVE(TaskGroup);
/**
* Constructs an empty TaskGroup.
*/
constexpr TaskGroup() = default;
/**
* TaskGroup destructor.
*
* @warning It is an error to destroy a TaskGroup that is not empty. Doing so can result in memory corruption.
*/
~TaskGroup()
{
CARB_CHECK(empty(), "Destroying busy TaskGroup!");
}
/**
* Returns (with high probability) whether the TaskGroup is empty.
*
* As TaskGroup atomically tracks tasks, this function may return an incorrect value as another task may have
* entered or left the TaskGroup before the return value could be processed.
*
* @returns `true` if there is high probability that the TaskGroup is empty (signaled); `false` otherwise.
*/
bool empty() const
{
// This cannot be memory_order_relaxed because it does not synchronize with anything and would allow the
// compiler to cache the value or hoist it out of a loop. Acquire semantics will require synchronization with
// all other locations that release m_count.
return m_count.load(std::memory_order_acquire) == 0;
}
/**
* "Enters" the TaskGroup.
*
* @warning Every call to this function must be paired with leave(). It is generally better to use with().
*/
void enter()
{
m_count.fetch_add(1, std::memory_order_acquire); // synchronizes-with all other locations releasing m_count
}
/**
* "Leaves" the TaskGroup.
*
* @warning Every call to this function must be paired with an earlier enter() call. It is generally better to use
* with().
*/
void leave()
{
size_t v = m_count.fetch_sub(1, std::memory_order_release);
CARB_ASSERT(v, "Mismatched enter()/leave() calls");
if (v == 1)
{
carb::getCachedInterface<ITasking>()->futexWakeup(m_count, UINT_MAX);
}
}
/**
* Returns `true` if the TaskGroup is empty (signaled) with high probability.
*
* @returns `true` if there is high probability that the TaskGroup is empty (signaled); `false` otherwise.
*/
bool try_wait() const
{
return empty();
}
/**
* Blocks the calling thread or task until the TaskGroup becomes empty.
*/
void wait() const
{
size_t v = m_count.load(std::memory_order_acquire); // synchronizes-with all other locations releasing m_count
if (v)
{
ITasking* tasking = carb::getCachedInterface<ITasking>();
while (v)
{
tasking->futexWait(m_count, v);
v = m_count.load(std::memory_order_relaxed);
}
}
}
/**
* Blocks the calling thread or task until the TaskGroup becomes empty or the given duration elapses.
*
* @param dur The duration to wait for.
* @returns `true` if the TaskGroup has become empty; `false` if the duration elapses.
*/
template <class Rep, class Period>
bool try_wait_for(std::chrono::duration<Rep, Period> dur)
{
return try_wait_until(std::chrono::steady_clock::now() + dur);
}
/**
* Blocks the calling thread or task until the TaskGroup becomes empty or the given time is reached.
*
* @param when The time to wait until.
* @returns `true` if the TaskGroup has become empty; `false` if the given time is reached.
*/
template <class Clock, class Duration>
bool try_wait_until(std::chrono::time_point<Clock, Duration> when)
{
size_t v = m_count.load(std::memory_order_acquire); // synchronizes-with all other locations releasing m_count
if (v)
{
ITasking* tasking = carb::getCachedInterface<ITasking>();
while (v)
{
if (!tasking->futexWaitUntil(m_count, v, when))
{
return false;
}
v = m_count.load(std::memory_order_relaxed);
}
}
return true;
}
/**
* A helper function for entering the TaskGroup during a call to `invoke()` and leaving afterwards.
*
* @param args Arguments to pass to `carb::cpp::invoke`. The TaskGroup is entered (via \ref enter()) before the
* invoke and left (via \ref leave()) when the invoke completes.
* @returns the value returned by `carb::cpp::invoke`.
*/
template <class... Args>
auto with(Args&&... args)
{
enter();
CARB_SCOPE_EXIT
{
leave();
};
return carb::cpp::invoke(std::forward<Args>(args)...);
}
private:
friend struct Tracker;
friend struct RequiredObject;
std::atomic_size_t m_count{ 0 };
};
/**
* Wrapper for a carb::tasking::Mutex that conforms to C++ Named Requirements of <a
* href="https://en.cppreference.com/w/cpp/named_req/Lockable">Lockable</a>.
*
* Non-recursive. If a recursive mutex is desired, use RecursiveMutexWrapper.
*/
class MutexWrapper
{
public:
/**
* Constructs a new MutexWrapper object
*/
MutexWrapper() : m_mutex(carb::getCachedInterface<ITasking>()->createMutex())
{
}
/**
* Constructs a new MutexWrapper object
* @note Deprecated: ITasking no longer needed.
*/
CARB_DEPRECATED("ITasking no longer needed.")
MutexWrapper(ITasking*) : m_mutex(carb::getCachedInterface<ITasking>()->createMutex())
{
}
/**
* Destructor
*
* @warning It is an error to destroy a mutex that is locked.
*/
~MutexWrapper()
{
carb::getCachedInterface<ITasking>()->destroyMutex(m_mutex);
}
/**
* Attempts to lock the mutex immediately.
*
* @warning It is an error to lock recursively. Use RecursiveSharedMutex if recursive locking is desired.
*
* @returns true if the mutex was locked; false otherwise
*/
bool try_lock()
{
return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, 0);
}
/**
* Locks the mutex, waiting until it becomes available.
*
* @warning It is an error to lock recursively. Use RecursiveSharedMutex if recursive locking is desired.
*/
void lock()
{
carb::getCachedInterface<ITasking>()->lockMutex(m_mutex);
}
/**
* Unlocks a mutex previously acquired with try_lock() or lock()
*
* @warning It is undefined behavior to unlock a mutex that is not owned by the current thread or task.
*/
void unlock()
{
carb::getCachedInterface<ITasking>()->unlockMutex(m_mutex);
}
/**
* Attempts to lock a mutex within a specified duration.
*
* @warning It is an error to lock recursively. Use RecursiveSharedMutex if recursive locking is desired.
*
* @param duration The duration to wait for the mutex to be available
* @returns true if the mutex was locked; false if the timeout period expired
*/
template <class Rep, class Period>
bool try_lock_for(const std::chrono::duration<Rep, Period>& duration)
{
return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, detail::convertDuration(duration));
}
/**
* Attempts to lock a mutex waiting until a specific clock time.
*
* @warning It is an error to lock recursively. Use RecursiveSharedMutex if recursive locking is desired.
*
* @param time_point The clock time to wait until.
* @returns true if the mutex was locked; false if the timeout period expired
*/
template <class Clock, class Duration>
bool try_lock_until(const std::chrono::time_point<Clock, Duration>& time_point)
{
return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, detail::convertAbsTime(time_point));
}
/**
* Convertible to Mutex*.
*/
operator Mutex*() const
{
return m_mutex;
}
/**
* Returns the acquired ITasking interface that was used to construct this object.
* @note Deprecated: Use carb::getCachedInterface instead.
*/
CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const
{
return carb::getCachedInterface<ITasking>();
}
CARB_PREVENT_COPY_AND_MOVE(MutexWrapper);
private:
Mutex* m_mutex;
};
/**
* Wrapper for a recursive carb::tasking::Mutex that conforms to C++ Named Requirements of <a
* href="https://en.cppreference.com/w/cpp/named_req/Lockable">Lockable</a>.
*/
class RecursiveMutexWrapper
{
public:
/**
* Constructs a new RecursiveMutexWrapper object
*/
RecursiveMutexWrapper() : m_mutex(carb::getCachedInterface<ITasking>()->createRecursiveMutex())
{
}
/**
* Constructs a new RecursiveMutexWrapper object
* @note Deprecated: ITasking no longer needed.
*/
CARB_DEPRECATED("ITasking no longer needed.")
RecursiveMutexWrapper(ITasking*) : m_mutex(carb::getCachedInterface<ITasking>()->createRecursiveMutex())
{
}
/**
* Destructor
*
* @warning It is an error to destroy a mutex that is locked.
*/
~RecursiveMutexWrapper()
{
carb::getCachedInterface<ITasking>()->destroyMutex(m_mutex);
}
/**
* Attempts to lock the mutex immediately.
*
* @returns true if the mutex was locked or already owned by this thread/task; false otherwise. If true is returned,
* unlock() must be called to release the lock.
*/
bool try_lock()
{
return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, 0);
}
/**
* Locks the mutex, waiting until it becomes available. Call unlock() to release the lock.
*/
void lock()
{
carb::getCachedInterface<ITasking>()->lockMutex(m_mutex);
}
/**
* Unlocks a mutex previously acquired with try_lock() or lock()
*
* @note The unlock() function must be called for each successful lock.
* @warning It is undefined behavior to unlock a mutex that is not owned by the current thread or task.
*/
void unlock()
{
carb::getCachedInterface<ITasking>()->unlockMutex(m_mutex);
}
/**
* Attempts to lock a mutex within a specified duration.
*
* @param duration The duration to wait for the mutex to be available
* @returns true if the mutex was locked; false if the timeout period expired. If true is returned, unlock() must be
* called to release the lock.
*/
template <class Rep, class Period>
bool try_lock_for(const std::chrono::duration<Rep, Period>& duration)
{
return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, detail::convertDuration(duration));
}
/**
* Attempts to lock a mutex waiting until a specific clock time.
*
* @param time_point The clock time to wait until.
* @returns true if the mutex was locked; false if the timeout period expired. If true is returned, unlock() must be
* called to release the lock.
*/
template <class Clock, class Duration>
bool try_lock_until(const std::chrono::time_point<Clock, Duration>& time_point)
{
return carb::getCachedInterface<ITasking>()->timedLockMutex(m_mutex, detail::convertAbsTime(time_point));
}
/**
* Convertible to Mutex*.
*/
operator Mutex*() const
{
return m_mutex;
}
/**
* Returns the acquired ITasking interface that was used to construct this object.
* @note Deprecated: Use carb::getCachedInterface instead.
*/
CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const
{
return carb::getCachedInterface<ITasking>();
}
CARB_PREVENT_COPY_AND_MOVE(RecursiveMutexWrapper);
private:
Mutex* m_mutex;
};
/**
* Wrapper for a carb::tasking::Semaphore
*
* @note SemaphoreWrapper can be used for @rstref{Throttling <tasking-throttling-label>} tasks.
*/
class SemaphoreWrapper
{
public:
/**
* Constructs a new SemaphoreWrapper object
*
* @param value The initial value of the semaphore (i.e. how many times acquire() can be called without blocking).
*/
SemaphoreWrapper(unsigned value) : m_sema(carb::getCachedInterface<ITasking>()->createSemaphore(value))
{
}
/**
* Constructs a new SemaphoreWrapper object
*
* @note Deprecated: ITasking no longer needed.
* @param value The initial value of the semaphore (i.e. how many times acquire() can be called without blocking).
*/
CARB_DEPRECATED("ITasking no longer needed.")
SemaphoreWrapper(ITasking*, unsigned value) : m_sema(carb::getCachedInterface<ITasking>()->createSemaphore(value))
{
}
/**
* Destructor
*/
~SemaphoreWrapper()
{
carb::getCachedInterface<ITasking>()->destroySemaphore(m_sema);
}
/**
* Increases the value of the semaphore, potentially unblocking any threads waiting in acquire().
*
* @param count The value to add to the Semaphore's value. That is, the number of threads to either unblock while
* waiting in acquire(), or to allow to call acquire() without blocking.
*/
void release(unsigned count = 1)
{
carb::getCachedInterface<ITasking>()->releaseSemaphore(m_sema, count);
}
/**
* Reduce the value of the Semaphore by one, potentially blocking if the count is already zero.
*
* @note Threads that are blocked by acquire() must be released by other threads calling release().
*/
void acquire()
{
carb::getCachedInterface<ITasking>()->waitSemaphore(m_sema);
}
/**
* Attempts to reduce the value of the Semaphore by one. If the Semaphore's value is zero, false is returned.
*
* @returns true if the count of the Semaphore was reduced by one; false if the count is already zero.
*/
bool try_acquire()
{
return carb::getCachedInterface<ITasking>()->timedWaitSemaphore(m_sema, 0);
}
/**
* Attempts to reduce the value of the Semaphore by one, waiting until the duration expires if the value is zero.
*
* @returns true if the count of the Semaphore was reduced by one; false if the duration expires.
*/
template <class Rep, class Period>
bool try_acquire_for(const std::chrono::duration<Rep, Period>& dur)
{
return carb::getCachedInterface<ITasking>()->timedWaitSemaphore(m_sema, detail::convertDuration(dur));
}
/**
* Attempts to reduce the value of the Semaphore by one, waiting until the given time point is reached if the value
* is zero.
*
* @returns true if the count of the Semaphore was reduced by one; false if the time point is reached by the clock.
*/
template <class Clock, class Duration>
bool try_acquire_until(const std::chrono::time_point<Clock, Duration>& tp)
{
return carb::getCachedInterface<ITasking>()->timedWaitSemaphore(m_sema, detail::convertAbsTime(tp));
}
/**
* Convertible to Semaphore*.
*/
operator Semaphore*() const
{
return m_sema;
}
/**
* Returns the acquired ITasking interface that was used to construct this object.
* @note Deprecated: Use carb::getCachedInterface instead.
*/
CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const
{
return carb::getCachedInterface<ITasking>();
}
CARB_PREVENT_COPY_AND_MOVE(SemaphoreWrapper);
private:
Semaphore* m_sema;
};
/**
* Wrapper for a carb::tasking::SharedMutex that (mostly) conforms to C++ Named Requirements of SharedMutex.
*/
class SharedMutexWrapper
{
public:
/**
* Constructs a new SharedMutexWrapper object
*/
SharedMutexWrapper() : m_mutex(carb::getCachedInterface<ITasking>()->createSharedMutex())
{
}
/**
* Constructs a new SharedMutexWrapper object
* @note Deprecated: ITasking no longer needed.
*/
CARB_DEPRECATED("ITasking no longer needed.")
SharedMutexWrapper(ITasking*) : m_mutex(carb::getCachedInterface<ITasking>()->createSharedMutex())
{
}
/**
* Destructor
*
* @note It is an error to destroy a shared mutex that is locked.
*/
~SharedMutexWrapper()
{
carb::getCachedInterface<ITasking>()->destroySharedMutex(m_mutex);
}
/**
* Attempts to shared-lock the shared mutex immediately.
*
* @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
*
* @returns true if the mutex was shared-locked; false otherwise
*/
bool try_lock_shared()
{
return carb::getCachedInterface<ITasking>()->timedLockSharedMutex(m_mutex, 0);
}
/**
* Attempts to exclusive-lock the shared mutex immediately.
*
* @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
*
* @returns true if the mutex was shared-locked; false otherwise
*/
bool try_lock()
{
return carb::getCachedInterface<ITasking>()->timedLockSharedMutexExclusive(m_mutex, 0);
}
/**
* Attempts to exclusive-lock the shared mutex within a specified duration.
*
* @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
*
* @param duration The duration to wait for the mutex to be available
* @returns true if the mutex was exclusive-locked; false if the timeout period expired
*/
template <class Rep, class Period>
bool try_lock_for(const std::chrono::duration<Rep, Period>& duration)
{
return carb::getCachedInterface<ITasking>()->timedLockSharedMutexExclusive(
m_mutex, detail::convertDuration(duration));
}
/**
* Attempts to shared-lock the shared mutex within a specified duration.
*
* @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
*
* @param duration The duration to wait for the mutex to be available
* @returns true if the mutex was shared-locked; false if the timeout period expired
*/
template <class Rep, class Period>
bool try_lock_shared_for(const std::chrono::duration<Rep, Period>& duration)
{
return carb::getCachedInterface<ITasking>()->timedLockSharedMutex(m_mutex, detail::convertDuration(duration));
}
/**
* Attempts to exclusive-lock the shared mutex until a specific clock time.
*
* @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
*
* @param time_point The clock time to wait until.
* @returns true if the mutex was exclusive-locked; false if the timeout period expired
*/
template <class Clock, class Duration>
bool try_lock_until(const std::chrono::time_point<Clock, Duration>& time_point)
{
return try_lock_for(time_point - Clock::now());
}
/**
* Attempts to shared-lock the shared mutex until a specific clock time.
*
* @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
*
* @param time_point The clock time to wait until.
* @returns true if the mutex was shared-locked; false if the timeout period expired
*/
template <class Clock, class Duration>
bool try_lock_shared_until(const std::chrono::time_point<Clock, Duration>& time_point)
{
return try_lock_shared_for(time_point - Clock::now());
}
/**
* Shared-locks the shared mutex, waiting until it becomes available.
*
* @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
*/
void lock_shared()
{
carb::getCachedInterface<ITasking>()->lockSharedMutex(m_mutex);
}
/**
* Unlocks a mutex previously shared-locked by this thread/task.
*
* @note It is undefined behavior to unlock a mutex that is not owned by the current thread or task.
*/
void unlock_shared()
{
carb::getCachedInterface<ITasking>()->unlockSharedMutex(m_mutex);
}
/**
* Exclusive-locks the shared mutex, waiting until it becomes available.
*
* @note It is an error to lock recursively or shared-lock when exclusive-locked, or vice versa.
*/
void lock()
{
carb::getCachedInterface<ITasking>()->lockSharedMutexExclusive(m_mutex);
}
/**
* Unlocks a mutex previously exclusive-locked by this thread/task.
*
* @note It is undefined behavior to unlock a mutex that is not owned by the current thread or task.
*/
void unlock()
{
carb::getCachedInterface<ITasking>()->unlockSharedMutex(m_mutex);
}
/**
* Convertible to SharedMutex*.
*/
operator SharedMutex*() const
{
return m_mutex;
}
/**
* Returns the acquired ITasking interface that was used to construct this object.
* @note Deprecated: Use carb::getCachedInterface instead.
*/
CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const
{
return carb::getCachedInterface<ITasking>();
}
CARB_PREVENT_COPY_AND_MOVE(SharedMutexWrapper);
private:
SharedMutex* m_mutex;
};
/**
* Wrapper for carb::tasking::ConditionVariable
*/
class ConditionVariableWrapper
{
public:
/**
* Constructs a new ConditionVariableWrapper object
*/
ConditionVariableWrapper() : m_cv(carb::getCachedInterface<ITasking>()->createConditionVariable())
{
}
/**
* Constructs a new ConditionVariableWrapper object
* @note Deprecated: ITasking no longer needed.
*/
CARB_DEPRECATED("ITasking no longer needed.")
ConditionVariableWrapper(ITasking*) : m_cv(carb::getCachedInterface<ITasking>()->createConditionVariable())
{
}
/**
* Destructor
*
* @note It is an error to destroy a condition variable that has waiting threads.
*/
~ConditionVariableWrapper()
{
carb::getCachedInterface<ITasking>()->destroyConditionVariable(m_cv);
}
/**
* Waits until the condition variable is notified.
*
* @note @p m must be locked when calling this function. The mutex will be unlocked while waiting and re-locked
* before returning to the caller.
*
* @param m The mutex to unlock while waiting for the condition variable to be notified.
*/
void wait(Mutex* m)
{
carb::getCachedInterface<ITasking>()->waitConditionVariable(m_cv, m);
}
/**
* Waits until a predicate has been satisfied and the condition variable is notified.
*
* @note @p m must be locked when calling this function. The mutex will be locked when calling @p pred and when this
* function returns, but unlocked while waiting.
*
* @param m The mutex to unlock while waiting for the condition variable to be notified.
* @param pred A predicate that is called repeatedly. When it returns true, the function returns. If it returns
* false, @p m is unlocked and the thread/task waits until the condition variable is notified.
*/
template <class Pred>
void wait(Mutex* m, Pred&& pred)
{
carb::getCachedInterface<ITasking>()->waitConditionVariablePred(m_cv, m, std::forward<Pred>(pred));
}
/**
* Waits until the condition variable is notified or the specified duration expires.
*
* @note @p m must be locked when calling this function. The mutex will be unlocked while waiting and re-locked
* before returning to the caller.
*
* @param m The mutex to unlock while waiting for the condition variable to be notified.
* @param duration The amount of time to wait for.
* @returns `std::cv_status::no_timeout` if the condition variable was notified; `std::cv_status::timeout` if the
* timeout period expired.
*/
template <class Rep, class Period>
std::cv_status wait_for(Mutex* m, const std::chrono::duration<Rep, Period>& duration)
{
return carb::getCachedInterface<ITasking>()->timedWaitConditionVariable(
m_cv, m, detail::convertDuration(duration)) ?
std::cv_status::no_timeout :
std::cv_status::timeout;
}
/**
* Waits until a predicate is satisfied and the condition variable is notified, or the specified duration expires.
*
* @note @p m must be locked when calling this function. The mutex will be unlocked while waiting and re-locked
* before returning to the caller.
*
* @param m The mutex to unlock while waiting for the condition variable to be notified.
* @param duration The amount of time to wait for.
* @param pred A predicate that is called repeatedly. When it returns true, the function returns. If it returns
* false, @p m is unlocked and the thread/task waits until the condition variable is notified.
* @returns true if the predicate was satisfied; false if a timeout occurred.
*/
template <class Rep, class Period, class Pred>
bool wait_for(Mutex* m, const std::chrono::duration<Rep, Period>& duration, Pred&& pred)
{
return carb::getCachedInterface<ITasking>()->timedWaitConditionVariablePred(
m_cv, m, detail::convertDuration(duration), std::forward<Pred>(pred));
}
/**
* Waits until the condition variable is notified or the clock reaches the given time point.
*
* @note @p m must be locked when calling this function. The mutex will be unlocked while waiting and re-locked
* before returning to the caller.
*
* @param m The mutex to unlock while waiting for the condition variable to be notified.
* @param time_point The clock time to wait until.
* @returns `std::cv_status::no_timeout` if the condition variable was notified; `std::cv_status::timeout` if the
* timeout period expired.
*/
template <class Clock, class Duration>
std::cv_status wait_until(Mutex* m, const std::chrono::time_point<Clock, Duration>& time_point)
{
return carb::getCachedInterface<ITasking>()->timedWaitConditionVariable(
m_cv, m, detail::convertAbsTime(time_point)) ?
std::cv_status::no_timeout :
std::cv_status::timeout;
}
/**
* Waits until a predicate is satisfied and the condition variable is notified or the clock reaches the given time
* point.
*
* @note @p m must be locked when calling this function. The mutex will be unlocked while waiting and re-locked
* before returning to the caller.
*
* @param m The mutex to unlock while waiting for the condition variable to be notified.
* @param time_point The clock time to wait until.
* @param pred A predicate that is called repeatedly. When it returns true, the function returns. If it returns
* false, @p m is unlocked and the thread/task waits until the condition variable is notified.
* @returns true if the predicate was satisfied; false if a timeout occurred.
*/
template <class Clock, class Duration, class Pred>
bool wait_until(Mutex* m, const std::chrono::time_point<Clock, Duration>& time_point, Pred&& pred)
{
return carb::getCachedInterface<ITasking>()->timedWaitConditionVariablePred(
m_cv, m, detail::convertAbsTime(time_point), std::forward<Pred>(pred));
}
/**
* Notifies one waiting thread/task to wake and check the predicate (if applicable).
*/
void notify_one()
{
carb::getCachedInterface<ITasking>()->notifyConditionVariableOne(m_cv);
}
/**
* Notifies all waiting threads/tasks to wake and check the predicate (if applicable).
*/
void notify_all()
{
carb::getCachedInterface<ITasking>()->notifyConditionVariableAll(m_cv);
}
/**
* Convertible to ConditionVariable*.
*/
operator ConditionVariable*() const
{
return m_cv;
}
/**
* Returns the acquired ITasking interface that was used to construct this object.
* @note Deprecated: Use carb::getCachedInterface instead.
*/
CARB_DEPRECATED("Use carb::getCachedInterface") ITasking* getTasking() const
{
return carb::getCachedInterface<ITasking>();
}
CARB_PREVENT_COPY_AND_MOVE(ConditionVariableWrapper);
private:
ConditionVariable* m_cv;
};
/**
* When instantiated, begins tracking the passed Trackers. At destruction, tracking on the given Trackers is ended.
*
* This is similar to the manner in which ITasking::addTask() accepts Trackers and begins tracking them prior to the
* task starting, and then leaves them when the task finishes. This class allows performing the same tracking behavior
* without the overhead of a task.
*/
class ScopedTracking
{
public:
/**
* Default constructor.
*/
ScopedTracking() : m_tracker{ ObjectType::eNone, nullptr }
{
}
/**
* Constructor that accepts a Trackers object.
* @param trackers The Trackers to begin tracking.
*/
ScopedTracking(Trackers trackers);
/**
* Destructor. The Trackers provided to the constructor finish tracking when `this` is destroyed.
*/
~ScopedTracking();
CARB_PREVENT_COPY(ScopedTracking);
/**
* Allows move-construct.
*/
ScopedTracking(ScopedTracking&& rhs);
/**
* Allows move-assign.
*/
ScopedTracking& operator=(ScopedTracking&& rhs) noexcept;
private:
Object m_tracker;
};
inline constexpr RequiredObject::RequiredObject(const TaskGroup& tg)
: Object{ ObjectType::eTaskGroup, const_cast<std::atomic_size_t*>(&tg.m_count) }
{
}
inline constexpr RequiredObject::RequiredObject(const TaskGroup* tg)
: Object{ ObjectType::eTaskGroup, tg ? const_cast<std::atomic_size_t*>(&tg->m_count) : nullptr }
{
}
inline All::All(std::initializer_list<RequiredObject> il)
{
static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption");
m_counter = carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAll, il.begin(), il.size());
}
template <class InputIt, std::enable_if_t<detail::IsForwardIter<InputIt, RequiredObject>::value, bool>>
inline All::All(InputIt begin, InputIt end)
{
static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption");
std::vector<RequiredObject> objects;
for (; begin != end; ++begin)
objects.push_back(*begin);
m_counter =
carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAll, objects.data(), objects.size());
}
template <class InputIt, std::enable_if_t<detail::IsRandomAccessIter<InputIt, RequiredObject>::value, bool>>
inline All::All(InputIt begin, InputIt end)
{
static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption");
size_t const count = end - begin;
RequiredObject* objects = CARB_STACK_ALLOC(RequiredObject, count);
size_t index = 0;
for (; begin != end; ++begin)
objects[index++] = *begin;
CARB_ASSERT(index == count);
m_counter = carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAll, objects, count);
}
inline Any::Any(std::initializer_list<RequiredObject> il)
{
static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption");
m_counter = carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAny, il.begin(), il.size());
}
template <class InputIt, std::enable_if_t<detail::IsForwardIter<InputIt, RequiredObject>::value, bool>>
inline Any::Any(InputIt begin, InputIt end)
{
static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption");
std::vector<RequiredObject> objects;
for (; begin != end; ++begin)
objects.push_back(*begin);
m_counter =
carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAny, objects.data(), objects.size());
}
template <class InputIt, std::enable_if_t<detail::IsRandomAccessIter<InputIt, RequiredObject>::value, bool>>
inline Any::Any(InputIt begin, InputIt end)
{
static_assert(sizeof(RequiredObject) == sizeof(Object), "Invalid assumption");
size_t const count = end - begin;
RequiredObject* objects = CARB_STACK_ALLOC(RequiredObject, count);
size_t index = 0;
for (; begin != end; ++begin)
objects[index++] = *begin;
CARB_ASSERT(index == count);
m_counter = carb::getCachedInterface<ITasking>()->internalGroupObjects(ITasking::eAny, objects, count);
}
inline Tracker::Tracker(TaskGroup& grp) : Object{ ObjectType::eTaskGroup, &grp.m_count }
{
}
inline Tracker::Tracker(TaskGroup* grp) : Object{ ObjectType::eTaskGroup, grp ? &grp->m_count : nullptr }
{
}
inline ScopedTracking::ScopedTracking(Trackers trackers)
{
Tracker const* ptrackers;
size_t numTrackers;
trackers.output(ptrackers, numTrackers);
m_tracker = carb::getCachedInterface<ITasking>()->beginTracking(ptrackers, numTrackers);
}
inline ScopedTracking::~ScopedTracking()
{
Object tracker = std::exchange(m_tracker, { ObjectType::eNone, nullptr });
if (tracker.type == ObjectType::eTrackerGroup)
{
carb::getCachedInterface<ITasking>()->endTracking(tracker);
}
}
inline ScopedTracking::ScopedTracking(ScopedTracking&& rhs)
: m_tracker(std::exchange(rhs.m_tracker, { ObjectType::eNone, nullptr }))
{
}
inline ScopedTracking& ScopedTracking::operator=(ScopedTracking&& rhs) noexcept
{
std::swap(m_tracker, rhs.m_tracker);
return *this;
}
} // namespace tasking
} // namespace carb
| 42,050 | C | 31.247699 | 121 | 0.648466 |
omniverse-code/kit/include/carb/memory/MemoryTrackerReplaceAllocation.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#if CARB_PLATFORM_WINDOWS && defined CARB_MEMORY_TRACKER_ENABLED && defined CARB_MEMORY_TRACKER_MODE_REPLACE
# include <vcruntime_new.h>
# pragma warning(push)
# pragma warning(disable : 4595) // non-member operator new or delete functions may not be declared inline
/**
* Replacement of the new/delete operator in C++
*/
inline void* operator new(size_t size)
{
return malloc(size);
}
inline void operator delete(void* address)
{
free(address);
}
inline void* operator new[](size_t size)
{
return malloc(size);
}
inline void operator delete[](void* address)
{
free(address);
}
/*
void* operator new(size_t size, const std::nothrow_t&)
{
return malloc(size);
}
void operator delete(void* address, const std::nothrow_t&)
{
free(address);
}
void* operator new[](size_t size, const std::nothrow_t&)
{
return malloc(size);
}
void operator delete[](void* address, const std::nothrow_t&)
{
free(address);
}*/
# pragma warning(pop)
#endif
| 1,465 | C | 21.90625 | 109 | 0.714676 |
omniverse-code/kit/include/carb/memory/Memory.h | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
#include "IMemoryTracker.h"
#if CARB_MEMORY_WORK_AS_PLUGIN
# define CARB_MEMORY_GLOBALS() CARB_MEMORY_TRACKER_GLOBALS()
class MemoryInitializerScoped
{
public:
MemoryInitializerScoped()
{
carb::memory::registerMemoryTrackerForClient();
}
~MemoryInitializerScoped()
{
carb::memory::deregisterMemoryTrackerForClient();
}
};
#endif
#if defined(CARB_MEMORY_TRACKER_MODE_REPLACE)
inline void* mallocWithRecord(size_t size)
{
void* address = malloc(size);
if (address)
{
carb::memory::IMemoryTracker* tracker = carb::memory::getMemoryTracker();
if (tracker)
{
// Set allocationGroup to nullptr means using default allocation group(HEAP)
tracker->recordAllocation(nullptr, address, size);
}
}
return address;
}
inline void freeWithRecord(void* address)
{
carb::memory::IMemoryTracker* tracker = carb::memory::getMemoryTracker();
if (tracker)
{
// Set allocationGroup to nullptr means using default allocation group(HEAP)
tracker->recordFree(nullptr, address);
}
}
# if CARB_PLATFORM_WINDOWS
inline void* operator new(size_t size) throw()
# else
void* operator new(size_t size) throw()
# endif
{
return mallocWithRecord(size);
}
# if CARB_PLATFORM_WINDOWS
inline void operator delete(void* address) throw()
# else
void operator delete(void* address) throw()
# endif
{
freeWithRecord(address);
}
# if CARB_PLATFORM_WINDOWS
inline void operator delete(void* address, unsigned long) throw()
# else
void operator delete(void* address, unsigned long) throw()
# endif
{
freeWithRecord(address);
}
# if CARB_PLATFORM_WINDOWS
inline void* operator new[](size_t size) throw()
# else
void* operator new[](size_t size) throw()
# endif
{
return mallocWithRecord(size);
}
# if CARB_PLATFORM_WINDOWS
inline void operator delete[](void* address) throw()
# else
void operator delete[](void* address) throw()
# endif
{
freeWithRecord(address);
}
# if CARB_PLATFORM_WINDOWS
inline void operator delete[](void* address, unsigned long) throw()
# else
void operator delete[](void* address, unsigned long) throw()
# endif
{
freeWithRecord(address);
}
void* operator new(size_t size, const std::nothrow_t&)
{
return mallocWithRecord(size);
}
void operator delete(void* address, const std::nothrow_t&)
{
freeWithRecord(address);
}
void* operator new[](size_t size, const std::nothrow_t&)
{
return mallocWithRecord(size);
}
void operator delete[](void* address, const std::nothrow_t&)
{
freeWithRecord(address);
}
#endif
inline void* _carbMalloc(size_t size, va_list args)
{
carb::memory::Context* context = va_arg(args, carb::memory::Context*);
carb::memory::IMemoryTracker* tracker = carb::memory::getMemoryTracker();
if (tracker && context)
tracker->pushContext(*context);
#if defined(CARB_MEMORY_TRACKER_MODE_REPLACE)
void* address = mallocWithRecord(size);
#else
void* address = malloc(size);
#endif
if (tracker && context)
tracker->popContext();
return address;
}
inline void* carbMalloc(size_t size, ...)
{
va_list args;
va_start(args, size);
void* address = _carbMalloc(size, args);
va_end(args);
return address;
}
inline void carbFree(void* address)
{
#if defined(CARB_MEMORY_TRACKER_MODE_REPLACE)
freeWithRecord(address);
#else
free(address);
#endif
}
inline void* operator new(size_t size, const char* file, int line, ...)
{
CARB_UNUSED(file);
va_list args;
va_start(args, line);
void* address = _carbMalloc(size, args);
va_end(args);
return address;
}
inline void* operator new[](size_t size, const char* file, int line, ...)
{
CARB_UNUSED(file);
va_list args;
va_start(args, line);
void* address = _carbMalloc(size, args);
va_end(args);
return address;
}
#define NV_MALLOC(size, ...) carbMalloc(size, ##__VA_ARGS__)
#define NV_FREE(p) carbFree(p)
#define NV_NEW(...) new (__FILE__, __LINE__, ##__VA_ARGS__)
#define NV_DELETE delete
#define NV_DELETE_ARRAY delete[]
| 4,609 | C | 22.88601 | 88 | 0.678672 |
omniverse-code/kit/include/carb/memory/PooledAllocator.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../container/LocklessQueue.h"
#include "../thread/Mutex.h"
#include <memory>
// Change this to 1 to enable pooled allocator leak checking. This captures a callstack and puts everything into an
// intrusive list.
#define CARB_POOLEDALLOC_LEAKCHECK 0
#if CARB_POOLEDALLOC_LEAKCHECK
# include "../extras/Debugging.h"
# include "../container/IntrusiveList.h"
#endif
#if CARB_DEBUG
# include "../logging/Log.h"
#endif
namespace carb
{
namespace memory
{
/**
* PooledAllocator implements the Allocator named requirements. It is thread-safe and (mostly) lockless. The given
* Allocator type must be thread-safe as well. Memory is never returned to the given Allocator until destruction.
*
* @param T The type created by this PooledAllocator
* @param Allocator The allocator to use for underlying memory allocation. Must be able to allocate many instances
* contiguously.
*/
template <class T, class Allocator = std::allocator<T>>
class PooledAllocator
{
public:
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using void_pointer = void*;
using const_void_pointer = const void*;
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
template <class U>
struct rebind
{
using other = PooledAllocator<U>;
};
PooledAllocator() : m_emo(ValueInitFirst{}), m_debugName(CARB_PRETTY_FUNCTION)
{
}
~PooledAllocator()
{
#if CARB_DEBUG
// Leak checking
size_type freeCount = 0;
m_emo.second.forEach([&freeCount](MemBlock*) { ++freeCount; });
size_t const totalCount =
m_bucketCount ? (size_t(1) << (m_bucketCount + kBucketShift)) - (size_t(1) << kBucketShift) : 0;
size_t const leaks = totalCount - freeCount;
if (leaks != 0)
{
CARB_LOG_ERROR("%s: leaked %zu items", m_debugName, leaks);
}
#endif
#if CARB_POOLEDALLOC_LEAKCHECK
m_list.clear();
#endif
// Deallocate everything
m_emo.second.popAll();
for (size_type i = 0; i != m_bucketCount; ++i)
{
m_emo.first().deallocate(m_buckets[i], size_t(1) << (i + kBucketShift));
}
}
pointer allocate(size_type n = 1)
{
CARB_CHECK(n <= 1); // cannot allocate more than 1 item simultaneously
MemBlock* p = m_emo.second.pop();
p = p ? p : _expand();
#if CARB_POOLEDALLOC_LEAKCHECK
size_t frames = extras::debugBacktrace(0, p->entry.callstack, CARB_COUNTOF(p->entry.callstack));
memset(p->entry.callstack + frames, 0, sizeof(void*) * (CARB_COUNTOF(p->entry.callstack) - frames));
new (&p->entry.link) decltype(p->entry.link){};
std::lock_guard<carb::thread::mutex> g(m_listMutex);
m_list.push_back(p->entry);
#endif
return reinterpret_cast<pointer>(p);
}
pointer allocate(size_type n, const_void_pointer p)
{
pointer mem = p ? pointer(p) : allocate(n);
return mem;
}
void deallocate(pointer p, size_type n = 1)
{
CARB_CHECK(n <= 1); // cannot free more than 1 item simultaneously
MemBlock* mb = reinterpret_cast<MemBlock*>(p);
#if CARB_POOLEDALLOC_LEAKCHECK
{
std::lock_guard<carb::thread::mutex> g(m_listMutex);
m_list.remove(mb->entry);
}
#endif
m_emo.second.push(mb);
}
size_type max_size() const
{
return 1;
}
private:
constexpr static size_type kBucketShift = 10; // First bucket contains 1<<10 items
constexpr static size_type kAlignment = ::carb_max(alignof(T), alignof(carb::container::LocklessQueueLink<void*>));
struct alignas(kAlignment) PoolEntry
{
T obj;
#if CARB_POOLEDALLOC_LEAKCHECK
void* callstack[32];
carb::container::IntrusiveListLink<PoolEntry> link;
#endif
};
struct NontrivialDummyType
{
constexpr NontrivialDummyType() noexcept
{
// Avoid zero-initialization when value initialized
}
};
struct alignas(kAlignment) MemBlock
{
union
{
NontrivialDummyType dummy{};
PoolEntry entry;
carb::container::LocklessQueueLink<MemBlock> m_link;
};
~MemBlock()
{
}
};
#if CARB_POOLEDALLOC_LEAKCHECK
carb::thread::mutex m_listMutex;
carb::container::IntrusiveList<PoolEntry, &PoolEntry::link> m_list;
#endif
// std::allocator<>::rebind<> has been deprecated in C++17 on mac.
CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Wdeprecated-declarations")
using BaseAllocator = typename Allocator::template rebind<MemBlock>::other;
CARB_IGNOREWARNING_GNUC_POP
MemBlock* _expand()
{
std::lock_guard<Lock> g(m_mutex);
// If we get the lock, first check to see if another thread populated the buckets first
if (MemBlock* mb = m_emo.second.pop())
{
return mb;
}
size_t const bucket = m_bucketCount;
size_t const allocationCount = size_t(1) << (bucket + kBucketShift);
// Allocate from base. The underlying allocator may throw
MemBlock* mem = m_emo.first().allocate(allocationCount);
CARB_FATAL_UNLESS(mem, "PooledAllocator underlying allocation failed: Out of memory");
// If any further exceptions are thrown, deallocate `mem`.
CARB_SCOPE_EXCEPT
{
m_emo.first().deallocate(mem, allocationCount);
};
// Resize the number of buckets. This can throw if make_unique() fails.
auto newBuckets = std::make_unique<MemBlock*[]>(m_bucketCount + 1);
if (m_bucketCount++ > 0)
memcpy(newBuckets.get(), m_buckets.get(), sizeof(MemBlock*) * (m_bucketCount - 1));
m_buckets = std::move(newBuckets);
// Populate the new bucket
// Add entries (after the first) to the free list
m_emo.second.push(mem + 1, mem + allocationCount);
m_buckets[bucket] = mem;
// Return the first entry that we reserved for the caller
return mem;
}
using LocklessQueue = carb::container::LocklessQueue<MemBlock, &MemBlock::m_link>;
EmptyMemberPair<BaseAllocator, LocklessQueue> m_emo;
using Lock = carb::thread::mutex;
Lock m_mutex;
std::unique_ptr<MemBlock* []> m_buckets {};
size_t m_bucketCount{ 0 };
const char* const m_debugName;
};
} // namespace memory
} // namespace carb
| 6,979 | C | 29.347826 | 119 | 0.634188 |
omniverse-code/kit/include/carb/memory/IMemoryTracker.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "MemoryTrackerDefines.h"
#include "MemoryTrackerReplaceAllocation.h"
#include "MemoryTrackerTypes.h"
#if CARB_MEMORY_WORK_AS_PLUGIN
# include "../Framework.h"
#endif
#include "../Types.h"
namespace carb
{
namespace memory
{
/**
* Defines a toolkit Memory Tracker, used to monitor/track memory usage/leak.
*/
struct IMemoryTracker
{
CARB_PLUGIN_INTERFACE("carb::memory::IMemoryTracker", 1, 0)
/**
* Setting this number either in the debugger, or in code will result in causing
* the memory allocator to break when this allocation is encountered.
*/
intptr_t* breakOnAlloc;
/**
* Specify that the debugger signal should be triggered nth allocation within a context.
* @param context The context to modify.
* @param nAlloc Signal the debugger on the nth allocation within context. -1 disables
* this feature.
* This feature only respects the top of the Context stack.
*/
void(CARB_ABI* contextBreakOnAlloc)(const Context& context, intptr_t nAlloc);
/**
* Makes the context active on the context stack for this thread.
*
* @param context The context to become active
*/
void(CARB_ABI* pushContext)(const Context& context);
/**
* Pops the context on the top of the stack off for this thread.
*/
void(CARB_ABI* popContext)();
/**
* Creates an allocation group.
*
* @param name The name of the memory address group.
* @return The address group object.
*/
AllocationGroup*(CARB_ABI* createAllocationGroup)(const char* name);
/**
* Destroys an allocation group.
*
* @param allocationGroup The address group to destroy
*/
void(CARB_ABI* destroyAllocationGroup)(AllocationGroup* allocationGroup);
/**
* Records an allocation on behalf of a region.
*
* The context recorded is on the top of the context stack. Additionally, the backtrace
* associated with this allocation is recorded from this call site.
*
* @param allocationGroup The allocationGroup to record the allocation into
* @param address The address that the allocation exists at
* @param size The size of the allocation.
*/
void(CARB_ABI* recordAllocation)(AllocationGroup* allocationGroup, const void* const address, size_t size);
/**
* Records an allocation on behalf of a region.
*
* Additionally, the backtrace associated with this allocation is recorded from this call
* site.
*
* @param allocationGroup The allocationGroup to record the allocation into
* @param context The context that the allocation is associated with.
* @param address The address that the allocation exists at
* @param size The size of the allocation.
*/
void(CARB_ABI* recordAllocationWithContext)(AllocationGroup* allocationGroup,
const Context& context,
const void* const address,
size_t size);
/**
* Records that an allocation that was previously recorded was released.
*
* @param allocationGroup The allocation group that the allocation was associated with.
* @param address The address the allocation was associated with.
*/
void(CARB_ABI* recordFree)(AllocationGroup* allocationGroup, const void* const address);
/**
* Creates a bookmark of the current state of the memory system.
*
* This is somewhat of a heavy-weight operation and should only be used at certain times
* such as level load.
*
* @return A snapshot of the current state of the memory system.
*/
Bookmark*(CARB_ABI* createBookmark)();
/**
* Destroys a memory bookmark.
*
* @param bookmark The bookmark to destroy.
*/
void(CARB_ABI* destroyBookmark)(Bookmark* bookmark);
/**
* Get a basic summary of the current state of the memory system, that is of a low enough overhead that we could put
* on a ImGui page that updates ever frame.
*
* @return The Summary struct of current state.
*/
Summary(CARB_ABI* getSummary)();
/**
* Generates a memory report.
*
* @param reportFlags The flags about the report.
* @param report The generated report, it is up to the user to release the report with releaseReport.
* @return nullptr if the report couldn't be generated, otherwise the report object.
*/
Report*(CARB_ABI* createReport)(ReportFlags reportFlags);
/**
* Generates a memory report, starting at a bookmark to now.
*
* @param reportFlags The flags about the report.
* @param bookmark Any allocations before bookmark will be ignored in the report.
* @param report The generated report, it is up to the user to release the report with
* releaseReport.
* @return nullptr if the report couldn't be generated, otherwise the report object.
*/
Report*(CARB_ABI* createReportFromBookmark)(ReportFlags reportFlags, Bookmark* bookmark);
/**
* Frees underlying data for the report.
*
* @param report The report to free.
*/
void(CARB_ABI* destroyReport)(Report* report);
/**
* Returns a pointer to the report data. The returned pointer can not be stored for persistence usage, and it will
* be freed along with the report.
*
* @param report The report data to inspect.
* @return The raw report data.
*/
const char*(CARB_ABI* reportGetData)(Report* report);
/**
* Returns the number of leaks stored in a memory report.
*
* @param report The report to return the number of leaks for.
* @return The number of leaks associated with the report.
*/
size_t(CARB_ABI* getReportMemoryLeakCount)(const Report* report);
/**
* When exiting, memory tracker will create a memory leak report.
* The report file name could be (from high priority to low):
* - In command line arguments (top priority) as format: --memory.report.path
* - Parameter in this function
* - The default: * ${WorkingDir}/memoryleak.json
* @param fileName The file name (including full path) to save memory leak report when exiting
*/
void(CARB_ABI* setReportFileName)(const char* fileName);
};
} // namespace memory
} // namespace carb
#if CARB_MEMORY_WORK_AS_PLUGIN
CARB_WEAKLINK carb::memory::IMemoryTracker* g_carbMemoryTracker;
# define CARB_MEMORY_TRACKER_GLOBALS()
#endif
namespace carb
{
namespace memory
{
#if CARB_MEMORY_WORK_AS_PLUGIN
inline void registerMemoryTrackerForClient()
{
Framework* framework = getFramework();
g_carbMemoryTracker = framework->acquireInterface<memory::IMemoryTracker>();
}
inline void deregisterMemoryTrackerForClient()
{
g_carbMemoryTracker = nullptr;
}
/**
* Get the toolkit Memory Tracker
* @return the memory tracker toolkit
*/
inline IMemoryTracker* getMemoryTracker()
{
return g_carbMemoryTracker;
}
#else
/**
* Get the toolkit Memory Tracker
* @return the memory tracker toolkit
*/
CARB_EXPORT memory::IMemoryTracker* getMemoryTracker();
#endif
/**
* RAII Context helper
*
* This class uses RAII to automatically set a context as active and then release it.
*
* @code
* {
* ScopedContext(SoundContext);
* // Allocate some sound resources
* }
* @endcode
*/
class ScopedContext
{
public:
ScopedContext(const Context& context)
{
CARB_UNUSED(context);
#if CARB_MEMORY_TRACKER_ENABLED
IMemoryTracker* tracker = getMemoryTracker();
CARB_ASSERT(tracker);
if (tracker)
tracker->pushContext(context);
#endif
}
~ScopedContext()
{
#if CARB_MEMORY_TRACKER_ENABLED
IMemoryTracker* tracker = getMemoryTracker();
CARB_ASSERT(tracker);
if (tracker)
tracker->popContext();
#endif
}
};
} // namespace memory
} // namespace carb
| 8,453 | C | 31.022727 | 120 | 0.671951 |
omniverse-code/kit/include/carb/memory/MemoryTrackerTypes.h | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// ver: 0.1
//
#pragma once
#include <cstddef>
#include <cstdint>
namespace carb
{
namespace memory
{
/**
* A context is a thin wrapper of a string pointer, as such it is up to the programmer
* to ensure that the pointer is valid at the invocation.
*
* To minimize the possibility of error any API receiving the context should copy the
* string rather than reference its pointer.
*/
class Context
{
public:
explicit Context(const char* contextName) : m_contextName(contextName)
{
}
const char* getContextName() const
{
return m_contextName;
}
private:
const char* m_contextName;
};
/**
* An address space is a type of memory that the user wishes to track. Normal
* allocation goes into the Global address space. This is used to track manual heaps, as
* well as resources that behave like memory but are not directly tied to the memory
* systems provided by the global heap. This can also be used to track an object who has
* unique id for the life-time of the object. Example: OpenGL Texture Ids
*
* Examples include GPU resources and Object Pools.
*/
struct AllocationGroup;
#define DEFAULT_ALLOCATION_GROUP_NAME ""
/**
* A bookmark is a point in time in the memory tracker, it allows the user to
* create a view of the memory between a bookmark and now.
*/
struct Bookmark;
struct ReportFlag
{
enum
{
eReportLeaks = 0x1, ///< Report any memory leaks as well.
eSummary = 0x2, ///< Just a summary.
eFull = eReportLeaks | eSummary,
};
};
typedef uint32_t ReportFlags;
/**
* This structure wraps up the data of the report.
*/
class Report;
/**
* A Summary is a really simple report.
*/
struct Summary
{
size_t allocationGroupCount;
size_t allocationCount;
size_t allocationBytes;
size_t freeCount;
size_t freeBytes;
};
enum class MemoryType
{
eMalloc,
eCalloc,
eRealloc,
eAlignedAlloc,
eStrdup,
eNew,
eNewArray,
eExternal,
eMemalign, // Linux only
eValloc, // Linux only
ePosixMemalign, // Linux only
eHeapAlloc,
eHeapRealloc,
};
} // namespace memory
} // namespace carb
| 2,588 | C | 22.324324 | 88 | 0.703632 |
omniverse-code/kit/include/carb/memory/MemoryTrackerDefines.h | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Defines.h"
// In plugin mode, memory tracker is required to be loaded/unloaded as other plugins
// In this mode, always track memory allocation/free after loaded
#define CARB_MEMORY_WORK_AS_PLUGIN 1
// JMK 2021-09-13: disabling carb.memory as it can lead to shutdown issues. The hooks are not added or removed in a
// thread-safe way, which means that other threads can be in a trampoline or hook function when they are removed. This
// leads to potential crashes at shutdown.
#ifndef CARB_MEMORY_TRACKER_ENABLED
// # define CARB_MEMORY_TRACKER_ENABLED (CARB_DEBUG)
# define CARB_MEMORY_TRACKER_ENABLED 0
#endif
// Option on work mode for Windows
// Set to 1: Hook windows heap API (only for Windows)
// Set to 0: Replace malloc/free, new/delete
// Linux always use replace mode
#define CARB_MEMORY_HOOK 1
#if CARB_PLATFORM_LINUX && CARB_MEMORY_TRACKER_ENABLED
# define CARB_MEMORY_TRACKER_MODE_REPLACE
#elif CARB_PLATFORM_WINDOWS && CARB_MEMORY_TRACKER_ENABLED
# if CARB_MEMORY_HOOK
# define CARB_MEMORY_TRACKER_MODE_HOOK
# else
# define CARB_MEMORY_TRACKER_MODE_REPLACE
# endif
#endif
// Option to add addition header before allocated memory
// See MemoryBlockHeader for header structure
#define CARB_MEMORY_ADD_HEADER 0
#if !CARB_MEMORY_ADD_HEADER
// If header not added, will verify the 6 of 8 bytes before allocated memory
// ---------------------------------
// | Y | Y | Y | Y | N | N | Y | Y | Allocated memory
// ---------------------------------
// Y means to verify, N means to ignore
// These 8 bytes should be part of heap chunk header
// During test, the 6 bytes will not changed before free while other 2 bytes may changed.
// Need investigate more for reason.
# define CARB_MEMORY_VERIFY_HEAP_CHUNK_HEADER 1
#else
# define CARB_MEMORY_VERIFY_HEAP_CHUNK_HEADER 0
#endif
| 2,295 | C | 38.586206 | 118 | 0.725926 |
omniverse-code/kit/include/carb/memory/ArenaAllocator.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Allocator that initially uses a memory arena first (typically on the stack) and then falls back to the heap.
#pragma once
#include "../Defines.h"
#include <memory>
namespace carb
{
namespace memory
{
/**
* An allocator that initially allocates from a memory arena (typically on the stack) and falls back to another
* allocator when that is exhausted.
*
* ArenaAllocator conforms to the C++ Named Requirement of <a
* href="https://en.cppreference.com/w/cpp/named_req/Allocator">Allocator</a>.
* @tparam T The type allocated by this allocator.
* @tparam FallbackAllocator The Allocator that is used when the arena is exhausted.
*/
template <class T, class FallbackAllocator = std::allocator<T>>
class ArenaAllocator
{
public:
//! \c T*
using pointer = typename std::allocator_traits<FallbackAllocator>::pointer;
//! `T const*`
using const_pointer = typename std::allocator_traits<FallbackAllocator>::const_pointer;
//! \c void*
using void_pointer = typename std::allocator_traits<FallbackAllocator>::void_pointer;
//! `void const*`
using const_void_pointer = typename std::allocator_traits<FallbackAllocator>::const_void_pointer;
//! \c T
using value_type = typename std::allocator_traits<FallbackAllocator>::value_type;
//! \c std::size_t
using size_type = typename std::allocator_traits<FallbackAllocator>::size_type;
//! \c std::ptrdiff_t
using difference_type = typename std::allocator_traits<FallbackAllocator>::difference_type;
//! Rebinds ArenaAllocator to a different type \c U
template <class U>
struct rebind
{
//! The rebound ArenaAllocator
using other = ArenaAllocator<U, typename FallbackAllocator::template rebind<U>::other>;
};
/**
* Default constructor. Only uses \c FallbackAllocator as no arena is given.
*/
ArenaAllocator() : m_members(ValueInitFirst{}, nullptr), m_current(nullptr), m_end(nullptr)
{
}
/**
* Constructs \c ArenaAllocator with a specific \c FallbackAllocator. Only uses \c FallbackAllocator as no arena is
* given.
*
* @param fallback A \c FallbackAllocator instance to copy.
*/
explicit ArenaAllocator(const FallbackAllocator& fallback)
: m_members(InitBoth{}, fallback, nullptr), m_current(nullptr), m_end(nullptr)
{
}
/**
* Constructs \c ArenaAllocator with an arena and optionally a specific \c FallbackAllocator.
*
* @warning It is the caller's responsibility to ensure that the given memory arena outlives \c *this and any other
* \ref ArenaAllocator which it may be moved to.
*
* @param begin A pointer to the beginning of the arena.
* @param end A pointer immediately past the end of the arena.
* @param fallback A \c FallbackAllocator instance to copy.
*/
ArenaAllocator(void* begin, void* end, const FallbackAllocator& fallback = FallbackAllocator())
: m_members(InitBoth{}, fallback, static_cast<uint8_t*>(begin)),
m_current(alignForward(m_members.second)),
m_end(static_cast<uint8_t*>(end))
{
}
/**
* Move constructor: constructs \c ArenaAllocator by moving from a different \c ArenaAllocator.
*
* @param other The \c ArenaAllocator to copy from.
*/
ArenaAllocator(ArenaAllocator&& other)
: m_members(InitBoth{}, std::move(other.m_members.first()), other.m_members.second),
m_current(other.m_current),
m_end(other.m_end)
{
// Prevent `other` from allocating memory from the arena. By adding 1 we put it past the end which prevents
// other->deallocate() from reclaiming the last allocation.
other.m_current = other.m_end + 1;
}
/**
* Copy constructor: constructs \c ArenaAllocator from a copy of a given \c ArenaAllocator.
*
* @note Even though \p other is passed via const-reference, the arena is transferred from \p other to `*this`.
* Further allocations from \p other will defer to the FallbackAllocator.
*
* @param other The \c ArenaAllocator to copy from.
*/
ArenaAllocator(const ArenaAllocator& other)
: m_members(InitBoth{}, other.m_members.first(), other.m_members.second),
m_current(other.m_current),
m_end(other.m_end)
{
// Prevent `other` from allocating memory from the arena. By adding 1 we put it past the end which prevents
// other->deallocate() from reclaiming the last allocation.
other.m_current = other.m_end + 1;
}
/**
* Copy constructor: constructs \c ArenaAllocator for type \c T from a copy of a given \c ArenaAllocator for type
* \c U.
*
* @note This does not copy the arena; that is retained by the original allocator.
*
* @param other The \c ArenaAllocator to copy from.
*/
template <class U, class UFallbackAllocator>
ArenaAllocator(const ArenaAllocator<U, UFallbackAllocator>& other)
: m_members(InitBoth{}, other.m_members.first(), other.m_members.second),
m_current(other.m_end + 1),
m_end(other.m_end)
{
// m_current is explicitly assigned to `other.m_end + 1` to prevent further allocations from the arena from
// *this and to prevent this->deallocate() from reclaiming the last allocation.
}
/**
* Allocates (but does not construct) memory for one or more instances of \c value_type.
*
* @param n The number of contiguous \c value_type instances to allocate. If the request cannot be serviced by the
* arena, the \c FallbackAllocator is used.
* @returns An uninitialized memory region that will fit \p n contiguous instances of \c value_type.
* @throws Memory Any exception that would be thrown by \c FallbackAllocator.
*/
pointer allocate(size_type n = 1)
{
if ((m_current + (sizeof(value_type) * n)) <= end())
{
pointer p = reinterpret_cast<pointer>(m_current);
m_current += (sizeof(value_type) * n);
return p;
}
return m_members.first().allocate(n);
}
/**
* Deallocates (but does not destruct) memory for one or more instances of \c value_type.
*
* @note If the memory came from the arena, the memory will not be available for reuse unless the memory is the
* most recent allocation from the arena.
* @param in The pointer previously returned from \ref allocate().
* @param n The same \c n value that was passed to \ref allocate() that produced \p in.
*/
void deallocate(pointer in, size_type n = 1)
{
uint8_t* p = reinterpret_cast<uint8_t*>(in);
if (p >= begin() && p < end())
{
if ((p + (sizeof(value_type) * n)) == m_current)
m_current -= (sizeof(value_type) * n);
}
else
m_members.first().deallocate(in, n);
}
private:
uint8_t* begin() const noexcept
{
return m_members.second;
}
uint8_t* end() const noexcept
{
return m_end;
}
static uint8_t* alignForward(void* p)
{
uint8_t* out = reinterpret_cast<uint8_t*>(p);
constexpr static size_t align = alignof(value_type);
size_t aligned = (size_t(out) + (align - 1)) & -(ptrdiff_t)align;
return out + (aligned - size_t(out));
}
template <class U, class UFallbackAllocator>
friend class ArenaAllocator;
mutable EmptyMemberPair<FallbackAllocator, uint8_t* /*begin*/> m_members;
mutable uint8_t* m_current;
mutable uint8_t* m_end;
};
//! Equality operator
//! @param lhs An allocator to compare
//! @param rhs An allocator to compare
//! @returns \c true if \p lhs and \p rhs can deallocate each other's allocations.
template <class T, class U, class Allocator1, class Allocator2>
bool operator==(const ArenaAllocator<T, Allocator1>& lhs, const ArenaAllocator<U, Allocator2>& rhs)
{
return (void*)lhs.m_members.second == (void*)rhs.m_members.second && lhs.m_members.first() == rhs.m_members.first();
}
//! Inequality operator
//! @param lhs An allocator to compare
//! @param rhs An allocator to compare
//! @returns the inverse of the equality operator.
template <class T, class U, class Allocator1, class Allocator2>
bool operator!=(const ArenaAllocator<T, Allocator1>& lhs, const ArenaAllocator<U, Allocator2>& rhs)
{
return !(lhs == rhs);
}
} // namespace memory
} // namespace carb
| 8,915 | C | 37.597402 | 120 | 0.661245 |
omniverse-code/kit/include/carb/memory/Util.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Helper utilities for memory
#pragma once
#include "../Defines.h"
#if CARB_PLATFORM_LINUX
# include <unistd.h>
#endif
namespace carb
{
namespace memory
{
// Turn off optimization for testReadable() for Visual Studio, otherwise the read will be elided and it will always
// return true.
CARB_OPTIMIZE_OFF_MSC()
/**
* Tests if a memory word (size_t) can be read from an address without crashing.
*
* @note This is not a particularly efficient function and should not be depended on for performance.
*
* @param mem The address to attempt to read
* @returns `true` if a value could be read successfully, `false` if attempting to read the value would cause an access
* violation or SIGSEGV.
*/
CARB_ATTRIBUTE(no_sanitize_address) inline bool testReadable(const void* mem)
{
#if CARB_PLATFORM_WINDOWS
// Use SEH to catch a read failure. This is very fast unless an exception occurs as no setup work is needed on
// x86_64.
__try
{
size_t s = *reinterpret_cast<const size_t*>(mem);
CARB_UNUSED(s);
return true;
}
__except (1)
{
return false;
}
#elif CARB_POSIX
// The pipes trick: use the kernel to validate that the memory can be read. write() will return -1 with errno=EFAULT
// if the memory is not readable.
int pipes[2];
CARB_FATAL_UNLESS(pipe(pipes) == 0, "Failed to create pipes");
int ret = CARB_RETRY_EINTR(write(pipes[1], mem, sizeof(size_t)));
CARB_FATAL_UNLESS(
ret == sizeof(size_t) || errno == EFAULT, "Unexpected result from write(): {%d/%s}", errno, strerror(errno));
close(pipes[0]);
close(pipes[1]);
return ret == sizeof(size_t);
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
CARB_OPTIMIZE_ON_MSC()
/**
* Copies memory as via memmove, but returns false if a read access violation occurs while reading.
*
* @rst
* .. warning:: This function is designed for protection, not performance, and may be very slow to execute.
* @endrst
* @thread_safety This function is safe to call concurrently. However, this function makes no guarantees about the
* consistency of data copied when the data is modified while copied, only the attempting to read invalid memory
* will not result in an access violation.
*
* As with `memmove()`, the memory areas may overlap: copying takes place as though the bytes in @p source are first
* copied into a temporary array that does not overlap @p source or @p dest, and the bytes are then copied from the
* temporary array to @p dest.
*
* @param dest The destination buffer that will receive the copied bytes.
* @param source The source buffer to copy bytes from.
* @param len The number of bytes of @p source to copy to @p dest.
* @returns `true` if the memory was successfully copied. If `false` is returned, @p dest is in a valid but undefined
* state.
*/
CARB_ATTRIBUTE(no_sanitize_address) inline bool protectedMemmove(void* dest, const void* source, size_t len)
{
if (!source)
return false;
#if CARB_PLATFORM_WINDOWS
// Use SEH to catch a read failure. This is very fast unless an exception occurs as no setup work is needed on
// x86_64.
__try
{
memmove(dest, source, len);
return true;
}
__except (1)
{
return false;
}
#elif CARB_POSIX
// Create a pipe and read the data through the pipe. The kernel will sanitize the reads.
int pipes[2];
if (pipe(pipes) != 0)
return false;
while (len != 0)
{
ssize_t s = ::carb_min((ssize_t)len, (ssize_t)4096);
if (CARB_RETRY_EINTR(write(pipes[1], source, s)) != s || CARB_RETRY_EINTR(read(pipes[0], dest, s)) != s)
break;
len -= size_t(s);
dest = static_cast<uint8_t*>(dest) + s;
source = static_cast<const uint8_t*>(source) + s;
}
close(pipes[0]);
close(pipes[1]);
return len == 0;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/**
* Copies memory as via strncpy, but returns false if an access violation occurs while reading.
*
* @rst
* .. warning:: This function is designed for safety, not performance, and may be very slow to execute.
* .. warning:: The `source` and `dest` buffers may not overlap.
* @endrst
* @thread_safety This function is safe to call concurrently. However, this function makes no guarantees about the
* consistency of data copied when the data is modified while copied, only the attempting to read invalid memory
* will not result in an access violation.
* @param dest The destination buffer that will receive the memory. Must be at least @p n bytes in size.
* @param source The source buffer. Up to @p n bytes will be copied.
* @param n The maximum number of characters of @p source to copy to @p dest. If no `NUL` character was encountered in
* the first `n - 1` characters of `source`, then `dest[n - 1]` will be a `NUL` character. This is a departure
* from `strncpy()` but similar to `strncpy_s()`.
* @returns `true` if the memory was successfully copied; `false` otherwise. If `false` is returned, `dest` is in a
* valid but undefined state.
*/
CARB_ATTRIBUTE(no_sanitize_address) inline bool protectedStrncpy(char* dest, const char* source, size_t n)
{
if (!source)
return false;
#if CARB_PLATFORM_WINDOWS
// Use SEH to catch a read failure. This is very fast unless an exception occurs as no setup work is needed on
// x86_64.
__try
{
size_t len = strnlen(source, n - 1);
memcpy(dest, source, len);
dest[len] = '\0';
return true;
}
__except (1)
{
return false;
}
#elif CARB_POSIX
if (n == 0)
return false;
// Create a pipe and read the data through the pipe. The kernel will sanitize the reads.
struct Pipes
{
bool valid;
int fds[2];
Pipes()
{
valid = pipe(fds) == 0;
}
~Pipes()
{
if (valid)
{
close(fds[0]);
close(fds[1]);
}
}
int operator[](int p) const noexcept
{
return fds[p];
}
} pipes;
if (!pipes.valid)
return false;
constexpr static size_t kBytes = sizeof(size_t);
constexpr static size_t kMask = kBytes - 1;
// Unaligned reads
while (n != 0 && (size_t(source) & kMask) != 0)
{
if (CARB_RETRY_EINTR(write(pipes[1], source, 1)) != 1 || CARB_RETRY_EINTR(read(pipes[0], dest, 1)) != 1)
return false;
if (*dest == '\0')
return true;
++source, ++dest, --n;
}
// Aligned reads
while (n >= kBytes)
{
CARB_ASSERT((size_t(source) & kMask) == 0);
union
{
size_t value;
char chars[kBytes];
} u;
if (CARB_RETRY_EINTR(write(pipes[1], source, kBytes)) != kBytes ||
CARB_RETRY_EINTR(read(pipes[0], &u.value, kBytes)) != kBytes)
return false;
// Use the strlen bit trick to check if any bytes that make up a word are definitely not zero
if (CARB_UNLIKELY(((u.value - 0x0101010101010101) & 0x8080808080808080)))
{
// One of the bytes could be zero
for (int i = 0; i != sizeof(size_t); ++i)
{
dest[i] = u.chars[i];
if (!dest[i])
return true;
}
}
else
{
memcpy(dest, u.chars, kBytes);
}
source += kBytes;
dest += kBytes;
n -= kBytes;
}
// Trailing reads
while (n != 0)
{
if (CARB_RETRY_EINTR(write(pipes[1], source, 1)) != 1 || CARB_RETRY_EINTR(read(pipes[0], dest, 1)) != 1)
return false;
if (*dest == '\0')
return true;
++source, ++dest, --n;
}
// Truncate
*(dest - 1) = '\0';
return true;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
} // namespace memory
} // namespace carb
| 8,469 | C | 31.083333 | 120 | 0.614358 |
omniverse-code/kit/include/carb/windowing/IGLContext.h | // Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Interface.h"
#include "../Types.h"
namespace carb
{
namespace windowing
{
struct GLContext;
/**
* Defines a GL context interface for off-screen rendering.
*/
struct IGLContext
{
CARB_PLUGIN_INTERFACE("carb::windowing::IGLContext", 1, 0)
/**
* Creates a context for OpenGL.
*
* @param width The width of the off-screen surface for the context.
* @param height The height of the off-screen surface for the context.
* @return The GL context created.
*/
GLContext*(CARB_ABI* createContextOpenGL)(int width, int height);
/**
* Creates a context for OpenGL(ES).
*
* @param width The width of the off-screen surface for the context.
* @param height The height of the off-screen surface for the context.
* @return The GL context created.
*/
GLContext*(CARB_ABI* createContextOpenGLES)(int width, int height);
/**
* Destroys a GL context.
*
* @param ctx The GL context to be destroyed.
*/
void(CARB_ABI* destroyContext)(GLContext* ctx);
/**
* Makes the GL context current.
*
* After calling this you can make any GL function calls.
*
* @param ctx The GL context to be made current.
*/
void(CARB_ABI* makeContextCurrent)(GLContext* ctx);
/**
* Try and resolve an OpenGL or OpenGL(es) procedure address from name.
*
* @param procName The name of procedure to load.
* @return The address of procedure.
*/
void*(CARB_ABI* getProcAddress)(const char* procName);
};
} // namespace windowing
} // namespace carb
| 2,052 | C | 27.123287 | 77 | 0.674951 |
omniverse-code/kit/include/carb/windowing/WindowingBindingsPython.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../BindingsPythonUtils.h"
#include "../BindingsPythonTypes.h"
#include "IGLContext.h"
#include "IWindowing.h"
#include <memory>
#include <string>
#include <vector>
namespace carb
{
namespace windowing
{
struct Cursor
{
};
struct GLContext
{
};
struct Monitor
{
};
struct ImagePy
{
int32_t width;
int32_t height;
py::bytes pixels;
ImagePy(int32_t _width, int32_t _height, py::bytes& _pixels) : width(_width), height(_height), pixels(_pixels)
{
}
};
inline void definePythonModule(py::module& m)
{
using namespace carb;
using namespace carb::windowing;
m.doc() = "pybind11 carb.windowing bindings";
py::class_<Window>(m, "Window");
py::class_<Cursor>(m, "Cursor");
py::class_<GLContext>(m, "GLContext");
py::class_<Monitor>(m, "Monitor");
py::class_<ImagePy>(m, "Image")
.def(py::init<int32_t, int32_t, py::bytes&>(), py::arg("width"), py::arg("height"), py::arg("pixels"));
m.attr("WINDOW_HINT_NONE") = py::int_(kWindowHintNone);
m.attr("WINDOW_HINT_NO_RESIZE") = py::int_(kWindowHintNoResize);
m.attr("WINDOW_HINT_NO_DECORATION") = py::int_(kWindowHintNoDecoration);
m.attr("WINDOW_HINT_NO_AUTO_ICONIFY") = py::int_(kWindowHintNoAutoIconify);
m.attr("WINDOW_HINT_NO_FOCUS_ON_SHOW") = py::int_(kWindowHintNoFocusOnShow);
m.attr("WINDOW_HINT_SCALE_TO_MONITOR") = py::int_(kWindowHintScaleToMonitor);
m.attr("WINDOW_HINT_FLOATING") = py::int_(kWindowHintFloating);
m.attr("WINDOW_HINT_MAXIMIZED") = py::int_(kWindowHintMaximized);
py::enum_<CursorStandardShape>(m, "CursorStandardShape")
.value("ARROW", CursorStandardShape::eArrow)
.value("IBEAM", CursorStandardShape::eIBeam)
.value("CROSSHAIR", CursorStandardShape::eCrosshair)
.value("HAND", CursorStandardShape::eHand)
.value("HORIZONTAL_RESIZE", CursorStandardShape::eHorizontalResize)
.value("VERTICAL_RESIZE", CursorStandardShape::eVerticalResize);
py::enum_<CursorMode>(m, "CursorMode")
.value("NORMAL", CursorMode::eNormal)
.value("HIDDEN", CursorMode::eHidden)
.value("DISABLED", CursorMode::eDisabled);
py::enum_<InputMode>(m, "InputMode")
.value("STICKY_KEYS", InputMode::eStickyKeys)
.value("STICKY_MOUSE_BUTTONS", InputMode::eStickyMouseButtons)
.value("LOCK_KEY_MODS", InputMode::eLockKeyMods)
.value("RAW_MOUSE_MOTION", InputMode::eRawMouseMotion);
defineInterfaceClass<IWindowing>(m, "IWindowing", "acquire_windowing_interface")
.def("create_window",
[](const IWindowing* iface, int width, int height, const char* title, bool fullscreen, int hints) {
WindowDesc desc = {};
desc.width = width;
desc.height = height;
desc.title = title;
desc.fullscreen = fullscreen;
desc.hints = hints;
return iface->createWindow(desc);
},
py::arg("width"), py::arg("height"), py::arg("title"), py::arg("fullscreen"),
py::arg("hints") = kWindowHintNone, py::return_value_policy::reference)
.def("destroy_window", wrapInterfaceFunction(&IWindowing::destroyWindow))
.def("show_window", wrapInterfaceFunction(&IWindowing::showWindow))
.def("hide_window", wrapInterfaceFunction(&IWindowing::hideWindow))
.def("get_window_width", wrapInterfaceFunction(&IWindowing::getWindowWidth))
.def("get_window_height", wrapInterfaceFunction(&IWindowing::getWindowHeight))
.def("get_window_position", wrapInterfaceFunction(&IWindowing::getWindowPosition))
.def("set_window_position", wrapInterfaceFunction(&IWindowing::setWindowPosition))
.def("set_window_title", wrapInterfaceFunction(&IWindowing::setWindowTitle))
.def("set_window_opacity", wrapInterfaceFunction(&IWindowing::setWindowOpacity))
.def("get_window_opacity", wrapInterfaceFunction(&IWindowing::getWindowOpacity))
.def("set_window_fullscreen", wrapInterfaceFunction(&IWindowing::setWindowFullscreen))
.def("is_window_fullscreen", wrapInterfaceFunction(&IWindowing::isWindowFullscreen))
.def("resize_window", wrapInterfaceFunction(&IWindowing::resizeWindow))
.def("focus_window", wrapInterfaceFunction(&IWindowing::focusWindow))
.def("is_window_focused", wrapInterfaceFunction(&IWindowing::isWindowFocused))
.def("maximize_window", wrapInterfaceFunction(&IWindowing::maximizeWindow))
.def("minimize_window", wrapInterfaceFunction(&IWindowing::minimizeWindow))
.def("restore_window", wrapInterfaceFunction(&IWindowing::restoreWindow))
.def("is_window_maximized", wrapInterfaceFunction(&IWindowing::isWindowMaximized))
.def("is_window_minimized", wrapInterfaceFunction(&IWindowing::isWindowMinimized))
.def("should_window_close", wrapInterfaceFunction(&IWindowing::shouldWindowClose))
.def("set_window_should_close", wrapInterfaceFunction(&IWindowing::setWindowShouldClose))
.def("get_window_user_pointer", wrapInterfaceFunction(&IWindowing::getWindowUserPointer))
.def("set_window_user_pointer", wrapInterfaceFunction(&IWindowing::setWindowUserPointer))
.def("set_window_content_scale", wrapInterfaceFunction(&IWindowing::getWindowContentScale))
.def("get_native_display", wrapInterfaceFunction(&IWindowing::getNativeDisplay))
.def("get_native_window", wrapInterfaceFunction(&IWindowing::getNativeWindow), py::return_value_policy::reference)
.def("set_input_mode", wrapInterfaceFunction(&IWindowing::setInputMode))
.def("get_input_mode", wrapInterfaceFunction(&IWindowing::getInputMode))
.def("update_input_devices", wrapInterfaceFunction(&IWindowing::updateInputDevices))
.def("poll_events", wrapInterfaceFunction(&IWindowing::pollEvents))
.def("wait_events", wrapInterfaceFunction(&IWindowing::waitEvents))
.def("get_keyboard", wrapInterfaceFunction(&IWindowing::getKeyboard), py::return_value_policy::reference)
.def("get_mouse", wrapInterfaceFunction(&IWindowing::getMouse), py::return_value_policy::reference)
.def("create_cursor_standard", wrapInterfaceFunction(&IWindowing::createCursorStandard),
py::return_value_policy::reference)
.def("create_cursor",
[](IWindowing* windowing, ImagePy& imagePy, int32_t xhot, int32_t yhot) {
py::buffer_info info(py::buffer(imagePy.pixels).request());
uint8_t* data = reinterpret_cast<uint8_t*>(info.ptr);
Image image{ imagePy.width, imagePy.height, data };
return windowing->createCursor(image, xhot, yhot);
},
py::return_value_policy::reference)
.def("destroy_cursor", wrapInterfaceFunction(&IWindowing::destroyCursor))
.def("set_cursor", wrapInterfaceFunction(&IWindowing::setCursor))
.def("set_cursor_mode", wrapInterfaceFunction(&IWindowing::setCursorMode))
.def("get_cursor_mode", wrapInterfaceFunction(&IWindowing::getCursorMode))
.def("set_cursor_position", wrapInterfaceFunction(&IWindowing::setCursorPosition))
.def("get_cursor_position", wrapInterfaceFunction(&IWindowing::getCursorPosition))
.def("set_clipboard", wrapInterfaceFunction(&IWindowing::setClipboard))
.def("get_clipboard", wrapInterfaceFunction(&IWindowing::getClipboard))
.def("get_monitors",
[](IWindowing* iface) {
size_t monitorCount;
const Monitor** monitors = iface->getMonitors(&monitorCount);
py::tuple tuple(monitorCount);
for (size_t i = 0; i < monitorCount; ++i)
{
tuple[i] = monitors[i];
}
return tuple;
})
.def("get_monitor_position", wrapInterfaceFunction(&IWindowing::getMonitorPosition))
.def("get_monitor_work_area",
[](IWindowing* iface, Monitor* monitor) {
Int2 pos, size;
iface->getMonitorWorkArea(monitor, &pos, &size);
py::tuple tuple(2);
tuple[0] = pos;
tuple[1] = size;
return tuple;
})
.def("set_window_icon", [](IWindowing* windowing, Window* window, ImagePy& imagePy) {
py::buffer_info info(py::buffer(imagePy.pixels).request());
uint8_t* data = reinterpret_cast<uint8_t*>(info.ptr);
Image image{ imagePy.width, imagePy.height, data };
windowing->setWindowIcon(window, image);
});
defineInterfaceClass<IGLContext>(m, "IGLContext", "acquire_gl_context_interface")
.def("create_context_opengl",
[](const IGLContext* iface, int width, int height) { return iface->createContextOpenGL(width, height); },
py::arg("width"), py::arg("height"), py::return_value_policy::reference)
.def("create_context_opengles",
[](const IGLContext* iface, int width, int height) { return iface->createContextOpenGLES(width, height); },
py::arg("width"), py::arg("height"), py::return_value_policy::reference)
.def("destroy_context", wrapInterfaceFunction(&IGLContext::destroyContext))
.def("make_context_current", wrapInterfaceFunction(&IGLContext::makeContextCurrent));
}
} // namespace windowing
} // namespace carb
| 9,947 | C | 50.27835 | 122 | 0.660903 |
omniverse-code/kit/include/carb/windowing/IWindowing.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Interface.h"
#include "../Types.h"
namespace carb
{
namespace input
{
struct Keyboard;
struct Mouse;
struct Gamepad;
} // namespace input
namespace windowing
{
struct Window;
struct Cursor;
struct Monitor;
enum class MonitorChangeEvent : uint32_t
{
eUnknown,
eConnected,
eDisconnected
};
typedef void (*OnWindowMoveFn)(Window* window, int x, int y, void* userData);
typedef void (*OnWindowResizeFn)(Window* window, int width, int height, void* userData);
typedef void (*OnWindowDropFn)(Window* window, const char** paths, int count, void* userData);
typedef void (*OnWindowCloseFn)(Window* window, void* userData);
typedef void (*OnWindowContentScaleFn)(Window* window, float scaleX, float scaleY, void* userData);
typedef void (*OnWindowFocusFn)(Window* window, bool isFocused, void* userData);
typedef void (*OnWindowMaximizeFn)(Window* window, bool isMaximized, void* userData);
typedef void (*OnWindowMinimizeFn)(Window* window, bool isMinimized, void* userData);
typedef void (*OnMonitorChangeFn)(const Monitor* monitor, MonitorChangeEvent evt);
typedef uint32_t WindowHints;
constexpr WindowHints kWindowHintNone = 0;
constexpr WindowHints kWindowHintNoResize = 1 << 0;
constexpr WindowHints kWindowHintNoDecoration = 1 << 1;
constexpr WindowHints kWindowHintNoAutoIconify = 1 << 2;
constexpr WindowHints kWindowHintNoFocusOnShow = 1 << 3;
constexpr WindowHints kWindowHintScaleToMonitor = 1 << 4;
constexpr WindowHints kWindowHintFloating = 1 << 5;
constexpr WindowHints kWindowHintMaximized = 1 << 6;
/**
* Descriptor for how a window is to be created.
*/
struct WindowDesc
{
int width; ///! The initial window width.
int height; ///! The initial window height.
const char* title; ///! The initial title of the window.
bool fullscreen; ///! Should the window be initialized in fullscreen mode.
WindowHints hints; ///! Initial window hints / attributes.
};
/**
* Defines cursor standard shapes.
*/
enum class CursorStandardShape : uint32_t
{
eArrow, ///! The regular arrow cursor shape.
eIBeam, ///! The text input I-beam cursor shape.
eCrosshair, ///! The crosshair shape.
eHand, ///! The hand shape
eHorizontalResize, ///! The horizontal resize arrow shape.
eVerticalResize ///! The vertical resize arrow shape.
};
enum class CursorMode : uint32_t
{
eNormal, ///! Cursor visible and behaving normally.
eHidden, ///! Cursor invisible when over the content area of window but does not restrict the cursor from leaving.
eDisabled, ///! Hides and grabs the cursor, providing virtual and unlimited cursor movement. This is useful
/// for implementing for example 3D camera controls.
};
enum class InputMode : uint32_t
{
eStickyKeys, ///! Config sticky key.
eStickyMouseButtons, ///! Config sticky mouse button.
eLockKeyMods, ///! Config lock key modifier bits.
eRawMouseMotion ///! Config raw mouse motion.
};
struct VideoMode
{
int width; ///! The width, in screen coordinates, of the video mode.
int height; ///! The height, in screen coordinates, of the video mode.
int redBits; ///! The bit depth of the red channel of the video mode.
int greenBits; ///! The bit depth of the green channel of the video mode.
int blueBits; ///! The bit depth of the blue channel of the video mode.
int refreshRate; ///! The refresh rate, in Hz, of the video mode.
};
/**
* This describes a single 2D image. See the documentation for each related function what the expected pixel format is.
*/
struct Image
{
int32_t width; ///! The width, in pixels, of this image.
int32_t height; ///! The height, in pixels, of this image.
uint8_t* pixels; ///! The pixel data of this image, arranged left-to-right, top-to-bottom.
};
/**
* Defines a windowing interface.
*/
struct IWindowing
{
CARB_PLUGIN_INTERFACE("carb::windowing::IWindowing", 1, 4)
/**
* Creates a window.
*
* @param desc The descriptor for the window.
* @return The window created.
*/
Window*(CARB_ABI* createWindow)(const WindowDesc& desc);
/**
* Destroys a window.
*
* @param window The window to be destroyed.
*/
void(CARB_ABI* destroyWindow)(Window* window);
/**
* Shows a window making it visible.
*
* @param window The window to use.
*/
void(CARB_ABI* showWindow)(Window* window);
/**
* Hides a window making it hidden.
*
* @param window The window to use.
*/
void(CARB_ABI* hideWindow)(Window* window);
/**
* Gets the current window width.
*
* @param window The window to use.
* @return The current window width.
*/
uint32_t(CARB_ABI* getWindowWidth)(Window* window);
/**
* Gets the current window height.
*
* @param window The window to use.
* @return The current window height.
*/
uint32_t(CARB_ABI* getWindowHeight)(Window* window);
/**
* Gets the current window position.
*
* @param window The window to use.
* @return The current window position.
*/
Int2(CARB_ABI* getWindowPosition)(Window* window);
/**
* Sets the current window position.
*
* @param window The window to use.
* @param position The position to set the window to.
*/
void(CARB_ABI* setWindowPosition)(Window* window, const Int2& position);
/**
* Sets the window title.
*
* @param window The window to use.
* @param title The window title to be set (as a utf8 string)
*/
void(CARB_ABI* setWindowTitle)(Window* window, const char* title);
/**
* Sets the window opacity.
*
* @param window The window to use.
* @param opacity The window opacity. 1.0f is fully opaque. 0.0 is fully transparent.
*/
void(CARB_ABI* setWindowOpacity)(Window* window, float opacity);
/**
* Gets the window opacity.
*
* @param window The window to use.
* @return The window opacity. 1.0f is fully opaque. 0.0 is fully transparent.
*/
float(CARB_ABI* getWindowOpacity)(Window* window);
/**
* Sets the window into fullscreen or windowed mode.
*
* @param window The window to use.
* @param fullscreen true to be set to fullscreen, false to be set to windowed.
*/
void(CARB_ABI* setWindowFullscreen)(Window* window, bool fullscreen);
/**
* Determines if the window is in fullscreen mode.
*
* @param window The window to use.
* @return true if the window is in fullscreen mode, false if in windowed mode.
*/
bool(CARB_ABI* isWindowFullscreen)(Window* window);
/**
* Sets the function for handling resize events.
*
* @param window The window to use.
* @param onWindowResize The function callback to handle resize events on the window.
*/
void(CARB_ABI* setWindowResizeFn)(Window* window, OnWindowResizeFn onWindowResize, void* userData);
/**
* Resizes the window.
*
* @param window The window to resize.
* @param width The width to resize to.
* @param height The height to resize to.
*/
void(CARB_ABI* resizeWindow)(Window* window, int width, int height);
/**
* Set the window in focus.
*
* @param window The window to use.
*/
void(CARB_ABI* focusWindow)(Window* window);
/**
* Sets the function for handling window focus events.
*
* @param window The window to use.
* @param onWindowFocusFn The function callback to handle focus events on the window.
*/
void(CARB_ABI* setWindowFocusFn)(Window* window, OnWindowFocusFn onWindowFocusFn, void* userData);
/**
* Determines if the window is in focus.
*
* @param window The window to use.
* @return true if the window is in focus, false if it is not.
*/
bool(CARB_ABI* isWindowFocused)(Window* window);
/**
* Sets the function for handling window minimize events.
*
* @param window The window to use.
* @param onWindowMinimizeFn The function callback to handle minimize events on the window.
*/
void(CARB_ABI* setWindowMinimizeFn)(Window* window, OnWindowMinimizeFn onWindowMinimizeFn, void* userData);
/**
* Determines if the window is minimized.
*
* @param window The window to use.
* @return true if the window is minimized, false if it is not.
*/
bool(CARB_ABI* isWindowMinimized)(Window* window);
/**
* Sets the function for handling drag-n-drop events.
*
* @param window The window to use.
* @param onWindowDrop The function callback to handle drop events on the window.
*/
void(CARB_ABI* setWindowDropFn)(Window* window, OnWindowDropFn onWindowDrop, void* userData);
/**
* Sets the function for handling window close events.
*
* @param window The window to use.
* @param onWindowClose The function callback to handle window close events.
*/
void(CARB_ABI* setWindowCloseFn)(Window* window, OnWindowCloseFn onWindowClose, void* userData);
/**
* Determines if the user has attempted to closer the window.
*
* @param window The window to use.
* @return true if the user has attempted to closer the window, false if still open.
*/
bool(CARB_ABI* shouldWindowClose)(Window* window);
/**
* Hints to the window that it should close.
*
* @param window The window to use.
* @param value true to request the window to close, false to request it not to close.
*/
void(CARB_ABI* setWindowShouldClose)(Window* window, bool value);
/**
* This function returns the current value of the user-defined pointer of the specified window.
* The initial value is nullptr.
*
* @param window The window to use.
* @return the current value of the user-defined pointer of the specified window.
*/
void*(CARB_ABI* getWindowUserPointer)(Window* window);
/**
* This function sets the user-defined pointer of the specified window.
* The current value is retained until the window is destroyed. The initial value is nullptr.
*
* @param window The window to use.
* @param pointer The new pointer value.
*/
void(CARB_ABI* setWindowUserPointer)(Window* window, void* pointer);
/**
* Sets the function for handling content scale events.
*
* @param window The window to use.
* @param onWindowContentScale The function callback to handle content scale events on the window.
*/
void(CARB_ABI* setWindowContentScaleFn)(Window* window, OnWindowContentScaleFn onWindowContentScale, void* userData);
/**
* Retrieves the content scale for the specified monitor.
*
* @param window The window to use.
* @return The content scale of the window.
*/
Float2(CARB_ABI* getWindowContentScale)(Window* window);
/**
* Gets the native display handle.
*
* windows = nullptr
* linux = ::Display*
*
* @param window The window to use.
* @return The native display handle.
*/
void*(CARB_ABI* getNativeDisplay)(Window* window);
/**
* Gets the native window handle.
*
* windows = ::HWND
* linux = ::Window
*
* @param window The window to use.
* @return The native window handle.
*/
void*(CARB_ABI* getNativeWindow)(Window* window);
/**
* Sets an input mode option for the specified window.
*
* @param window The window to set input mode.
* @param mode The mode to set.
* @param enabled The new value @ref mode should be changed to.
*/
void(CARB_ABI* setInputMode)(Window* window, InputMode mode, bool enabled);
/**
* Gets the value of a input mode option for the specified window.
*
* @param window The window to get input mode value.
* @param mode The input mode to get value from.
* @return The input mode value associated with the window.
*/
bool(CARB_ABI* getInputMode)(Window* window, InputMode mode);
/**
* Updates input device states.
*/
void(CARB_ABI* updateInputDevices)();
/**
* Polls and processes only those events that have already been received and then returns immediately.
*/
void(CARB_ABI* pollEvents)();
/**
* Puts the calling thread to sleep until at least one event has been received.
*/
void(CARB_ABI* waitEvents)();
/**
* Gets the logical keyboard associated with the window.
*
* @param window The window to use.
* @return The keyboard.
*/
input::Keyboard*(CARB_ABI* getKeyboard)(Window* window);
/**
* Gets the logical mouse associated with the window.
*
* @param window The window to use.
* @return The mouse.
*/
input::Mouse*(CARB_ABI* getMouse)(Window* window);
/**
* Creates a cursor with a standard shape, that can be set for a window with @ref setCursor.
*
* Use @ref destroyCursor to destroy cursors.
*
* @param shape The standard shape of cursor to be created.
* @return A new cursor ready to use or nullptr if an error occurred.
*/
Cursor*(CARB_ABI* createCursorStandard)(CursorStandardShape shape);
/**
* Destroys a cursor previously created with @ref createCursorStandard.
* If the specified cursor is current for any window, that window will be reverted to the default cursor.
*
* @param cursor the cursor object to destroy.
*/
void(CARB_ABI* destroyCursor)(Cursor* cursor);
/**
* Sets the cursor image to be used when the cursor is over the content area of the specified window.
*
* @param window The window to set the cursor for.
* @param cursor The cursor to set, or nullptr to switch back to the default arrow cursor.
*/
void(CARB_ABI* setCursor)(Window* window, Cursor* cursor);
/**
* Sets cursor mode option for the specified window.
*
* @param window The window to set cursor mode.
* @param mode The mouse mode to set to.
*/
void(CARB_ABI* setCursorMode)(Window* window, CursorMode mode);
/**
* Gets cursor mode option for the specified window.
*
* @param window The window to get cursor mode.
* @return The mouse mode associated with the window.
*/
CursorMode(CARB_ABI* getCursorMode)(Window* window);
/**
* Sets cursor position relative to the window.
*
* @param window The window to set input mode.
* @param position The x/y coordinates relative to the window.
*/
void(CARB_ABI* setCursorPosition)(Window* window, const Int2& position);
/**
* Gets cursor position relative to the window.
*
* @param window The window to set input mode.
* @return The x/y coordinates relative to the window.
*/
Int2(CARB_ABI* getCursorPosition)(Window* window);
/**
* The set clipboard function, which expects a Window and text.
*
* @param window The window that contains a glfwWindow
* @param text The text to set to the clipboard
*/
void(CARB_ABI* setClipboard)(Window* window, const char* text);
/**
* Gets the clipboard text.
*
* @param window The window that contains a glfwWindow
* @return The text from the clipboard
*/
const char*(CARB_ABI* getClipboard)(Window* window);
/**
* Sets the monitors callback function for configuration changes
*
* The onMonitorChange function callback will occur when monitors are changed.
* Current changes that can occur are connected/disconnected.
*
* @param onMonitorChange The callback function when monitors change.
*/
void(CARB_ABI* setMonitorsChangeFn)(OnMonitorChangeFn onMonitorChange);
/**
* Gets the primary monitor.
*
* A Monitor object represents a currently connected monitor and is represented as a pointer
* to the opaque native monitor. Monitor objects cannot be created or destroyed by the application
* and retain their addresses until the monitors they represent are disconnected.
*
* @return The primary monitor.
*/
const Monitor*(CARB_ABI* getMonitorPrimary)();
/**
* Gets the enumerated monitors.
*
* This represents a currently connected monitors and is represented as a pointer
* to the opaque native monitor. Monitors cannot be created or destroyed
* and retain their addresses until the monitors are disconnected.
*
* Use @ref setMonitorsChangeFn to know when a monitor is disconnected.
*
* @param monitorCount The returned number of monitors enumerated.
* @return The enumerated monitors.
*/
const Monitor**(CARB_ABI* getMonitors)(size_t* monitorCount);
/**
* Gets the human read-able monitor name.
*
* The name pointer returned is only valid for the life of the Monitor.
* When the Monitor is disconnected, the name pointer becomes invalid.
*
* Use @ref setMonitorsChangeFn to know when a monitor is disconnected.
*
* @param monitor The monitor to use.
* @return The human read-able monitor name. Pointer returned is owned by monitor.
*/
const char*(CARB_ABI* getMonitorName)(const Monitor* monitor);
/**
* Gets a monitors physical size in millimeters.
*
* The size returned is only valid for the life of the Monitor.
* When the Monitor is disconnected, the size becomes invalid.
*
* Use @ref setMonitorsChangeFn to know when a monitor is disconnected.
*
* @param monitor The monitor to use.
* @param size The monitor physical size returned.
*/
Int2(CARB_ABI* getMonitorPhysicalSize)(const Monitor* monitor);
/**
* Gets a monitors current video mode.
*
* The pointer returned is only valid for the life of the Monitor.
* When the Monitor is disconnected, the pointer becomes invalid.
*
* Use @ref setMonitorsChangeFn to know when a monitor is disconnected.
*
* @param monitor The monitor to use.
* @return The video mode.
*/
const VideoMode*(CARB_ABI* getMonitorVideoMode)(const Monitor* monitor);
/**
* Gets a monitors virtual position.
*
* The position returned is only valid for the life of the Monitor.
* When the Monitor is disconnected, the position becomes invalid.
*
* Use @ref setMonitorsChangeFn to know when a monitor is disconnected.
*
* @param monitor The monitor to use.
* @param position The monitor virtual position returned.
*/
Int2(CARB_ABI* getMonitorPosition)(const Monitor* monitor);
/**
* Gets a monitors content scale.
*
* The content scale is the ratio between the current DPI and the platform's default DPI.
* This is especially important for text and any UI elements. If the pixel dimensions of
* your UI scaled by this look appropriate on your machine then it should appear at a
* reasonable size on other machines regardless of their DPI and scaling settings.
* This relies on the system DPI and scaling settings being somewhat correct.
*
* The content scale returned is only valid for the life of the Monitor.
* When the Monitor is disconnected, the content scale becomes invalid.
*
* Use @ref setMonitorsChangeFn to know when a monitor is disconnected.
*
* @param monitor The monitor to use.
* @return The monitor content scale (dpi).
*/
Float2(CARB_ABI* getMonitorContentScale)(const Monitor* monitor);
/**
* Gets a monitors work area.
*
* The area of a monitor not occupied by global task bars or
* menu bars is the work area
*
* The work area returned is only valid for the life of the Monitor.
* When the Monitor is disconnected, the work area becomes invalid.
*
* Use @ref setMonitorsChangeFn to know when a monitor is disconnected.
*
* @param monitor The monitor to use.
* @param position The returned position.
* @param size The returned size.
*/
void(CARB_ABI* getMonitorWorkArea)(const Monitor* monitor, Int2* positionOut, Int2* sizeOut);
/**
* Sets the function for handling move events. Must be called on a main thread.
*
* @param window The window to use (shouldn't be nullptr).
* @param onWindowMove The function callback to handle move events on the window (can be nullptr).
* @param userData User-specified pointer to the data. Lifetime and value can be anything.
*/
void(CARB_ABI* setWindowMoveFn)(Window* window, OnWindowMoveFn onWindowMove, void* userData);
/**
* Determines if the window is floating (or always-on-top).
*
* @param window The window to use.
* @return true if the window is floating.
*/
bool(CARB_ABI* isWindowFloating)(Window* window);
/**
* Sets the window into floating (always-on-top) or regular mode.
*
* @param window The window to use.
* @param fullscreen true to be set to floating (always-on-top), false to be set to regular.
*/
void(CARB_ABI* setWindowFloating)(Window* window, bool isFloating);
/**
* Creates a new custom cursor image that can be set for a window with @ref setCursor. The cursor can be destroyed
* with @ref destroyCursor.
*
* The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with the red channel
* first. They are arranged canonically as packed sequential rows, starting from the top-left corner.
*
* The cursor hotspot is specified in pixels, relative to the upper-left corner of the cursor image. Like all other
* coordinate systems in GLFW, the X-axis points to the right and the Y-axis points down.
*
* @param image The desired cursor image.
* @param xhot The desired x-coordinate, in pixels, of the cursor hotspot.
* @param yhot The desired y-coordinate, in pixels, of the cursor hotspot.
* @return created cursor, or nullptr if error occurred.
*/
Cursor*(CARB_ABI* createCursor)(const Image& image, int32_t xhot, int32_t yhot);
/**
* Maximize the window.
*
* @param window The window to use.
*/
void(CARB_ABI* maximizeWindow)(Window* window);
/**
* Minimize the window.
*
* @param window The window to use.
*/
void(CARB_ABI* minimizeWindow)(Window* window);
/**
* Restore the window.
*
* @param window The window to use.
*/
void(CARB_ABI* restoreWindow)(Window* window);
/**
* Sets the function for handling window maximize events.
*
* @param window The window to use.
* @param onWindowMaximizeFn The function callback to handle maximize events on the window.
*/
void(CARB_ABI* setWindowMaximizeFn)(Window* window, OnWindowMaximizeFn onWindowMaximizeFn, void* userData);
/**
* Determines if the window is maximized.
*
* @param window The window to use.
* @return true if the window is maximized, false if it is not.
*/
bool(CARB_ABI* isWindowMaximized)(Window* window);
/**
* This function sets the icon of the specified window.
*
* This function will do nothing when pass a invalid image, i.e. image.width==0 or
* image.height ==0 or image.pixels == nullptr
*
* The image.pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight
* bits per channel with the red channel first. They are arranged canonically
* as packed sequential rows, starting from the top-left corner.
*
* The desired image sizes varies depending on platform and system settings.
* The selected images will be rescaled as needed. Good sizes include 16x16,
* 32x32 and 48x48.
*
* @param window The window to use.
* @param image The desired icon image.
*/
void(CARB_ABI* setWindowIcon)(Window* window, const Image& image);
};
} // namespace windowing
} // namespace carb
| 24,565 | C | 33.166898 | 121 | 0.663953 |
omniverse-code/kit/include/carb/dictionary/DictionaryUtils.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Utility helper functions for common dictionary operations.
#pragma once
#include "../Framework.h"
#include "../InterfaceUtils.h"
#include "../datasource/IDataSource.h"
#include "../extras/CmdLineParser.h"
#include "../filesystem/IFileSystem.h"
#include "../logging/Log.h"
#include "IDictionary.h"
#include "ISerializer.h"
#include <algorithm>
#include <string>
namespace carb
{
/** Namespace for @ref carb::dictionary::IDictionary related interfaces and helpers. */
namespace dictionary
{
/** helper function to retrieve the IDictionary interface.
*
* @returns The cached @ref carb::dictionary::IDictionary interface. This will be cached
* until the plugin is unloaded.
*/
inline IDictionary* getCachedDictionaryInterface()
{
return getCachedInterface<IDictionary>();
}
/** Prototype for a callback function used to walk items in a dictionary.
*
* @tparam ElementData An arbitrary data type used as both a parameter and the return
* value of the callback. The callback itself is assumed to know
* how to interpret and use this value.
* @param[in] srcItem The current item being visited. This will never be `nullptr`.
* @param[in] elementData An arbitrary data object passed into the callback by the caller of
* walkDictionary(). The callback is assumed that it knows how to
* interpret and use this value.
* @param[in] userData An opaque data object passed by the caller of walkDictionary().
* The callback is assumed that it knows how to interpret and use
* this object.
* @returns An \a ElementData object or value to pass back to the dictionary walker. When
* the callback returns from passing in a new dictionary value (ie: a child of the
* original dictionary), this value is stored and passed on to following callbacks.
*/
template <typename ElementData>
using OnItemFn = ElementData (*)(const Item* srcItem, ElementData elementData, void* userData);
/** Prototype for a callback function used to walk children in a dictionary.
*
* @tparam ItemPtrType The data type of the dictionary item in the dictionary being walked.
* This should be either `Item` or `const Item`.
* @param[in] dict The @ref IDictionary interface being used to access the items in the
* dictionary during the walk. This must not be `nullptr`.
* @param[in] item The dictionary item to retrieve one of the child items from. This
* must not be `nullptr`. This is assumed to be an item of type
* @ref ItemType::eDictionary.
* @param[in] idx The zero based index of the child item of @p item to retrieve. This
* is expected to be within the range of the number of children in the
* given dictionary item.
* @returns The child item at the requested index in the given dictionary item @p item. Returns
* `nullptr` if the given index is out of range of the number of children in the given
* dictionary item.
*
* @remarks This callback provides a way to control the order in which the items in a dictionary
* are walked. An basic implementation is provided below.
*/
template <typename ItemPtrType>
inline ItemPtrType* getChildByIndex(IDictionary* dict, ItemPtrType* item, size_t idx);
/** Specialization for the getChildByIndex() callback that implements a simple retrieval of the
* requested child item using @ref IDictionary::getItemChildByIndex().
*
* @sa getChildByIndex(IDictionary*,ItemPtrType*,size_t).
*/
template <>
inline const Item* getChildByIndex(IDictionary* dict, const Item* item, size_t idx)
{
return dict->getItemChildByIndex(item, idx);
}
/** Mode names for the ways to walk the requested dictionary. */
enum class WalkerMode
{
/** When walking the dictionary, include the root item itself. */
eIncludeRoot,
/** When walking the dictionary, skip the root item and start with the enumeration with
* the immediate children of the root item.
*/
eSkipRoot
};
/** Walk a dictionary item to enumerate all of its values.
*
* @tparam ElementData The data type for the per-item element data that is maintained
* during the walk. This can be used for example to track which
* level of the dictionary a given item is at by using an `int`
* type here.
* @tparam OnItemFnType The type for the @p onItemFn callback function.
* @tparam ItemPtrType The type used for the item type in the @p GetChildByIndexFuncType
* callback. This must either be `const Item` or `Item`. This
* defaults to `const Item`. If a non-const type is used here
* it is possible that items' values could be modified during the
* walk. Using a non-const value is discouraged however since it
* can lead to unsafe use or undefined behavior.
* @tparam GetChildByIndexFuncType The type for the @p getChildByIndexFunc callback function.
* @param[in] dict The @ref IDictionary interface to use to access the items
* in the dictionary. This must not be `nullptr`. This must
* be the same interface that was originally used to create
* the dictionary @p root being walked.
* @param[in] walkerMode The mode to walk the given dictionary in.
* @param[in] root The root dictionary to walk. This must not be `nullptr`.
* @param[in] rootElementData The user specified element data value that is to be associated
* with the @p root element. This value can be changed during
* the walk by the @p onItemFn callback function.
* @param[in] onItemFn The callback function that is performed for each value in the
* given dictionary. The user specified element data value can
* be modified on each non-leaf item. This modified element data
* value is then passed to all further children of the given
* item. The element data value returned for leaf items is
* discarded. This must not be `nullptr`.
* @param[in] userData Opaque user data object that is passed to each @p onItemFn
* callback. The caller is responsible for knowing how to
* interpret and access this value.
* @param[in] getChildByIndexFunc Callback function to enumerate the children of a given
* item in the dictionary being walked. This must not be
* `nullptr`. This can be used to either control the order
* in which the child items are enumerated (ie: sort them
* before returning), or to return them as non-const objects
* so that the item's value can be changed during enumeration.
* Attempting to insert or remove items by using a non-const
* child enumerator is unsafe and will generally result in
* undefined behavior.
* @returns No return value.
*
* @remarks This walks a dictionary and enumerates all of its values of all types. This
* includes even @ref ItemType::eDictionary items. Non-leaf items in the walk will
* be passed to the @p onItemFn callback before walking through its children.
* The @p getChildByIndexFunc callback function can be used to control the order in
* which the children of each level of the dictionary are enumerated. The default
* implementation simply enumerates the items in the order they are stored in (which
* is generally arbitrary). The dictionary's full tree is walked in a depth first
* manner so sibling items are not guaranteed to be enumerated consecutively.
*
* @thread_safety This function is thread safe as long as nothing else is concurrently modifying
* the dictionary being walked. It is the caller's responsibility to ensure that
* neither the dictionary nor any of its children will be modified until the walk
* is complete.
*/
template <typename ElementData,
typename OnItemFnType,
typename ItemPtrType = const Item,
typename GetChildByIndexFuncType CARB_NO_DOC(= decltype(getChildByIndex<ItemPtrType>))>
inline void walkDictionary(IDictionary* dict,
WalkerMode walkerMode,
ItemPtrType* root,
ElementData rootElementData,
OnItemFnType onItemFn,
void* userData,
GetChildByIndexFuncType getChildByIndexFunc = getChildByIndex<ItemPtrType>)
{
if (!root)
{
return;
}
struct ValueToParse
{
ItemPtrType* srcItem;
ElementData elementData;
};
std::vector<ValueToParse> valuesToParse;
valuesToParse.reserve(100);
if (walkerMode == WalkerMode::eSkipRoot)
{
size_t numChildren = dict->getItemChildCount(root);
for (size_t chIdx = 0; chIdx < numChildren; ++chIdx)
{
valuesToParse.push_back({ getChildByIndexFunc(dict, root, numChildren - chIdx - 1), rootElementData });
}
}
else
{
valuesToParse.push_back({ root, rootElementData });
}
while (valuesToParse.size())
{
const ValueToParse valueToParse = valuesToParse.back();
ItemPtrType* curItem = valueToParse.srcItem;
ItemType curItemType = dict->getItemType(curItem);
valuesToParse.pop_back();
if (curItemType == ItemType::eDictionary)
{
size_t numChildren = dict->getItemChildCount(curItem);
ElementData elementData = onItemFn(curItem, valueToParse.elementData, userData);
for (size_t chIdx = 0; chIdx < numChildren; ++chIdx)
{
valuesToParse.push_back({ getChildByIndexFunc(dict, curItem, numChildren - chIdx - 1), elementData });
}
}
else
{
onItemFn(curItem, valueToParse.elementData, userData);
}
}
}
/** Attempts to retrieve the name of an item from a given path in a dictionary.
*
* @param[in] dict The @ref IDictionary interface to use to access the items in the
* dictionary. This must not be `nullptr`. This must be the same
* interface that was originally used to create the dictionary
* @p baseItem.
* @param[in] baseItem The base item to retrieve the item name relative to. This is expected
* to contain the child path @p path. This may not be `nullptr`.
* @param[in] path The item path relative to @p baseItem that indicates where to find the
* item whose name should be retrieved. This may be `nullptr` to retrieve
* the name of @p baseItem itself.
* @returns A string containing the name of the item at the given path relative to @p baseItem
* if it exists. Returns an empty string if no item could be found at the requested
* path or a string buffer could not be allocated for its name.
*
* @thread_safety This call is thread safe.
*/
inline std::string getStringFromItemName(const IDictionary* dict, const Item* baseItem, const char* path = nullptr)
{
const Item* item = dict->getItem(baseItem, path);
if (!item)
{
return std::string();
}
const char* itemNameBuf = dict->createStringBufferFromItemName(item);
std::string returnString = itemNameBuf;
dict->destroyStringBuffer(itemNameBuf);
return returnString;
}
/** Attempts to retrieve the value of an item from a given path in a dictionary.
*
* @param[in] dict The @ref IDictionary interface to use to access the items in the
* dictionary. This must not be `nullptr`. This must be the same
* interface that was originally used to create the dictionary
* @p baseItem.
* @param[in] baseItem The base item to retrieve the item value relative to. This is expected
* to contain the child path @p path. This may not be `nullptr`.
* @param[in] path The item path relative to @p baseItem that indicates where to find the
* item whose value should be retrieved. This may be `nullptr` to retrieve
* the value of @p baseItem itself.
* @returns A string containing the value of the item at the given path relative to @p baseItem
* if it exists. If the requested item was not of type @ref ItemType::eString, the
* value will be converted to a string as best it can. Returns an empty string if no
* item could be found at the requested path or a string buffer could not be allocated
* for its name.
*
* @thread_safety This call is thread safe.
*/
inline std::string getStringFromItemValue(const IDictionary* dict, const Item* baseItem, const char* path = nullptr)
{
const Item* item = dict->getItem(baseItem, path);
if (!item)
{
return std::string();
}
const char* stringBuf = dict->createStringBufferFromItemValue(item);
std::string returnString = stringBuf;
dict->destroyStringBuffer(stringBuf);
return returnString;
}
/** Attempts to retrieve an array of string values from a given dictionary path.
*
* @param[in] dict The @ref IDictionary interface to use to access the items in the
* dictionary. This must not be `nullptr`. This must be the same
* interface that was originally used to create the dictionary
* @p baseItem.
* @param[in] baseItem The base item to retrieve the item values relative to. This is expected
* to contain the child path @p path. This may not be `nullptr`.
* @param[in] path The item path relative to @p baseItem that indicates where to find the
* item whose value should be retrieved. This may be `nullptr` to retrieve
* the values of @p baseItem itself. The value at this path is expected to
* be an array of strings.
* @returns A vector of string values for the array at the path @p path relative to @p baseItem.
* If the given path is not an array item, a vector containing a single value will be
* returned. If @p path points to an item that is an array of something other than
* strings, a vector of empty strings will be returned instead.
*
* @thread_safety This call in itself is thread safe, however the retrieved array may contain
* unexpected or incorrect values if another thread is modifying the same item
* in the dictionary simultaneously.
*/
inline std::vector<std::string> getStringArray(const IDictionary* dict, const Item* baseItem, const char* path)
{
const Item* itemAtKey = dict->getItem(baseItem, path);
std::vector<std::string> stringArray(dict->getArrayLength(itemAtKey));
for (size_t i = 0; i < stringArray.size(); i++)
{
stringArray[i] = dict->getStringBufferAt(itemAtKey, i);
}
return stringArray;
}
/** Attempts to retrieve an array of string values from a given dictionary path.
*
* @param[in] dict The @ref IDictionary interface to use to access the items in the
* dictionary. This must not be `nullptr`. This must be the same
* interface that was originally used to create the dictionary
* @p baseItem.
* @param[in] item The base item to retrieve the item values relative to. This is expected
* to contain the child path @p path. This may not be `nullptr`.
* @returns A vector of string values for the array at the path @p path relative to @p baseItem.
* If the given path is not an array item, a vector containing a single value will be
* returned. If @p path points to an item that is an array of something other than
* strings, a vector of empty strings will be returned instead.
*
* @thread_safety This call in itself is thread safe, however the retrieved array may contain
* unexpected or incorrect values if another thread is modifying the same item
* in the dictionary simultaneously.
*/
inline std::vector<std::string> getStringArray(const IDictionary* dict, const Item* item)
{
return getStringArray(dict, item, nullptr);
}
/** Sets an array of values at a given path relative to a dictionary item.
*
* @param[in] dict The @ref IDictionary interface to use to access the items in the
* dictionary. This must not be `nullptr`. This must be the same
* interface that was originally used to create the dictionary
* @p baseItem.
* @param[in] baseItem The base item to act as the root of where to set the values relative
* to. This is expected to contain the child path @p path. This may not
* be `nullptr`.
* @param[in] path The path to the item to set the array of strings in. This path must
* either already exist as an array of strings or be an empty item in the
* dictionary. This may be `nullptr` to set the string array into the
* item @p baseItem itself.
* @param[in] stringArray The array of strings to set in the dictionary. This may contain a
* different number of items than the existing array. If the number of
* items differs, this new array of values will replace the existing
* item at @p path entirely. If the count is the same as the previous
* item, values will simply be replaced.
* @returns No return value.
*
* @thread_safety This call itself is thread safe as long as no other call is trying to
* concurrently modify the same item in the dictionary. Results are undefined
* if another thread is modifying the same item in the dictionary. Similarly,
* undefined behavior may result if another thread is concurrently trying to
* retrieve the items from this same dictionary.
*/
inline void setStringArray(IDictionary* dict, Item* baseItem, const char* path, const std::vector<std::string>& stringArray)
{
Item* itemAtKey = dict->getItemMutable(baseItem, path);
if (dict->getItemType(itemAtKey) != dictionary::ItemType::eCount)
{
dict->destroyItem(itemAtKey);
}
for (size_t i = 0, stringCount = stringArray.size(); i < stringCount; ++i)
{
dict->setStringAt(itemAtKey, i, stringArray[i].c_str());
}
}
/** Sets an array of values at a given path relative to a dictionary item.
*
* @param[in] dict The @ref IDictionary interface to use to access the items in the
* dictionary. This must not be `nullptr`. This must be the same
* interface that was originally used to create the dictionary
* @p baseItem.
* @param[in] item The base item to act as the root of where to set the values relative
* to. This is expected to contain the child path @p path. This may not
* be `nullptr`.
* @param[in] stringArray The array of strings to set in the dictionary. This may contain a
* different number of items than the existing array. If the number of
* items differs, this new array of values will replace the existing
* item at @p path entirely. If the count is the same as the previous
* item, values will simply be replaced.
* @returns No return value.
*
* @thread_safety This call itself is thread safe as long as no other call is trying to
* concurrently modify the same item in the dictionary. Results are undefined
* if another thread is modifying the same item in the dictionary. Similarly,
* undefined behavior may result if another thread is concurrently trying to
* retrieve the items from this same dictionary.
*/
inline void setStringArray(IDictionary* dict, Item* item, const std::vector<std::string>& stringArray)
{
setStringArray(dict, item, nullptr, stringArray);
}
/** Attempts to set a value in a dictionary with an attempt to detect the value type.
*
* @param[in] id The @ref IDictionary interface to use to access the items in the
* dictionary. This must not be `nullptr`. This must be the same
* interface that was originally used to create the dictionary
* @p dict.
* @param[in] dict The base item to act as the root of where to set the value relative
* to. This may not be `nullptr`.
* @param[in] path The path to the item to set the value in. This path does not need to
* exist yet in the dictionary. This may be `nullptr` to create the new
* value in the @p dict item itself.
* @param[in] value The new value to set expressed as a string. An attempt will be made to
* detect the type of the data from the contents of the string. If there
* are surrounding quotation marks, it will be treated as a string. If the
* value is a case insensitive variant on `FALSE` or `TRUE`, it will be
* treated as a boolean value. If the value fully converts to an integer or
* floating point value, it will be treated as those types. Otherwise the
* value is stored unmodified as a string.
* @returns No return value.
*
* @thread_safety This call is thread safe.
*/
inline void setDictionaryElementAutoType(IDictionary* id, Item* dict, const std::string& path, const std::string& value)
{
if (!path.empty())
{
// We should validate that provided path is a proper path but for now we just use it
//
// Simple rules to support basic values:
// if the value starts and with quotes (" or ') then it's the string inside the quotes
// else if we can parse the value as a bool, int or float then we read it
// according to the type. Otherwise we consider it to be a string.
// Special case, if the string is empty, write an empty string early
if (value.empty())
{
constexpr const char* kEmptyString = "";
id->makeStringAtPath(dict, path.c_str(), kEmptyString);
return;
}
if (value.size() > 1 &&
((value.front() == '"' && value.back() == '"') || (value.front() == '\'' && value.back() == '\'')))
{
// string value - chop off quotes
id->makeStringAtPath(dict, path.c_str(), value.substr(1, value.size() - 2).c_str());
return;
}
// Convert the value to upper case to simplify checks
std::string uppercaseValue = value;
std::transform(value.begin(), value.end(), uppercaseValue.begin(),
[](const char c) { return static_cast<char>(::toupper(c)); });
// let's see if it's a boolean
if (uppercaseValue == "TRUE")
{
id->makeBoolAtPath(dict, path.c_str(), true);
return;
}
if (uppercaseValue == "FALSE")
{
id->makeBoolAtPath(dict, path.c_str(), false);
return;
}
// let's see if it's an integer
size_t valueLen = value.length();
char* endptr;
// Use a radix of 0 to allow for decimal, octal, and hexadecimal values to all be parsed.
const long long int valueAsInt = strtoll(value.c_str(), &endptr, 0);
if (endptr - value.c_str() == (ptrdiff_t)valueLen)
{
id->makeInt64AtPath(dict, path.c_str(), valueAsInt);
return;
}
// let's see if it's a float
const double valueAsFloat = strtod(value.c_str(), &endptr);
if (endptr - value.c_str() == (ptrdiff_t)valueLen)
{
id->makeFloat64AtPath(dict, path.c_str(), valueAsFloat);
return;
}
// consider the value to be a string even if it's empty
id->makeStringAtPath(dict, path.c_str(), value.c_str());
}
}
/** Sets a series of values in a dictionary based on keys and values in a map object.
*
* @param[in] id The @ref IDictionary interface to use to access the items in the
* dictionary. This must not be `nullptr`. This must be the same
* interface that was originally used to create the dictionary
* @p dict.
* @param[in] dict The base item to act as the root of where to set the values relative
* to. This may not be `nullptr`.
* @param[in] mapping A map containing item paths (as the map keys) and their values to be
* set in the dictionary.
* @returns No return value.
*
* @remarks This takes a map of path and value pairs and sets those values into the given
* dictionary @p dict. Each entry in the map identifies a potential new value to
* create in the dictionary. The paths to each of the new values do not have to
* already exist in the dictionary. The new items will be created as needed. If
* a given path already exists in the dictionary, its value is replaced with the
* one from the map. All values will attempt to auto-detect their type based on
* the content of the string value. See setDictionaryElementAutoType() for more
* info on how the types are detected.
*
* @note If the map contains entries for an array and the array also exists in the dictionary,
* the resulting dictionary could have more or fewer elements in the array entries if the
* map either contained fewer items than the previous array's size or contained a
* non-consecutive set of numbered elements in the array. If the array already exists in
* the dictionary, it will not be destroyed or removed before adding the new values.
*
* @thread_safety This itself operation is thread safe, but a race condition may still exist
* if multiple threads are trying to set the values for the same set of items
* simultaneously. The operation will succeed, but the value that gets set in
* each item in the end is undefined.
*/
inline void setDictionaryFromStringMapping(IDictionary* id, Item* dict, const std::map<std::string, std::string>& mapping)
{
for (const auto& kv : mapping)
{
setDictionaryElementAutoType(id, dict, kv.first, kv.second);
}
}
/** Parses a set of command line arguments for dictionary items arguments and sets them.
*
* @param[in] id The @ref IDictionary interface to use to access the items in the
* dictionary. This must not be `nullptr`. This must be the same
* interface that was originally used to create the dictionary
* @p dict.
* @param[in] dict The base item to act as the root of where to set the values relative
* to. This may not be `nullptr`.
* @param[in] argv The Unix style argument array for the command line to the process. This
* must not be `nullptr`. The first entry in this array is expected to be
* the process's name. Only the arguments starting with @p prefix will be
* parsed here.
* @param[in] argc The Unix style argument count for the total number of items in @p argv
* to parse.
* @param[in] prefix A string indicating the prefix of arguments that should be parsed by this
* operation. This may not be `nullptr`. Arguments that do not start with
* this prefix will simply be ignored.
* @returns No return value.
*
* @remarks This parses command line arguments to find ones that should be added to a settings
* dictionary. Only arguments beginning with the given prefix will be added. The
* type of each individual item added to the dictionary will be automatically detected
* based on the same criteria used for setDictionaryElementAutoType().
*
* @thread_safety This operation itself is thread safe, but a race condition may still exist
* if multiple threads are trying to set the values for the same set of items
* simultaneously. The operation will succeed, but the value that gets set in
* each item in the end is undefined.
*/
inline void setDictionaryFromCmdLine(IDictionary* id, Item* dict, char** argv, int argc, const char* prefix = "--/")
{
carb::extras::CmdLineParser cmdLineParser(prefix);
cmdLineParser.parse(argv, argc);
const std::map<std::string, std::string>& opts = cmdLineParser.getOptions();
setDictionaryFromStringMapping(id, dict, opts);
}
/** Parses a string representation of an array and sets it relative to a dictionary path.
*
* @param[in] dictionaryInterface The @ref IDictionary interface to use to access the items in
* the dictionary. This must not be `nullptr`. This must be the
* same interface that was originally used to create the
* dictionary @p targetDictionary.
* @param[in] targetDictionary The base item to act as the root of where to set the values
* relative to. This may not be `nullptr`.
* @param[in] elementPath The path to the item to set the values in. This path does not
* need to exist yet in the dictionary. This may be an empty
* string to create the new values in the @p dict item itself.
* Any item at this path will be completely overwritten by this
* operation.
* @param[in] elementValue The string containing the values to parse for the new array
* value. These are expected to be expressed in the format
* "[<value1>, <value2>, <value3>, ...]" (ie: all values enclosed
* in a single set of square brackets with each individual value
* separated by commas). Individual value strings may not
* contain a comma (even if escaped or surrounded by quotation
* marks) otherwise they will be seen as separate values and
* likely not set appropriately in the dictionary. This must
* not be an empty string and must contain at least the square
* brackets at either end of the string.
* @returns No return value.
*
* @remarks This parses an array of values from a string into a dictionary array item. The array
* string is expected to have the format "[<value1>, <value2>, <value3>, ...]". Quoted
* values are not respected if they contain internal commas (the comma is still seen as
* a value separator in this case). Each value parsed from the array will be set in the
* dictionary item with its data type detected from its content. This detection is done
* in the same manner as in setDictionaryElementAutoType().
*
* @thread_safety This call itself is thread safe. However, if another thread is simultaneously
* attempting to modify, retrieve, or delete items or values in the same branch of
* the dictionary, the results may be undefined.
*/
inline void setDictionaryArrayElementFromStringValue(dictionary::IDictionary* dictionaryInterface,
dictionary::Item* targetDictionary,
const std::string& elementPath,
const std::string& elementValue)
{
if (elementPath.empty())
{
return;
}
CARB_ASSERT(elementValue.size() >= 2 && elementValue.front() == '[' && elementValue.back() == ']');
// Force delete item if it exists before creating a new array
dictionary::Item* arrayItem = dictionaryInterface->getItemMutable(targetDictionary, elementPath.c_str());
if (arrayItem)
{
dictionaryInterface->destroyItem(arrayItem);
}
// Creating a new dictionary element at the required path
arrayItem = dictionaryInterface->makeDictionaryAtPath(targetDictionary, elementPath.c_str());
// Setting necessary flag to make it a proper empty array
// This will result in correct item replacement in case of dictionary merging
dictionaryInterface->setItemFlag(arrayItem, dictionary::ItemFlag::eUnitSubtree, true);
// Skip initial and the last square brackets and consider all elements separated by commas one by one
// For each value create corresponding new path including index
// Ex. "/some/path=[10,20]" will be processed as "/some/path/0=10" and "/some/path/1=20"
const std::string commonElementPath = elementPath + '/';
size_t curElementIndex = 0;
// Helper adds provided value into the dictionary and increases index for the next addition
auto dictElementAddHelper = [&](std::string value) {
carb::extras::trimStringInplace(value);
// Processing only non empty strings, empty string values should be stated as "": [ "a", "", "b" ]
if (value.empty())
{
CARB_LOG_WARN(
"Encountered and skipped an empty value for dictionary array element '%s' while parsing value '%s'",
elementPath.c_str(), elementValue.c_str());
return;
}
carb::dictionary::setDictionaryElementAutoType(
dictionaryInterface, targetDictionary, commonElementPath + std::to_string(curElementIndex), value);
++curElementIndex;
};
std::string::size_type curValueStartPos = 1;
// Add comma-separated values (except for the last one)
for (std::string::size_type curCommaPos = elementValue.find(',', curValueStartPos);
curCommaPos != std::string::npos; curCommaPos = elementValue.find(',', curValueStartPos))
{
dictElementAddHelper(elementValue.substr(curValueStartPos, curCommaPos - curValueStartPos));
curValueStartPos = curCommaPos + 1;
}
// Now only the last value is left for addition
std::string lastValue = elementValue.substr(curValueStartPos, elementValue.size() - curValueStartPos - 1);
carb::extras::trimStringInplace(lastValue);
// Do nothing if it's just a trailing comma: [ 1, 2, 3, ]
if (!lastValue.empty())
{
carb::dictionary::setDictionaryElementAutoType(
dictionaryInterface, targetDictionary, commonElementPath + std::to_string(curElementIndex), lastValue);
}
}
/** Attempts to read the contents of a file into a dictionary.
*
* @param[in] serializer The @ref ISerializer interface to use to parse the data in the file.
* This serializer must be able to parse the assumed format of the named
* file (ie: JSON or TOML). This must not be `nullptr`. Note that this
* interface will internally depend on only a single implementation of
* the @ref IDictionary interface having been loaded. If multiple
* implementations are available, this operation will be likely to
* result in undefined behavior.
* @param[in] filename The name of the file to parse in the format assumed by the serializer
* interface @p serializer. This must not be `nullptr`.
* @returns A new dictionary item containing the information parsed from the file @p filename if
* it is successfully opened, read, and parsed. When no longer needed, this must be
* passed to @ref IDictionary::destroyItem() to destroy it. Returns `nullptr` if the
* file does not exit, could not be opened, or a parsing error occurred.
*
* @remarks This attempts to parse a dictionary data from a file. The format that the file's
* data is parsed from will be implied by the specific implementation of the @ref
* ISerializer interface that is passed in. The data found in the file will be parsed
* into a full dictionary hierarchy if it is parsed correctly. If the file contains
* a syntax error, the specific result (ie: full failure vs partial success) is
* determined by the specific behavior of the @ref ISerializer interface.
*
* @thread_safety This operation is thread safe.
*/
inline Item* createDictionaryFromFile(ISerializer* serializer, const char* filename)
{
carb::filesystem::IFileSystem* fs = carb::getCachedInterface<carb::filesystem::IFileSystem>();
auto file = fs->openFileToRead(filename);
if (!file)
return nullptr;
const size_t fileSize = fs->getFileSize(file);
const size_t contentLen = fileSize + 1;
std::unique_ptr<char[]> heap;
char* content;
if (contentLen <= 4096)
{
content = CARB_STACK_ALLOC(char, contentLen);
}
else
{
heap.reset(new char[contentLen]);
content = heap.get();
}
const size_t readBytes = fs->readFileChunk(file, content, contentLen);
fs->closeFile(file);
if (readBytes != fileSize)
{
CARB_LOG_ERROR("Only read %zu bytes of a total of %zu bytes from file '%s'", readBytes, fileSize, filename);
}
// NUL terminate
content[readBytes] = '\0';
return serializer->createDictionaryFromStringBuffer(content, readBytes, fDeserializerOptionInSitu);
}
/** Writes the contents of a dictionary to a file.
*
* @param[in] serializer The @ref ISerializer interface to use to format the dictionary
* data before writing it to file. This may not be `nullptr`.
* @param[in] dictionary The dictionary root item to format and write to file. This
* not be `nullptr`. This must have been created by the same
* @ref IDictionary interface that @p serializer uses internally.
* @param[in] filename The name of the file to write the formatted dictionary data
* to. This file will be unconditionally overwritten. It is the
* caller's responsibility to ensure any previous file at this
* location can be safely overwritten. This must not be
* `nullptr`.
* @param[in] serializerOptions Option flags passed to the @p serializer interface when
* formatting the dictionary data.
* @returns No return value.
*
* @remarks This formats the contents of a dictionary to a string and writes it to a file. The
* file will be formatted according to the serializer interface that is used. The
* extra flag options passed to the serializer in @p serializerOptions control the
* specifics of the formatting. The formatted data will be written to the file as
* long as it can be opened successfully for writing.
*
* @thread_safety This operation itself is thread safe. However, if another thread is attempting
* to modify the dictionary @p dictionary at the same time, a race condition may
* exist and undefined behavior could occur. It won't crash but the written data
* may be unexpected.
*/
inline void saveFileFromDictionary(ISerializer* serializer,
const dictionary::Item* dictionary,
const char* filename,
SerializerOptions serializerOptions)
{
const char* serializedString = serializer->createStringBufferFromDictionary(dictionary, serializerOptions);
filesystem::IFileSystem* fs = getFramework()->acquireInterface<filesystem::IFileSystem>();
filesystem::File* sFile = fs->openFileToWrite(filename);
if (sFile == nullptr)
{
CARB_LOG_ERROR("failed to open file '%s' - unable to save the dictionary", filename);
return;
}
fs->writeFileChunk(sFile, serializedString, strlen(serializedString));
fs->closeFile(sFile);
serializer->destroyStringBuffer(serializedString);
}
/** Writes a dictionary to a string.
*
* @param[in] c The dictionary to be serialized. This must not be `nullptr`.
* This dictionary must have been created by the same dictionary
* interface that the serializer will use. The serializer that is
* used controls how the string is formatted.
* @param[in] serializerName The name of the serializer plugin to use. This must be the name
* of the serializer plugin to be potentially loaded and used. For
* example, "carb.dictionary.serializer-json.plugin" to serialize to
* use the JSON serializer. The serializer plugin must already be
* known to the framework. This may be `nullptr` to pick the first
* or best serializer plugin instead. If the serializer plugin with
* this name cannot be found or the @ref ISerializer interface
* cannot be acquired from it, the first loaded serializer interface
* will be acquired and used instead.
* @returns A string containing the human readable contents of the dictionary @p c. If the
* dictionary failed to be written, an empty string will be returned but the operation
* will still be considered successful. The dictionary will always be formatted using
* the @ref fSerializerOptionMakePretty flag so that it is as human-readable as
* possible.
*
* @thread_safety This operation itself is thread safe. However, if the dictionary @p c is
* being modified concurrently by another thread, the output contents may be
* unexpected.
*/
inline std::string dumpToString(const dictionary::Item* c, const char* serializerName = nullptr)
{
std::string serializedDictionary;
Framework* framework = carb::getFramework();
dictionary::ISerializer* configSerializer = nullptr;
// First, try to acquire interface with provided plugin name, if any
if (serializerName)
{
configSerializer = framework->tryAcquireInterface<dictionary::ISerializer>(serializerName);
}
// If not available, or plugin name is not provided, try to acquire any serializer interface
if (!configSerializer)
{
configSerializer = framework->tryAcquireInterface<dictionary::ISerializer>();
}
const char* configString =
configSerializer->createStringBufferFromDictionary(c, dictionary::fSerializerOptionMakePretty);
if (configString != nullptr)
{
serializedDictionary = configString;
configSerializer->destroyStringBuffer(configString);
}
return serializedDictionary;
};
/** Retrieves the full path to dictionary item from its top-most ancestor.
*
* @param[in] dict The @ref IDictionary interface to use to retrieve the full path to the
* requested dictionary item. This must not be `nullptr`.
* @param[in] item The dictionary item to retrieve the full path to. This may not be `nullptr`.
* This item must have been created by the same @ref IDictionary interface passed
* in as @p dict.
* @returns A string containing the full path to the dictionary item @p item. This path will be
* relative to its top-most ancestor. On failure, an empty string is returned.
*
* @thread_safety This operation itself is thread safe. However, if the item or its chain of
* ancestors is being modified concurrently, undefined behavior may result.
*/
inline std::string getItemFullPath(dictionary::IDictionary* dict, const carb::dictionary::Item* item)
{
if (!item)
{
return std::string();
}
std::vector<const char*> pathElementsNames;
while (item)
{
pathElementsNames.push_back(dict->getItemName(item));
item = dict->getItemParent(item);
}
size_t totalSize = 0;
for (const auto& elementName : pathElementsNames)
{
totalSize += 1; // the '/' separator
if (elementName)
{
totalSize += std::strlen(elementName);
}
}
std::string result;
result.reserve(totalSize);
for (size_t idx = 0, elementCount = pathElementsNames.size(); idx < elementCount; ++idx)
{
const char* elementName = pathElementsNames[elementCount - idx - 1];
result += '/';
if (elementName)
{
result += elementName;
}
}
return result;
}
/** Helper function to convert a data type to a corresponding dictionary item type.
*
* @tparam Type The primitive data type to convert to a dictionary item type. This operation
* is undefined for types other than the handful of primitive types it is
* explicitly specialized for. If a another data type is used here, a link
* link error will occur.
* @returns The dictionary item type corresponding to the templated primitive data type.
*
* @thread_safety This operation is thread safe.
*/
template <typename Type>
inline ItemType toItemType();
/** Specialization for an `int32_t` item value.
* @copydoc toItemType().
*/
template <>
inline ItemType toItemType<int32_t>()
{
return ItemType::eInt;
}
/** Specialization for an `int64_t` item value.
* @copydoc toItemType().
*/
template <>
inline ItemType toItemType<int64_t>()
{
return ItemType::eInt;
}
/** Specialization for an `float` item value.
* @copydoc toItemType().
*/
template <>
inline ItemType toItemType<float>()
{
return ItemType::eFloat;
}
/** Specialization for an `double` item value.
* @copydoc toItemType().
*/
template <>
inline ItemType toItemType<double>()
{
return ItemType::eFloat;
}
/** Specialization for an `bool` item value.
* @copydoc toItemType().
*/
template <>
inline ItemType toItemType<bool>()
{
return ItemType::eBool;
}
/** Specialization for an `char*` item value.
* @copydoc toItemType().
*/
template <>
inline ItemType toItemType<char*>()
{
return ItemType::eString;
}
/** Specialization for an `const char*` item value.
* @copydoc toItemType().
*/
template <>
inline ItemType toItemType<const char*>()
{
return ItemType::eString;
}
/** Unsubscribes all items in a dictionary tree from change notifications.
*
* @param[in] dict The @ref IDictionary interface to use when walking the dictionary. This must
* not be `nullptr`. This must be the same @ref IDictionary interface that was
* used to create the dictionary item @p item.
* @param[in] item The dictionary item to unsubscribe all nodes from change notifications. This
* must not be `nullptr`. Each item in this dictionary's tree will have all of
* its tree and node change subscriptions removed.
* @returns No return value.
*
* @remarks This removes all change notification subscriptions for an entire tree in a
* dictionary. This should only be used as a last cleanup effort to prevent potential
* shutdown crashes since it will even remove subscriptions that the caller didn't
* necessarily setup.
*
* @thread_safety This operation is thread safe.
*/
inline void unsubscribeTreeFromAllEvents(IDictionary* dict, Item* item)
{
auto unsubscribeItem = [](Item* srcItem, uint32_t elementData, void* userData) -> uint32_t {
IDictionary* dict = (IDictionary*)userData;
dict->unsubscribeItemFromNodeChangeEvents(srcItem);
dict->unsubscribeItemFromTreeChangeEvents(srcItem);
return elementData;
};
const auto getChildByIndexMutable = [](IDictionary* dict, Item* item, size_t index) {
return dict->getItemChildByIndexMutable(item, index);
};
walkDictionary(dict, WalkerMode::eIncludeRoot, item, 0, unsubscribeItem, dict, getChildByIndexMutable);
}
/** Helper function for IDictionary::update() that ensures arrays are properly overwritten.
*
* @param[in] dstItem The destination dictionary item for the merge operation. This
* may be `nullptr` if the destination item doesn't already exist
* in the tree (ie: a new item is being merged into the tree).
* @param[in] dstItemType The data type of the item @p dstItem. If @p dstItem is
* `nullptr`, this will be @ref ItemType::eCount.
* @param[in] srcItem The source dictionary item for the merge operation. This will
* never be `nullptr`. This will be the new value or node that
* is being merged into the dictionary tree.
* @param[in] srcItemType The data type of the item @p srcItem.
* @param[in] dictionaryInterface The @ref IDictionary interface to use when merging the new
* item into the dictionary tree. This is expected to be passed
* into the @a userData parameter for IDictionary::update().
* @returns an @ref UpdateAction value indicating how the merge operation should proceed.
*
* @remarks This is intended to be used as the @ref OnUpdateItemFn callback function for the
* @ref IDictionary::update() function when the handling of merging array items is
* potentially needed. When this is used, the @ref IDictionary interface object must
* be passed into the @a userData parameter of IDictionary::update().
*
* @thread_safety This operation is thread safe. However, this call isn't expected to be used
* directly, but rather through the IDictionary::update() function. The overall
* thread safety of that operation should be noted instead.
*/
inline UpdateAction overwriteOriginalWithArrayHandling(
const Item* dstItem, ItemType dstItemType, const Item* srcItem, ItemType srcItemType, void* dictionaryInterface)
{
CARB_UNUSED(dstItemType, srcItemType);
if (dstItem && dictionaryInterface)
{
carb::dictionary::IDictionary* dictInt = static_cast<carb::dictionary::IDictionary*>(dictionaryInterface);
if (dictInt->getItemFlag(srcItem, carb::dictionary::ItemFlag::eUnitSubtree))
{
return carb::dictionary::UpdateAction::eReplaceSubtree;
}
}
return carb::dictionary::UpdateAction::eOverwrite;
}
} // namespace dictionary
} // namespace carb
| 53,296 | C | 49.904489 | 124 | 0.627402 |
omniverse-code/kit/include/carb/dictionary/DictionaryBindingsPython.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../BindingsPythonUtils.h"
#include "../cpp/Optional.h"
#include "DictionaryUtils.h"
#include "IDictionary.h"
#include "ISerializer.h"
#include <memory>
#include <vector>
namespace carb
{
namespace dictionary
{
struct Item
{
};
} // namespace dictionary
} // namespace carb
namespace carb
{
namespace dictionary
{
template <typename T>
inline py::tuple toTuple(const std::vector<T>& v)
{
py::tuple tuple(v.size());
for (size_t i = 0; i < v.size(); i++)
tuple[i] = v[i];
return tuple;
}
// Prerequisites: dictionary lock must be held followed by GIL
inline py::object getPyObjectLocked(dictionary::ScopedRead& lock,
const dictionary::IDictionary* idictionary,
const Item* baseItem,
const char* path = "")
{
CARB_ASSERT(baseItem);
const Item* item = path && *path != '\0' ? idictionary->getItem(baseItem, path) : baseItem;
ItemType itemType = idictionary->getItemType(item);
switch (itemType)
{
case ItemType::eInt:
{
return py::int_(idictionary->getAsInt64(item));
}
case ItemType::eFloat:
{
return py::float_(idictionary->getAsFloat64(item));
}
case ItemType::eBool:
{
return py::bool_(idictionary->getAsBool(item));
}
case ItemType::eString:
{
return py::str(getStringFromItemValue(idictionary, item));
}
case ItemType::eDictionary:
{
size_t const arrayLength = idictionary->getArrayLength(item);
if (arrayLength > 0)
{
py::tuple v(arrayLength);
bool needsList = false;
for (size_t idx = 0; idx != arrayLength; ++idx)
{
v[idx] = getPyObjectLocked(lock, idictionary, idictionary->getItemChildByIndex(item, idx));
if (py::isinstance<py::dict>(v[idx]))
{
// The old code would return a list of dictionaries, but a tuple of everything else. *shrug*
needsList = true;
}
}
if (needsList)
{
return py::list(std::move(v));
}
return v;
}
else
{
size_t childCount = idictionary->getItemChildCount(item);
py::dict v;
for (size_t idx = 0; idx < childCount; ++idx)
{
const dictionary::Item* childItem = idictionary->getItemChildByIndex(item, idx);
if (childItem)
{
v[idictionary->getItemName(childItem)] = getPyObjectLocked(lock, idictionary, childItem);
}
}
return v;
}
}
default:
return py::none();
}
}
inline py::object getPyObject(const dictionary::IDictionary* idictionary, const Item* baseItem, const char* path = "")
{
if (!baseItem)
{
return py::none();
}
// We need both the dictionary lock and the GIL, but we should take the GIL last, so release the GIL temporarily,
// grab the dictionary lock and then re-lock the GIL by resetting the optional<>.
cpp::optional<py::gil_scoped_release> nogil{ cpp::in_place };
dictionary::ScopedRead readLock(*idictionary, baseItem);
nogil.reset();
return getPyObjectLocked(readLock, idictionary, baseItem, path);
}
inline void setPyObject(dictionary::IDictionary* idictionary, Item* baseItem, const char* path, const py::handle& value)
{
auto createDict = [](dictionary::IDictionary* idictionary, Item* baseItem, const char* path, const py::handle& value) {
py::dict valueDict = value.cast<py::dict>();
for (auto kv : valueDict)
{
std::string basePath = path ? path : "";
if (!basePath.empty())
basePath = basePath + "/";
std::string subPath = basePath + kv.first.cast<std::string>().c_str();
setPyObject(idictionary, baseItem, subPath.c_str(), kv.second);
}
};
if (py::isinstance<py::bool_>(value))
{
auto val = value.cast<bool>();
py::gil_scoped_release nogil;
idictionary->makeBoolAtPath(baseItem, path, val);
}
else if (py::isinstance<py::int_>(value))
{
auto val = value.cast<int64_t>();
py::gil_scoped_release nogil;
idictionary->makeInt64AtPath(baseItem, path, val);
}
else if (py::isinstance<py::float_>(value))
{
auto val = value.cast<double>();
py::gil_scoped_release nogil;
idictionary->makeFloat64AtPath(baseItem, path, val);
}
else if (py::isinstance<py::str>(value))
{
auto val = value.cast<std::string>();
py::gil_scoped_release nogil;
idictionary->makeStringAtPath(baseItem, path, val.c_str());
}
else if (py::isinstance<py::tuple>(value) || py::isinstance<py::list>(value))
{
Item* item;
py::sequence valueSeq = value.cast<py::sequence>();
{
py::gil_scoped_release nogil;
item = idictionary->makeDictionaryAtPath(baseItem, path);
idictionary->deleteChildren(item);
}
for (size_t idx = 0, valueSeqSize = valueSeq.size(); idx < valueSeqSize; ++idx)
{
py::object valueSeqElement = valueSeq[idx];
if (py::isinstance<py::bool_>(valueSeqElement))
{
auto val = valueSeqElement.cast<bool>();
py::gil_scoped_release nogil;
idictionary->setBoolAt(item, idx, val);
}
else if (py::isinstance<py::int_>(valueSeqElement))
{
auto val = valueSeqElement.cast<int64_t>();
py::gil_scoped_release nogil;
idictionary->setInt64At(item, idx, val);
}
else if (py::isinstance<py::float_>(valueSeqElement))
{
auto val = valueSeqElement.cast<double>();
py::gil_scoped_release nogil;
idictionary->setFloat64At(item, idx, val);
}
else if (py::isinstance<py::str>(valueSeqElement))
{
auto val = valueSeqElement.cast<std::string>();
py::gil_scoped_release nogil;
idictionary->setStringAt(item, idx, val.c_str());
}
else if (py::isinstance<py::dict>(valueSeqElement))
{
std::string basePath = path ? path : "";
std::string elemPath = basePath + "/" + std::to_string(idx);
createDict(idictionary, baseItem, elemPath.c_str(), valueSeqElement);
}
else
{
CARB_LOG_WARN("Unknown type in sequence being written to item");
}
}
}
else if (py::isinstance<py::dict>(value))
{
createDict(idictionary, baseItem, path, value);
}
}
inline carb::dictionary::IDictionary* getDictionary()
{
return getCachedInterfaceForBindings<carb::dictionary::IDictionary>();
}
inline void definePythonModule(py::module& m)
{
using namespace carb;
using namespace carb::dictionary;
m.doc() = "pybind11 carb.dictionary bindings";
py::enum_<ItemType>(m, "ItemType")
.value("BOOL", ItemType::eBool)
.value("INT", ItemType::eInt)
.value("FLOAT", ItemType::eFloat)
.value("STRING", ItemType::eString)
.value("DICTIONARY", ItemType::eDictionary)
.value("COUNT", ItemType::eCount);
py::enum_<UpdateAction>(m, "UpdateAction").value("OVERWRITE", UpdateAction::eOverwrite).value("KEEP", UpdateAction::eKeep);
py::class_<Item>(m, "Item")
.def("__getitem__", [](const Item& self, const char* path) { return getPyObject(getDictionary(), &self, path); })
.def("__setitem__",
[](Item& self, const char* path, py::object value) { setPyObject(getDictionary(), &self, path, value); })
.def("__len__", [](Item& self) { return getDictionary()->getItemChildCount(&self); },
py::call_guard<py::gil_scoped_release>())
.def("get",
[](const Item& self, const char* path, py::object defaultValue) {
py::object v = getPyObject(getDictionary(), &self, path);
return v.is_none() ? defaultValue : v;
})
.def("get_key_at",
[](const Item& self, size_t index) -> py::object {
cpp::optional<std::string> name;
{
py::gil_scoped_release nogil;
dictionary::ScopedRead readlock(*getDictionary(), &self);
auto child = getDictionary()->getItemChildByIndex(&self, index);
if (child)
name.emplace(getDictionary()->getItemName(child));
}
if (name)
return py::str(name.value());
return py::none();
})
.def("__contains__",
[](const Item& self, py::object value) -> bool {
auto name = value.cast<std::string>();
py::gil_scoped_release nogil;
dictionary::ScopedRead readlock(*getDictionary(), &self);
ItemType type = getDictionary()->getItemType(&self);
if (type != ItemType::eDictionary)
return false;
return getDictionary()->getItem(&self, name.c_str()) != nullptr;
})
.def("get_keys",
[](const Item& self) {
IDictionary* idictionary = getDictionary();
dictionary::ScopedRead readlock(*idictionary, &self);
std::vector<std::string> keys(idictionary->getItemChildCount(&self));
for (size_t i = 0; i < keys.size(); i++)
{
const Item* child = idictionary->getItemChildByIndex(&self, i);
if (child)
keys[i] = idictionary->getItemName(child);
}
return keys;
},
py::call_guard<py::gil_scoped_release>())
.def("clear", [](Item& self) { getDictionary()->deleteChildren(&self); },
py::call_guard<py::gil_scoped_release>())
.def("get_dict", [](Item& self) { return getPyObject(getDictionary(), &self, nullptr); })
.def("__str__", [](Item& self) { return py::str(getPyObject(getDictionary(), &self, nullptr)); })
.def("__repr__", [](Item& self) {
return py::str("carb.dictionary.Item({0})").format(getPyObject(getDictionary(), &self, nullptr));
});
using UpdateFunctionWrapper =
ScriptCallbackRegistryPython<void*, dictionary::UpdateAction, const dictionary::Item*, dictionary::ItemType,
const dictionary::Item*, dictionary::ItemType>;
defineInterfaceClass<IDictionary>(m, "IDictionary", "acquire_dictionary_interface")
.def("get_dict_copy", getPyObject,
R"(
Creates python object from the supplied dictionary at path (supplied item is unchanged). Item is calculated
via the path relative to the base item.
Args:
base_item: The base item.
path: Path, relative to the base item - to the item
Returns:
Python object with copies of the item data.)",
py::arg("base_item"), py::arg("path") = "")
.def("get_item", wrapInterfaceFunction(&IDictionary::getItem), py::arg("base_item"), py::arg("path") = "",
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>())
.def("get_item_mutable", wrapInterfaceFunction(&IDictionary::getItemMutable), py::arg("base_item"),
py::arg("path") = "", py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>())
.def("get_item_child_count", wrapInterfaceFunction(&IDictionary::getItemChildCount),
py::call_guard<py::gil_scoped_release>())
.def("get_item_child_by_index", wrapInterfaceFunction(&IDictionary::getItemChildByIndex),
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>())
.def("get_item_child_by_index_mutable", wrapInterfaceFunction(&IDictionary::getItemChildByIndexMutable),
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>())
.def("get_item_parent", wrapInterfaceFunction(&IDictionary::getItemParent), py::return_value_policy::reference,
py::call_guard<py::gil_scoped_release>())
.def("get_item_parent_mutable", wrapInterfaceFunction(&IDictionary::getItemParentMutable),
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>())
.def("get_item_type", wrapInterfaceFunction(&IDictionary::getItemType), py::call_guard<py::gil_scoped_release>())
.def("get_item_name",
[](const dictionary::IDictionary* idictionary, const Item* baseItem, const char* path) {
return getStringFromItemName(idictionary, baseItem, path);
},
py::arg("base_item"), py::arg("path") = "", py::call_guard<py::gil_scoped_release>())
.def("create_item",
[](const dictionary::IDictionary* idictionary, const py::object& item, const char* path,
dictionary::ItemType itemType) {
Item* p = item.is_none() ? nullptr : item.cast<Item*>();
py::gil_scoped_release nogil;
return idictionary->createItem(p, path, itemType);
},
py::return_value_policy::reference)
.def("is_accessible_as", wrapInterfaceFunction(&IDictionary::isAccessibleAs),
py::call_guard<py::gil_scoped_release>())
.def("is_accessible_as_array_of", wrapInterfaceFunction(&IDictionary::isAccessibleAsArrayOf),
py::call_guard<py::gil_scoped_release>())
.def("get_array_length", wrapInterfaceFunction(&IDictionary::getArrayLength),
py::call_guard<py::gil_scoped_release>())
.def("get_preferred_array_type", wrapInterfaceFunction(&IDictionary::getPreferredArrayType),
py::call_guard<py::gil_scoped_release>())
.def("get_as_int", wrapInterfaceFunction(&IDictionary::getAsInt64), py::call_guard<py::gil_scoped_release>())
.def("set_int", wrapInterfaceFunction(&IDictionary::setInt64), py::call_guard<py::gil_scoped_release>())
.def("get_as_float", wrapInterfaceFunction(&IDictionary::getAsFloat64), py::call_guard<py::gil_scoped_release>())
.def("set_float", wrapInterfaceFunction(&IDictionary::setFloat64), py::call_guard<py::gil_scoped_release>())
.def("get_as_bool", wrapInterfaceFunction(&IDictionary::getAsBool), py::call_guard<py::gil_scoped_release>())
.def("set_bool", wrapInterfaceFunction(&IDictionary::setBool), py::call_guard<py::gil_scoped_release>())
.def("get_as_string",
[](const dictionary::IDictionary* idictionary, const Item* baseItem, const char* path) {
return getStringFromItemValue(idictionary, baseItem, path);
},
py::arg("base_item"), py::arg("path") = "", py::call_guard<py::gil_scoped_release>())
.def("set_string",
[](dictionary::IDictionary* idictionary, Item* item, const std::string& str) {
idictionary->setString(item, str.c_str());
},
py::call_guard<py::gil_scoped_release>())
.def("get", &getPyObject, py::arg("base_item"), py::arg("path") = "")
.def("set", &setPyObject, py::arg("item"), py::arg("path") = "", py::arg("value"))
.def("set_int_array",
[](const dictionary::IDictionary* idictionary, Item* item, const std::vector<int64_t>& v) {
idictionary->setInt64Array(item, v.data(), v.size());
},
py::call_guard<py::gil_scoped_release>())
.def("set_float_array",
[](const dictionary::IDictionary* idictionary, Item* item, const std::vector<double>& v) {
idictionary->setFloat64Array(item, v.data(), v.size());
},
py::call_guard<py::gil_scoped_release>())
.def("set_bool_array",
[](const dictionary::IDictionary* idictionary, Item* item, const std::vector<bool>& v) {
if (v.size() == 0)
return;
bool* pbool = CARB_STACK_ALLOC(bool, v.size());
for (size_t i = 0; i != v.size(); ++i)
pbool[i] = v[i];
idictionary->setBoolArray(item, pbool, v.size());
},
py::call_guard<py::gil_scoped_release>())
.def("set_string_array",
[](const dictionary::IDictionary* idictionary, Item* item, const std::vector<std::string>& v) {
if (v.size() == 0)
return;
const char** pstr = CARB_STACK_ALLOC(const char*, v.size());
for (size_t i = 0; i != v.size(); ++i)
pstr[i] = v[i].c_str();
idictionary->setStringArray(item, pstr, v.size());
},
py::call_guard<py::gil_scoped_release>())
.def("destroy_item", wrapInterfaceFunction(&IDictionary::destroyItem), py::call_guard<py::gil_scoped_release>())
.def("update",
[](dictionary::IDictionary* idictionary, dictionary::Item* dstItem, const char* dstPath,
const dictionary::Item* srcItem, const char* srcPath, const py::object& updatePolicy) {
if (py::isinstance<dictionary::UpdateAction>(updatePolicy))
{
dictionary::UpdateAction updatePolicyEnum = updatePolicy.cast<dictionary::UpdateAction>();
py::gil_scoped_release nogil;
if (updatePolicyEnum == dictionary::UpdateAction::eOverwrite)
{
idictionary->update(dstItem, dstPath, srcItem, srcPath, dictionary::overwriteOriginal, nullptr);
}
else if (updatePolicyEnum == dictionary::UpdateAction::eKeep)
{
idictionary->update(dstItem, dstPath, srcItem, srcPath, dictionary::keepOriginal, nullptr);
}
else
{
CARB_LOG_ERROR("Unknown update policy type");
}
}
else
{
const UpdateFunctionWrapper::FuncT updateFn =
updatePolicy.cast<const UpdateFunctionWrapper::FuncT>();
py::gil_scoped_release nogil;
idictionary->update(
dstItem, dstPath, srcItem, srcPath, UpdateFunctionWrapper::call, (void*)&updateFn);
}
})
.def("readLock", wrapInterfaceFunction(&IDictionary::readLock), py::call_guard<py::gil_scoped_release>())
.def("writeLock", wrapInterfaceFunction(&IDictionary::writeLock), py::call_guard<py::gil_scoped_release>())
.def("unlock", wrapInterfaceFunction(&IDictionary::unlock), py::call_guard<py::gil_scoped_release>());
carb::defineInterfaceClass<ISerializer>(m, "ISerializer", "acquire_serializer_interface")
.def("create_dictionary_from_file", &createDictionaryFromFile, py::arg("path"),
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>())
.def("create_dictionary_from_string_buffer",
[](ISerializer* self, std::string val) {
return self->createDictionaryFromStringBuffer(
val.data(), val.size(), carb::dictionary::fDeserializerOptionInSitu);
},
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>())
.def("create_string_buffer_from_dictionary",
[](ISerializer* self, const carb::dictionary::Item* dictionary, SerializerOptions serializerOptions) {
const char* buf = self->createStringBufferFromDictionary(dictionary, serializerOptions);
std::string ret = buf; // Copy
self->destroyStringBuffer(buf);
return ret;
},
py::arg("item"), py::arg("ser_options") = 0, py::call_guard<py::gil_scoped_release>())
.def("save_file_from_dictionary", &saveFileFromDictionary, py::arg("dict"), py::arg("path"),
py::arg("options") = 0, py::call_guard<py::gil_scoped_release>());
m.def("get_toml_serializer",
[]() {
static ISerializer* s_serializer =
carb::getFramework()->acquireInterface<ISerializer>("carb.dictionary.serializer-toml.plugin");
return s_serializer;
},
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>());
m.def("get_json_serializer",
[]() {
static ISerializer* s_serializer =
carb::getFramework()->acquireInterface<ISerializer>("carb.dictionary.serializer-json.plugin");
return s_serializer;
},
py::return_value_policy::reference, py::call_guard<py::gil_scoped_release>());
}
} // namespace dictionary
} // namespace carb
| 22,161 | C | 45.170833 | 127 | 0.561076 |
omniverse-code/kit/include/carb/dictionary/ISerializer.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Interface to handle serializing data from a file format into an
//! @ref carb::dictionary::IDictionary item. This interface is
//! currently implemented in two plugins, each offering a different
//! input/output format - JSON and TOML. The plugins are called
//! `carb.dictionary.serializer-json.plugin` and
//! `carb.dictionary.serializer-toml.plugin`. The caller must ensure
//! they are using the appropriate one for their needs when loading,
//! the plugin, acquiring the interface, and performing serialization
//! operations (both to and from strings).
#pragma once
#include "../Framework.h"
#include "../Interface.h"
#include "../datasource/IDataSource.h"
#include "../dictionary/IDictionary.h"
#include <cstdint>
namespace carb
{
/** Namespace for @ref carb::dictionary::IDictionary related interfaces and helpers. */
namespace dictionary
{
/** Base type for flags for the ISerializer::createStringBufferFromDictionary() function. */
using SerializerOptions = uint32_t;
/** Flags to affect the behavior of the ISerializer::createStringBufferFromDictionary()
* function. Zero or more flags may be combined with the `|` operator. Use `0` to
* specify no flags.
* @{
*/
/** Flag to indicate that the generated string should include the name of the root node of the
* dictionary that is being serialized. If this flag is not used, the name of the root node
* will be skipped and only the children of the node will be serialized. This is only used
* when serializing to JSON with the `carb.dictionary.serializer-json.plugin` plugin. This
* flag will be ignored otherwise.
*/
constexpr SerializerOptions fSerializerOptionIncludeDictionaryName = 1;
/** Flag to indicate that the generated string should be formatted to be human readable and
* look 'pretty'. If this flag is not used, the default behavior is to format the string
* as compactly as possible with the aim of it being machine consumable. This flag may be
* used for both the JSON and TOML serializer plugins.
*/
constexpr SerializerOptions fSerializerOptionMakePretty = (1 << 1);
/** Flag to indicate that if an empty dictionary item is found while walking the dictionary
* that is being serialized, it should be represented by an empty array. If this flag is
* not used, the default behavior is to write out the empty dictionary item as an empty
* object. This flag may be used for both the JSON and TOML serializer plugins.
*/
constexpr SerializerOptions fSerializerOptionEmptyDictionaryIsArray = (1 << 2);
/** Flag to indicate that the JSON serializer should write out infinity and NaN floating point
* values as a null object. If this flag is not used, the default behavior is to write out
* the value as a special string that can later be serialized back to an infinite value by
* the same serializer plugin. This flag is only used in the JSON serializer plugin since
* infinite values are not supported by the JSON standard itself.
*/
constexpr SerializerOptions fSerializerOptionSerializeInfinityAsNull = (1 << 3);
/** Deprecated flag name for @ref fSerializerOptionIncludeDictionaryName. This flag should
* no longer be used for new code. Please use @ref fSerializerOptionIncludeDictionaryName
* instead.
*/
CARB_DEPRECATED("Use fSerializerOptionIncludeDictionaryName instead.")
constexpr SerializerOptions fSerializerOptionIncludeCollectionName = fSerializerOptionIncludeDictionaryName;
/** @} */
/** Deprecated serializer option flag names. Please use the `fSerializerOption*` flags instead.
* @{
*/
/** Deprecated flag. Please use @ref fSerializerOptionIncludeDictionaryName instead. */
CARB_DEPRECATED("Use fSerializerOptionIncludeDictionaryName instead.")
constexpr SerializerOptions kSerializerOptionIncludeDictionaryName = fSerializerOptionIncludeDictionaryName;
/** Deprecated flag. Please use @ref fSerializerOptionMakePretty instead. */
CARB_DEPRECATED("Use fSerializerOptionMakePretty instead.")
constexpr SerializerOptions kSerializerOptionMakePretty = fSerializerOptionMakePretty;
/** Deprecated flag. Please use @ref fSerializerOptionEmptyDictionaryIsArray instead. */
CARB_DEPRECATED("Use fSerializerOptionEmptyDictionaryIsArray instead.")
constexpr SerializerOptions kSerializerOptionEmptyDictionaryIsArray = fSerializerOptionEmptyDictionaryIsArray;
/** Deprecated flag. Please use @ref fSerializerOptionSerializeInfinityAsNull instead. */
CARB_DEPRECATED("Use fSerializerOptionSerializeInfinityAsNull instead.")
constexpr SerializerOptions kSerializerOptionSerializeInfinityAsNull = fSerializerOptionSerializeInfinityAsNull;
/** Deprecated flag. Please use @ref fSerializerOptionIncludeDictionaryName instead. */
CARB_DEPRECATED("Use fSerializerOptionIncludeDictionaryName instead.")
constexpr SerializerOptions kSerializerOptionIncludeCollectionName = fSerializerOptionIncludeDictionaryName;
/* @} **/
//! Flags for deserializing a string (for @ref ISerializer::createDictionaryFromStringBuffer())
using DeserializerOptions = uint32_t;
//! Default value for @ref DeserializerOptions that specifies no options.
constexpr DeserializerOptions kDeserializerOptionNone = 0;
//! Flag that indicates that the `const char* string` value can actually be considered as `char*` and treated
//! destructively (allow in-situ modification by the deserializer).
constexpr DeserializerOptions fDeserializerOptionInSitu = (1 << 0);
/** Interface intended to serialize dictionary objects to and from plain C strings. Each
* implementation of this interface is intended to handle a different format for the string
* data. The current implementations include support for JSON and TOML strings. It is left
* as an exercise for the caller to handle reading the string from a file before serializing
* or writing it to a file after serializing. Each implementation is assumed that it will be
* passed a dictionary item object has been created by the @ref carb::dictionary::IDictionary
* interface implemented by the `carb.dictionary.plugin` plugin or that the only IDictionary
* interface that can be acquired is also the one that created the item object.
*
* @note If multiple plugins that implement IDictionary are loaded, behavior may be undefined.
*/
struct ISerializer
{
CARB_PLUGIN_INTERFACE("carb::dictionary::ISerializer", 1, 1)
//! @private
CARB_DEPRECATED("use the new createDictionaryFromStringBuffer")
dictionary::Item*(CARB_ABI* deprecatedCreateDictionaryFromStringBuffer)(const char* serializedString);
/** Creates a new string representation of a dictionary.
*
* @param[in] dictionary The dictionary to be serialized. This must not be
* `nullptr` but may be an empty dictionary. The entire
* contents of the dictionary and all its children will be
* serialized to the output string.
* @param[in] serializerOptions Option flags to control how the output string is created.
* These flags can affect both the formatting and the content
* of the string.
* @returns On success, this returns a string containing the serialized dictionary. When
* this string is no longer needed, it must be destroyed using a call to
* ISerializer::destroyStringBuffer().
*
* On failure, `nullptr` is returned. This call can fail if an allocation error
* occurs, if a bad dictionary item object is encountered, or an error occurs
* formatting the output to the string.
*/
const char*(CARB_ABI* createStringBufferFromDictionary)(const dictionary::Item* dictionary,
SerializerOptions serializerOptions);
/** Destroys a string buffer returned from ISerializer::createStringBufferFromDictionary().
*
* @param[in] serializedString The string buffer to be destroyed. This must have been
* returned from a previous successful call to
* createStringBufferFromDictionary().
* @returns No return value.
*/
void(CARB_ABI* destroyStringBuffer)(const char* serializedString);
//! @private
dictionary::Item*(CARB_ABI* internalCreateDictionaryFromStringBuffer)(const char* string,
size_t len,
DeserializerOptions options);
/** Creates a new dictionary object from the contents of a string.
*
* @param[in] string The string containing the data to be serialized into a new
* dictionary object. This is assumed to be in the format that
* is supported by this specific interface object's
* implementation (for example, JSON or TOML for the default
* built-in implementations). If this string is not formatted
* correctly for the implementation, the operation will fail. Must
* be `NUL`-terminated even if the length is known.
* @param[in] len The length of the string data, if known. If not known, provide `size_t(-1)`
* as the length, which is also the default. The length should not include the
* `NUL` terminator.
* @param[in] options Options, if any, to pass to the deserializer. If no options are desired,
* pass @ref kDeserializerOptionNone.
* @returns On success, this returns a new dictionary item object containing the serialized
* data from the string. When this dictionary is no longer needed, it must be
* destroyed using the carb::dictionary::IDictionary::destroyItem() function.
*
* On failure, `nullptr` is returned. This call can fail if the input string is not
* in the correct format (ie: in TOML format when using the JSON serializer or
* vice versa), if the string is malformed, or has a syntax error in it.
*/
dictionary::Item* createDictionaryFromStringBuffer(const char* string,
size_t len = size_t(-1),
DeserializerOptions options = kDeserializerOptionNone)
{
return internalCreateDictionaryFromStringBuffer(string, len, options);
}
};
} // namespace dictionary
} // namespace carb
| 11,201 | C | 56.446154 | 112 | 0.702259 |
omniverse-code/kit/include/carb/dictionary/IDictionary.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief carb.dictionary interface definition file.
#pragma once
#include "../Framework.h"
#include "../Interface.h"
#include "../Types.h"
#include "../extras/Hash.h"
#include "../cpp/StringView.h"
#include "../../omni/String.h"
#include <cstdint>
namespace carb
{
namespace dictionary
{
/**
* Supported item types. Other types need to be converted from the string item.
*/
enum class ItemType
{
eBool, //!< Boolean type
eInt, //!< 64-bit integer type
eFloat, //!< 64-bit floating-point type
eString, //!< String type
eDictionary, //!< Dictionary type (may act as either an array type or a map type)
eCount //! Number of ItemTypes, not a valid item type
};
//! Structure used in opaque pointers to each dictionary node
struct Item DOXYGEN_EMPTY_CLASS;
//! Actions that may be returned by OnUpdateItemFn.
//! @see IDictionary::update() OnUpdateItemFn
enum class UpdateAction
{
eOverwrite, //!< The target item should be overwritten by the source item
eKeep, //!< The target item item should be retained, ignoring the source item
eReplaceSubtree //!< The entire subtree should be replaced (dictionary source item only)
};
//! Item flags that can be specified by the user.
//! @see IDictionary::getItemFlag() IDictionary::setItemFlag() IDictionary::copyItemFlags()
enum class ItemFlag
{
eUnitSubtree, //!< Indicates that this \ref Item is a subtree
};
/**
* Function that will tell whether the merger should overwrite the destination item
* with the source item. dstItem could be nullptr, meaning that the destination item
* doesn't exist. This function will be triggered not only for the leaf item, but also
* for the intermediate eDictionary items that need to be created.
* @see IDictionary::update()
*/
typedef UpdateAction (*OnUpdateItemFn)(
const Item* dstItem, ItemType dstItemType, const Item* srcItem, ItemType srcItemType, void* userData);
/**
* Note that this function does not properly handle overwriting of arrays due to
* overwriting array being shorter, potentially leaving part of the older array in-place
* after the merge
* Use \ref overwriteOriginalWithArrayHandling() if dictionaries are expected to contain array data.
* @see IDictionary::update()
*/
inline UpdateAction overwriteOriginal(
const Item* dstItem, ItemType dstItemType, const Item* srcItem, ItemType srcItemType, void* userData)
{
CARB_UNUSED(dstItem, dstItemType, srcItem, srcItemType, userData);
return UpdateAction::eOverwrite;
}
/**
* Function that indicates that the merger should retain the existing destination item.
* @see IDictionary::update()
*/
inline UpdateAction keepOriginal(
const Item* dstItem, ItemType dstItemType, const Item* srcItem, ItemType srcItemType, void* userData)
{
CARB_UNUSED(dstItemType, srcItem, srcItemType, userData);
if (!dstItem)
{
// If the destination item doesn't exist - allow to create a new one
return UpdateAction::eOverwrite;
}
return UpdateAction::eKeep;
}
//! Alias for \ref overwriteOriginal().
constexpr OnUpdateItemFn kUpdateItemOverwriteOriginal = overwriteOriginal;
//! Alias for \ref keepOriginal().
constexpr OnUpdateItemFn kUpdateItemKeepOriginal = keepOriginal;
//! Opaque value representing a subscription.
//! @see IDictionary::subscribeToNodeChangeEvents() IDictionary::subscribeToTreeChangeEvents()
struct SubscriptionId DOXYGEN_EMPTY_CLASS;
//! Type of a change passed to a subscription callback.
//! @see IDictionary::subscribeToNodeChangeEvents() IDictionary::subscribeToTreeChangeEvents() OnNodeChangeEventFn
//! OnTreeChangeEventFn
enum class ChangeEventType
{
eCreated, //!< An \ref Item was created.
eChanged, //!< An \ref Item was changed.
eDestroyed //!< An \ref Item was destroyed.
};
/**
* A callback that, once registered with subscribeToNodeChangeEvents(), receives callbacks when Items change.
*
* @note The callbacks happen in the context of the thread performing the change. It is safe to call back into the
* IDictionary and unsubscribe or otherwise make changes. For \ref ChangeEventType::eCreated and
* \ref ChangeEventType::eChanged types, no internal locks are held; for \ref ChangeEventType::eDestroyed internal locks
* are held which can cause thread-synchronization issues with locking order.
*
* @param changedItem The \ref Item that is changing
* @param eventType The event occurring on \p changedItem
* @param userData The user data given to \ref IDictionary::subscribeToNodeChangeEvents()
*/
using OnNodeChangeEventFn = void (*)(const Item* changedItem, ChangeEventType eventType, void* userData);
/**
* A callback that, once registered with subscribeToTreeChangeEvents(), receives callbacks when Items change.
*
* @note The callbacks happen in the context of the thread performing the change. It is safe to call back into the
* IDictionary and unsubscribe or otherwise make changes. For \ref ChangeEventType::eCreated and
* \ref ChangeEventType::eChanged types, no internal locks are held; for \ref ChangeEventType::eDestroyed internal locks
* are held which can cause thread-synchronization issues with locking order.
*
* @param treeItem The tree \ref Item given to \ref IDictionary::subscribeToTreeChangeEvents()
* @param changedItem The \ref Item that is changing. May be \p treeItem or a descendant,
* @param eventType The event occurring on \p changedItem
* @param userData The user data given to \ref IDictionary::subscribeToTreeChangeEvents()
*/
using OnTreeChangeEventFn = void (*)(const Item* treeItem,
const Item* changedItem,
ChangeEventType eventType,
void* userData);
/**
* DOM-style dictionary (keeps the whole structure in-memory).
*
* In most functions, item is specified using the relative root index and path from
* the relative root. Path can be nullptr, meaning that baseItem will be considered
* a specified item.
*
* @thread_safety
* IDictionary functions are thread-safe unless otherwise indicated. Where possible, a shared ("read") lock is held so
* that multiple threads may query data from a \ref carb::dictionary::Item without blocking each other. Functions that
* contain `Mutable` in the name, and functions that exchange non-const \ref carb::dictionary::Item pointers will hold
* an exclusive ("write") lock, which will block any other threads attempting to perform read/write operations on the
* \ref carb::dictionary::Item. These locks are held at the true-root level of the Item hierarchy which ensures safety
* across that root Item's hierarchy (see \ref IDictionary::createItem).
*
* In some cases, a read or write lock must be held across multiple function calls. An example of this would be a call
* to \ref getItemChildCount() followed by one or more calls to \ref getItemChildByIndex(). Since you would not want
* another thread to change the dictionary between the two calls, you must use a lock to keep the state consistent. In
* this case \ref ScopedWrite and \ref ScopedRead exist to maintain a lock across multiple calls.
*
* @par Ordering
* Dictionary items of type \ref ItemType::eDictionary can function as either an array type (sequential integer keys
* starting with `0`), or a map type. For map types, dictionary attempts to order child items in the order that they
* were created, provided that the items were created by \ref createItem(), \ref update(), or \ref duplicateItem() (the
* "creation functions"). This order is reflected when retrieving child items via \ref getItemChildByIndex(). Performing
* one of the creation functions on a key that already exists will move it to the end of the order, but merely setting a
* value on an existing item will not change its order.
*
* @par Subscriptions
* Dictionary \ref Item objects may have subscriptions for notification of changes, either for an individual \ref Item
* (\ref subscribeToNodeChangeEvents), or a sub-tree (\ref subscribeToTreeChangeEvents). Subscriptions are called in the
* context of the thread that triggered the change, and only once that thread has fully released the lock for the
* dictionary hierarchy that contains the changed \ref Item (since looks are at the true-root level). Subscription
* callbacks also follow the principles of Basic Callback Hygiene:
* 1. \ref unsubscribeToChangeEvents may be called from within the callback to unregister the called subscription or any
* other subscription.
* 2. Unregistering the subscription ensures that it will never be called again, and any calls in process on another
* thread will complete before \ref unsubscribeToChangeEvents returns.
* 3. The true-root level lock is not held while the callback is called, but may be temporarily taken for API calls
* within the callback.
*/
struct IDictionary
{
// Version 1.0: Initial
// Version 1.1: Ordering guarantees for createItem(), update(), duplicateItem().
CARB_PLUGIN_INTERFACE("carb::dictionary::IDictionary", 1, 1)
/**
* Returns opaque pointer to read-only item.
*
* @param baseItem Base item to apply path from (required)
* @param path Child path, separated with forward slash ('/'), can be nullptr
* @return Opaque item pointer if the item is valid and present, or nullptr otherwise
*/
const Item*(CARB_ABI* getItem)(const Item* baseItem, const char* path);
/**
* Returns opaque pointer to mutable item.
*
* @param baseItem Base item to apply path from (required)
* @param path Child path, separated with forward slash ('/'), can be nullptr
* @return Opaque item pointer if the item is valid and present, or nullptr otherwise
*/
Item*(CARB_ABI* getItemMutable)(Item* baseItem, const char* path);
/**
* Returns number of children that belong to the specified item, if this item
* is a dictionary. Returns 0 if item is not a dictionary, or doesn't exist.
*
* @param item Item to query number of children from.
* @return Number of children if applicable, 0 otherwise.
*/
size_t(CARB_ABI* getItemChildCount)(const Item* item);
/**
* Returns opaque pointer to a read-only child item by its index. Mostly for dynamic dictionary processing.
* This function is different from getItemAt function, in a sense that this function doesn't work with
* the array view of the supplied item - for example if the item has children named "A", "B", "0", this
* function will return all of them in an undefined succession. While getItemAt functions work only with
* items which has array-like names (e.g. "0", "1", "2", etc.).
*
* @param item Item to query child from.
* @param childIndex Child index.
* @return Opaque const item pointer if the item and index are valid, or nullptr otherwise.
*/
const Item*(CARB_ABI* getItemChildByIndex)(const Item* item, size_t childIndex);
/**
* Returns opaque pointer to a mutable child item by its index. Mostly for dynamic dictionary processing.
* This function is different from getItemAtMutable function, in a sense that this function doesn't work with
* the array view of the supplied item - for example if the item has children named "A", "B", "0", this
* function will return all of them in an undefined succession. While getItemAt functions work only with
* items which has array-like names (e.g. "0", "1", "2", etc.).
*
* @param item Item to query child from.
* @param childIndex Child index.
* @return Opaque item pointer if the item and index are valid, or nullptr otherwise.
*/
Item*(CARB_ABI* getItemChildByIndexMutable)(Item* item, size_t childIndex);
/**
* Returns read-only parent item, or nullptr if the supplied item is true root item.
*
* @param item Item to get parent for.
* @return Opaque item pointer if the item is valid and has parent, or nullptr otherwise.
*/
const Item*(CARB_ABI* getItemParent)(const Item* item);
/**
* Returns opaque pointer to a mutable parent item, or nullptr if the supplied item is true root item.
*
* @param item Item to get parent for.
* @return Opaque item pointer if the item is valid and has parent, or nullptr otherwise.
*/
Item*(CARB_ABI* getItemParentMutable)(Item* item);
/**
* Returns original item type. If the item is not a valid item, returns eCount.
*
* @param item \ref dictionary::Item
* @return Original item type if item is valid, eCount otherwise.
*/
ItemType(CARB_ABI* getItemType)(const Item* item);
/**
* Securely string buffer filled with the item name.
*
* @note Please use \ref destroyStringBuffer() to free the created buffer.
*
* @param item \ref dictionary::Item
* @return Pointer to the created item name buffer if applicable, nullptr otherwise.
*/
const char*(CARB_ABI* createStringBufferFromItemName)(const Item* item);
/**
* Returns pointer to an item name, if the item is valid.
* Dangerous function which only guarantees safety of the data when item is not changing.
*
* @param item \ref dictionary::Item
* @return Pointer to an internal item name string if the item is valid, nullptr otherwise.
*/
const char*(CARB_ABI* getItemName)(const Item* item);
/**
* Creates item, and all the required items along the path if necessary.
* If baseItem supplied is nullptr, the created item is created as a true root.
*
* @param baseItem Base \ref Item to apply path from. Passing \c nullptr means that the created item will be a true
* root (i.e. has no parent \ref Item).
* @param path Path to the new item.
* @param itemType \ref ItemType of the \ref Item to create.
* @return Opaque \ref Item pointer if it was successfully created, or \c nullptr otherwise.
*/
Item*(CARB_ABI* createItem)(Item* baseItem, const char* path, ItemType itemType);
/**
* Checks if the item could be accessible as the provided type, either directly, or via a cast.
*
* Generally this means for a given \ref ItemType to return `true` for \p item:
* * \ref ItemType::eDictionary -- \p item must be of type \ref ItemType::eDictionary.
* * \ref ItemType::eString -- \p item must be of any type \a except \ref ItemType::eDictionary.
* * \ref ItemType::eInt -- \p item must be of type \ref ItemType::eInt, \ref ItemType::eFloat, or
* \ref ItemType::eBool, or \ref ItemType::eString that contains only a string representation of an integer (in
* in decimal, hex or octal, as convertible by `strtoll()`) or a floating-point number (as convertible by
* `strtod()`).
* * \ref ItemType::eFloat -- \p item must be of type \ref ItemType::eFloat, \ref ItemType::eInt or
* \ref ItemType::eBool, or \ref ItemType::eString that contains only a string representation of a floating point
* number (as convertible by `strtod()`).
* * \ref ItemType::eBool -- \p item must be of type \ref ItemType::eBool, \ref ItemType::eInt, or
* \ref ItemType::eFloat, or \ref ItemType::eString that either contains only case-insensitive versions of
* `"true"` or `"false"` or only a string representation of a floating point number (as convertible by
* `strtod()`).
*
* @param itemType Item type to check for.
* @param item \ref dictionary::Item
* @return \c true if accessible (see above); \c false otherwise.
*/
bool(CARB_ABI* isAccessibleAs)(ItemType itemType, const Item* item);
/**
* Attempts to get the supplied item as integer, either directly or via a cast.
*
* @param[in] item The item to retrieve the integer value from.
* @return The 64 bit integer value of @p item. This will be converted from
* the existing type if this \ref Item is not a 64 bit integer.
* For an \ref Item of type `int32_t`, `float` or `double`,
* this conversion will be a direct cast.
* Note that overly large `double` values convert to `INT64_MIN`
* on x86_64.
* For an \ref Item of string type, the string data will be interpreted
* as a number.
* If the string is not a valid number, 0 will be returned.
* If the string is a valid number, but exceeds the range of an `int64_t`,
* it will be parsed as a `double` and converted to an `int64_t`.
*
* @note carb.dictionary.serializer-toml.plugin cannot handle integers that
* exceed `INT64_MAX`.
*
* @note When carb.dictionary.serializer-json.plugin reads integers exceeding `UINT64_MAX`,
* it will store the result as a double, so you may get unexpected 64 bit integer values.
* Unsigned 64 bit values are still retrievable with full precision though;
* they will just be wrapped around when returned from this function.
*/
int64_t(CARB_ABI* getAsInt64)(const Item* item);
/**
* Sets the integer value for the supplied item. If an item was already present,
* changes its original type to eInt. If the present item is a eDictionary item,
* destroys all its children.
* If the item doesn't exist, creates eInt item, and all the required items along
* the path if necessary.
*
* @param item \ref dictionary::Item
* @param value Integer value that will be set to the supplied item.
*/
void(CARB_ABI* setInt64)(Item* item, int64_t value);
/**
* Attempts to get the supplied item as 32-bit integer, either directly or via a cast.
*
* @warning The value is truncated by casting to 32-bits. In debug builds, an assert occurs if the value read from
* the item would be truncated.
* @param[in] item The item to retrieve the integer value from.
* @return The 64 bit integer value of @p item. This will be converted from
* the existing type if this \ref Item is not a 64 bit integer.
* The conversion semantics are the same as for getAsInt64().
* Note that the string conversion behavior has the same clamping
* limits as getAsInt64(), which may result in unexpected wraparound
* behavior; you should use getAsInt64() instead if you may be reading
* string values.
*/
int32_t getAsInt(const Item* item);
/**
* Sets the 32-bit integer value for the supplied item. If an item was already present,
* changes its original type to eInt. If the present item is a eDictionary item,
* destroys all its children.
* If the item doesn't exist, creates eInt item, and all the required items along
* the path if necessary.
*
* @param item \ref dictionary::Item
* @param value Integer value that will be set to the supplied item.
*/
void setInt(Item* item, int32_t value);
/**
* Helper function that sets the value to an item at path. Creates item at path if
* it doesn't exist.
*
* @param baseItem Base item to apply path from.
* @param path Path.
* @param value Integer value that will be set to the supplied item.
*/
Item* makeInt64AtPath(Item* baseItem, const char* path, int64_t value);
/**
* Helper function that sets the value to an item at path. Creates item at path if
* it doesn't exist.
*
* @param baseItem Base item to apply path from.
* @param path Path.
* @param value Integer value that will be set to the supplied item.
*/
Item* makeIntAtPath(Item* baseItem, const char* path, int32_t value);
/**
* Attempts to get the supplied item as float, either directly or via a cast.
*
* @param[in] item The item to retrieve the floating point value from.
* @return The 64 bit floating point value of @p item.
* This will be converted from the existing type if this \ref Item
* is not a `double`.
* For an \ref Item of type `int32_t`, `int64_t` or `float`,
* this conversion will be a direct cast.
* For an \ref Item of string type, the string data will be interpreted
* as a number.
* If the string is not a valid number, 0 will be returned.
* If the string is a valid number, but exceeds the range of a `double`
* `INFINITY` or `-INFINITY` will be returned.
* Some precision may be lost on overly precise strings.
*/
double(CARB_ABI* getAsFloat64)(const Item* item);
/**
* Sets the floating point value for the supplied item. If an item was already present,
* changes its original type to eFloat. If the present item is a eDictionary item,
* destroys all its children.
* If the item doesn't exist, creates eFloat item, and all the required items along
* the path if necessary.
*
* @param item \ref dictionary::Item
* @param value Floating point value that will be set to the supplied item.
*/
void(CARB_ABI* setFloat64)(Item* item, double value);
/**
* Attempts to get the supplied item as 32-bit float, either directly or via a cast.
*
* @param[in] item The item to retrieve the floating point value from.
* @return The 64 bit floating point value of @p item.
* This will be converted from the existing type if this \ref Item
* is not a `double`.
* The conversion semantics are the same as with getAsFloat64().
*/
float getAsFloat(const Item* item);
/**
* Sets the 32-bit floating point value for the supplied item. If an item was already present,
* changes its original type to eFloat. If the present item is a eDictionary item,
* destroys all its children.
* If the item doesn't exist, creates eFloat item, and all the required items along
* the path if necessary.
*
* @param item \ref dictionary::Item
* @param value Floating point value that will be set to the supplied item.
*/
void setFloat(Item* item, float value);
/**
* Helper function that sets the value to an item at path. Creates item at path if
* it doesn't exist.
*
* @param baseItem Base item to apply path from.
* @param path Path.
* @param value Float value that will be set to the supplied item.
*/
Item* makeFloat64AtPath(Item* baseItem, const char* path, double value);
/**
* Helper function that sets the value to an item at path. Creates item at path if
* it doesn't exist.
*
* @param baseItem Base item to apply path from.
* @param path Path.
* @param value Float value that will be set to the supplied item.
*/
Item* makeFloatAtPath(Item* baseItem, const char* path, float value);
/**
* Attempts to get the supplied item as eBool, either directly or via a cast.
*
* @param item \ref dictionary::Item
* @return Boolean value, either value directly or cast from the real item type.
*/
bool(CARB_ABI* getAsBool)(const Item* item);
/**
* Sets the boolean value for the supplied item. If an item was already present,
* changes its original type to eBool. If the present item is a eDictionary item,
* destroys all its children.
* If the item doesn't exist, creates eBool item, and all the required items along
* the path if necessary.
*
* @param item \ref dictionary::Item
* @param value Boolean value that will be set to the supplied item.
*/
void(CARB_ABI* setBool)(Item* item, bool value);
/**
* Helper function that sets the value to an item at path. Creates item at path if
* it doesn't exist.
*
* @param baseItem Base item to apply path from.
* @param path Path.
* @param value Bool value that will be set to the supplied item.
*/
Item* makeBoolAtPath(Item* baseItem, const char* path, bool value);
//! @private
const char*(CARB_ABI* internalCreateStringBufferFromItemValue)(const Item* item, size_t* pStringLen);
/**
* Attempts to create a new string buffer with a value, either the real string value or a string resulting
* from converting the item value to a string.
*
* @note Please use \ref destroyStringBuffer() to free the created buffer.
*
* @param item \ref dictionary::Item
* @param pStringLen (optional) Receives the length of the string. This can be useful if the string contains NUL
* characters (i.e. byte data).
* @return Pointer to the created string buffer if applicable, nullptr otherwise.
*/
const char* createStringBufferFromItemValue(const Item* item, size_t* pStringLen = nullptr) const
{
return internalCreateStringBufferFromItemValue(item, pStringLen);
}
//! @private
const char*(CARB_ABI* internalGetStringBuffer)(const Item* item, size_t* pStringLen);
/**
* Returns internal raw data pointer to the string value of an item. Thus, doesn't perform any
* conversions.
*
* @warning This function returns the internal string buffer. Another thread may change the setting value which can
* cause the string buffer to be destroyed. It is recommended to take a \ref ScopedRead lock around calling this
* function and using the return value.
*
* @param item \ref dictionary::Item
* @param pStringLen (optional) Receives the length of the string. This can be useful if the string contains NUL
* characters (i.e. byte data).
* @return Raw pointer to the internal string value if applicable, nullptr otherwise.
*/
const char* getStringBuffer(const Item* item, size_t* pStringLen = nullptr)
{
return internalGetStringBuffer(item, pStringLen);
}
//! @private
void(CARB_ABI* internalSetString)(Item* item, const char* value, size_t stringLen);
/**
* Sets a string value for the supplied item.
*
* If @p item is not of type `eString` it is changed to be `eString`. Change notifications for
* subscriptions are queued. The given string is then set in the item at @p path. If @p value is \c nullptr, the
* string item will store an empty string.
*
* @param item \ref dictionary::Item
* @param value String value that will be set to the supplied item.
* @param stringLen (optional) The length of the string at \p value to copy. This can be useful if only a portion
* of the string should be copied, or if \p value contains NUL characters (i.e. byte data). The default value of
* size_t(-1) treats \p value as a NUL-terminated string.
*/
void setString(Item* item, const char* value, size_t stringLen = size_t(-1)) const
{
internalSetString(item, value, stringLen);
}
/**
* Helper function that sets the value to an item at path. Creates item at path if
* it doesn't exist.
*
* @param baseItem Base item to apply path from.
* @param path Path.
* @param value String value that will be set to the supplied item.
* @param stringLen (optional) The length of the string at \p value to copy. This can be useful if only a portion
* of the string should be copied, or if \p value contains NUL characters (i.e. byte data). The default value of
* size_t(-1) treats \p value as a NUL-terminated string.
* @return The item at the given \p path
*/
Item* makeStringAtPath(Item* baseItem, const char* path, const char* value, size_t stringLen = size_t(-1));
/**
* Helper function that ensures the item at path is a dictionary. Creates item at path if
* it doesn't exist.
*
* @param parentItem Base item to apply path from.
* @param path Path.
*/
Item* makeDictionaryAtPath(Item* parentItem, const char* path);
/**
* Reads the value from an Item, converting if necessary.
* @tparam T The type of item to read. Must be a supported type.
* @param item The \ref Item to read from.
* @returns The value read from the \ref Item.
*/
template <typename T>
T get(const dictionary::Item* item);
/**
* Reads the value from an Item, converting if necessary.
* @tparam T The type of item to read. Must be a supported type.
* @param baseItem The base \ref Item to read from. Must not be `nullptr`.
* @param path The path from \p baseItem to determine the child \ref Item. May be an empty string.
* @returns The value read from the \ref Item.
*/
template <typename T>
T get(const dictionary::Item* baseItem, const char* path);
/**
* Constructs a new Item with the given value or changes an existing item to hold the given value.
* @tparam T The type of the value stored. Must be a supported type.
* @param baseItem The base \ref Item to read from. Must not be `nullptr`.
* @param path The path from \p baseItem where the child \ref Item will be constructed.
* @param value The value to assign to the new \ref Item.
*/
template <typename T>
void makeAtPath(dictionary::Item* baseItem, const char* path, T value);
/**
* Checks if the item could be accessible as array.
*
* @param item \ref dictionary::Item
* @return \c true if accessible, that is, all child items have names which are contiguous non-negative integers
* starting with zero; \c false otherwise or if \p item has no children (empty dictionary).
*/
bool(CARB_ABI* isAccessibleAsArray)(const Item* item);
/**
* Checks if the item could be accessible as the array of items of provided type,
* either directly, or via a cast of all elements.
*
* For this function to return `true`, \ref isAccessibleAsArray must be satisfied, as well as each child item must
* satisfy \ref isAccessibleAs for the given \p itemType. Empty dictionaries and non-dictionary types of \p item
* will always return `false`.
*
* @param itemType Item type to check for.
* @param item \ref dictionary::Item
* @return True if a valid array and with all items accessible (see above), or false otherwise.
*/
bool(CARB_ABI* isAccessibleAsArrayOf)(ItemType itemType, const Item* item);
/**
* Checks if the all the children of the item have array-style indices. If yes, returns the number
* of children (array elements).
*
* @param item \ref dictionary::Item
* @return Non-zero number of array elements if applicable (implies \ref isAccessibleAsArray), or 0 otherwise.
*/
size_t(CARB_ABI* getArrayLength)(const Item* item);
/**
* Runs through all the array elements and infers a type that is most suitable for the
* array.
*
* The rules are thus:
* - Strings attempt to convert to float or bool if possible (see \ref isAccessibleAs for possibilities).
* - The converted type of the first element is the initial type.
* - If the initial type is a \ref ItemType::eBool and later elements can be converted to \ref ItemType::eBool
* without losing precision, \ref ItemType::eBool is kept. (String variants of "true"/"false", or values exactly
* equal to 0/1)
* - Elements of type \ref ItemType::eFloat can convert to \ref ItemType::eInt if they don't lose precision.
*
* @param item \ref dictionary::Item
* @return Item type that is most suitable for the array, or \ref ItemType::eCount on failure.
*/
ItemType(CARB_ABI* getPreferredArrayType)(const Item* item);
/**
* Attempts to read an array item as a 64-bit integer.
*
* Attempts to get the child item as integer, either directly or via a cast, considering the item at path
* to be an array, and using the supplied index to access its child.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @return Integer value, either value directly or cast from the real item type. Zero is returned on conversion
* failure.
*/
int64_t(CARB_ABI* getAsInt64At)(const Item* item, size_t index);
/**
* Set an integer value in an array item.
*
* Sets the integer value for the supplied item. If \p item is not an `eDictionary`, \p item is changed to an
* `eDictionary` and notifications are queued. \p index is used as the name of the child item.
* If the child item already existed and matches type `eInt` it is updated with the new value, otherwise any
* previous child item is destroyed (along with any of its children) and a new child item is created of type
* `eInt`; finally the new value is set into this child item. Change notifications are queued for every change that
* occurs. Subscriptions are notified of changes when the calling thread no longer holds any locks on the true root
* of \p item.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @param value Integer value that will be set to the supplied item.
*/
void(CARB_ABI* setInt64At)(Item* item, size_t index, int64_t value);
/**
* Attempts to read an array item as a 32-bit integer.
*
* Attempts to get the child item as integer, either directly or via a cast, considering the item at path
* to be an array, and using the supplied index to access its child.
* @warning The value is truncated by casting to 32-bits. In debug builds, an assert occurs if the value read from
* the item would be truncated.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @return Integer value, either value directly or cast from the real item type. Zero is returned on conversion
* failure.
*/
int32_t getAsIntAt(const Item* item, size_t index);
/**
* Set an integer value in an array item.
*
* Sets the integer value for the supplied item. If \p item is not an `eDictionary`, \p item is changed to an
* `eDictionary` and notifications are queued. \p index is used as the name of the child item.
* If the child item already existed and matches type `eInt` it is updated with the new value, otherwise any
* previous child item is destroyed (along with any of its children) and a new child item is created of type
* `eInt`; finally the new value is set into this child item. Change notifications are queued for every change that
* occurs. Subscriptions are notified of changes when the calling thread no longer holds any locks on the true root
* of \p item.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @param value Integer value that will be set to the supplied item.
*/
void setIntAt(Item* item, size_t index, int32_t value);
/**
* Fills the given buffer with the array values from the given path.
*
* If the provided @p item is not an array item, @p arrayOut is not modified. If the array item contains more items
* than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p item is a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and only if \ref isAccessibleAsArray
* or \ref isAccessibleAsArrayOf return \c true.
*
* @param item \ref dictionary::Item
* @param arrayOut Array buffer to fill with integer values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getAsInt64Array)(const Item* item, int64_t* arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be an integer array.
*
* \p item is changed to `eDictionary`, or if it already was, has all child items cleared (change notifications will
* will be queued for any child items that are destroyed). New child items will be created for all elements of the
* given @p array.
*
* @param item \ref dictionary::Item
* @param array Integer array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setInt64Array)(Item* item, const int64_t* array, size_t arrayLength);
/**
* Fills the given buffer with the array values from the given path.
*
* If the provided @p item is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p item is a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
* @warning Any integer element that does not fit within \c int32_t is truncated by casting.
*
* @param item \ref dictionary::Item
* @param arrayOut Array buffer to fill with integer values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getAsIntArray)(const Item* item, int32_t* arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be an integer array.
*
* \p item is changed to `eDictionary`, or if it already was, has all child items cleared (change notifications will
* will be queued for any child items that are destroyed). New child items will be created for all elements of the
* given @p array.
*
* @param item \ref dictionary::Item
* @param array Integer array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setIntArray)(Item* item, const int32_t* array, size_t arrayLength);
/**
* Attempts to read an array item as a `double`.
*
* Attempts to read the path and array index as a `double`, either directly or via a cast, considering the
* item at path to be an array, and using the supplied index to access its child.
* Default value (`0.0`) is returned if \p item is `nullptr`, index doesn't exist, or there is a conversion
* failure.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @return `double` value, either value directly or cast from the real item type.
*/
double(CARB_ABI* getAsFloat64At)(const Item* item, size_t index);
/**
* Set a `double` value in an array item.
*
* Sets the `double` value for the supplied item. If \p item is not an `eDictionary`, \p item is changed to an
* `eDictionary` and notifications are queued. \p index is used as the name of the child item.
* If the child item already existed and matches type `eFloat` it is updated with the new value, otherwise any
* previous child item is destroyed (along with any of its children) and a new child item is created of type
* `eFloat`; finally the new value is set into this child item. Change notifications are queued for every change
* that occurs. Subscriptions are notified of changes when the calling thread no longer holds any locks on the true
* root of \p item.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @param value `double` value that will be set to the supplied item.
*/
void(CARB_ABI* setFloat64At)(Item* item, size_t index, double value);
/**
* Attempts to read an array item as a `float`.
*
* Attempts to read the path and array index as a `float`, either directly or via a cast, considering the
* item at path to be an array, and using the supplied index to access its child.
* Default value (`0.0f`) is returned if \p item is `nullptr`, index doesn't exist, or there is a conversion
* failure.
* @warning The value is truncated by casting to 32-bits.
*
* @param item An \ref Item
* @param index Index of the element in array
* @return `float` value, either value directly or cast from the real item type.
*/
float getAsFloatAt(const Item* item, size_t index);
/**
* Set a `float` value in an array item.
*
* Sets the `float` value for the supplied item. If \p item is not an `eDictionary`, \p item is changed to an
* `eDictionary` and notifications are queued. \p index is used as the name of the child item.
* If the child item already existed and matches type `eFloat` it is updated with the new value, otherwise any
* previous child item is destroyed (along with any of its children) and a new child item is created of type
* `eFloat`; finally the new value is set into this child item. Change notifications are queued for every change
* that occurs. Subscriptions are notified of changes when the calling thread no longer holds any locks on the true
* root of \p item.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @param value Floating point value that will be set to the supplied item.
*/
void setFloatAt(Item* item, size_t index, float value);
/**
* Fills the given buffer with the array values from the given path.
*
* If the provided @p item is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p item is a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
*
* @param item \ref dictionary::Item
* @param arrayOut Array buffer to fill with floating point values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getAsFloat64Array)(const Item* item, double* arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be a `double` array.
*
* \p item is changed to `eDictionary`, or if it already was, has all child items cleared (change notifications will
* will be queued for any child items that are destroyed). New child items will be created for all elements of the
* given @p array.
*
* @param item \ref dictionary::Item
* @param array Floating point array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setFloat64Array)(Item* item, const double* array, size_t arrayLength);
/**
* Fills the given buffer with the array values from the given path.
*
* If the provided @p item is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p item is a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
* @warning Any element that does not fit within \c float is truncated by casting.
*
* @param item \ref dictionary::Item
* @param arrayOut Array buffer to fill with floating point values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getAsFloatArray)(const Item* item, float* arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be a `float` array.
*
* \p item is changed to `eDictionary`, or if it already was, has all child items cleared (change notifications will
* will be queued for any child items that are destroyed). New child items will be created for all elements of the
* given @p array.
*
* @param item \ref dictionary::Item
* @param array Floating point array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setFloatArray)(Item* item, const float* array, size_t arrayLength);
/**
* Attempts to read an array item as a `bool`.
*
* Attempts to read the path and array index as a `bool`, either directly or via a cast, considering the
* item at path to be an array, and using the supplied index to access its child.
* Default value (`false`) is returned if \p item is `nullptr`, index doesn't exist, or there is a conversion
* failure.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @return Boolean value, either value directly or cast from the real item type.
*/
bool(CARB_ABI* getAsBoolAt)(const Item* item, size_t index);
/**
* Set a `bool` value in an array item.
*
* Sets the `bool` value for the supplied item. If \p item is not an `eDictionary`, \p item is changed to an
* `eDictionary` and notifications are queued. \p index is used as the name of the child item.
* If the child item already existed and matches type `eBool` it is updated with the new value, otherwise any
* previous child item is destroyed (along with any of its children) and a new child item is created of type
* `eBool`; finally the new value is set into this child item. Change notifications are queued for every change
* that occurs. Subscriptions are notified of changes when the calling thread no longer holds any locks on the true
* root of \p item.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @param value Boolean value that will be set to the supplied item.
*/
void(CARB_ABI* setBoolAt)(Item* item, size_t index, bool value);
/**
* Fills the given buffer with the array values from the given path.
*
* If the provided @p item is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p item is a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
*
* @param item \ref dictionary::Item
* @param arrayOut Array buffer to fill with boolean values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getAsBoolArray)(const Item* item, bool* arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be a `bool` array.
*
* \p item is changed to `eDictionary`, or if it already was, has all child items cleared (change notifications will
* will be queued for any child items that are destroyed). New child items will be created for all elements of the
* given @p array.
*
* @param item \ref dictionary::Item
* @param array Boolean array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setBoolArray)(Item* item, const bool* array, size_t arrayLength);
//! @private
const char*(CARB_ABI* internalCreateStringBufferFromItemValueAt)(const Item* item, size_t index, size_t* pStringLen);
/**
* Attempts to create new string buffer with a value, either the real string value or a string resulting from
* converting the item value to a string. Considers the item to be an array, and using the supplied index
* to access its child.
*
* @note Please use destroyStringBuffer to free the created buffer.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @param pStringLen (optional) Receives the length of the string. This can be useful if the string contains NUL
* characters (i.e. byte data). Undefined if the function returns nullptr.
* @return Pointer to the created string buffer if applicable, nullptr otherwise.
*/
const char* createStringBufferFromItemValueAt(const Item* item, size_t index, size_t* pStringLen = nullptr) const
{
return internalCreateStringBufferFromItemValueAt(item, index, pStringLen);
}
//! @private
const char*(CARB_ABI* internalGetStringBufferAt)(const Item* item, size_t index, size_t* pStringLen);
/**
* Returns internal raw data pointer to the string value of an item. Thus, doesn't perform any
* conversions. Considers the item at path to be an array, and using the supplied index to access
* its child.
* Dangerous function which only guarantees safety of the data when dictionary is not changing.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @param pStringLen (optional) Receives the length of the string. This can be useful if the string contains NUL
* characters (i.e. byte data). Undefined if the function returns nullptr.
* @return Raw pointer to the internal string value if applicable, nullptr otherwise.
*/
const char* getStringBufferAt(const Item* item, size_t index, size_t* pStringLen = nullptr) const
{
return internalGetStringBufferAt(item, index, pStringLen);
}
//! @private
void(CARB_ABI* internalSetStringAt)(Item* item, size_t index, const char* value, size_t stringLen);
/**
* Sets a string value in the supplied array item.
*
* Sets the string value for the supplied item. If \p item is not an `eDictionary`, \p item is changed to an
* `eDictionary` and notifications are queued. \p index is used as the name of the child item.
* If the child item already existed and matches type `eString` it is updated with the new value, otherwise any
* previous child item is destroyed (along with any of its children) and a new child item is created of type
* `eString`; finally the new value is set into this child item. Change notifications are queued for every change
* that occurs. Subscriptions are notified of changes when the calling thread no longer holds any locks on the true
* root of \p item.
*
* @param item \ref dictionary::Item
* @param index Index of the element in array.
* @param value String value that will be set to the supplied item. May be `nullptr` which is interpreted to be an
* empty string.
* @param stringLen (optional) The length of the string at \p value to copy. This can be useful if only a portion
* of the string should be copied, or if \p value contains NUL characters (i.e. byte data). The default value of
* size_t(-1) treats \p value as a NUL-terminated string, or ignored if \p value is `nullptr`.
*/
void setStringAt(Item* item, size_t index, const char* value, size_t stringLen = size_t(-1)) const
{
internalSetStringAt(item, index, value, stringLen);
}
/**
* Returns internal raw data pointers to the string value of all child items of an array. Thus, doesn't perform any
* conversions.
*
* @warning This function returns the internal string buffer(s) for several items. Another thread may change the
* setting value which can cause the string buffer to be destroyed. It is recommended to take a \ref ScopedRead lock
* around calling this function and use of the filled items in @p arrayOut.
*
* If the provided @p item is not a dictionary item, @p arrayOut is not modified. If the array item contains more
* items than @p arrayBufferLength, a warning message is logged and items past the end are ignored.
* @warning Dictionary items that are not arrays will only have child keys which are convertible to array indices
* written to @p arrayOut. For example, if @p item is a dictionary item with keys '5' and '10',
* only those items will be written into @p arrayOut; the other indices will not be written. It is highly
* recommended to take a \ref ScopedRead lock around calling this function, and call only if
* \ref isAccessibleAsArray or \ref isAccessibleAsArrayOf return \c true.
*
* @param item \ref dictionary::Item
* @param arrayOut Array buffer to fill with integer values.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getStringBufferArray)(const Item* item, const char** arrayOut, size_t arrayBufferLength);
/**
* Creates or updates an item to be a string array.
*
* \p item is changed to `eDictionary`, or if it already was, has all child items cleared (change notifications will
* will be queued for any child items that are destroyed). New child items will be created for all elements of the
* given @p array.
*
* @param item \ref dictionary::Item
* @param array String array to copy values from.
* @param arrayLength Array length.
*/
void(CARB_ABI* setStringArray)(Item* item, const char* const* array, size_t arrayLength);
/**
* Returns opaque pointer to a read-only child item by its index. Mostly for dynamic dictionary processing.
* This function is designed for array view access, if you just want to enumerate all children, use
* getItemChildCount and getItemChildByIndex instead.
*
* @param item \ref dictionary::Item
* @return Opaque const item pointer if the item and index are valid, or nullptr otherwise.
*/
const Item*(CARB_ABI* getItemAt)(const Item* item, size_t index);
/**
* Returns opaque pointer to a mutable item by its index. Mostly for dynamic dictionary processing.
* This function is designed for array view access, if you just want to enumerate all children, use
* getItemChildCount and getItemChildByIndex instead.
*
* @param item \ref dictionary::Item
* @return Opaque item pointer if the item and index are valid, or nullptr otherwise.
*/
Item*(CARB_ABI* getItemAtMutable)(Item* item, size_t index);
/**
* Attempts to securely fill the supplied arrayOut buffer with read-only opaque pointers to
* the items that are array elements.
* arrayBufferLength is used as a buffer overflow detection.
* This function should not be used for simple dynamic processing purposes, use
* getItemChildCount and getItemChildByIndex instead.
*
* @param item The \ref Item.
* @param arrayOut Array buffer to fill with opaque item pointers.
* @param arrayBufferLength Size of the supplied array buffer.
*/
void(CARB_ABI* getItemArray)(const Item* item, const Item** arrayOut, size_t arrayBufferLength);
/**
* Updates an item to be an array of the given type with provided values.
*
* This is a helper function that will call the appropriate API function based on \c ArrayElementType:
* * `bool`: \ref setBoolArray
* * `int32_t`: \ref setIntArray
* * `int64_t`: \ref setInt64Array
* * `float`: \ref setFloatArray
* * `double`: \ref setFloat64Array
* * `const char*`: \ref setStringArray
*
* @note Any existing children in \p item are removed.
* @tparam ArrayElementType The type of elements to fill the array with.
* @param item The \ref Item that will be changed to an array type
* @param array An array that is used to fill \p item. The values are copied.
* @param arrayLength The length of \p array as a count of the items.
*/
template <typename ArrayElementType>
void setArray(Item* item, const ArrayElementType* array, size_t arrayLength);
/**
* Merges the source item into a destination item. Destination path may be non-existing, then
* missing items in the path will be created as new dictionary items.
*
* @param dstBaseItem Destination base item to apply path from.
* @param dstPath Destination Child path, separated with forward slash ('/'), can be nullptr.
* @param srcBaseItem Source base item to apply path from.
* @param srcPath Source Child path, separated with forward slash ('/'), can be nullptr.
* @param onUpdateItemFn Function that will tell whether the update should overwrite the destination item with the
* source item. See \ref carb::dictionary::keepOriginal(), \ref carb::dictionary::overwriteOriginal(), or
* \ref carb::dictionary::overwriteOriginalWithArrayHandling().
* @param userData User data pointer that will be passed into the onUpdateItemFn.
*/
void(CARB_ABI* update)(Item* dstBaseItem,
const char* dstPath,
const Item* srcBaseItem,
const char* srcPath,
OnUpdateItemFn onUpdateItemFn,
void* userData);
/**
* Destroys given item, and all of its children, if any. Change notifications are queued.
*
* @param item \ref dictionary::Item
*/
void(CARB_ABI* destroyItem)(Item* item);
/**
* Frees a string buffer.
*
* The string buffers are created by \ref createStringBufferFromItemValue(), \ref createStringBufferFromItemName or
* \ref createStringBufferFromItemValueAt().
* @param stringBuffer String buffer to destroy. Undefined behavior results if this is not a value returned from one
* of the functions listed above.
*/
void(CARB_ABI* destroyStringBuffer)(const char* stringBuffer);
/**
* Delete all children of a specified item.
*
* @param item \ref dictionary::Item
*/
void deleteChildren(Item* item);
/**
* Retrieves the value of an item flag.
* @param item \ref dictionary::Item
* @param flag ItemFlag.
* @return Original item type if item is valid, eCount otherwise.
*/
bool(CARB_ABI* getItemFlag)(const Item* item, ItemFlag flag);
/**
* Sets the value of an item flag.
* @param item \ref dictionary::Item
* @param flag ItemFlag.
* @return Original item type if item is valid, eCount otherwise.
*/
void(CARB_ABI* setItemFlag)(Item* item, ItemFlag flag, bool flagValue);
/**
* Copies all item flags from one Item to another.
* @param dstItem The destination \ref Item that will receive the flags.
* @param srcItem The source \ref Item from which flags are copied.
*/
void copyItemFlags(Item* dstItem, const Item* srcItem);
/**
* Subscribes to change events about a specific item.
*
* When finished with the subscription, call \ref unsubscribeToChangeEvents.
*
* @param baseItem An item
* @param path The subpath from \p baseItem or `nullptr`
* @param onChangeEventFn The function to call when a change event occurs
* @param userData User-specific data that will be provided to \p onChangeEventFn
* @return A subscription handle that can be used with \ref unsubscribeToChangeEvents
*/
SubscriptionId*(CARB_ABI* subscribeToNodeChangeEvents)(Item* baseItem,
const char* path,
OnNodeChangeEventFn onChangeEventFn,
void* userData);
/**
* Subscribes to change events for all items in a subtree.
*
* All items under `<baseItem>/<path>` will trigger change notifications.
*
* When finished with the subscription, call \ref unsubscribeToChangeEvents.
*
* @param baseItem An item
* @param path The subpath from \p baseItem or `nullptr`
* @param onChangeEventFn The function to call when a change event occurs
* @param userData User-specific data that will be provided to \p onChangeEventFn
* @return A subscription handle that can be used with \ref unsubscribeToChangeEvents()
*/
SubscriptionId*(CARB_ABI* subscribeToTreeChangeEvents)(Item* baseItem,
const char* path,
OnTreeChangeEventFn onChangeEventFn,
void* userData);
/**
* Unsubscribes from change events
*
* @param subscriptionId The subscription handle from \ref subscribeToNodeChangeEvents or
* \ref subscribeToTreeChangeEvents
*/
void(CARB_ABI* unsubscribeToChangeEvents)(SubscriptionId* subscriptionId);
/**
* Unsubscribes all node change handles for a specific Item.
*
* @param item An item
*/
void(CARB_ABI* unsubscribeItemFromNodeChangeEvents)(Item* item);
/**
* Unsubscribes all subtree change handles for a specific Item.
*
* @param item An item
*/
void(CARB_ABI* unsubscribeItemFromTreeChangeEvents)(Item* item);
/**
* Locks an Item for reading.
*
* Mutex-locks `item` for reading. This is only necessary if you are doing multiple read operations and require
* thread-safe consistency across the multiple operations. May be called multiple times within a thread, but
* unlock() must be called for each readLock() call, once the read lock is no longer needed.
* @warning Do not use readLock() directly; prefer \ref ScopedRead instead.
* @warning If a read lock is held and the same thread later takes a write lock, all locks will be released for a
* brief period of time, in which case another thread may be able to make changes.
* @see unlock writeLock ScopedRead ScopedWrite
* @param item The item to read-lock. `item`'s entire hierarchy will be read-locked. `nullptr` is ignored, but
* passing `nullptr` may cause synchronization issues. `item` must not be destroyed while the read lock is held.
* The same `item` should be passed to \ref unlock to unlock at a later point.
*/
void(CARB_ABI* readLock)(const Item* item);
/**
* Locks an Item for writing.
*
* Mutex-locks `item` for writing (exclusive access). This is only necessary if you are doing multiple read/write
* operations and require thread-safe consistency across the multiple operations. May be called multiple times
* within a thread, but unlock() must be called for each writeLock() call, once the write lock is no longer
* needed. Calling writeLock() when a readLock() is already held will release the lock and wait until exclusive
* write lock can be gained.
* @warning Do not use writeLock() directly; prefer \ref ScopedWrite instead.
* @see readLock unlock ScopedRead ScopedWrite
* @param item The item to write-lock. `item`'s entire hierarchy will be write-locked. `nullptr` is ignored, but
* passing `nullptr` may cause synchronization issues. `item` must not be destroyed while the write lock is held.
* The same `item` should be passed to \ref unlock to unlock at a later point.
*/
void(CARB_ABI* writeLock)(Item* item);
/**
* Releases a lock from a prior readLock() or writeLock().
*
* Releases a held read- or write-lock. Must be called once for each read- or write-lock that is held. Must be
* called in the same thread that initiated the read- or write-lock.
* @warning Do not use unlock() directly; prefer using \ref ScopedWrite or \ref ScopedRead instead.
* @see readLock writeLock ScopedRead ScopedWrite
* @param item The item to unlock. `item`'s entire hierarchy will be unlocked
*/
void(CARB_ABI* unlock)(const Item* item);
/**
* Returns a 128-bit hash representing the value.
*
* This hash is invariant to the order of keys and values.
*
* We guarantee that the hashing algorithm will not change unless the version number
* of the interface changes.
*
* @param item The item to take the hash of.
* @return The 128-bit hash of the item.
*/
const extras::hash128_t(CARB_ABI* getHash)(const Item* item);
/**
* Duplicates a dictionary
*
* @note The function duplicateItem should be preferred to this internal function.
*
* @param srcItem The item to duplicate
* @param newParent The new parent of the dictionary, if nullptr, makes a new root.
* @param newKey If new parent is given, then newKey is new the key of that parent. If, the key already exists it is
* overwritten.
* @returns The created item.
*/
Item*(CARB_ABI* duplicateItemInternal)(const Item* item, Item* newParent, const char* newKey);
/**
* Lexicographically compares two Items.
*
* The items being compared do not need to be root items. If the items are a key of a parent object, that key is not
* included in the comparison.
*
* The rules match https://en.cppreference.com/w/cpp/algorithm/lexicographical_compare, treating the key and values
* in the dictionary as an ordered set. The "type" is included in the comparison, however the rules of what types
* are ordered differently than others may change on a version change of this interface.
*
* The function will return a negative, zero, or positive number. The magnitude of the number bears no importance,
* and shouldn't be assumed to. A negative number means that itemA < itemB, zero itemA = itemB, and positive itemA >
* itemB.
*
* @param itemA The first item to compare.
* @param itemB The second item to compare.
* @returns The result of a lexicographical compare of itemA and itemB.
*/
int(CARB_ABI* lexicographicalCompare)(const Item* itemA, const Item* itemB);
/**
* Duplicates a given item as a new root.
*
* @param item The item to duplicate.
* @returns A new item that where item is to root.
*/
Item* duplicateItem(const Item* item)
{
return duplicateItemInternal(item, nullptr, nullptr);
}
/**
* Duplicates a item where another item is the parent.
*
* If the key already exists, the item will be overridden.
*
* @param item The item to duplicate.
* @param newParent The parent item to own the duplicated item.
* @param newKey the key in the parent.
* @returns The newly duplicated item.
*/
Item* duplicateItem(const Item* item, Item* newParent, const char* newKey)
{
return duplicateItemInternal(item, newParent, newKey);
}
};
/**
* A helper class for calling writeLock() and unlock(). Similar to `std::unique_lock`.
*/
class ScopedWrite
{
const IDictionary* m_pDictionary;
Item* m_pItem;
public:
/**
* RAII constructor. Immediately takes a write lock until *this is destroyed.
* @note Dictionary locks are recursive.
* @warning If the current thread already owns a read lock (i.e. via \ref ScopedRead), promotion to a write lock
* necessitates *releasing* all locks and then waiting for a write lock. This can cause state to change. Always
* re-evaluate state if this is the case.
* @param dictionary A reference to \ref IDictionary.
* @param item The item in the subtree to lock. The root of this item is found and the entire subtree from the root
* is locked. **NOTE:** Undefined behavior occurs if `item` is destroyed before `*this` is destroyed.
*/
ScopedWrite(const IDictionary& dictionary, Item* item) : m_pDictionary(std::addressof(dictionary)), m_pItem(item)
{
m_pDictionary->writeLock(m_pItem);
}
//! Destructor. Releases the write lock.
~ScopedWrite()
{
m_pDictionary->unlock(m_pItem);
}
CARB_PREVENT_COPY_AND_MOVE(ScopedWrite);
};
/**
* A helper class for calling readLock() and unlock(). Similar to `std::shared_lock`.
*/
class ScopedRead
{
const IDictionary* m_pDictionary;
const Item* m_pItem;
public:
/**
* RAII constructor. Immediately takes a read lock until *this is destroyed.
*
* @note Dictionary locks are recursive.
* @param dictionary A reference to \ref IDictionary.
* @param item The item in the subtree to lock. The root of this item is found and the entire subtree from the root
* is locked. **NOTE:** Undefined behavior occurs if `item` is destroyed before `*this` is destroyed.
*/
ScopedRead(const IDictionary& dictionary, const Item* item)
: m_pDictionary(std::addressof(dictionary)), m_pItem(item)
{
m_pDictionary->readLock(m_pItem);
}
//! Destructor. Releases the read lock.
~ScopedRead()
{
m_pDictionary->unlock(m_pItem);
}
CARB_PREVENT_COPY_AND_MOVE(ScopedRead);
};
inline int32_t IDictionary::getAsInt(const Item* item)
{
auto val = getAsInt64(item);
CARB_ASSERT(val >= INT_MIN && val <= INT_MAX);
return int32_t(val);
}
inline void IDictionary::setInt(Item* item, int32_t value)
{
setInt64(item, static_cast<int64_t>(value));
}
inline Item* IDictionary::makeIntAtPath(Item* baseItem, const char* path, int32_t value)
{
return makeInt64AtPath(baseItem, path, static_cast<int64_t>(value));
}
inline float IDictionary::getAsFloat(const Item* item)
{
return static_cast<float>(getAsFloat64(item));
}
inline void IDictionary::setFloat(Item* item, float value)
{
setFloat64(item, static_cast<double>(value));
}
inline Item* IDictionary::makeFloatAtPath(Item* baseItem, const char* path, float value)
{
return makeFloat64AtPath(baseItem, path, static_cast<double>(value));
}
inline int32_t IDictionary::getAsIntAt(const Item* item, size_t index)
{
auto val = getAsInt64At(item, index);
CARB_ASSERT(val >= INT_MIN && val <= INT_MAX);
return int32_t(val);
}
inline void IDictionary::setIntAt(Item* item, size_t index, int32_t value)
{
setInt64At(item, index, static_cast<int64_t>(value));
}
inline float IDictionary::getAsFloatAt(const Item* item, size_t index)
{
return static_cast<float>(getAsFloat64At(item, index));
}
inline void IDictionary::setFloatAt(Item* item, size_t index, float value)
{
setFloat64At(item, index, static_cast<double>(value));
}
inline Item* IDictionary::makeInt64AtPath(Item* parentItem, const char* path, int64_t value)
{
ScopedWrite g(*this, parentItem);
Item* item = getItemMutable(parentItem, path);
if (!item)
{
item = createItem(parentItem, path, ItemType::eInt);
}
setInt64(item, value);
return item;
}
inline Item* IDictionary::makeFloat64AtPath(Item* parentItem, const char* path, double value)
{
ScopedWrite g(*this, parentItem);
Item* item = getItemMutable(parentItem, path);
if (!item)
{
item = createItem(parentItem, path, ItemType::eFloat);
}
setFloat64(item, value);
return item;
}
inline Item* IDictionary::makeBoolAtPath(Item* parentItem, const char* path, bool value)
{
ScopedWrite g(*this, parentItem);
Item* item = getItemMutable(parentItem, path);
if (!item)
{
item = createItem(parentItem, path, ItemType::eBool);
}
setBool(item, value);
return item;
}
inline Item* IDictionary::makeStringAtPath(Item* parentItem, const char* path, const char* value, size_t stringLen)
{
ScopedWrite g(*this, parentItem);
Item* item = getItemMutable(parentItem, path);
if (!item)
{
item = createItem(parentItem, path, ItemType::eString);
}
setString(item, value, stringLen);
return item;
}
inline Item* IDictionary::makeDictionaryAtPath(Item* parentItem, const char* path)
{
ScopedWrite g(*this, parentItem);
Item* item = getItemMutable(parentItem, path);
if (!item)
{
item = createItem(parentItem, path, ItemType::eDictionary);
return item;
}
ItemType itemType = getItemType(item);
if (itemType != ItemType::eDictionary)
{
destroyItem(item);
item = createItem(parentItem, path, ItemType::eDictionary);
}
return item;
}
#ifndef DOXYGEN_BUILD
template <>
inline int32_t IDictionary::get<int32_t>(const dictionary::Item* item)
{
return getAsInt(item);
}
template <>
inline int64_t IDictionary::get<int64_t>(const dictionary::Item* item)
{
return getAsInt64(item);
}
template <>
inline float IDictionary::get<float>(const dictionary::Item* item)
{
return getAsFloat(item);
}
template <>
inline double IDictionary::get<double>(const dictionary::Item* item)
{
return getAsFloat64(item);
}
template <>
inline bool IDictionary::get<bool>(const dictionary::Item* item)
{
return getAsBool(item);
}
template <>
inline const char* IDictionary::get<const char*>(const dictionary::Item* item)
{
return getStringBuffer(item);
}
template <>
inline Int2 IDictionary::get<Int2>(const dictionary::Item* item)
{
Int2 value;
getAsIntArray(item, &value.x, 2);
return value;
}
template <>
inline Int3 IDictionary::get<Int3>(const dictionary::Item* item)
{
Int3 value;
getAsIntArray(item, &value.x, 3);
return value;
}
template <>
inline Int4 IDictionary::get<Int4>(const dictionary::Item* item)
{
Int4 value;
getAsIntArray(item, &value.x, 4);
return value;
}
template <>
inline Uint2 IDictionary::get<Uint2>(const dictionary::Item* item)
{
int64_t value[2];
getAsInt64Array(item, value, 2);
return { static_cast<uint32_t>(value[0]), static_cast<uint32_t>(value[1]) };
}
template <>
inline Uint3 IDictionary::get<Uint3>(const dictionary::Item* item)
{
int64_t value[3];
getAsInt64Array(item, value, 3);
return { static_cast<uint32_t>(value[0]), static_cast<uint32_t>(value[1]), static_cast<uint32_t>(value[2]) };
}
template <>
inline Uint4 IDictionary::get<Uint4>(const dictionary::Item* item)
{
int64_t value[4];
getAsInt64Array(item, value, 4);
return { static_cast<uint32_t>(value[0]), static_cast<uint32_t>(value[1]), static_cast<uint32_t>(value[2]),
static_cast<uint32_t>(value[3]) };
}
template <>
inline Float2 IDictionary::get<Float2>(const dictionary::Item* item)
{
Float2 value;
getAsFloatArray(item, &value.x, 2);
return value;
}
template <>
inline Float3 IDictionary::get<Float3>(const dictionary::Item* item)
{
Float3 value;
getAsFloatArray(item, &value.x, 3);
return value;
}
template <>
inline Float4 IDictionary::get<Float4>(const dictionary::Item* item)
{
Float4 value;
getAsFloatArray(item, &value.x, 4);
return value;
}
template <>
inline Double2 IDictionary::get<Double2>(const dictionary::Item* item)
{
Double2 value;
getAsFloat64Array(item, &value.x, 2);
return value;
}
template <>
inline Double3 IDictionary::get<Double3>(const dictionary::Item* item)
{
Double3 value;
getAsFloat64Array(item, &value.x, 3);
return value;
}
template <>
inline Double4 IDictionary::get<Double4>(const dictionary::Item* item)
{
Double4 value;
getAsFloat64Array(item, &value.x, 4);
return value;
}
template <class T>
inline T IDictionary::get(const dictionary::Item* baseItem, const char* path)
{
return get<T>(getItem(baseItem, path));
}
template <>
inline void IDictionary::makeAtPath<int32_t>(dictionary::Item* baseItem, const char* path, int32_t value)
{
makeIntAtPath(baseItem, path, value);
}
template <>
inline void IDictionary::makeAtPath<int64_t>(dictionary::Item* baseItem, const char* path, int64_t value)
{
makeInt64AtPath(baseItem, path, value);
}
template <>
inline void IDictionary::makeAtPath<float>(dictionary::Item* baseItem, const char* path, float value)
{
makeFloatAtPath(baseItem, path, value);
}
template <>
inline void IDictionary::makeAtPath<double>(dictionary::Item* baseItem, const char* path, double value)
{
makeFloat64AtPath(baseItem, path, value);
}
template <>
inline void IDictionary::makeAtPath<bool>(dictionary::Item* baseItem, const char* path, bool value)
{
makeBoolAtPath(baseItem, path, value);
}
template <>
inline void IDictionary::makeAtPath<const char*>(dictionary::Item* baseItem, const char* path, const char* value)
{
makeStringAtPath(baseItem, path, value);
}
template <>
inline void IDictionary::makeAtPath<std::string>(dictionary::Item* baseItem, const char* path, std::string value)
{
makeStringAtPath(baseItem, path, value.data(), value.size());
}
template <>
inline void IDictionary::makeAtPath<cpp::string_view>(dictionary::Item* baseItem, const char* path, cpp::string_view value)
{
makeStringAtPath(baseItem, path, value.data(), value.length());
}
template <>
inline void IDictionary::makeAtPath<omni::string>(dictionary::Item* baseItem, const char* path, omni::string value)
{
makeStringAtPath(baseItem, path, value.data(), value.size());
}
template <>
inline void IDictionary::setArray(Item* baseItem, const bool* array, size_t arrayLength)
{
setBoolArray(baseItem, array, arrayLength);
}
template <>
inline void IDictionary::setArray(Item* baseItem, const int32_t* array, size_t arrayLength)
{
setIntArray(baseItem, array, arrayLength);
}
template <>
inline void IDictionary::setArray(Item* baseItem, const int64_t* array, size_t arrayLength)
{
setInt64Array(baseItem, array, arrayLength);
}
template <>
inline void IDictionary::setArray(Item* baseItem, const float* array, size_t arrayLength)
{
setFloatArray(baseItem, array, arrayLength);
}
template <>
inline void IDictionary::setArray(Item* baseItem, const double* array, size_t arrayLength)
{
setFloat64Array(baseItem, array, arrayLength);
}
template <>
inline void IDictionary::setArray(Item* baseItem, const char* const* array, size_t arrayLength)
{
setStringArray(baseItem, array, arrayLength);
}
template <>
inline void IDictionary::makeAtPath<Int2>(dictionary::Item* baseItem, const char* path, Int2 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
setArray<int32_t>(item, &value.x, 2);
}
template <>
inline void IDictionary::makeAtPath<Int3>(dictionary::Item* baseItem, const char* path, Int3 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
setArray<int32_t>(item, &value.x, 3);
}
template <>
inline void IDictionary::makeAtPath<Int4>(dictionary::Item* baseItem, const char* path, Int4 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
setArray<int32_t>(item, &value.x, 4);
}
template <>
inline void IDictionary::makeAtPath<Uint2>(dictionary::Item* baseItem, const char* path, Uint2 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
int64_t values64[] = { value.x, value.y };
setArray<int64_t>(item, values64, 2);
}
template <>
inline void IDictionary::makeAtPath<Uint3>(dictionary::Item* baseItem, const char* path, Uint3 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
int64_t values64[] = { value.x, value.y, value.z };
setArray<int64_t>(item, values64, 3);
}
template <>
inline void IDictionary::makeAtPath<Uint4>(dictionary::Item* baseItem, const char* path, Uint4 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
int64_t values64[] = { value.x, value.y, value.z, value.w };
setArray<int64_t>(item, values64, 4);
}
template <>
inline void IDictionary::makeAtPath<Float2>(dictionary::Item* baseItem, const char* path, Float2 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
setArray<float>(item, &value.x, 2);
}
template <>
inline void IDictionary::makeAtPath<Float3>(dictionary::Item* baseItem, const char* path, Float3 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
setArray<float>(item, &value.x, 3);
}
template <>
inline void IDictionary::makeAtPath<Float4>(dictionary::Item* baseItem, const char* path, Float4 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
setArray<float>(item, &value.x, 4);
}
template <>
inline void IDictionary::makeAtPath<Double2>(dictionary::Item* baseItem, const char* path, Double2 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
setArray<double>(item, &value.x, 2);
}
template <>
inline void IDictionary::makeAtPath<Double3>(dictionary::Item* baseItem, const char* path, Double3 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
setArray<double>(item, &value.x, 3);
}
template <>
inline void IDictionary::makeAtPath<Double4>(dictionary::Item* baseItem, const char* path, Double4 value)
{
dictionary::Item* item = baseItem;
if (path && path[0] != '\0')
{
item = makeDictionaryAtPath(baseItem, path);
}
setArray<double>(item, &value.x, 4);
}
#endif
inline void IDictionary::deleteChildren(Item* item)
{
ScopedWrite g(*this, item);
size_t childCount = getItemChildCount(item);
while (childCount != 0)
destroyItem(getItemChildByIndexMutable(item, --childCount));
}
inline void IDictionary::copyItemFlags(Item* dstItem, const Item* srcItem)
{
setItemFlag(dstItem, ItemFlag::eUnitSubtree, getItemFlag(srcItem, ItemFlag::eUnitSubtree));
}
} // namespace dictionary
} // namespace carb
| 83,622 | C | 42.216021 | 123 | 0.682069 |
omniverse-code/kit/include/carb/variant/VariantUtils.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Utilities for *carb.variant.plugin*
#pragma once
#include "VariantTypes.h"
namespace carb
{
namespace variant
{
/**
* A helper function to translate a typed value into a \ref VariantData via a \ref Translator. A compile error will
* occur if no \ref Translator could be found for the decayed type.
* @param type The value of type \c Type.
* @returns A VariantData constructed from \p type. \ref traits::destruct() must be called on the VariantData when
* finished with it.
*/
template <class Type>
VariantData translate(Type&& type) noexcept;
//! A structure containing functions for performing the prescribed actions on a \ref VariantData. The functions handle
//! the default behavior if the v-table or v-table function are \c nullptr.
struct traits
{
/**
* Swaps two \ref VariantData members.
* @note \ref VariantData is treated as a trivial type and no v-table functions are required to perform this.
* @param lhs The left-hand VariantData.
* @param rhs The right-hand VariantData.
*/
static void swap(VariantData& lhs, VariantData& rhs) noexcept;
/**
* Destructs a \ref VariantData.
* @note The default behavior (if `!self.vtable->Destructor`) treats \p self as trivially destructible.
* @param self The VariantData to destruct.
*/
static void destruct(VariantData& self) noexcept;
/**
* Copies a \ref VariantData.
* @note The default behavior (if `!self.vtable->Copy`) treats \p self as trivially copyable.
* @param self The VariantData to copy.
* @returns A VariantData that represents a copy of \p self. The v-table of the return value must be the same as
* `self.vtable`. When finished with the return value, it must be destroyed via destruct().
*/
static VariantData copy(const VariantData& self) noexcept;
/**
* Tests two \ref VariantData instances for equality.
* @note The default behavior (if `!self.vtable->Equals`) treats \p self and \p other as trivially comparable (i.e.
* bitwise compare via \c std::memcmp).
* @param self The VariantData to compare. This parameter provides the v-table for the comparison.
* @param other The other VariantData to compare.
* @returns \c true if \p self and \p other are equal; \c false otherwise.
*/
static bool equals(const VariantData& self, const VariantData& other) noexcept;
/**
* Renders a \ref VariantData as a string for debugging purposes.
* @note The default behavior (if `!self.vtable->ToString`) produces `"<vtable>:<data>"`.
* @param self The VariantData to render as a string.
* @returns A string representing \p self for debugging purposes.
*/
static omni::string toString(const VariantData& self) noexcept;
/**
* Attempts to convert a \ref VariantData to a different type. If \p newType is the same as `self.vtable`, then
* \ref traits::copy() is invoked instead.
* @note The default behavior (if `!self.vtable->ConvertTo`) merely returns \c false.
* @param self The VariantData to convert. This parameter provides the v-table for the comparison.
*/
static bool convertTo(const VariantData& self, const VTable* newType, VariantData& out) noexcept;
/**
* Computes a hash of a \ref VariantData.
* @note The default behavior (if `!self.vtable->Hash`) produces `size_t(self.data)`.
* @param self The VariantData to hash.
* @returns A hash value representing \p self.
*/
static size_t hash(const VariantData& self) noexcept;
};
//! A wrapper class for managing the lifetime of \ref VariantData and converting the contained value to C++ types.
class Variant final : protected VariantData
{
public:
/**
* Default constructor. Produces an empty Variant, that is, \ref hasValue() will return \c false. Any attempt to
* \ref getValue() will fail and \ref convertTo() will produce an empty Variant. Empty Variants are only equal to
* other empty Variants.
*/
Variant() noexcept;
/**
* Construct based on given type.
*
* To allow copy/move constructors to work properly, this constructor participates in overload resolution only if
* \c T is not \ref Variant.
*
* @warning This function will fail to compile if a \ref Translator cannot be found for \c T.
* @param val The value to store in the variant.
*/
#ifndef DOXYGEN_BUILD
template <class T, typename std::enable_if_t<!std::is_same<std::decay_t<T>, Variant>::value, bool> = true>
#else
template <class T>
#endif
explicit Variant(T&& val) noexcept
{
// This function cannot be externally inlined due to MSVC not understanding the enable_if in the inlined
// function.
data() = translate(std::forward<T>(val));
}
/**
* Destructor.
*/
~Variant() noexcept;
/**
* Copy constructor.
* @param other The Variant to copy.
*/
Variant(const Variant& other) noexcept;
/**
* Copy-assign operator.
* @param other The Variant to copy.
* @returns \c *this
*/
Variant& operator=(const Variant& other) noexcept;
/**
* Move constructor.
* @param other The Variant to move from. \p other is left in an empty state.
*/
Variant(Variant&& other) noexcept;
/**
* Move-assign operator.
* @param other The Variant to move from.
* @returns \c *this
*/
Variant& operator=(Variant&& other) noexcept;
/**
* Tests for equality between two variants.
* @param other The other Variant.
* @returns \c true if the Variants are equal; \c false otherwise.
*/
bool operator==(const Variant& other) const noexcept;
/**
* Tests for inequality between two variants.
* @param other The other Variant.
* @returns \c true if the Variants are not equal; \c false otherwise.
*/
bool operator!=(const Variant& other) const noexcept;
/**
* Tests if a Variant is empty (i.e. contains no value).
* @returns \c true if the Variant is empty; \c false otherwise.
*/
bool hasValue() const noexcept;
/**
* Renders the Variant as a string for debugging purposes.
* @returns The string value of the variant.
*/
omni::string toString() const noexcept;
/**
* Obtains the hash value of the variant.
* @returns The hash value of the variant.
*/
size_t getHash() const noexcept;
/**
* Attempts to convert the Variant to the given type.
* @returns A \c optional containing the requested value if conversion succeeds; an empty \c optional otherwise.
*/
template <class T>
cpp::optional<T> getValue() const noexcept;
/**
* Attempts to convert the Variant to the given type with a fallback value if conversion fails.
* @param fallback The default value to return if conversion fails.
* @returns The contained value if conversion succeeds, or \p fallback if conversion fails.
*/
template <class T>
T getValueOr(T&& fallback) const noexcept;
/**
* Attempts to convert to a Variant of a different type.
* @returns A Variant representing a different C++ type if conversion succeeds, otherwise returns an empty Variant.
*/
template <class T>
Variant convertTo() const noexcept;
/**
* Access the underlying \ref VariantData.
* @returns The underlying \ref VariantData.
*/
const VariantData& data() const noexcept
{
return *this;
}
private:
VariantData& data() noexcept
{
return *this;
}
};
// The Variant class is intended only to add functions on top of VariantData. Therefore, the size must match.
static_assert(sizeof(Variant) == sizeof(VariantData), "");
// This is an ABI-stable representation of std::pair<Variant, Variant>, used only by Translator and internally by
// carb.variant.plugin.
//! @private
struct VariantPair
{
Variant first;
Variant second;
};
static_assert(std::is_standard_layout<VariantPair>::value, ""); // not interop-safe because not trivially copyable
/**
* A representation of a key value pair, similar to `std::pair<const Variant, Variant>`.
* ABI-stable representation to transact with *carb.variant.plugin*.
*/
struct KeyValuePair
{
const Variant first; //!< The first item in the pair; the key.
Variant second; //!< The second item in the pair; the value.
};
static_assert(std::is_standard_layout<KeyValuePair>::value, ""); // not interop-safe because not trivially copyable
//! Lifetime management wrapper for @ref IVariant::registerType().
class Registrar
{
public:
/**
* Default constructor. Constructs an empty registrar.
*/
constexpr Registrar() noexcept;
/**
* Constructor. Registers the type.
* @note If registration fails, isEmpty() will return `true`.
* @see IVariant::registerType()
* @param vtable The v-table pointer to register.
*/
Registrar(const VTable* vtable) noexcept;
/**
* Destructor. Unregisters the type. No-op if isEmpty() returns `true`.
*/
~Registrar() noexcept;
/**
* Move-construct. Moves the registered type to \c *this and leaves \p other empty.
* @param other The other Registrar to move from.
*/
Registrar(Registrar&& other) noexcept;
/**
* Move-assign. Swaps state with \p other.
* @param other The other Registrar to swap state with.
* @returns \c *this
*/
Registrar& operator=(Registrar&& other) noexcept;
/**
* Checks whether \c *this is empty.
* @returns \c true if \c *this does not contain a valid type; \c false otherwise.
*/
bool isEmpty() const noexcept;
/**
* Retrieves the registered type.
* @returns The managed type, or an empty \c RString if \c *this is empty and no type is managed.
*/
RString getType() const noexcept;
/**
* Resets \c *this to an empty state, unregistering any registered type.
*/
void reset() noexcept;
private:
RString m_type;
};
} // namespace variant
//! Namespace for *carb.variant* literal helpers.
namespace variant_literals
{
/** Literal cast operator for an unsigned long long variant value.
*
* @param[in] val The value to be contained in the variant object.
* @returns The variant object containing the requested value.
*/
CARB_NODISCARD inline variant::Variant operator"" _v(unsigned long long val) noexcept
{
return variant::Variant{ val };
}
/** Literal cast operator for a long double variant value.
*
* @param[in] val The value to be contained in the variant object.
* @returns The variant object containing the requested value.
*/
CARB_NODISCARD inline variant::Variant operator"" _v(long double val) noexcept
{
return variant::Variant{ (double)val };
}
/** Literal cast operator for a string variant value.
*
* @param[in] str The string to be contained in the variant object.
* @param[in] length The length of the string to be contained in the variant object.
* @returns The variant object containing the requested value.
*/
CARB_NODISCARD inline variant::Variant operator"" _v(const char* str, size_t length) noexcept
{
CARB_UNUSED(length);
return variant::Variant{ str };
}
} // namespace variant_literals
} // namespace carb
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace std
{
template <>
struct hash<carb::variant::Variant>
{
size_t operator()(const carb::variant::Variant& v) const noexcept
{
return v.getHash();
}
};
inline std::string to_string(const carb::variant::Variant& v)
{
auto str = v.toString();
return std::string(str.begin(), str.end());
}
} // namespace std
#endif
| 12,182 | C | 31.927027 | 119 | 0.673124 |
omniverse-code/kit/include/carb/variant/IVariant.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Interface definition for *carb.variant.plugin*
#pragma once
#include "../Interface.h"
#include "VariantTypes.h"
namespace carb
{
//! Namespace for *carb.variant.plugin* and related utilities.
namespace variant
{
//! Interface for *carb.variant.plugin*
struct IVariant
{
CARB_PLUGIN_INTERFACE("carb::variant::IVariant", 0, 1)
/**
* Retrieves a v-table by variant type. Typically not used; see \ref Translator instead.
* @param type The type to translate.
* @returns A v-table for the given type, or \c nullptr in case of an unknown type.
*/
const VTable*(CARB_ABI* getVTable)(RString type) noexcept;
/**
* Registers a user variant type.
*
* @note `vtable->typeName` must be a unique name within the running process and may not match any of the built-in
* type names.
* @param vtable Must not be \c nullptr. This pointer is retained by *carb.variant.plugin* so the caller must
* guarantee its lifetime until it is unregistered with \ref unregisterType(). A program that still references the
* v-table in a \ref VariantData (or \ref Variant) after it is unregistered is malformed.
* @returns \c true if `vtable->typeName` was available and the type was successfully registered; \c false
* otherwise.
*/
bool(CARB_ABI* registerType)(const VTable* vtable) noexcept;
/**
* Registers a user variant type.
*
* @param type The name of the type previously registered with \ref registerType().
* @returns \c true if the type was unregistered; \c false otherwise (i.e. the type was not previously registered).
*/
bool(CARB_ABI* unregisterType)(RString type) noexcept;
//! @private
VariantArray*(CARB_ABI* internalCreateArray)(const Variant* p, size_t count);
/**
* Creates a \ref VariantArray object from the given parameters.
*
* @param p The raw array to copy into the new \ref VariantArray; may be \c nullptr to produce an empty array.
* @param count The count of items in @p p.
* @returns A newly created \ref VariantArray object.
*/
CARB_NODISCARD VariantArrayPtr createArray(const Variant* p = nullptr, size_t count = 0);
//! @private
VariantMap*(CARB_ABI* internalCreateMap)();
/**
* Creates a \ref VariantMap object.
* @returns A newly created \ref VariantMap object.
*/
CARB_NODISCARD VariantMapPtr createMap();
};
} // namespace variant
} // namespace carb
#include "IVariant.inl"
| 2,952 | C | 34.154761 | 119 | 0.695122 |
omniverse-code/kit/include/carb/variant/VariantBindingsPython.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../BindingsPythonUtils.h"
#include "IVariant.h"
#include "VariantUtils.h"
#include "../extras/EnvironmentVariable.h"
namespace carb
{
namespace variant
{
// PyObjectVTable for python variant types
struct PyObjectVTable
{
static_assert(sizeof(py::object) == sizeof(void*), "Bad assumption");
static void Destructor(VariantData* self) noexcept
{
try
{
py::object* p = reinterpret_cast<py::object*>(&self->data);
py::gil_scoped_acquire gil;
p->~object();
}
catch (...)
{
}
}
static VariantData Copy(const VariantData* self) noexcept
{
const py::object* p = reinterpret_cast<const py::object*>(&self->data);
VariantData d{ self->vtable, nullptr };
try
{
py::gil_scoped_acquire gil;
new (&d.data) py::object(*p);
}
catch (...)
{
}
return d;
}
static bool Equals(const VariantData* self, const VariantData* other) noexcept
{
if (self->vtable == other->vtable)
{
CARB_ASSERT(self->vtable == get());
const py::object* pself = reinterpret_cast<const py::object*>(&self->data);
const py::object* pother = reinterpret_cast<const py::object*>(&other->data);
try
{
py::gil_scoped_acquire gil;
return pself->is(*pother);
}
catch (...)
{
return false;
}
}
// Try to convert us into the other type since it's not a python type
VariantData temp;
if (traits::convertTo(*self, other->vtable, temp))
{
bool b = traits::equals(temp, *other);
traits::destruct(temp);
return b;
}
return false;
}
static omni::string ToString(const VariantData* self) noexcept
{
const py::object* pself = reinterpret_cast<const py::object*>(&self->data);
try
{
py::gil_scoped_acquire gil;
auto str = pself->cast<std::string>();
return omni::string(str.begin(), str.end());
}
catch (...)
{
return omni::string(omni::formatted, "py::object:%p", pself->ptr());
}
}
template <class T>
static bool Convert(const py::object& val, void*& out) noexcept
{
Translator<T> t{};
try
{
out = t.data(val.cast<T>());
return true;
}
catch (...)
{
}
return false;
}
static bool ConvertTo(const VariantData* self, const VTable* newtype, VariantData* target) noexcept
{
const py::object* pself = reinterpret_cast<const py::object*>(&self->data);
try
{
static std::unordered_map<RString, bool (*)(const py::object&, void*&)> converters{
{ eBool, Convert<bool> },
{ eUInt8, Convert<uint8_t> },
{ eUInt16, Convert<uint16_t> },
{ eUInt32, Convert<uint32_t> },
{ eUInt64, Convert<uint64_t> },
{ eInt8, Convert<int8_t> },
{ eInt16, Convert<int16_t> },
{ eInt32, Convert<int32_t> },
{ eInt64, Convert<int64_t> },
{ eFloat, Convert<float> },
{ eDouble, Convert<double> },
{ eString,
[](const py::object& val, void*& out) {
Translator<omni::string> t{};
try
{
py::gil_scoped_acquire gil;
auto str = val.cast<std::string>();
out = t.data(omni::string(str.begin(), str.end()));
return true;
}
catch (...)
{
}
return false;
} },
};
auto iter = converters.find(newtype->typeName);
if (iter != converters.end() && iter->second(*pself, target->data))
{
auto iface = getCachedInterface<IVariant>();
CARB_ASSERT(iface, "Failed to acquire interface IVariant");
target->vtable = iface->getVTable(iter->first);
return true;
}
return false;
}
catch (...)
{
}
return false;
}
static size_t Hash(const VariantData* self) noexcept
{
const py::object* pself = reinterpret_cast<const py::object*>(&self->data);
try
{
py::gil_scoped_acquire gil;
return py::hash(*pself);
}
catch (...)
{
return size_t(pself);
}
}
static const VTable* get() noexcept
{
static const VTable v{
sizeof(VTable), RString("py::object"), Destructor, Copy, Equals, ToString, ConvertTo, Hash
};
return &v;
}
};
// Translator for python
template <>
struct Translator<py::object, void>
{
static_assert(sizeof(py::object) == sizeof(void*), "Bad assumption");
RString type() const noexcept
{
static const RString t("py::object");
return t;
}
void* data(py::object o) const noexcept
{
void* d{};
py::gil_scoped_acquire gil;
new (&d) py::object(std::move(o));
return d;
}
py::object value(void* d) const noexcept
{
py::object* p = reinterpret_cast<py::object*>(&d);
py::gil_scoped_acquire gil;
return *p;
}
};
inline void definePythonModule(py::module& m)
{
// Try to load the variant module
IVariant* v = getFramework()->tryAcquireInterface<IVariant>();
if (!v)
{
PluginLoadingDesc desc = PluginLoadingDesc::getDefault();
extras::EnvironmentVariable ev("CARB_APP_PATH");
std::string str = ev.getValue().value_or(std::string{});
const char* p = str.c_str();
desc.searchPaths = &p;
desc.searchPathCount = 1;
const char* loaded[] = { "carb.variant.plugin" };
desc.loadedFileWildcards = loaded;
desc.loadedFileWildcardCount = CARB_COUNTOF(loaded);
getFramework()->loadPlugins(desc);
v = getFramework()->tryAcquireInterface<IVariant>();
CARB_ASSERT(v);
}
// Make sure our python handler is registered
if (v)
v->registerType(PyObjectVTable::get());
defineInterfaceClass<IVariant>(m, "IVariant", "acquire_variant_interface");
}
} // namespace variant
} // namespace carb
| 7,149 | C | 29.555555 | 103 | 0.522031 |
omniverse-code/kit/include/carb/variant/VariantTypes.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Type definitions for *carb.variant.plugin*
#pragma once
#include "../RString.h"
#include "../IObject.h"
#include "../../omni/String.h"
#include "../../omni/detail/PointerIterator.h"
namespace carb
{
namespace variant
{
//! @defgroup Types that are known (by default) to *carb.variant.plugin*.
//! @{
constexpr RString eNull{ carb::eRString::RS_null }; //!< Represents \c nullptr
constexpr RString eBool{ carb::eRString::RS_bool }; //!< Represents \c bool
constexpr RString eUInt8{ carb::eRString::RS_uint8 }; //!< Represents \c uint8_t or `unsigned char`
constexpr RString eUInt16{ carb::eRString::RS_uint16 }; //!< Represents \c uint16_t or `unsigned short`
constexpr RString eUInt32{ carb::eRString::RS_uint32 }; //!< Represents \c uint32_t or `unsigned int`
constexpr RString eUInt64{ carb::eRString::RS_uint64 }; //!< Represents \c uint64_t or `unsigned long long`
constexpr RString eInt8{ carb::eRString::RS_int8 }; //!< Represents \c int8_t or `signed char`
constexpr RString eInt16{ carb::eRString::RS_int16 }; //!< Represents \c int16_t or `short`
constexpr RString eInt32{ carb::eRString::RS_int32 }; //!< Represents \c int32_t or `int`
constexpr RString eInt64{ carb::eRString::RS_int64 }; //!< Represents \c int64_t or `long long`
constexpr RString eFloat{ carb::eRString::RS_float }; //!< Represents \c float
constexpr RString eDouble{ carb::eRString::RS_double }; //!< Represents \c double
constexpr RString eString{ carb::eRString::RS_string }; //!< Represents \c omni::string
constexpr RString eCharPtr{ carb::eRString::RS_charptr }; //!< Represents `char*` or `const char*`
constexpr RString eDictionary{ carb::eRString::RS_dictionary }; //!< Represents `dictionary::Item`.
constexpr RString eVariantPair{ carb::eRString::RS_variant_pair }; //!< Represents `std::pair<Variant, Variant>`
constexpr RString eVariantArray{ carb::eRString::RS_variant_array }; //!< Represents `VariantArray*`.
constexpr RString eVariantMap{ carb::eRString::RS_variant_map }; //!< Represents `VariantMap*`.
constexpr RString eRString{ carb::eRString::RS_RString }; //!< Represents \c RString
constexpr RString eRStringU{ carb::eRString::RS_RStringU }; //!< Represents \c RStringU
constexpr RString eRStringKey{ carb::eRString::RS_RStringKey }; //!< Represents \c RStringKey
constexpr RString eRStringUKey{ carb::eRString::RS_RStringUKey }; //!< Represents \c RStringUKey
//! @}
struct VTable;
class Variant;
/**
* A standard-layout @rstref{ABI-safe <abi-compatibility>} struct for communicating variant data. This struct is filled
* out by \ref Translator specializations.
*
* This class should generally not be used directly except by \ref Translator specializations. Instead use the
* \ref Variant wrapper-class.
*
* @see \ref Translator, \ref Variant
*/
struct VariantData
{
//! The v-table for this variant. Only empty variants are allowed a \c nullptr v-table. The v-table is used to
//! provide functions for variant behavior and can be used as a type-identifier of sorts.
const VTable* vtable;
//! A generic pointer whose interpretation is based on the v-table and the \ref Translator specialization that
//! created it.
void* data;
};
CARB_ASSERT_INTEROP_SAFE(VariantData);
//! A v-table definition for a variant type. Each registered type has a unique v-table pointer that is retrievable via
//! IVariant::getVTable(). Each entry in the v-table is a function with a default behavior if \c nullptr.
//! @note This class is applicable only to users of *carb.variant.plugin* that author a custom \ref Translator class.
//! @warning Functions in the v-table should not be called directly; the Variant wrapper class calls them through
//! various \ref traits functions.
//! @warning All functions require that `self->vtable->[function]` is equal to the function called.
struct VTable
{
/**
* A member used as version control. This member should be set to `sizeof(VTable)` for the version of the
* v-table that a module is built against.
*/
uint32_t sizeOf;
/**
* Indicates the type name of the v-table. Once registered with \ref IVariant::registerType(), this name can be used
* to look up the type with \ref IVariant::getVTable().
*
* @warning This must be a unique name within the running process and may not match any of the built-in type names.
*/
RString typeName;
/**
* Used to destroy the VariantData::data member. A \c nullptr destructor function indicates that no destruction
* needs to take place.
*
* @param self The VariantData to destroy. Can assume that `self->vtable->Destructor` is the same as the function
* called.
*/
void (*Destructor)(VariantData* self) noexcept;
/**
* Called to create a functional copy of the given VariantData. A \c nullptr function indicates that VariantData can
* be trivially copied.
* @note The resulting VariantData need not have the same v-table as \p self.
* @param self The VariantData to copy. Can assume that `self->vtable->Copy` is the same as the function called.
* @returns A VariantData that is a functional copy of \p self. \ref traits::equals() should be \c true for \c *self
* and the returned VariantData.
*/
VariantData (*Copy)(const VariantData* self) noexcept;
/**
* Called to test equality of \c *self with (possibly different type) \c *other. A \c nullptr function indicates
* that a trivial comparison of the \ref VariantData is performed (i.e. \c memcmp).
* @warning Generally speaking, order should not matter: assuming that \c lhs and \c rhs are both
* `const VariantData*` with non-null \c Equals, it should hold that `lhs->vtable->Equals(lhs, rhs)` should always
* equal `rhs->vtable->Equals(rhs, lhs)` regardless of their respective v-tables.
* @param self The VariantData performing the compare. Can assume that `self->vtable->Equals` is the same as the
* function called.
* @param other The same or a different VariantData to compare with \p self. May have a different \c vtable than
* \p self.
* @returns \c true if the types are equal; \c false otherwise.
*/
bool (*Equals)(const VariantData* self, const VariantData* other) noexcept;
/**
* Called to render the \ref VariantData as a string. A \c nullptr function indicates that a string is produced that
* contains "<vtable pointer>:<data pointer>".
* @param self The VariantData to render. Can assume that `self->vtable->ToString` is the same as the function
* called.
* @returns A type-dependent printable string representing the type, useful for debugging.
*/
omni::string (*ToString)(const VariantData* self) noexcept;
/**
* Called to attempt to convert \p self to a different type. A \c nullptr function is the same as returning false.
* @warning If \c false is returned, \p out is in an undefined state. If and only if \c true is returned,
* \ref traits::destruct() must be called at some later point on \c *out.
* @note Generally speaking, \ref Equals() and \ref ConvertTo() should understand the same types.
* @param self The VariantData performing the conversion. Can assume that `self->vtable->ConvertTo` is this same as
* the function called.
* @param newtype A v-table representing the type to attempt to convert to. If the function recognizes the given
* v-table (which should not be the same as `self->vtable`) and can convert to that type then the function should
* write to \p out and return \c true. If the v-table is not recognized, the function must return \c false.
* @param out If \c true is returned from the function, this must be a valid \ref VariantData and must be later
* destroyed with \ref traits::destruct(). If \c false is returned then the state of \p out is undefined. There is
* no requirement that `out->vtable` matches \p newtype if \c true is returned; it must merely be valid.
* @returns \c true if and only if \p out contains a valid converted representation of \p self; \c false otherwise.
*/
bool (*ConvertTo)(const VariantData* self, const VTable* newtype, VariantData* out) noexcept;
/**
* Computes a hash of \p self. A \c nullptr function casts `self->data` to a `size_t` for use as a hash.
* @param self The VariantData to hash. Can assume that `self->vtable->Hash` is the same as the function called.
* @returns A value to use as a hash identifying \c *self.
*/
size_t (*Hash)(const VariantData* self) noexcept;
// Note to maintainers: adding new functions here does not necessarily require a version change for IVariant. Add a
// `struct traits` function that performs a default behavior if the function is `nullptr` or if the `sizeOf` is less
// than the offset of your new member. All calls to the v-table function should happen in the new `traits` function.
};
CARB_ASSERT_INTEROP_SAFE(VTable);
/**
* An array-of-variants type that can itself be contained in a \ref Variant.
*
* Similar in many respects to `std::vector`, but reference-counted and implemented within *carb.variant.plugin*.
*
* Created via \ref IVariant::createArray().
*/
class VariantArray : public IObject
{
public:
//! A type conforming to RandomAccessIterator.
using iterator = omni::detail::PointerIterator<Variant*, VariantArray>;
//! A type conforming to RandomAccessIterator.
using const_iterator = omni::detail::PointerIterator<const Variant*, VariantArray>;
/**
* Provides direct access to the underlying array.
* @returns the beginning of the underlying array.
*/
virtual Variant* data() noexcept = 0;
//! @copydoc data()
virtual const Variant* data() const noexcept = 0;
/**
* Returns the number of variants contained.
* @returns the number of variants contained.
*/
virtual size_t size() const noexcept = 0;
/**
* Adds a variant to the end of the array.
* @param v The \ref Variant to add to the array.
*/
virtual void push_back(Variant v) noexcept = 0;
/**
* Attempts to insert a variant at the given offset.
*
* The given @p offset must be in `[0, size()]`, otherwise \c false is returned.
*
* @warning This is an O(n) operation.
*
* @param offset The 0-based offset indicating where to insert. The elements at that position (and all subsequent
* elements) will be pushed back to make room for @p v.
* @param v The \ref Variant to insert.
* @returns \c true if the given variant was inserted; \c false otherwise.
*/
virtual bool insert(size_t offset, Variant v) noexcept = 0;
/**
* Attempts to erase the variant at the given offset.
*
* The given @p offset must be in `[0, size())`, otherwise \c false is returned.
*
* @warning This is an O(n) operation.
*
* @param offset The 0-based offset indicating which element to erase. The elements following that position will be
* moved forward to fill in the gap removed at @p offset.
* @returns \c true if the variant was erased; \c false otherwise.
*/
virtual bool erase(size_t offset) noexcept = 0;
/**
* Pops the last element from the array.
*
* @returns \c true if the element was popped; \c false if the array is empty.
*/
virtual bool pop_back() noexcept = 0;
/**
* Clears the existing array elements and assigns new elements.
*
* @param p The beginning of the new array elements.
* @param count The number of array elements in the raw array @p p.
*/
virtual void assign(const Variant* p, size_t count) noexcept = 0;
/**
* Reserves space for elements.
*
* @param count The number of elements to reserve space for, exactly. If this amount is less than the current space,
* the request is ignored.
*/
virtual void reserve(size_t count) noexcept = 0;
/**
* Changes the number of elements stored.
*
* @param count The number of elements to store in the array. Elements at the end of the array are added (as via
* \ref Variant default construction) or removed so that following this call \ref size() matches @p count. Note that
* resizing heuristics may be applied, so \ref capacity() following this call may be greater than @p count.
*/
virtual void resize(size_t count) noexcept = 0;
/**
* Returns the number of elements that can be stored with the current allocated space.
* @returns The number of elements that can be stored with the current allocated space.
*/
virtual size_t capacity() const noexcept = 0;
/**
* Erases all elements from the array and leaves the array empty.
*/
void clear() noexcept;
/**
* Checks whether the array is empty.
*
* @returns \c true if the array is empty (contains no elements); \c false otherwise.
*/
bool empty() const noexcept;
/**
* Accesses an element with bounds checking.
* @throws std::out_of_range if @p index is outside of `[0, size())`.
* @param index The index of the array to access.
* @returns a reference to the element at the requested @p index.
*/
Variant& at(size_t index);
//! @copydoc at()
const Variant& at(size_t index) const;
/**
* Accesses an element without bounds checking.
* @warning Providing an @p index value outside of `[0, size())` is undefined behavior.
* @param index The index of the array to access.
* @returns a reference to the element at the requested @p index.
*/
Variant& operator[](size_t index) noexcept;
//! @copydoc operator[]()
const Variant& operator[](size_t index) const noexcept;
/**
* Accesses the element at the front of the array.
* @warning Undefined behavior if \ref empty().
* @returns a reference to the element at the front of the array.
*/
Variant& front() noexcept;
//! @copydoc front()
const Variant& front() const noexcept;
/**
* Accesses the element at the back of the array.
* @warning Undefined behavior if \ref empty().
* @returns a reference to the element at the back of the array.
*/
Variant& back() noexcept;
//! @copydoc back()
const Variant& back() const noexcept;
/**
* Provides iteration and ranged-for support; returns an iterator to the first element.
*
* @warning Iterators follow invalidation rules for `std::vector`.
* @returns An iterator to the first element.
*/
iterator begin() noexcept;
/**
* Provides iteration and ranged-for support; returns an iterator representing the iteration end.
*
* @warning Iterators follow invalidation rules for `std::vector`.
* @returns An iterator representing the iteration end.
*/
iterator end() noexcept;
//! @copydoc begin()
const_iterator begin() const noexcept;
//! @copydoc end()
const_iterator end() const noexcept;
};
//! Helper definition.
using VariantArrayPtr = ObjectPtr<VariantArray>;
struct KeyValuePair;
/**
* An associative array (i.e. "map") of key/value Variant pairs that can itself be contained in a \ref Variant.
*
* Similar in many respects to `std::unordered_map`, but reference-counted and implemented within *carb.variant.plugin*.
*
* @note This is an *unordered* container, meaning that iterating over all values may not be in the same order as they
* were inserted. This is a *unique* container, meaning that inserting a key that already exists in the container will
* replace the previous key/value pair.
*
* Created via \ref IVariant::createMap().
*/
class VariantMap : public IObject
{
public:
//! The key type
using key_type = Variant;
//! The mapped value type
using mapped_type = Variant;
//! The value type
using value_type = KeyValuePair;
//! Unsigned integer type
using size_type = size_t;
//! Signed integer type
using difference_type = ptrdiff_t;
//! Reference type
using reference = value_type&;
//! Const reference type
using const_reference = const value_type&;
//! Pointer type
using pointer = value_type*;
//! Const pointer type
using const_pointer = const value_type*;
// clang-format off
#ifndef DOXYGEN_SHOULD_SKIP_THIS
private:
class iter_base
{
public:
constexpr iter_base() noexcept = default;
bool operator == (const iter_base& other) const noexcept { CARB_ASSERT(owner == other.owner); return where == other.where; }
bool operator != (const iter_base& other) const noexcept { CARB_ASSERT(owner == other.owner); return where != other.where; }
protected:
constexpr iter_base(const VariantMap* owner_, pointer where_) noexcept : owner(owner_), where(where_) {}
const VariantMap* owner{ nullptr };
pointer where{ nullptr };
};
public:
class const_find_iterator : public iter_base
{
using Base = iter_base;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = VariantMap::value_type;
using difference_type = VariantMap::difference_type;
using pointer = VariantMap::const_pointer;
using reference = VariantMap::const_reference;
constexpr const_find_iterator() noexcept = default;
reference operator * () const noexcept { CARB_ASSERT(this->where); return *this->where; }
pointer operator -> () const noexcept { CARB_ASSERT(this->where); return this->where; }
const_find_iterator& operator ++ () noexcept { incr(); return *this; }
const_find_iterator operator ++ (int) noexcept { const_find_iterator i{ *this }; incr(); return i; }
protected:
friend class VariantMap;
constexpr const_find_iterator(const VariantMap* owner_, value_type* where_) noexcept : Base(owner_, where_) {}
void incr() { CARB_ASSERT(this->owner && this->where); this->where = this->owner->findNext(this->where); }
};
class find_iterator : public const_find_iterator
{
using Base = const_find_iterator;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = VariantMap::value_type;
using difference_type = VariantMap::difference_type;
using pointer = VariantMap::pointer;
using reference = VariantMap::reference;
constexpr find_iterator() noexcept = default;
reference operator * () const noexcept { CARB_ASSERT(this->where); return *this->where; }
pointer operator -> () const noexcept { CARB_ASSERT(this->where); return this->where; }
find_iterator& operator ++ () noexcept { this->incr(); return *this; }
find_iterator operator ++ (int) noexcept { find_iterator i{ *this }; this->incr(); return i; }
protected:
friend class VariantMap;
constexpr find_iterator(const VariantMap* owner_, value_type* where_) noexcept : Base(owner_, where_) {}
};
class const_iterator : public iter_base
{
using Base = iter_base;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = VariantMap::value_type;
using difference_type = VariantMap::difference_type;
using pointer = VariantMap::const_pointer;
using reference = VariantMap::const_reference;
constexpr const_iterator() noexcept = default;
reference operator * () const noexcept { CARB_ASSERT(this->where); return *this->where; }
pointer operator -> () const noexcept { CARB_ASSERT(this->where); return this->where; }
const_iterator& operator ++ () noexcept { incr(); return *this;}
const_iterator operator ++ (int) noexcept { const_iterator i{ *this }; incr(); return i; }
protected:
friend class VariantMap;
constexpr const_iterator(const VariantMap* owner_, value_type* where_) noexcept : Base{ owner_, where_ } {}
void incr() { CARB_ASSERT(this->owner && this->where); this->where = this->owner->iterNext(this->where); }
};
class iterator : public const_iterator
{
using Base = const_iterator;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = VariantMap::value_type;
using difference_type = VariantMap::difference_type;
using pointer = VariantMap::pointer;
using reference = VariantMap::reference;
constexpr iterator() noexcept = default;
reference operator * () const noexcept { CARB_ASSERT(this->where); return *this->where; }
pointer operator -> () const noexcept { CARB_ASSERT(this->where); return this->where; }
iterator& operator ++ () noexcept { this->incr(); return *this; }
iterator operator ++ (int) noexcept { iterator i{ *this }; this->incr(); return i; }
protected:
friend class VariantMap;
constexpr iterator(const VariantMap* owner_, value_type* where_) noexcept : Base(owner_, where_) {}
};
#endif
// clang-format on
/**
* Creates an iterator to the first element in the container.
*
* @returns a `const_iterator` to the first element in the container. If the container is empty() the iterator
* will be equal to \ref cend().
*/
const_iterator cbegin() const noexcept;
/**
* Creates an iterator to the first element in the container.
*
* @returns a `const_iterator` to the first element in the container. If the container is empty() the iterator
* will be equal to \ref end().
*/
const_iterator begin() const noexcept;
/**
* Creates an iterator to the first element in the container.
*
* @returns an `iterator` to the first element in the container. If the container is empty() the iterator
* will be equal to \ref end().
*/
iterator begin() noexcept;
/**
* Creates an iterator to the past-the-end element in the container.
*
* @returns a `const_iterator` to the past-the-end element in the container. This iterator is a placeholder;
* attempting to access it results in undefined behavior.
*/
const_iterator cend() const noexcept;
/**
* Creates an iterator to the past-the-end element in the container.
*
* @returns a `const_iterator` to the past-the-end element in the container. This iterator is a placeholder;
* attempting to access it results in undefined behavior.
*/
const_iterator end() const noexcept;
/**
* Creates an iterator to the past-the-end element in the container.
*
* @returns an `iterator` to the past-the-end element in the container. This iterator is a placeholder;
* attempting to access it results in undefined behavior.
*/
iterator end() noexcept;
/**
* Checks if the container is empty.
* @returns `true` if the container is empty; `false` otherwise.
*/
bool empty() const noexcept;
/**
* Returns the number of keys contained.
* @returns the number of keys contained.
*/
virtual size_t size() const noexcept = 0;
/**
* Attempts to insert a new element into the container.
*
* If insertion is successful, all iterators, references and pointers are invalidated.
*
* \warning Variant comparison rules are taken in account. For instance, since Variant(bool) is considered equal
* with Variant(int) for false/0 and true/1, these values would conflict.
*
* @param key The key to insert into the map.
* @param value The value to associate with \p key. If the key already exists in the container, this value is not
* used.
* @returns A `pair` consisting of an `iterator` to the inserted element (or the existing element that prevented the
* insertion) and a `bool` that will be `true` if insertion took place or `false` if insertion did *not* take place.
*/
std::pair<iterator, bool> insert(const Variant& key, Variant value);
/**
* Erases a key from the map.
* @param key The key value to erase.
* @returns The number of entries removed from the map. This will be `0` if the key was not found or `1` if the key
* was found and removed.
*/
size_t erase(const Variant& key) noexcept;
/**
* Removes the given element.
*
* References, pointers and iterators to the erased element are invalidated. All other iterators, pointers and
* references remain valid.
*
* @param pos The `const_iterator` to the element to remove. This iterator must be valid and dereferenceable.
* @returns the iterator immediately following \p pos.
*/
iterator erase(const_iterator pos) noexcept;
/**
* Removes the given element.
*
* References, pointers and iterators to the erased element are invalidated. All other iterators, pointers and
* references remain valid.
*
* @param pos The `const_find_iterator` to the element to remove. This iterator must be valid and dereferenceable.
* @returns the iterator immediately following \p pos.
*/
find_iterator erase(const_find_iterator pos) noexcept;
/**
* Finds the first element with the specified key.
*
* \note `find_iterator` objects returned from this function will only iterate through elements with the same key;
* they cannot be used to iterate through the entire container.
*
* @param key The key to search for.
* @returns a `find_iterator` to the first element matching \p key, or \ref end() if no element was found matching
* \p key.
*/
find_iterator find(const Variant& key) noexcept;
/**
* Finds the first element with the specified key.
*
* \note `const_find_iterator` objects returned from this function will only iterate through elements with the same
* key; they cannot be used to iterate through the entire container.
*
* @param key The key to search for.
* @returns a `const_find_iterator` to the first element matching \p key, or \ref end() if no element was found
* matching \p key.
*/
const_find_iterator find(const Variant& key) const noexcept;
/**
* Checks whether the container has an element matching a given key.
*
* @param key The key of the element to search for.
* @returns `true` if at least one element matching \p key exists in the container; \c false otherwise.
*/
bool contains(const Variant& key) const noexcept;
/**
* Counts the number of elements matching a given key.
*
* \note as this is a unique container, this will always be either 0 or 1.
* @param key The key to count.
* @returns the number of elements matching \p key.
*/
size_t count(const Variant& key) const noexcept;
#if CARB_EXCEPTIONS_ENABLED || defined(DOXYGEN_BUILD)
/**
* Access specified element with bounds checking.
*
* This function is only available if exceptions are enabled.
*
* @param key The key of the element to find.
* @returns a reference to the mapped value of the element with key equivalent to \p key.
* @throws std::out_of_range if no such element exists.
*/
mapped_type& at(const Variant& key);
//! @copydoc at()
const mapped_type& at(const Variant& key) const;
#endif
/**
* Returns a reference to a value that is mapped to the given key, performing an insertion if such key does not
* already exist.
*
* If \p key does not exist, the returned type will be a default-constructed \ref Variant.
*
* @param key the key of the element to find or insert
* @returns a reference to the \ref mapped_type mapped to \p key.
*/
mapped_type& operator[](const Variant& key);
/**
* Clears the contents. O(n) over \ref capacity().
*
* Erases all elements from the container. After this call \ref size() returns zero. Invalidates all iterators,
* pointers and references to contained elements.
*
* @note This does not free the memory used by the container. To free the hash table memory, use `rehash(0)` after
* this call.
*/
virtual void clear() noexcept = 0;
/**
* Returns the number of elements that can be stored with the current memory usage.
* @see reserve()
* @returns the number of elements that can be stored with the current memory usage.
*/
virtual size_t capacity() const noexcept = 0;
/**
* Reserves space for at least the specified number of elements and regenerates the hash table.
*
* Sets \ref capacity() of \c *this to a value greater-than-or-equal-to \p n. If \ref capacity() already exceeds
* \p n, nothing happens.
*
* If a rehash occurs, all iterators, pointers and references to existing elements are invalidated.
*
* @param n The desired minimum capacity of `*this`.
*/
virtual void reserve(size_t n) noexcept = 0;
/**
* Sets the capacity of the container to the lowest valid value greater-than-or-equal-to the given value, and
* rehashes the container.
*
* If \p n is less-than \ref size(), \ref size() is used instead.
*
* If the container is empty and \p n is zero, the memory for the container is freed.
*
* After this function is called, all iterators, pointers and references to existing elements are invalidated.
*
* @param n The minimum capacity for the container. The actual size of the container may be larger than this.
*/
virtual void rehash(size_t n) noexcept = 0;
private:
virtual KeyValuePair* internalInsert(const Variant& key, bool& success) noexcept = 0;
virtual void internalErase(const KeyValuePair*) noexcept = 0;
virtual KeyValuePair* internalFind(const Variant& key) const noexcept = 0;
virtual KeyValuePair* internalBegin() const noexcept = 0;
virtual KeyValuePair* iterNext(KeyValuePair*) const noexcept = 0;
virtual KeyValuePair* findNext(KeyValuePair*) const noexcept = 0;
};
//! Helper definition.
using VariantMapPtr = ObjectPtr<VariantMap>;
/**
* Default implementation of a Translator type.
*
* Translator structs provide a \ref VTable and instruct the Variant system in how the \ref VariantData::data
* member is to be interpreted for conversion to-and-from C++ types.
*
* All Translator specializations must provide three functions:
* - `RString type() const noexcept` - Retrieves the registered name of the type known to \ref IVariant via
* \ref IVariant::registerType(). The v-table will be looked up via \ref translate().
* - `void* data(T&&) const noexcept` - This function must convert the given value to a \c void* representation that
* is stored in the \ref VariantData struct. If this function allocates memory it should be from
* \ref carb::allocate() or originate within the plugin that contains the \ref VTable::Destructor() function
* that will be freeing the memory.
* - `T value(void*) const noexcept` - This function is the opposite of the \c data() function--it converts the
* \c void* value from \ref VariantData::data and converts it back to type \c T.
*
* Translator specializations are present for the following built-in types:
* - \c std::nullptr_t.
* * Does not convert to any other type.
* * Is only equal with other \c std::nullptr_t types.
* - \c bool
* * Can be convert to any integral type (will produce 0 or 1).
* * Will be equal with integer values of 0 or 1.
* - Integral types (8-, 16-, 32- and 64-bit; signed and unsigned).
* * Will convert to any other integral type as long as the value is representable in that type. For instance, a
* `Variant(-1)` would fail to convert to `unsigned`, and `Variant(999)` would fail to convert to `uint8_t`, but
* `Variant(uint64_t(-1))` would convert just fine to `int8_t`.
* * Equality checks follow the same rules as conversion.
* * Not convertible to floating point due to potential data loss.
* * Convertible to \c bool only if the value is 0 or 1.
* - \c float and \c double
* * Will convert to each other, but will not convert to integral types due to potential data loss.
* * Equality checks follows conversion rules, but will compare as the larger type.
* - \c omni::string
* * Convertible to `const char*`, but this value must only be used transiently--it is equivalent to `c_str()` and
* follows the same rules for lifetime of the pointer from `c_str()`.
* * Equality compares via `operator ==` for \c omni::string, and comparable with `[const] char*`.
* - `const char*`
* * Stores the pointer, so memory lifetime must be longer than the Variant.
* * Accepts a `char*` but stored as a `const char*`; any attempts to convert to `char*` will fail.
* * Attempts to copy a Variant containing a `const char*` just copy the same pointer, so the lifetime guarantee
* must include these copies as well.
* * Comparable with \c omni::string.
* - `dictionary::Item*`
* * Stores the pointer, so memory lifetime must be longer than the Variant.
* * Copying the variant will trivially copy the pointer.
* * Comparison will trivially compare the pointer.
* - `carb::Strong` (Carbonite strong types)
* * Auto-converts to and from the underlying numeric type (i.e. `int`, `size_t`, etc.), so it will lose the type
* safety of the strong type.
* * Comparable with similar numeric types.
* - \ref VariantArray* / \ref VariantArrayPtr
* * Comparable only with other VariantArray types, by pointer value.
* * Hashes based on the pointer value, not the contained values.
* * Variants containing this type always hold a reference.
* - \ref VariantMap* / \ref VariantMapPtr
* * Comparable only with other VariantMap types, by pointer value.
* * Hashes based on the pointer value, not the contained values.
* * Variants containing this type always hold a reference.
* - \ref RString / \ref RStringU / \ref RStringKey / \ref RStringUKey
* * Types are comparable with other instances of the same type.
* * Key types are only comparable with Key types; RString and RStringKey will compare with RStringU and RStringKeyU
* respectively, as uncased comparisons.
* * Hashing is as by the `getHash()` function for each of the RString types.
* * RString and RStringU can be converted to `const char*` or `omni::string` as if by `c_str()`.
* * RStringKey and RStringUKey can be converted to `omni::string` as if by `toString()`.
*
* @warning The default template does not provide the above functions which will allow compile to fail for unrecognized
* types. Translations are available through specializations only.
*
* @tparam T The type handled by the specialization.
* @tparam Enable A template parameter that can be used for SFINAE.
*/
template <class T, class Enable = void>
struct Translator;
} // namespace variant
} // namespace carb
| 35,782 | C | 44.583439 | 132 | 0.672433 |
omniverse-code/kit/include/carb/events/IEvents.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief carb.events interface definition file.
#pragma once
#include "../IObject.h"
#include "../Interface.h"
#include "../InterfaceUtils.h"
#include "../dictionary/IDictionary.h"
#include <utility>
namespace carb
{
/**
* Namespace for the *carb.events* plugin.
*/
namespace events
{
/**
* Event type is 64-bit number. To use strings as event types hash function can be used. @see CARB_EVENTS_TYPE_FROM_STR
*/
using EventType = uint64_t;
/**
* Event sender identifier. It is useful in some cases to differentiate who send an event. E.g. to know that is was you.
*/
using SenderId = uint32_t;
/**
* Default sender id to use if you don't want it to be unique
*/
constexpr SenderId kGlobalSenderId = 0;
/**
* Event notification order.
*/
using Order = int32_t;
/**
* Default order. If 2 subscriptions are done with the same Order value, their callback order is undefined.
*/
constexpr Order kDefaultOrder = 0;
/**
* Event object which is sent and received. Lifetime is managed by carb::IObject refcounting.
*/
class IEvent : public IObject
{
public:
EventType type; //!< Event type.
SenderId sender; //!< The sender of the event, or carb::events::kGlobalSenderId.
dictionary::Item* payload; //!< Event payload is dictionary Item. Any data can be put into.
/**
* Helper function to build a *carb.dictionary* of values.
* @param param The key/value pair to include in the *carb.dictionary*.
*/
template <typename ValueT>
void setValues(const std::pair<const char*, ValueT>& param);
/**
* Helper function to build a *carb.dictionary* of values.
* @param param The key/value pair to include in the *carb.dictionary*.
* @param params Additional key/value pairs.
*/
template <typename ValueT, typename... ValuesT>
void setValues(const std::pair<const char*, ValueT>& param, ValuesT&&... params);
/**
* Stops propagation of an event during dispatch.
*/
virtual void consume() = 0;
/**
* Attaches a \ref carb::IObject to this event by name and holds a reference to the object.
*
* The object can be retrieved with \ref retrieveObject(). If an object is already stored under the given name, the
* stored object is released and \p ptr is stored instead. References to stored objects are released when `*this` is
* destroyed. To clear the current reference for a given \p name, pass \p ptr as `nullptr`.
* @thread_safety This function is thread safe: all `attachObject()` calls are serialized with each other and all
* calls with \ref retrieveObject().
* @param name The name of the object to attach. Must not be `nullptr`. The same name must be passed to
* \ref retrieveObject() in order to retrieve the pointer. This parameter is case-sensitive.
* @param ptr The pointer to attach to \c *this with the given \p name.
*/
virtual void attachObject(const char* name, carb::IObject* ptr) = 0;
/**
* Retrieves a previously-stored \ref carb::IObject from this event by name.
*
* The object was previously set with \ref attachObject(). The object remains attached to `*this` until `*this` is
* destroyed or it is overwritten with a different object (or `nullptr`) by calling \ref attachObject() again.
* @thread_safety This function is thread safe: `retrieveObject()` can be called concurrently and will serialize
* calls to \ref attachObject().
* @param name The name of the object to retrieve. Must not be `nullptr`. This parameter is case-sensitive.
* @returns The object previously passed to \ref attachObject(). May be nullptr
*/
carb::ObjectPtr<carb::IObject> retrieveObject(const char* name)
{
// cannot pass ObjectPtr by value across ABI boundaries
carb::ObjectPtr<carb::IObject> ptr{};
internalRetrieveObject(name, ptr);
return ptr;
}
//! @private
virtual void internalRetrieveObject(const char* name, carb::ObjectPtr<carb::IObject>& out) = 0;
};
/// Helper definition for IEvent smart pointer.
using IEventPtr = ObjectPtr<IEvent>;
/**
* Interface to implement for event listener.
*/
class IEventListener : public IObject
{
public:
/**
* Function to be implemented that will handle an event.
* @param e The event to process. To stop further propagation of the event, call IEvent::consume().
*/
virtual void onEvent(IEvent* e) = 0;
};
/// Helper definition for IEventListener smart pointer.
using IEventListenerPtr = ObjectPtr<IEventListener>;
/**
* Subscription holder is created by all event listening subscription functions. Subscription is valid while the holder
* is alive.
*/
class ISubscription : public IObject
{
public:
/**
* Unsubscribes the associated IEventListener.
*/
virtual void unsubscribe() = 0;
/**
* Returns the name of the subscription.
*
* @note If a name was not given when the @ref IEventStream subscription function was called, a name is generated
* based on the address of the @ref IEventListener::onEvent() function.
*
* @returns The name of the subscription.
*/
virtual const char* getName() const noexcept = 0;
};
/// Helper definition for ISubscription smart pointer.
using ISubscriptionPtr = ObjectPtr<ISubscription>;
/**
* Compile-time conversion of string to carb::events::EventType.
* @param STR The string to convert.
* @returns The EventType corresponding to the given string.
*/
#define CARB_EVENTS_TYPE_FROM_STR(STR) CARB_HASH_STRING(STR)
/**
* Run-time conversion of string to carb::events::EventType.
* @param str The string to convert.
* @returns The EventType corresponding to the given string.
*/
inline EventType typeFromString(const char* str)
{
return carb::hashString(str);
}
/**
* Event stream is fundamental primitive used to send, receive and listen for events. Different event system models can
* be designed using it. It is thread-safe and can also be used as a sync primitive. Similar to Go Language Channels.
*
* Basically stream is just a queue with listeners:
*
* @code{.txt}
* +------------------+
* push() / pushBlocked() | | tryPop() / pop()
* +--------------------------->+ IEventStream +------------------------>
* ^ | | ^
* | +------------------+ |
* subscribeToPush() | | subscribeToPop()
* | |
* | |
* +---------+--------+ +--------+---------+
* | IEventListener | | IEventListener |
* +------------------+ +------------------+
* @endcode
*
* 1. You can push to stream and pop events (acts like a queue).
* 2. Given the stream you can listen for pushed and/or popped events. That is basically immediate callbacks vs deferred
* callbacks.
* 3. Blocking methods (pushBlocked() and pop()) will block the thread until event is popped (for push method) or any
* event is pushed (for pop method). That can be used as thread sync.
* 4. Pumping of stream is just popping all events until it is empty.
* 5. EventType allows you to filter which events to listen for. IEventStream may contain only one type, conceptually
* more like channels, or a lot of events - like event bus.
* 6. Listeners are subscribed specifying the order in which they want to receive events. When processing, they may
* consume an event which stops other listeners from receiving it (only when being dispatched).
*/
class IEventStream : public IObject
{
public:
/**
* Create new event of certain type.
* @param eventType The type of event to create.
* @param sender The sender of the event, or carb::events::kGlobalSenderId.
* @returns A pointer to a newly created event.
*/
virtual IEvent* createEventPtr(EventType eventType, SenderId sender) = 0;
/**
* @copydoc createEventPtr(EventType,SenderId)
* @param values Key/value pairs as passed to IEvent::setValues().
*/
template <typename... ValuesT>
ObjectPtr<IEvent> createEvent(EventType eventType, SenderId sender, ValuesT&&... values);
/**
* Dispatch event immediately without putting it into stream.
* @param e The event to dispatch.
*/
virtual void dispatch(IEvent* e) = 0;
/**
* Push event into the stream.
* @param e The event to push.
*/
virtual void push(IEvent* e) = 0;
/**
* Push event into the stream and block until it is dispatched by some other thread.
* @param e The event to push.
*/
virtual void pushBlocked(IEvent* e) = 0;
/**
* Get approximate number of events waiting for dispatch in the stream.
* @thread_safety While safe to call from multiple threads, since there is no lock involved this value should be
* considered approximate as another thread could modify the number before the return value is read. This call
* is strongly ordered with respect to other calls.
* @returns The approximate number of events waiting for dispatch in the stream.
*/
virtual size_t getCount() = 0;
/**
* Pop and dispatches a single event from the stream, blocking until one becomes available.
* @warning This function blocks until an event is available.
* @returns The event that was popped and dispatched.
*/
ObjectPtr<IEvent> pop();
/// @copydoc pop()
virtual IEvent* popPtr() = 0;
/**
* Pops and dispatches a single event from the stream, if available.
* @note Unlike pop(), this function does not wait for an event to become available.
* @returns The event that was popped and dispatched, or `nullptr` if no event was available.
*/
ObjectPtr<IEvent> tryPop();
/// @copydoc tryPop()
virtual IEvent* tryPopPtr() = 0;
/**
* Dispatches and pops all available events from the stream.
*/
void pump();
/**
* Subscribe to receive notification when event stream is popped.
* @sa pump() pop() tryPop()
* @note Adding or removing a subscription from \ref IEventListener::onEvent() is perfectly valid. The newly added
* subscription will not be called until the next event.
* @warning Recursively pushing and/or popping events from within \ref IEventListener::onEvent() is not recommended
* and can lead to undefined behavior.
* @param listener The listener to subscribe. IEventListener::onEvent() will be called for each popped event. If an
* event listener calls IEvent::consume() on the given event, propagation of the event will stop and no more event
* listeners will receive the event.
* @param order An optional value used to specify the order tier. Lower order tiers will be notified first.
* Multiple IEventListener objects at the same order tier are notified in an undefined order.
* @param subscriptionName An optional name for the subscription for debugging purposes. Names do not need to be
* unique. If `nullptr`, an internal name will be determined.
* @returns A ISubscription pointer. The subscription is valid as long as the ISubscription pointer is referenced.
* Alternately, the IEventListener can be unsubscribed by calling ISubscription::unsubscribe().
*/
ObjectPtr<ISubscription> createSubscriptionToPop(IEventListener* listener,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr);
/// @copydoc createSubscriptionToPop()
/// @param eventType A specific event to listen for.
ObjectPtr<ISubscription> createSubscriptionToPopByType(EventType eventType,
IEventListener* listener,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr);
/// @copydoc createSubscriptionToPop()
virtual ISubscription* createSubscriptionToPopPtr(IEventListener* listener,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr) = 0;
/// @copydoc createSubscriptionToPop()
/// @param eventType A specific event to listen for.
virtual ISubscription* createSubscriptionToPopByTypePtr(EventType eventType,
IEventListener* listener,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr) = 0;
/**
* Subscribe to receive notification when an event is pushed into the event stream.
* @sa push() pushBlocked()
* @note Adding or removing a subscription from \ref IEventListener::onEvent() is perfectly valid. The newly added
* subscription will not be called until the next event.
* @warning Recursively pushing and/or popping events from within \ref IEventListener::onEvent() is not recommended
* and can lead to undefined behavior.
* @param listener The listener to subscribe. IEventListener::onEvent() will be called for each pushed event. The
* IEvent::consume() function has no effect for notifications of push events.
* @param order An optional value used to specify the order tier. Lower order tiers will be notified first.
* Multiple IEventListener objects at the same order tier are notified in an undefined order.
* @param subscriptionName An optional name for the subscription for debugging purposes. Names do not need to be
* unique. If `nullptr`, an internal name will be determined.
* @returns A ISubscription pointer. The subscription is valid as long as the ISubscription pointer is referenced.
* Alternately, the IEventListener can be unsubscribed by calling ISubscription::unsubscribe().
*/
ObjectPtr<ISubscription> createSubscriptionToPush(IEventListener* listener,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr);
/// @copydoc createSubscriptionToPush()
/// @param eventType A specific event to listen for.
ObjectPtr<ISubscription> createSubscriptionToPushByType(EventType eventType,
IEventListener* listener,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr);
/// @copydoc createSubscriptionToPush()
virtual ISubscription* createSubscriptionToPushPtr(IEventListener* listener,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr) = 0;
/// @copydoc createSubscriptionToPush()
/// @param eventType A specific event to listen for.
virtual ISubscription* createSubscriptionToPushByTypePtr(EventType eventType,
IEventListener* listener,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr) = 0;
/**
* Sets the notification order for named subscriptions.
* @note If multiple subscriptions exist with the same name, all are updated.
* @param subscriptionName the name previously assigned when the subscription was created.
* @param order The new order tier. Lower order tiers will be notified first. Multiple IEventListener objects at the
* same order tier are notified in an undefined order.
* @returns `true` if the subscription was found and updated; `false` otherwise.
*/
virtual bool setSubscriptionToPopOrder(const char* subscriptionName, Order order) = 0;
/// @copydoc setSubscriptionToPopOrder
virtual bool setSubscriptionToPushOrder(const char* subscriptionName, Order order) = 0;
/**
* Retrieves the notification order for a named subscription.
* @param subscriptionName the name previously assigned when the subscription was created.
* @param order Must be a valid pointer that will receive the current order tier.
* @returns `true` if the subscription was found; `false` if the subscription was not found or @p order is
* `nullptr`.
*/
virtual bool getSubscriptionToPopOrder(const char* subscriptionName, Order* order) = 0;
/// @copydoc setSubscriptionToPopOrder
virtual bool getSubscriptionToPushOrder(const char* subscriptionName, Order* order) = 0;
/**
* Returns the name of the IEventStream.
*
* @note If a name was not given when @ref IEvents::createEventStream() was called, a name is generated based on the
* function that called @ref IEvents::createEventStream().
*
* @returns The name of the IEventStream.
*/
virtual const char* getName() const noexcept = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Helpers //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @defgroup helpers Helper functions
* @sa createEvent() push() pushBlocked() dispatch()
* @{
*/
/**
* @copydoc createEvent
*/
template <typename... ValuesT>
IEvent* createEventPtr(EventType eventType, SenderId sender, ValuesT&&... values);
/**
* Helper function that combines createEvent() with push().
* @param eventType The type of event to create.
* @param sender The sender of the event, or carb::events::kGlobalSenderId.
*/
void pushWithSender(EventType eventType, SenderId sender);
/// @copydoc pushWithSender
/// @param values Key/value pairs as passed to IEvent::setValues().
template <typename... ValuesT>
void pushWithSender(EventType eventType, SenderId sender, ValuesT&&... values);
/**
* Helper function that combines createEvent() with push().
* @param eventType The type of event to create.
* @param values Key/value pairs as passed to IEvent::setValues().
*/
template <typename... ValuesT>
void push(EventType eventType, ValuesT&&... values);
/**
* Helper function that combines createEvent() with pushBlocked().
* @param eventType The type of event to create.
* @param sender The sender of the event, or carb::events::kGlobalSenderId.
*/
void pushBlockedWithSender(EventType eventType, SenderId sender);
/// @copydoc pushBlockedWithSender
/// @param values Key/value pairs as passed to IEvent::setValues().
template <typename... ValuesT>
void pushBlockedWithSender(EventType eventType, SenderId sender, ValuesT&&... values);
/**
* Helper function that combines createEvent() with pushBlocked().
* @param eventType The type of event to create.
* @param values Key/value pairs as passed to IEvent::setValues().
*/
template <typename... ValuesT>
void pushBlocked(EventType eventType, ValuesT&&... values);
/**
* Helper function that combines createEvent() with dispatch().
* @param eventType The type of event to create.
* @param sender The sender of the event, or carb::events::kGlobalSenderId.
* @param values Key/value pairs as passed to IEvent::setValues().
*/
template <typename... ValuesT>
void dispatch(EventType eventType, SenderId sender, ValuesT&&... values);
/**
* Helper function that combines createEvent() with dispatch().
* @param eventType The type of event to create.
* @param sender The sender of the event, or carb::events::kGlobalSenderId.
*/
void dispatch(EventType eventType, SenderId sender);
///@}
};
/// Helper definition for IEventStream smart pointer.
using IEventStreamPtr = ObjectPtr<IEventStream>;
/**
* Interface definition for *carb.events*.
*/
struct IEvents
{
// 1.0 - Initial release
// 1.1 - added internalCreateEventStream
// 1.2 - added attachObject() and retrieveObject() to IEvent
CARB_PLUGIN_INTERFACE("carb::events::IEvents", 1, 2)
/**
* Create new event stream.
* @param name An optional name to give the event stream for logging and profiling. Names do not need to be unique
* but are recommended to be unique. If `nullptr`, an internal name will be determined.
* @returns A pointer to the new event stream.
*/
IEventStreamPtr createEventStream(const char* name = nullptr) noexcept;
/**
* Create new event stream.
* @rst
* .. deprecated:: ``carb::events::IEvents::internalCreateEventStream`` instead.
* @endrst
* @returns A pointer to the new event stream.
*/
CARB_DEPRECATED("Use internalCreateEventStream instead") virtual IEventStream* createEventStreamPtr() = 0;
/**
* Get a unique sender identifier.
* @note The sender identifier may be a previously released sender identifier.
* @returns A unique sender identifier. When finished with the sender identifier, it should be returned with
* releaseUniqueSenderId().
*/
virtual SenderId acquireUniqueSenderId() = 0;
/**
* Releases a unique sender identifier previously acquired with acquireUniqueSenderId().
* @param senderId The previously acquired senderId.
*/
virtual void releaseUniqueSenderId(SenderId senderId) = 0;
//! @private
virtual IEventStream* internalCreateEventStream(const char* name) noexcept = 0;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inline Functions //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////// IEvent //////////////
template <typename ValueT>
inline void IEvent::setValues(const std::pair<const char*, ValueT>& param)
{
carb::getCachedInterface<dictionary::IDictionary>()->makeAtPath<ValueT>(this->payload, param.first, param.second);
}
template <typename ValueT, typename... ValuesT>
inline void IEvent::setValues(const std::pair<const char*, ValueT>& param, ValuesT&&... params)
{
this->setValues<ValueT>(param);
this->setValues(std::forward<ValuesT>(params)...);
}
////////////// IEventStream //////////////
template <typename... ValuesT>
inline IEvent* IEventStream::createEventPtr(EventType type, SenderId sender, ValuesT&&... values)
{
IEvent* e = createEventPtr(type, sender);
e->setValues(std::forward<ValuesT>(values)...);
return e;
}
inline ObjectPtr<ISubscription> IEventStream::createSubscriptionToPop(IEventListener* listener,
Order order,
const char* name)
{
return stealObject(this->createSubscriptionToPopPtr(listener, order, name));
}
inline ObjectPtr<ISubscription> IEventStream::createSubscriptionToPopByType(EventType eventType,
IEventListener* listener,
Order order,
const char* name)
{
return stealObject(this->createSubscriptionToPopByTypePtr(eventType, listener, order, name));
}
inline ObjectPtr<ISubscription> IEventStream::createSubscriptionToPush(IEventListener* listener,
Order order,
const char* name)
{
return stealObject(this->createSubscriptionToPushPtr(listener, order, name));
}
inline ObjectPtr<ISubscription> IEventStream::createSubscriptionToPushByType(EventType eventType,
IEventListener* listener,
Order order,
const char* name)
{
return stealObject(this->createSubscriptionToPushByTypePtr(eventType, listener, order, name));
}
template <typename... ValuesT>
inline void IEventStream::pushWithSender(EventType type, SenderId sender, ValuesT&&... values)
{
IEvent* e = createEventPtr(type, sender, std::forward<ValuesT>(values)...);
push(e);
e->release();
}
inline void IEventStream::pushWithSender(EventType type, SenderId sender)
{
IEvent* e = createEventPtr(type, sender);
push(e);
e->release();
}
template <typename... ValuesT>
inline ObjectPtr<IEvent> IEventStream::createEvent(EventType eventType, SenderId sender, ValuesT&&... values)
{
return carb::stealObject(this->createEventPtr(eventType, sender, std::forward<ValuesT>(values)...));
}
template <typename... ValuesT>
inline void IEventStream::push(EventType type, ValuesT&&... values)
{
return pushWithSender(type, kGlobalSenderId, std::forward<ValuesT>(values)...);
}
template <typename... ValuesT>
inline void IEventStream::pushBlockedWithSender(EventType type, SenderId sender, ValuesT&&... values)
{
IEvent* e = createEventPtr(type, sender, std::forward<ValuesT>(values)...);
pushBlocked(e);
e->release();
}
inline void IEventStream::pushBlockedWithSender(EventType type, SenderId sender)
{
IEvent* e = createEventPtr(type, sender);
pushBlocked(e);
e->release();
}
template <typename... ValuesT>
inline void IEventStream::pushBlocked(EventType type, ValuesT&&... values)
{
return pushBlockedWithSender(type, kGlobalSenderId, std::forward<ValuesT>(values)...);
}
template <typename... ValuesT>
inline void IEventStream::dispatch(EventType type, SenderId sender, ValuesT&&... values)
{
IEvent* e = createEventPtr(type, sender, std::forward<ValuesT>(values)...);
dispatch(e);
e->release();
}
inline void IEventStream::dispatch(EventType type, SenderId sender)
{
IEvent* e = createEventPtr(type, sender);
dispatch(e);
e->release();
}
inline void IEventStream::pump()
{
const size_t eventCount = this->getCount();
for (size_t i = 0; i < eventCount; i++)
{
IEvent* e = this->tryPopPtr();
if (!e)
break;
e->release();
}
}
inline ObjectPtr<IEvent> IEventStream::pop()
{
return carb::stealObject(this->popPtr());
}
inline ObjectPtr<IEvent> IEventStream::tryPop()
{
return carb::stealObject(this->tryPopPtr());
}
inline ObjectPtr<IEventStream> IEvents::createEventStream(const char* name) noexcept
{
return carb::stealObject(this->internalCreateEventStream(name));
}
} // namespace events
} // namespace carb
| 28,085 | C | 40.794643 | 120 | 0.624996 |
omniverse-code/kit/include/carb/events/EventsBindingsPython.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../BindingsPythonUtils.h"
#include "../Framework.h"
#include "../dictionary/DictionaryBindingsPython.h"
#include "../cpp/Optional.h"
#include "EventsUtils.h"
#include "IEvents.h"
#include <memory>
#include <string>
#include <vector>
DISABLE_PYBIND11_DYNAMIC_CAST(carb::events::IEvents)
DISABLE_PYBIND11_DYNAMIC_CAST(carb::events::ISubscription)
DISABLE_PYBIND11_DYNAMIC_CAST(carb::events::IEvent)
DISABLE_PYBIND11_DYNAMIC_CAST(carb::events::IEventStream)
namespace carb
{
namespace events
{
struct IEventsHolder
{
IEvents* events{ nullptr };
IEventsHolder()
{
update();
}
~IEventsHolder()
{
if (events)
{
g_carbFramework->removeReleaseHook(events, sReleaseHook, this);
}
}
explicit operator bool() const noexcept
{
return events != nullptr;
}
IEvents* get(bool canUpdate = false)
{
if (canUpdate)
{
update();
}
return events;
}
private:
void update()
{
if (events)
return;
events = g_carbFramework->tryAcquireInterface<IEvents>();
if (events)
{
g_carbFramework->addReleaseHook(events, sReleaseHook, this);
}
}
CARB_PREVENT_COPY_AND_MOVE(IEventsHolder);
static void sReleaseHook(void* iface, void* user)
{
static_cast<IEventsHolder*>(user)->events = nullptr;
g_carbFramework->removeReleaseHook(iface, sReleaseHook, user);
}
};
inline IEvents* getIEvents(bool update = false)
{
static IEventsHolder holder;
return holder.get(update);
}
// Wrap ObjectPtr because the underlying carb.events module could be unloaded before things destruct. In this case, we
// want to prevent destroying them to avoid crashing.
template <class T>
class ObjectPtrWrapper : public carb::ObjectPtr<T>
{
using Base = ObjectPtr<T>;
public:
ObjectPtrWrapper() = default;
ObjectPtrWrapper(ObjectPtrWrapper&& other) : Base(std::move(other))
{
}
explicit ObjectPtrWrapper(T* o) : Base(o)
{
getIEvents(); // Ensure that we've resolved IEvents
}
~ObjectPtrWrapper()
{
// If IEvents no longer exists, detach the pointer without releasing it.
if (!getIEvents())
this->detach();
}
ObjectPtrWrapper& operator=(ObjectPtrWrapper&& other)
{
Base::operator=(std::move(other));
return *this;
}
using Base::operator=;
};
} // namespace events
} // namespace carb
PYBIND11_DECLARE_HOLDER_TYPE(T, carb::events::ObjectPtrWrapper<T>, true);
namespace carb
{
namespace events
{
namespace
{
class PythonEventListener : public IEventListener
{
public:
PythonEventListener(std::function<void(IEvent*)> fn) : m_fn(std::move(fn))
{
}
void onEvent(IEvent* e) override
{
carb::callPythonCodeSafe(m_fn, e);
}
private:
std::function<void(IEvent*)> m_fn;
CARB_IOBJECT_IMPL
};
// GIL must be held
std::string getPythonCaller() noexcept
{
// Equivalent python:
// def get_python_caller():
// try:
// from traceback import extract_stack
// tb = extract_stack(limit=1)
// l = tb.format()
// if len(l) >= 1:
// s = l[0]
// return s[0:s.find('\n')]
// except:
// pass
// return ""
// Determine a name based on the caller
try
{
// This cannot be static because the GIL won't be held for cleanup at shutdown
auto extract_stack = py::module::import("traceback").attr("extract_stack");
auto tb = extract_stack(py::arg("limit") = 1);
py::list list = tb.attr("format")();
if (list.size() >= 1)
{
std::string entry = py::str(list[0]);
// sample entry:
// ```File "C:\src\carbonite\source\tests\python\test_events.py", line 28, in main
// stream = events.create_event_stream()
// ```
// Return just the first line
auto index = entry.find('\n');
return entry.substr(0, index);
}
}
catch (...)
{
}
return {};
}
inline void definePythonModule(py::module& m)
{
using namespace carb::events;
m.def("acquire_events_interface", []() { return getIEvents(true); }, py::return_value_policy::reference,
py::call_guard<py::gil_scoped_release>());
m.def("type_from_string", [](const char* s) { return carb::events::typeFromString(s); },
py::call_guard<py::gil_scoped_release>());
py::class_<ISubscription, ObjectPtrWrapper<ISubscription>>(m, "ISubscription", R"(
Subscription holder.
)")
.def("unsubscribe", &ISubscription::unsubscribe, R"(
Unsubscribes this subscription.
)",
py::call_guard<py::gil_scoped_release>())
.def_property_readonly("name", &ISubscription::getName, R"(
Returns the name of this subscription.
Returns:
The name of this subscription.
)",
py::call_guard<py::gil_scoped_release>());
py::class_<IEvent, ObjectPtrWrapper<IEvent>>(m, "IEvent", R"(
Event.
Event has an Event type, a sender id and a payload. Payload is a dictionary like item with arbitrary data.
)")
.def_readonly("type", &IEvent::type)
.def_readonly("sender", &IEvent::sender)
.def_readonly("payload", &IEvent::payload)
.def("consume", &IEvent::consume, "Consume event to stop it propagating to other listeners down the line.",
py::call_guard<py::gil_scoped_release>());
py::class_<IEventStream, ObjectPtrWrapper<IEventStream>>(m, "IEventStream")
.def("create_subscription_to_pop",
[](IEventStream* stream, std::function<void(IEvent*)> onEventFn, Order order, const char* name) {
std::string sname;
if (!name || name[0] == '\0')
{
sname = getPythonCaller();
name = sname.empty() ? nullptr : sname.c_str();
}
py::gil_scoped_release gil;
return stream->createSubscriptionToPop(
carb::stealObject(new PythonEventListener(std::move(onEventFn))).get(), order, name);
},
R"(
Subscribes to event dispatching on the stream.
See :class:`.Subscription` for more information on subscribing mechanism.
Args:
fn: The callback to be called on event dispatch.
order: An integer order specifier. Lower numbers are called first. Negative numbers are allowed. Default is 0.
name: The name of the subscription for profiling. If no name is provided one is generated from the traceback of the calling function.
Returns:
The subscription holder.)",
py::arg("fn"), py::arg("order") = kDefaultOrder, py::arg("name") = nullptr)
.def("create_subscription_to_pop_by_type",
[](IEventStream* stream, EventType eventType, const std::function<void(IEvent*)>& onEventFn, Order order,
const char* name) {
std::string sname;
if (!name || name[0] == '\0')
{
sname = getPythonCaller();
name = sname.empty() ? nullptr : sname.c_str();
}
py::gil_scoped_release gil;
return stream->createSubscriptionToPopByType(
eventType, carb::stealObject(new PythonEventListener(onEventFn)).get(), order, name);
},
R"(
Subscribes to event dispatching on the stream.
See :class:`.Subscription` for more information on subscribing mechanism.
Args:
event_type: Event type to listen to.
fn: The callback to be called on event dispatch.
order: An integer order specifier. Lower numbers are called first. Negative numbers are allowed. Default is 0.
name: The name of the subscription for profiling. If no name is provided one is generated from the traceback of the calling function.
Returns:
The subscription holder.)",
py::arg("event_type"), py::arg("fn"), py::arg("order") = kDefaultOrder, py::arg("name") = nullptr)
.def("create_subscription_to_push",
[](IEventStream* stream, const std::function<void(IEvent*)>& onEventFn, Order order, const char* name) {
std::string sname;
if (!name || name[0] == '\0')
{
sname = getPythonCaller();
name = sname.empty() ? nullptr : sname.c_str();
}
py::gil_scoped_release gil;
return stream->createSubscriptionToPush(
carb::stealObject(new PythonEventListener(onEventFn)).get(), order, name);
},
R"(
Subscribes to pushing events into stream.
See :class:`.Subscription` for more information on subscribing mechanism.
Args:
fn: The callback to be called on event push.
order: An integer order specifier. Lower numbers are called first. Negative numbers are allowed. Default is 0.
name: The name of the subscription for profiling. If no name is provided one is generated from the traceback of the calling function.
Returns:
The subscription holder.)",
py::arg("fn"), py::arg("order") = kDefaultOrder, py::arg("name") = nullptr)
.def("create_subscription_to_push_by_type",
[](IEventStream* stream, EventType eventType, const std::function<void(IEvent*)>& onEventFn, Order order,
const char* name) {
std::string sname;
if (!name || name[0] == '\0')
{
sname = getPythonCaller();
name = sname.empty() ? nullptr : sname.c_str();
}
py::gil_scoped_release gil;
return stream->createSubscriptionToPushByType(
eventType, carb::stealObject(new PythonEventListener(onEventFn)).get(), order, name);
},
R"(
Subscribes to pushing events into stream.
See :class:`.Subscription` for more information on subscribing mechanism.
Args:
event_type: Event type to listen to.
fn: The callback to be called on event push.
order: An integer order specifier. Lower numbers are called first. Negative numbers are allowed. Default is 0.
name: The name of the subscription for profiling. If no name is provided one is generated from the traceback of the calling function.
Returns:
The subscription holder.)",
py::arg("event_type"), py::arg("fn"), py::arg("order") = kDefaultOrder, py::arg("name") = nullptr)
.def_property_readonly("event_count", &IEventStream::getCount, py::call_guard<py::gil_scoped_release>())
.def("set_subscription_to_pop_order", &IEventStream::setSubscriptionToPopOrder,
R"(
Set subscription to pop order by name of subscription.
)",
py::arg("name"), py::arg("order"), py::call_guard<py::gil_scoped_release>())
.def("set_subscription_to_push_order", &IEventStream::setSubscriptionToPushOrder,
R"(
Set subscription to push order by name of subscription.
)",
py::arg("name"), py::arg("order"), py::call_guard<py::gil_scoped_release>())
.def("get_subscription_to_pop_order",
[](IEventStream* self, const char* subscriptionName) -> py::object {
Order order;
bool b;
{
py::gil_scoped_release nogil;
b = self->getSubscriptionToPopOrder(subscriptionName, &order);
}
if (b)
return py::int_(order);
return py::none();
},
R"(
Get subscription to pop order by name of subscription. Return None if subscription was not found.
)",
py::arg("name"))
.def("get_subscription_to_push_order",
[](IEventStream* self, const char* subscriptionName) -> py::object {
Order order;
bool b;
{
py::gil_scoped_release nogil;
b = self->getSubscriptionToPushOrder(subscriptionName, &order);
}
if (b)
return py::int_(order);
return py::none();
},
R"(
Get subscription to push order by name of subscription. Return None if subscription was not found.
)",
py::arg("name"))
.def("pop", &IEventStream::pop,
R"(
Pop event.
This function blocks execution until there is an event to pop.
Returns:
(:class:`.Event`) object. You own this object, it can be stored.
)",
py::call_guard<py::gil_scoped_release>())
.def("try_pop", &IEventStream::tryPop,
R"(
Try pop event.
Returns:
Pops (:class:`.Event`) if stream is not empty or return `None`.
)",
py::call_guard<py::gil_scoped_release>()
)
.def("pump", &IEventStream::pump,
R"(
Pump event stream.
Dispatches all events in a stream.
)",
py::call_guard<py::gil_scoped_release>()
)
.def("push",
[](IEventStream* self, EventType eventType, SenderId sender, py::dict dict) {
ObjectPtrWrapper<IEvent> e;
{
py::gil_scoped_release nogil;
e = self->createEvent(eventType, sender);
}
carb::dictionary::setPyObject(carb::dictionary::getDictionary(), e->payload, nullptr, dict);
{
py::gil_scoped_release nogil;
self->push(e.get());
}
},
R"(
Push :class:`.Event` into stream.
Args:
event_type (int): :class:`.Event` type.
sender (int): Sender id. Unique can be acquired using :func:`.acquire_unique_sender_id`.
dict (typing.Dict): :class:`.Event` payload.
)",
py::arg("event_type") = 0, py::arg("sender") = 0, py::arg("payload") = py::dict())
.def("dispatch",
[](IEventStream* self, EventType eventType, SenderId sender, py::dict dict) {
ObjectPtrWrapper<IEvent> e;
{
py::gil_scoped_release nogil;
e = self->createEvent(eventType, sender);
}
carb::dictionary::setPyObject(carb::dictionary::getDictionary(), e->payload, nullptr, dict);
{
py::gil_scoped_release nogil;
self->dispatch(e.get());
}
},
R"(
Dispatch :class:`.Event` immediately without putting it into stream.
Args:
event_type (int): :class:`.Event` type.
sender (int): Sender id. Unique can be acquired using :func:`.acquire_unique_sender_id`.
dict (typing.Dict): :class:`.Event` payload.
)",
py::arg("event_type") = 0, py::arg("sender") = 0, py::arg("payload") = py::dict())
.def_property_readonly("name", &IEventStream::getName, R"(
Gets the name of the :class:`.EventStream`.
Returns:
The name of the event stream.
)",
py::call_guard<py::gil_scoped_release>());
CARB_IGNOREWARNING_MSC_WITH_PUSH(5205)
py::class_<IEvents>(m, "IEvents")
.def("create_event_stream",
[](IEvents* events, const char* name) {
std::string sname;
if (!name)
{
sname = getPythonCaller();
name = sname.empty() ? nullptr : sname.c_str();
}
py::gil_scoped_release gil;
return events->createEventStream(name);
},
R"(
Create new `.EventStream`.
Args:
name: The name of the .EventStream for profiling. If no name is provided one is generated from the traceback of the calling function.
)",
py::arg("name") = (const char*)nullptr)
.def("acquire_unique_sender_id", &IEvents::acquireUniqueSenderId,
R"(
Acquire unique sender id.
Call :func:`.release_unique_sender_id` when it is not needed anymore. It can be reused then.
)",
py::call_guard<py::gil_scoped_release>())
.def("release_unique_sender_id", &IEvents::releaseUniqueSenderId, py::call_guard<py::gil_scoped_release>());
CARB_IGNOREWARNING_MSC_POP
}
} // namespace
} // namespace events
} // namespace carb
| 18,101 | C | 35.495968 | 149 | 0.545826 |
omniverse-code/kit/include/carb/events/EventsUtils.h | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Helper utilities for carb.events.
#pragma once
#include "../Framework.h"
#include "../InterfaceUtils.h"
#include "../ObjectUtils.h"
#include "../dictionary/DictionaryUtils.h"
#include "IEvents.h"
#include <functional>
#include <utility>
namespace carb
{
namespace events
{
/**
* Helper for carb::getCachedInterface<IEvents>().
* @returns The cached carb::events::IEvents interface.
*/
inline IEvents* getCachedEventsInterface()
{
return getCachedInterface<IEvents>();
}
/**
* A helper to use a `std::function` as an carb::events::IEventListener.
*/
class LambdaEventListener : public IEventListener
{
public:
/**
* Constructor.
* @param fn The `std::function` to call when onEvent() is called.
*/
LambdaEventListener(std::function<void(IEvent*)> fn) : m_fn(std::move(fn))
{
}
/**
* Passes the event to the `std::function` given to the constructor.
* @param e The carb::events::IEvent to process.
*/
void onEvent(IEvent* e) override
{
if (m_fn)
m_fn(e);
}
private:
std::function<void(IEvent*)> m_fn;
CARB_IOBJECT_IMPL
};
/**
* A helper for IEvents::createSubscriptionToPop() that creates a @ref LambdaEventListener.
* @param stream The @ref IEventStream to use.
* @param onEventFn A handler that will be invoked for each carb::events::IEvent that is popped.
* @param order An optional value used to specify the order tier. Lower order tiers will be notified first.
* Multiple IEventListener objects at the same order tier are notified in an undefined order.
* @param subscriptionName An optional name for the subscription. Names do not need to be unique.
* @returns A ISubscription pointer. The subscription is valid as long as the ISubscription pointer is referenced.
* Alternately, the IEventListener can be unsubscribed by calling ISubscription::unsubscribe().
*/
inline ObjectPtr<ISubscription> createSubscriptionToPop(IEventStream* stream,
std::function<void(IEvent*)> onEventFn,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr)
{
return stream->createSubscriptionToPop(
carb::stealObject(new LambdaEventListener(std::move(onEventFn))).get(), order, subscriptionName);
}
/// @copydoc createSubscriptionToPop
/// @param eventType A specific event to listen for.
inline ObjectPtr<ISubscription> createSubscriptionToPopByType(IEventStream* stream,
EventType eventType,
std::function<void(IEvent*)> onEventFn,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr)
{
return stream->createSubscriptionToPopByType(
eventType, carb::stealObject(new LambdaEventListener(std::move(onEventFn))).get(), order, subscriptionName);
}
/**
* A helper for IEvents::createSubscriptionToPush() that creates a @ref LambdaEventListener.
* @param stream The @ref IEventStream to use.
* @param onEventFn A handler that will be invoked for each carb::events::IEvent that is pushed.
* @param order An optional value used to specify the order tier. Lower order tiers will be notified first.
* Multiple IEventListener objects at the same order tier are notified in an undefined order.
* @param subscriptionName An optional name for the subscription. Names do not need to be unique.
* @returns A ISubscription pointer. The subscription is valid as long as the ISubscription pointer is referenced.
* Alternately, the IEventListener can be unsubscribed by calling ISubscription::unsubscribe().
*/
inline ObjectPtr<ISubscription> createSubscriptionToPush(IEventStream* stream,
std::function<void(IEvent*)> onEventFn,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr)
{
return stream->createSubscriptionToPush(
carb::stealObject(new LambdaEventListener(std::move(onEventFn))).get(), order, subscriptionName);
}
/// @copydoc createSubscriptionToPush
/// @param eventType A specific event to listen for.
inline ObjectPtr<ISubscription> createSubscriptionToPushByType(IEventStream* stream,
EventType eventType,
std::function<void(IEvent*)> onEventFn,
Order order = kDefaultOrder,
const char* subscriptionName = nullptr)
{
return stream->createSubscriptionToPushByType(
eventType, carb::stealObject(new LambdaEventListener(std::move(onEventFn))).get(), order, subscriptionName);
}
} // namespace events
} // namespace carb
| 5,635 | C | 41.37594 | 116 | 0.635847 |
omniverse-code/kit/include/carb/assets/AssetsUtils.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Utilities for *carb.assets.plugin*
#pragma once
#include "IAssets.h"
namespace carb
{
namespace assets
{
/**
* A RAII-style helper class to manage the result of \ref IAssets::acquireSnapshot().
* `operator bool()` can be used to test if the asset successfully acquired.
* `getReason()` can be used to check why an asset failed to load.
* If the asset successfully loaded, it can be obtained with `get()`.
*/
template <class Type>
class ScopedSnapshot
{
public:
/**
* Default Constructor; produces an empty object
*/
ScopedSnapshot() = default;
/**
* \c nullptr Constructor; produces an empty object
*/
ScopedSnapshot(std::nullptr_t)
{
}
/**
* Constructs a \c ScopedSnapshot for the given asset ID.
*
* If snapshot acquisition fails, `*this` will be \c false; use \ref getReason() to determine why.
* @param assets The IAssets interface
* @param assetId The asset ID to acquire a snapshot for.
*/
ScopedSnapshot(IAssets* assets, Id assetId) : m_assets(assets)
{
m_snapshot = assets->acquireSnapshot(assetId, getAssetType<Type>(), m_reason);
m_value = reinterpret_cast<Type*>(assets->getDataFromSnapshot(m_snapshot));
}
//! Destructor
~ScopedSnapshot()
{
release();
}
//! ScopedSnapshot is move-constructible.
//! @param other The other \c ScopedSnapshot to move from; \c other will be empty.
ScopedSnapshot(ScopedSnapshot&& other)
{
m_value = other.m_value;
m_assets = other.m_assets;
m_snapshot = other.m_snapshot;
m_reason = other.m_reason;
other.m_assets = nullptr;
other.m_value = nullptr;
other.m_snapshot = kInvalidSnapshot;
other.m_reason = Reason::eFailed;
}
/**
* Move-assignment operator.
* @param other The other \c ScopedSnapshot to move from; \c other will be empty.
* @returns \c *this
*/
ScopedSnapshot& operator=(ScopedSnapshot&& other)
{
// This assert should never happen, but it is possible to accidentally write this
// code, though one has to contort themselves to do it. It is considered
// invalid nonetheless.
CARB_ASSERT(this != &other);
release();
m_value = other.m_value;
m_assets = other.m_assets;
m_snapshot = other.m_snapshot;
m_reason = other.m_reason;
other.m_assets = nullptr;
other.m_value = nullptr;
other.m_snapshot = kInvalidSnapshot;
other.m_reason = Reason::eFailed;
return *this;
}
CARB_PREVENT_COPY(ScopedSnapshot);
/**
* Obtain the asset data from the snapshot.
* @returns The loaded asset if the asset load was successful; \c nullptr otherwise.
*/
Type* get()
{
return m_value;
}
//! @copydoc get()
const Type* get() const
{
return m_value;
}
/**
* Dereference-access operator.
* @returns The loaded asset; malformed if `*this == false`.
*/
Type* operator->()
{
return get();
}
//! @copydoc operator->()
const Type* operator->() const
{
return get();
}
/**
* Dereference operator.
* @returns A reference to the loaded asset; malformed if `*this == false`.
*/
Type& operator*()
{
return *get();
}
//! @copydoc operator*()
const Type& operator*() const
{
return *get();
}
/**
* Test if the asset snapshot successfully loaded.
* @returns \c true if the asset snapshot successfully loaded and its value can be retrieved via \ref get();
* \c false otherwise.
*/
constexpr explicit operator bool() const noexcept
{
return m_value != nullptr;
}
/**
* Obtain the current asset status.
* @returns the \ref Reason status code based on acquiring the snapshot. An empty \c ScopedSnapshot will return
* \ref Reason::eFailed.
*/
Reason getReason() const
{
return m_reason;
}
private:
void release()
{
if (m_assets && m_snapshot)
{
m_assets->releaseSnapshot(m_snapshot);
}
m_value = nullptr;
m_assets = nullptr;
m_snapshot = kInvalidSnapshot;
m_reason = Reason::eFailed;
}
// Note this member is first to help in debugging.
Type* m_value = nullptr;
carb::assets::IAssets* m_assets = nullptr;
Snapshot m_snapshot = kInvalidSnapshot;
Reason m_reason = Reason::eFailed;
};
//! \c ScopedSnapshot equality operator
//! @param a A \c ScopedSnapshot to compare
//! @param b A \c ScopedSnapshot to compare
//! @returns \c true if \c a and \c b are equal; \c false otherwise.
template <class Type>
bool operator==(const carb::assets::ScopedSnapshot<Type>& a, const carb::assets::ScopedSnapshot<Type>& b)
{
return a.get() == b.get();
}
//! \c ScopedSnapshot inequality operator
//! @param a A \c ScopedSnapshot to compare
//! @param b A \c ScopedSnapshot to compare
//! @returns \c true if \c a and \c b are unequal; \c false otherwise.
template <class Type>
bool operator!=(const carb::assets::ScopedSnapshot<Type>& a, const carb::assets::ScopedSnapshot<Type>& b)
{
return a.get() != b.get();
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
template <class Type>
bool operator==(const carb::assets::ScopedSnapshot<Type>& a, std::nullptr_t)
{
return a.get() == nullptr;
}
template <class Type>
bool operator==(std::nullptr_t, const carb::assets::ScopedSnapshot<Type>& a)
{
return a.get() == nullptr;
}
template <class Type>
bool operator!=(const carb::assets::ScopedSnapshot<Type>& a, std::nullptr_t)
{
return a.get() != nullptr;
}
template <class Type>
bool operator!=(std::nullptr_t, const carb::assets::ScopedSnapshot<Type>& a)
{
return a.get() != nullptr;
}
#endif
} // namespace assets
} // namespace carb
| 6,379 | C | 26.033898 | 115 | 0.629409 |
omniverse-code/kit/include/carb/assets/IAssetsBlob.h | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief "Blob" (Binary Large OBject) asset type definition
#pragma once
#include "AssetsTypes.h"
namespace carb
{
namespace assets
{
//! An opaque type representing a binary large object. Use \ref IAssetsBlob to access the data.
//! Can be loaded with `IAssets::loadAsset<Blob>(...)`.
struct Blob;
/**
* Defines an interface for managing assets that are loaded asynchronously.
*/
struct IAssetsBlob
{
CARB_PLUGIN_INTERFACE("carb::assets::IAssetsBlob", 1, 0)
/**
* Gets the data from a blob.
*
* @param blob The blob to use.
* @return The blob byte data.
*/
const uint8_t*(CARB_ABI* getBlobData)(Blob* blob);
/**
* Gets the size of the blob in bytes.
*
* @param blob The blob to use.
* @return The size of the blob in bytes.
*/
size_t(CARB_ABI* getBlobSize)(Blob* blob);
};
} // namespace assets
} // namespace carb
CARB_ASSET(carb::assets::Blob, 1, 0)
| 1,388 | C | 25.207547 | 95 | 0.688761 |
omniverse-code/kit/include/carb/assets/IAssets.h | // Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Interface definition for *carb.assets.plugin*
#pragma once
#include "../Interface.h"
#include "../Types.h"
#include "../datasource/IDataSource.h"
#include "../tasking/TaskingHelpers.h"
#include "AssetsTypes.h"
namespace carb
{
//! Namespace for *carb.assets.plugin* and related utilities.
namespace assets
{
/**
* Defines an interface for managing assets that are loaded asynchronously.
*/
struct IAssets
{
CARB_PLUGIN_INTERFACE("carb::assets::IAssets", 2, 0)
/**
* Creates an asset pool for managing and caching assets together.
*
* @param name The name of the pool.
* @return The asset pool handle.
*/
Pool(CARB_ABI* createPool)(const char* name);
/**
* Destroys an asset pool previously created with \ref createPool().
*
* @param pool The pool to destroy.
*/
void(CARB_ABI* destroyPool)(Pool pool);
/**
* Gets basic statistics about a pool
*
* @note The resulting values from this function are transitive and the values may have changed by other threads
* before the results can be read. They should be used for debugging purposes only.
*
* @param pool The pool to get stats about.
* @param totalAssets Receives the number of assets in the pool.
* @param assetsLoading Receives the number of assets currently loading.
*/
void(CARB_ABI* poolStats)(Pool pool, int& totalAssets, int& assetsLoading);
//! @private
Id(CARB_ABI* internalLoadAsset)(carb::datasource::IDataSource* dataSource,
carb::datasource::Connection* connection,
const char* path,
Pool pool,
const Type& assetType,
const LoadParameters* loadParameters,
carb::tasking::Object const* trackers,
size_t numTrackers);
//! @private
CARB_DEPRECATED("Use loadAsset<> instead.")
Id loadAssetEx(carb::datasource::IDataSource* dataSource,
carb::datasource::Connection* connection,
const char* path,
Pool pool,
const Type& assetType,
const LoadParameters* loadParameters,
carb::tasking::Object const* trackers,
size_t numTrackers)
{
return internalLoadAsset(dataSource, connection, path, pool, assetType, loadParameters, trackers, numTrackers);
}
/**
* Unloads an asset previously loaded with \ref loadAsset().
*
* If an asset that is currently loading is unloaded, this will attempt to cancel the load.
*
* @param assetId The asset to unload.
*/
void(CARB_ABI* unloadAsset)(Id assetId);
/**
* Unloads all assets from the specified asset pool.
*
* If any assets in the pool are currently loading, this will attempt to cancel the load.
*
* @param pool The pool to clear the assets from.
*/
void(CARB_ABI* unloadAssets)(Pool pool);
/**
* Pauses the current thread or task until the requested asset has finished loading.
*
* @param assetId The assetId to wait for.
*/
void(CARB_ABI* yieldForAsset)(Id assetId);
/**
* Pauses the current thread or task until all assets in the given pool have finished loading.
*
* @param pool The pool containing the assets to wait for.
*/
void(CARB_ABI* yieldForAssets)(Pool pool);
/**
* Registers a callback that will be notified when an asset changes.
*
* The callback occurs after the asset has changed. At the point of the callback, \ref acquireSnapshot() will return
* the updated data.
*
* @note Only one callback can be registered for a given \p assetId. If the given \p assetId already has a callback
* registered, it is revoked in favor of this new callback.
*
* @param assetId The asset to monitor for changes.
* @param onChangeEvent The callback function to be called once the changes are made.
* @param userData The user data associated with the callback.
*/
void(CARB_ABI* subscribeToChangeEvent)(Id assetId, OnChangeEventFn onChangeEvent, void* userData);
/**
* Unsubscribes any asset change callbacks for a given asset previously registered with
* \ref subscribeToChangeEvent().
*
* When this function returns, it is guaranteed that the previously registered \c onChangeEvent function is not
* currently being called from another thread, and will not be called again.
*
* @param assetId The assetId to remove subscriptions for.
*/
void(CARB_ABI* unsubscribeToChangeEvent)(Id assetId);
/**
* Acquires a \ref Snapshot of the asset of the given type.
*
* @note It is the caller's responsibility to release the snapshot via \ref releaseSnapshot() when finished with it.
*
* If an asset changes (i.e. a change event was issued for the given \p assetId), existing snapshots are not
* updated; you will have to release existing snapshots and acquire a new snapshot to get the updated data.
*
* @param assetId The asset to take a snapshot of.
* @param assetType The asset type being requested.
* @param reason The reason the snapshot could, or couldn't be taken.
* While the snapshot is loading, it will return \ref Reason::eLoading;
* any other value returned means the snapshot has finished loading.
* It is recommended to use \ref carb::tasking::Trackers with \ref loadAsset() instead of polling this
* function until \ref Reason::eLoading is no longer returned.
* @returns The snapshot handle for the asset at the present time.
*/
Snapshot(CARB_ABI* acquireSnapshot)(Id assetId, const Type& assetType, Reason& reason);
/**
* Releases a snapshot of an asset previously returned by \ref acquireSnapshot().
*
* @param snapshot The snapshot to release.
*/
void(CARB_ABI* releaseSnapshot)(Snapshot snapshot);
/**
* Gets the underlying data for the asset based on a snapshot.
*
* @param snapshot The snapshot of the asset to get the data from.
* @returns The raw data of the asset at the snapshot. If the asset's \c Type has been unregistered then `nullptr`
* is returned.
*/
void*(CARB_ABI* getDataFromSnapshot)(Snapshot snapshot);
/**
* Forces all dirty (that is, assets with changed data) assets of a given \c Type to reload.
*
* This function is only necessary for registered types where \ref AssetTypeParams::autoReload is set to \c false.
*
* @param assetType The \c Type of asset to request a reload for.
*/
void(CARB_ABI* reloadAnyDirty)(Type assetType);
/**
* Used to register a loader for a specific asset \c Type.
*
* @warning Typically \ref registerAssetType() should be used instead of this lower-level function.
*
* @param assetType The asset type to register.
* @param desc The loader descriptor.
* @param params The \ref AssetTypeParams settings for this assetType
*/
void(CARB_ABI* registerAssetTypeEx)(const Type& assetType, const LoaderDesc& desc, const AssetTypeParams& params);
/**
* Unregisters a specific asset loader.
*
* @note Typically \ref unregisterAssetType() should be used instead of this lower-level function.
*
* @warning All data from any \ref Snapshot objects (i.e. from \ref acquireSnapshot()) is invalid after calling
* this function. The \ref Snapshot handle remains valid but any attempts to retrieve data from the \ref Snapshot
* (with \ref getDataFromSnapshot()) will return \c nullptr. Using a \ref ScopedSnapshot of the given \c Type after
* calling this function produces undefined behavior.
*
* @note This function will attempt to cancel all loading tasks for this \p assetType and will wait for all loading
* tasks to complete.
*
* @param assetType The asset type to unregister.
*/
void(CARB_ABI* unregisterAssetTypeEx)(const Type& assetType);
/**
* Loads an asset of the given type. This overload uses default \ref LoadParameters.
*
* Events:
* - `Asset.BeginLoading` - Sent in the calling thread if asset load starts. Also sent by \ref reloadAnyDirty() or
* by a background thread if underlying data changes. Parameters:
* - `Path` (`const char*`) - the path to the asset.
* - `AssetId` (\ref Id) - the asset ID that is loading.
* - `Asset.EndLoading` - Sent from a background thread whenever asset load finishes, only for assets that have
* previously sent a `Asset.BeginLoading` event.
* - `Path` (`const char*`) - the path to the asset.
* - `AssetId` (\ref Id) - the asset ID that finished loading.
* - `Success` (bool) - whether the load was successful or not. If \c true, \ref acquireSnapshot() will acquire
* the new data for the asset.
*
* @tparam Type The type of the asset. A compile error will occur if \ref getAssetType() for the given type does not
* resolve to a function. @see CARB_ASSET.
* @param dataSource The data source to load from.
* @param connection The connection (from the given data source) to load from.
* @param path The asset path to load.
* @param pool The pool to load the asset into.
* @param trackers (Optional) Trackers that can be queried to see when the asset is done loading.
* @returns A unique \ref Id that identifies this asset. The asset system internally de-duplicates based on path,
* datasource, connection and \ref LoadParameters, so several different asset \ref Id results may reference the same
* underlying asset.
*/
template <typename Type>
Id loadAsset(carb::datasource::IDataSource* dataSource,
carb::datasource::Connection* connection,
const char* path,
Pool pool,
carb::tasking::Trackers trackers = carb::tasking::Trackers{});
/**
* Loads an asset of the given type, with the given \ref LoadParameters.
*
* Events:
* - `Asset.BeginLoading` - Sent in the calling thread if asset load starts. Also sent by \ref reloadAnyDirty() or
* by a background thread if underlying data changes. Parameters:
* - `Path` (`const char*`) - the path to the asset.
* - `AssetId` (\ref Id) - the asset ID that is loading.
* - `Asset.EndLoading` - Sent from a background thread whenever asset load finishes, only for assets that have
* previously sent a `Asset.BeginLoading` event.
* - `Path` (`const char*`) - the path to the asset.
* - `AssetId` (\ref Id) - the asset ID that finished loading.
* - `Success` (bool) - whether the load was successful or not. If \c true, \ref acquireSnapshot() will acquire
* the new data for the asset.
*
* @tparam Type The type of the asset. A compile error will occur if \ref getAssetType() for the given type does not
* resolve to a function. @see CARB_ASSET.
* @param dataSource The data source to load from.
* @param connection The connection (from the given data source) to load from.
* @param path The asset path to load.
* @param pool The pool to load the asset into.
* @param loadParameters The \ref LoadParameters derived class containing information about how to load the asset.
* @param trackers (Optional) Trackers that can be queried to see when the asset is done loading.
* @returns A unique \ref Id that identifies this asset. The asset system internally de-duplicates based on path,
* datasource, connection and \ref LoadParameters, so several different asset \ref Id results may reference the same
* underlying asset.
*/
template <typename Type>
Id loadAsset(carb::datasource::IDataSource* dataSource,
carb::datasource::Connection* connection,
const char* path,
Pool pool,
const LoadParameters& loadParameters,
carb::tasking::Trackers trackers = carb::tasking::Trackers{});
/**
* Takes a snapshot of the asset in a RAII-style object.
*
* @tparam Type The asset type.
* @param assetId The assetId to take a snapshot of.
* @returns A RAII-style object that manages the snapshot of data for the object.
*/
template <typename Type>
ScopedSnapshot<Type> takeSnapshot(Id assetId);
/**
* Used to register a loader for a specific asset \c Type.
*
* @tparam Type The asset type to register.
* @param loaderDesc The loader descriptor.
* @param params The \ref AssetTypeParams settings for this assetType
*/
template <typename Type>
void registerAssetType(const LoaderDesc& loaderDesc, const AssetTypeParams& params = AssetTypeParams::getDefault());
/**
* Unregisters a specific asset loader.
*
* @note Typically \ref unregisterAssetType() should be used instead of this lower-level function.
*
* @warning All data from any \ref Snapshot objects (i.e. from \ref acquireSnapshot()) is invalid after calling
* this function. The \ref Snapshot handle remains valid but any attempts to retrieve data from the \ref Snapshot
* (with \ref getDataFromSnapshot()) will return \c nullptr. Using a \ref ScopedSnapshot of the given \c Type after
* calling this function produces undefined behavior.
*
* @note This function will attempt to cancel all loading tasks for this \p assetType and will wait for all loading
* tasks to complete.
*
* @tparam Type The asset type to unregister.
*/
template <typename Type>
void unregisterAssetType();
};
} // namespace assets
} // namespace carb
#include "IAssets.inl"
| 14,528 | C | 43.567485 | 120 | 0.659072 |
omniverse-code/kit/include/carb/assets/AssetsTypes.h | // Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Type definitions for *carb.assets.plugin*
#pragma once
#include "../Defines.h"
#include "../extras/Hash.h"
#include "../Strong.h"
namespace carb
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace datasource
{
struct IDataSource;
struct Connection;
} // namespace datasource
#endif
namespace assets
{
/**
* The reason a Snapshot was taken or not.
*/
enum class Reason
{
eSuccess, //!< The asset was loaded, and the snapshot is valid.
eInvalidHandle, //!< The asset handle was invalid, this may mean the asset was canceled.
eInvalidType, //!< Although the asset may or may not have loaded, the snapshot type did not match the type the asset
//!< was loaded from. This should be construed as a programmer error.
eFailed, //!< The asset was not loaded, because load asset failed. Notably loadAsset returned nullptr.
eLoading, //!< The asset is still in the process of loading.
};
// The following are handles to detect incorrect usage patters such as using a handle
// after it has be destroyed.
//! An Asset ID, used to identify a particular asset.
CARB_STRONGTYPE(Id, size_t);
//! An Asset Pool, used to group assets together.
CARB_STRONGTYPE(Pool, size_t);
//! A snapshot, representing asset data at a given point in time.
CARB_STRONGTYPE(Snapshot, size_t);
//! C++ Type hash used to identify a C++ type. Typically a hash of a type name string.
using HashedType = uint64_t;
//! Used to identify an invalid asset id.
constexpr Id kInvalidAssetId{};
//! Used to identify an invalid pool.
constexpr Pool kInvalidPool{};
//! Used to identify an invalid snapshot.
constexpr Snapshot kInvalidSnapshot{};
//! A load context that exists for the duration of the load phase. A loader may create a subclass of this to maintain
//! context data about a type.
struct LoadContext
{
};
//! Parameters that can be passed into \ref IAssets::loadAsset(). Asset types can create a subclass of this to pass
//! asset-type-specific load parameters through the asset system.
struct LoadParameters
{
};
/**
* Wrapper for an asset type that can be passed to various functions, identifies the asset as a hashed string
* plus the version number, which can impact the LoadParameters structure.
*/
struct Type
{
//! Constructor
Type(HashedType hashedType, uint32_t majorVersion, uint32_t minorVersion)
: hashedType(hashedType), majorVersion(majorVersion), minorVersion(minorVersion)
{
}
uint64_t hashedType; //!< The hashed string name of the Type.
uint32_t majorVersion; //!< The major version
uint32_t minorVersion; //!< The minor version
};
//! A scoped snapshot, this automatically releases the snapshot when it goes out of scope.
template <class Type>
class ScopedSnapshot;
/**
* The hash must be a strong (not necessarily cryptographically secure) 128-bit hash.
* 128-bit hashes are chosen because the if the hash is well distributed, then the probability of a collision even given
* a large set size is low. See: https://en.wikipedia.org/wiki/Birthday_problem#Probability_table
*
* For this reason when using hashing we do not do a deep compare on the objects.
*/
using AssetHash = extras::hash128_t;
/**
* Defines a template for users to specialize their asset type as unique identifiers.
*
* The \ref CARB_ASSET macro specializes this function for registered asset types.
*
* @see CARB_ASSET
*
* Example:
* ```cpp
* CARB_ASSET(carb::imaging::Image, 1, 0)
* ```
*/
template <typename T>
Type getAssetType();
/**
* Determines if a currently processed load has been canceled.
*
* @note This callback is only valid within the scope of the \ref LoadAssetFn function
*
* This function is used by the \ref LoadAssetFn to determine if it can abort processing early.
* Calling this function is optional. For longer or multi-stage loading processes, calling this function can be an
* indicator as to whether any assets still exist which are interested in the data that \ref LoadAssetFn is processing.
*
* @param userData Must be the `isLoadCanceledUserData` provided to \ref LoadAssetFn.
* @returns \c true if the load was canceled and should be aborted; \c false otherwise.
*/
using IsLoadCanceledFn = bool (*)(void* userData);
/**
* Loader function (member of \ref LoaderDesc) used to construct an asset from raw data.
*
* Though the raw data for \p path has already been loaded from \p dataSource and \p connection, they are all provided
* to this function in case additional data must be loaded.
*
* @note This function is called in Task Context (from carb::tasking::ITasking), therefore the called function is free
* to await any fiber-aware I/O functions (i.e. sleep in a fiber safe manner) without bottlenecking the system.
*
* @param dataSource The datasource the asset is being loaded from.
* @param connection The connection the asset is being loaded from.
* @param path The path the file was loaded from.
* @param data The data to be loaded.
* @param size The size of the data (in bytes) to be loaded.
* @param loadParameters Optional parameters passed from \ref IAssets::loadAsset() (Asset Type specific).
* @param loadContext A context generated by \ref CreateContextFn, if one was provided.
* @param isLoadCanceled A function that can be called periodically to determine if load should be canceled. This
* function need only be called if the load process has multiple steps or lots of processing.
* @param isLoadCanceledUserData User data that must be provided to \p isLoadCanceled when (if) it is called.
* @return The loaded Asset, or \c nullptr if loading is aborted or an error occurred.
*/
using LoadAssetFn = void* (*)(carb::datasource::IDataSource* dataSource,
carb::datasource::Connection* connection,
const char* path,
const uint8_t* data,
size_t size,
const LoadParameters* loadParameters,
LoadContext* loadContext,
IsLoadCanceledFn isLoadCanceled,
void* isLoadCanceledUserData);
/**
* Loader function (member of \ref LoaderDesc) used to unload an asset.
*
* @param asset The asset to be unloaded. This data was previously returned from \ref LoadAssetFn.
*/
using UnloadAssetFn = void (*)(void* asset);
/**
* Loader function (member of \ref LoaderDesc) that informs the asset type that loading a file has started and creates
* any load-specific context data necessary.
*
* @note This callback is optional, if it isn't provided, in future callbacks \c loadContext will be \c nullptr. If this
* function is provided, \ref DestroyContextFn should also be provided to destroy the context.
*
* @note This function is called in Task Context (from carb::tasking::ITasking), therefore the called function is free
* to await any fiber-aware I/O functions without bottlenecking the system.
*
* This function gives the programmer the option to do initial work that may be repetitive in the function calls
* that load the file.
*
* The created context only exists during the loading of the asset, after the asset is loaded this context is destroyed
* with \ref DestroyContextFn.
*
* @param dataSource The datasource the asset is being loaded from.
* @param connection The connection the asset is being loaded from.
* @param path The path of the file that is being loaded.
* @param data The data read at the asset's URI path.
* @param size The size of the data read in bytes.
* @param loadParameters The load parameters passed to \ref IAssets::loadAsset(), or \c nullptr.
* @returns A derivative of \ref LoadContext that is passed to \ref LoadAssetFn and \ref CreateDependenciesFn.
*/
using CreateContextFn = LoadContext* (*)(carb::datasource::IDataSource* dataSource,
carb::datasource::Connection* connection,
const char* path,
const uint8_t* data,
size_t size,
const LoadParameters* loadParameters);
/**
* Loader function (member of \ref LoaderDesc) that destroys the data created by \ref CreateContextFn.
*
* This function is optional, but always called if present, even if \p context is \c nullptr.
*
* @param context The context to destroy, previously created by \ref CreateContextFn.
*/
using DestroyContextFn = void (*)(LoadContext* context);
/**
* Loader function (member of \ref LoaderDesc) that returns a string of the asset dependencies, that is, other files to
* watch for changes.
*
* This function is optional, if it isn't provided, then only \p path (passed to \ref IAssets::loadAsset()) will be
* monitored for changes.
*
* Many asset types, such as shaders, include additional files to generate their content. In this case it isn't just
* the original file changing that requires the asset to be reloaded, if any dependent file changes, then the asset
* has to be reloaded as well.
*
* Multiple dependencies must separated by the `|` character.
*
* @param dataSource The datasource the asset is being loaded from.
* @param connection The connection the asset is being loaded from.
* @param path The path of the file that is being loaded.
* @param data The loaded data of the requested assets file.
* @param size The size of the requested asset file.
* @param loadParameters The load parameters provided to \ref IAssets::loadAsset().
* @param context The context if any generated by \ref CreateContextFn.
* @return A string containing dependencies to watch, delimited by `|`; \c nullptr may be returned to indicate no
* dependencies. The returned pointer will be passed to \ref DestroyDependenciesFn to clean up the returned memory.
*/
using CreateDependenciesFn = const char* (*)(carb::datasource::IDataSource* dataSource,
carb::datasource::Connection* connection,
const char* path,
const uint8_t* data,
size_t size,
const LoadParameters* loadParameters,
LoadContext* context);
/**
* Loader function (member of \ref LoaderDesc) that cleans up the previously returned value from
* \ref CreateDependenciesFn.
*
* @note This function is required and called if and only if \ref CreateDependenciesFn is provided.
*
* @param dependencies The string generated by a previous call to \ref CreateDependenciesFn.
* @param context The context if any generated by \ref CreateContextFn.
*/
using DestroyDependenciesFn = void (*)(const char* dependencies, LoadContext* context);
/**
* Loader function (member of \ref LoaderDesc) that is called when a dependency changes.
*
* @param dataSource The datasource of the dependency that changed.
* @param connection The connection of the dependency that changed.
* @param path The path of the dependency that changed.
*/
using OnDependencyChangedFn = void (*)(carb::datasource::IDataSource* dataSource,
carb::datasource::Connection* connection,
const char* path);
/**
* Loader function (member of \ref LoaderDesc) that hashes an asset's data, this is used to combine collisions in the
* asset system.
*
* This function is optional; if not provided, the path of the loaded file is hashed.
*
* If two different files return the same hash, then the system will return a copy of the first
* asset load. An example of where this is useful is programmatically generated shaders. In this
* context this system ensures that only one unique shader is created from many sources that generate
* the same shader.
*
* @param dataSource The datasource the asset is being loaded from.
* @param connection The connection the asset is being loaded from.
* @param path The path of the file that is being loaded.
* @param data The data to be loaded.
* @param size The size of the data (in bytes) to be loaded.
* @param loadParameters The load parameters passed to \ref IAssets::loadAsset().
* @param context A context generated by \ref CreateContextFn, if one was provided.
* @return The hash of the asset.
*/
using HashAssetFn = AssetHash (*)(carb::datasource::IDataSource* dataSource,
carb::datasource::Connection* connection,
const char* path,
const uint8_t* data,
size_t size,
const LoadParameters* loadParameters,
LoadContext* context);
/**
* Loader function (member of \ref LoaderDesc) that copies a \ref LoadParameters structure.
*
* @note This function is required for any types where a \ref LoadParameters derivative may be passed to
* \ref IAssets::loadAsset().
*
* @param loadParameters The load parameters to copy.
* @return The copied load parameters.
*/
using CreateLoadParametersFn = LoadParameters* (*)(const LoadParameters* loadParameters);
/**
* Loader function (member of \ref LoaderDesc) that destroys a copied \ref LoadParameters structure.
*
* @note This function is required for any types where a \ref LoadParameters derivative may be passed to
* \ref IAssets::loadAsset().
*
* @param loadParameters The load parameters to destroy.
*/
using DestroyLoadParametersFn = void (*)(LoadParameters* loadParameters);
/**
* Loader function (member of \ref LoaderDesc) that hashes a LoadParameters structure.
*
* @note This function is required for any types where a \ref LoadParameters derivative may be passed to
* \ref IAssets::loadAsset().
*
* @param loadParameters The load parameters to hash.
* @returns The hashed value of the load parameters structure.
*
* @note Be aware of struct padding when hashing the load parameter data.
* Passing an entire parameter struct into a hash function may result in
* padding being hashed, which will cause undefined behavior.
*/
using HashLoadParametersFn = uint64_t (*)(const LoadParameters* loadParameters);
/**
* Loader function (member of \ref LoaderDesc) that determines if two \ref LoadParameters derivatives are equal.
*
* @note This function is required for any types where a \ref LoadParameters derivative may be passed to
* \ref IAssets::loadAsset().
*
* @param loadParametersA A \ref LoadParameters to compare.
* @param loadParametersB A \ref LoadParameters to compare.
* @return \c true if loadParametersA == loadParametersB; \c false otherwise.
*
* @note Avoid using \c memcmp() to compare parameters structs as padding within
* the struct could cause the comparison to unexpectedly fail.
*/
using LoadParametersEqualsFn = bool (*)(const LoadParameters* loadParametersA, const LoadParameters* loadParametersB);
/**
* Defines the loader functions for an asset type.
*
* The following is the basic call order for loader functions (for clarity, parameters have been simplified).
*
* When an asset is being loaded for the first time, or reloaded:
* ```cpp
* context = createContext ? createContext() : nullptr;
*
* dependencies = createDependencies ? createDependencies() : nullptr;
* if (dependencies)
* {
* // dependencies are processed
* destroyDependencies(dependencies);
* }
*
* hash = hashAsset();
* // If the hash is already loaded then return that already loaded asset, otherwise:
*
* asset = loadAsset();
* if (context)
* destroyContext(context);
* ```
*
* When the asset is destroyed:
* ```cpp
* unloadAsset(asset)
* ```
*
*/
struct LoaderDesc
{
LoadAssetFn loadAsset; //!< @see LoadAssetFn
UnloadAssetFn unloadAsset; //!< @see UnloadAssetFn
CreateLoadParametersFn createLoadParameters; //!< @see CreateLoadParametersFn
DestroyLoadParametersFn destroyLoadParameters; //!< @see DestroyLoadParametersFn
HashLoadParametersFn hashLoadParameters; //!< @see HashLoadParametersFn
LoadParametersEqualsFn loadParametersEquals; //!< @see LoadParametersEqualsFn
HashAssetFn hashAsset; //!< @see HashAssetFn
CreateContextFn createContext; //!< @see CreateContextFn
DestroyContextFn destroyContext; //!< @see DestroyContextFn
CreateDependenciesFn createDependencies; //!< @see CreateDependenciesFn
DestroyDependenciesFn destroyDependencies; //!< @see DestroyDependenciesFn
OnDependencyChangedFn onDependencyChanged; //!< @see OnDependencyChangedFn
};
//! Parameters that describe an asset type's characteristics.
struct AssetTypeParams
{
//! Must be initialized to `sizeof(AssetTypeParams)`. This is used as a version for future expansion of this
//! `struct`.
size_t sizeofThis;
//! The maximum number of outstanding concurrent loads of this asset type. A value of \c 0 indicates "unlimited." A
//! value of \c 1 indicates that loading is not thread-safe and only one asset may be loading at a given time. Any
//! other value limits the number of loading assets for the given type. (default=`0`)
uint32_t maxConcurrency;
//! Specifies that the assets should automatically reload when the file or one of its dependencies changes. If this
//! is false, you must call \ref IAssets::reloadAnyDirty() in order to manually trigger a reload. (default=`true`)
bool autoReload;
//! The amount of time in milliseconds to delay when automatically reloading an asset. This is because a reload is
//! triggered immediately when a change is detected from the datasource. A filesystem for example can trigger
//! multiple change notifications for a write to a file. This value gives a sliding window of changes so that all
//! changes that happen within the window get condensed into a single reload. (default=`100` ms)
uint32_t reloadDelayMs;
/**
* Returns the default values for \c AssetTypeParams.
* @returns Default values.
*/
constexpr static AssetTypeParams getDefault()
{
return AssetTypeParams{ sizeof(AssetTypeParams), 0, true, 100 };
}
};
/**
* Function to provide as a callback on asset changes.
*
* @see IAssets::subscribeToChangeEvent()
*
* @param assetId The asset ID of the asset that was modified.
* @param userData The user data given when the subscription was created.
*/
using OnChangeEventFn = void (*)(Id assetId, void* userData);
} // namespace assets
} // namespace carb
#ifdef DOXYGEN_BUILD
/**
* Registers an asset type.
*
* The version is used to protect the LoadParameter class as it's definition could change thereby causing undefined
* behavior if the asset loader version doesn't match the users of that loader. Therefore, the version should be updated
* any time the LoadParameters is update to avoid runtime issues.
*
* Note the additional two parameters which specify the version of the Asset, in this case
* the imaging asset is version 1.0. This value should only need to be updated if the LoadParmeters structure is
* updated.
*
* @param t The type of the asset to register
* @param majorVersion The major version of the asset type.
* @param minorVersion The minor version of the asset type.
*/
# define CARB_ASSET(t, majorVersion, minorVersion)
#else
# define CARB_ASSET(t, majorVersion, minorVersion) \
namespace carb \
{ \
namespace assets \
{ \
template <> \
inline Type getAssetType<t>() \
{ \
return Type(CARB_HASH_TYPE(t), majorVersion, minorVersion); \
} \
} \
}
#endif
| 21,274 | C | 43.978858 | 120 | 0.669644 |
omniverse-code/kit/include/carb/logging/LoggingSettingsUtils.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Framework.h"
#include "../settings/ISettings.h"
#include "ILogging.h"
#include "Log.h"
#include "StandardLogger.h"
#include <vector>
namespace carb
{
namespace logging
{
/**
* Converts a string to its equivalent OutputStream value.
* @param[in] name The case-insensitive name of an output stream value.
*
* @returns This returns OutputStream::eStderr, if name is "stderr".
* @reutrns This returns OutputStream::eDefault for any other name.
*/
inline OutputStream stringToOutputStream(const char* name)
{
static constexpr struct
{
const char* name;
OutputStream value;
} kMappings[] = { { "stderr", OutputStream::eStderr } };
for (size_t i = 0; i < CARB_COUNTOF(kMappings); i++)
{
#if CARB_PLATFORM_WINDOWS
if (_stricmp(kMappings[i].name, name) == 0)
#else
if (strcasecmp(kMappings[i].name, name) == 0)
#endif
return kMappings[i].value;
}
return OutputStream::eDefault;
}
/**
* Configures global logging plugin with values from the config plugin values. Global logging
* configuration specifies behavior for any loggers registered later, and doesn't dictate
* neither how exactly any specific logger should operate, nor how the output will look like.
*
* Supported config fields:
* - "level": string log level value, available options: "verbose"|"info"|"warning"|"error"|"fatal"
* - "enabled": boolean value, enable or disable logging
*
* These values could be specified either per-source, in the source collection ("/log/sources/"),
* for example, <source> level should be specified as "/log/sources/<source>/level", or globally,
* as "/log/level". Similar pattern applies to "enabled" property.
*/
inline void configureLogging(settings::ISettings* settings)
{
Framework* f = getFramework();
logging::ILogging* logging = f->acquireInterface<logging::ILogging>();
if (settings == nullptr)
return;
if (logging)
{
const char* kLogLevel = "/log/level";
const char* kLogEnabled = "/log/enabled";
const char* kLogAsync = "/log/async";
// setting defaults
settings->setDefaultString(kLogLevel, "Warning");
settings->setDefaultBool(kLogEnabled, true);
settings->setDefaultBool(kLogAsync, false);
// The first order of business is to set logging according to config (this can be from file or command line):
const int32_t logLevel = logging::stringToLevel(settings->getStringBuffer(kLogLevel));
logging->setLevelThreshold(logLevel);
const bool logEnabled = settings->getAsBool(kLogEnabled);
logging->setLogEnabled(logEnabled);
logging->setLogAsync(settings->getAsBool(kLogAsync));
// Read config for source-specific setting overrides
// First, read the sources collection
const char* kLogSourcesKey = "/log/sources";
const carb::dictionary::Item* logSources = settings->getSettingsDictionary(kLogSourcesKey);
if (logSources != nullptr)
{
auto* dictInterface = f->acquireInterface<carb::dictionary::IDictionary>();
// Traverse the sources collection to set per-source overrides
for (size_t i = 0, totalChildren = dictInterface->getItemChildCount(logSources); i < totalChildren; ++i)
{
const carb::dictionary::Item* curSource = dictInterface->getItemChildByIndex(logSources, i);
if (curSource == nullptr)
{
CARB_LOG_ERROR("Null log source present in the configuration.");
continue;
}
const char* curSourceName = dictInterface->getItemName(curSource);
if (curSourceName == nullptr)
{
CARB_LOG_ERROR("Log source with no name present in the configuration.");
continue;
}
// Read the source level setting
const carb::dictionary::Item* curLogLevel = dictInterface->getItem(curSource, "level");
if (curLogLevel != nullptr)
{
logging->setLevelThresholdForSource(
curSourceName, logging::LogSettingBehavior::eOverride,
logging::stringToLevel(dictInterface->getStringBuffer(curLogLevel)));
}
// Read the source enabled setting
const carb::dictionary::Item* curLogEnabled = dictInterface->getItem(curSource, "enabled");
if (curLogEnabled != nullptr)
{
const bool isCurLogEnabled =
dictInterface->isAccessibleAs(dictionary::ItemType::eBool, curLogEnabled) ?
dictInterface->getAsBool(curLogEnabled) :
logEnabled;
logging->setLogEnabledForSource(
curSourceName, logging::LogSettingBehavior::eOverride, isCurLogEnabled);
}
}
}
}
}
// example-begin Configure StandardLogger
/**
* Configures default logger with values from the config plugin values. Default logger configuration
* specifies where to output the log stream and how the output will look.
*
* Further instructions on the meaning of fields is available from StandardLogger.h
*/
inline void configureDefaultLogger(settings::ISettings* settings)
{
Framework* f = getFramework();
logging::ILogging* logging = f->acquireInterface<logging::ILogging>();
if (settings == nullptr)
return;
if (logging)
{
// Config settings for default logger
auto* logger = logging->getDefaultLogger();
// setting defaults
const char* kFilePath = "/log/file";
const char* kFileFlushLevelPath = "/log/fileFlushLevel";
const char* kFlushStandardStreamOutputPath = "/log/flushStandardStreamOutput";
const char* kEnableStandardStreamOutputPath = "/log/enableStandardStreamOutput";
const char* kEnableDebugConsoleOutputPath = "/log/enableDebugConsoleOutput";
const char* kEnableColorOutputPath = "/log/enableColorOutput";
const char* kProcessGroupIdPath = "/log/processGroupId";
const char* kIncludeSourcePath = "/log/includeSource";
const char* kIncludeChannelPath = "/log/includeChannel";
const char* kIncludeFilenamePath = "/log/includeFilename";
const char* kIncludeLineNumberPath = "/log/includeLineNumber";
const char* kIncludeFunctionNamePath = "/log/includeFunctionName";
const char* kIncludeTimeStampPath = "/log/includeTimeStamp";
const char* kIncludeThreadIdPath = "/log/includeThreadId";
const char* kSetElapsedTimeUnitsPath = "/log/setElapsedTimeUnits";
const char* kIncludeProcessIdPath = "/log/includeProcessId";
const char* kLogOutputStream = "/log/outputStream";
const char* kOutputStreamLevelThreshold = "/log/outputStreamLevel";
const char* kDebugConsoleLevelThreshold = "/log/debugConsoleLevel";
const char* kFileOutputLevelThreshold = "/log/fileLogLevel";
const char* kDetailLogPath = "/log/detail";
const char* kFullDetailLogPath = "/log/fullDetail";
const char* kFileAppend = "/log/fileAppend";
const char* kForceAnsiColor = "/log/forceAnsiColor";
settings->setDefaultString(kFileFlushLevelPath, "verbose");
settings->setDefaultBool(kFlushStandardStreamOutputPath, false);
settings->setDefaultBool(kEnableStandardStreamOutputPath, true);
settings->setDefaultBool(kEnableDebugConsoleOutputPath, true);
settings->setDefaultBool(kEnableColorOutputPath, true);
settings->setDefaultInt(kProcessGroupIdPath, 0);
settings->setDefaultBool(kIncludeSourcePath, true);
settings->setDefaultBool(kIncludeChannelPath, true);
settings->setDefaultBool(kIncludeFilenamePath, false);
settings->setDefaultBool(kIncludeLineNumberPath, false);
settings->setDefaultBool(kIncludeFunctionNamePath, false);
settings->setDefaultBool(kIncludeTimeStampPath, false);
settings->setDefaultBool(kIncludeThreadIdPath, false);
settings->setDefaultBool(kIncludeProcessIdPath, false);
settings->setDefaultBool(kDetailLogPath, false);
settings->setDefaultBool(kFullDetailLogPath, false);
settings->setDefaultBool(kForceAnsiColor, false);
settings->setDefaultString(kOutputStreamLevelThreshold, "verbose");
settings->setDefaultString(kDebugConsoleLevelThreshold, "verbose");
settings->setDefaultString(kFileOutputLevelThreshold, "verbose");
// getting values from the settings
logger->setStandardStreamOutput(settings->getAsBool(kEnableStandardStreamOutputPath));
logger->setDebugConsoleOutput(settings->getAsBool(kEnableDebugConsoleOutputPath));
LogFileConfiguration config{};
settings->setDefaultBool(kFileAppend, config.append);
config.append = settings->getAsBool(kFileAppend);
logger->setFileConfiguration(settings->getStringBuffer(kFilePath), &config);
logger->setFileOuputFlushLevel(logging::stringToLevel(settings->getStringBuffer(kFileFlushLevelPath)));
logger->setFlushStandardStreamOutput(settings->getAsBool(kFlushStandardStreamOutputPath));
logger->setForceAnsiColor(settings->getAsBool(kForceAnsiColor));
logger->setColorOutputIncluded(settings->getAsBool(kEnableColorOutputPath));
logger->setMultiProcessGroupId(settings->getAsInt(kProcessGroupIdPath));
bool channel = settings->getAsBool(kIncludeSourcePath) && settings->getAsBool(kIncludeChannelPath);
// if this is set, it enabled everything
bool fullDetail = settings->getAsBool(kFullDetailLogPath);
// if this is set, it enables everything except file name and PID
bool detail = fullDetail || settings->getAsBool(kDetailLogPath);
logger->setSourceIncluded(detail || channel);
logger->setFilenameIncluded(fullDetail || settings->getAsBool(kIncludeFilenamePath));
logger->setLineNumberIncluded(detail || settings->getAsBool(kIncludeLineNumberPath));
logger->setFunctionNameIncluded(detail || settings->getAsBool(kIncludeFunctionNamePath));
logger->setTimestampIncluded(detail || settings->getAsBool(kIncludeTimeStampPath));
logger->setThreadIdIncluded(detail || settings->getAsBool(kIncludeThreadIdPath));
logger->setElapsedTimeUnits(settings->getStringBuffer(kSetElapsedTimeUnitsPath));
logger->setProcessIdIncluded(fullDetail || settings->getAsBool(kIncludeProcessIdPath));
if (auto buffer = settings->getStringBuffer(kLogOutputStream))
{
logger->setOutputStream(stringToOutputStream(buffer));
}
logger->setStandardStreamOutputLevelThreshold(
logging::stringToLevel(settings->getStringBuffer(kOutputStreamLevelThreshold)));
logger->setDebugConsoleOutputLevelThreshold(
logging::stringToLevel(settings->getStringBuffer(kDebugConsoleLevelThreshold)));
logger->setFileOutputLevelThreshold(logging::stringToLevel(settings->getStringBuffer(kFileOutputLevelThreshold)));
}
}
// example-end
} // namespace logging
} // namespace carb
| 11,808 | C | 43.901141 | 122 | 0.686399 |
omniverse-code/kit/include/carb/logging/StandardLogger2.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief carb.logging StandardLogger2 definitions
#pragma once
#include "LoggingTypes.h"
namespace carb
{
namespace logging
{
struct Logger;
struct StandardLogger;
/**
* A sub-interface of \ref ILogging for \ref StandardLogger instances.
*/
class StandardLogger2
{
// This class's ABI is versioned by the ILogging version.
public:
/**
* Adds a reference to *this.
*/
virtual void addRef() = 0;
/**
* Releases a reference to *this. When the last reference is released, *this is destroyed.
*/
virtual void release() = 0;
/**
* Retrieves access to the underlying \ref Logger for *this.
* @see ILogging::addLogger() ILogging::removeLogger()
* @returns the underlying \ref Logger.
*/
virtual Logger* getLogger() = 0;
/**
* Includes or excludes the filename of where the log message came from. A new instance
* will by default exclude this information.
*
* @param included Whether the filename information should be included in the log message
*/
virtual void setFilenameIncluded(bool included) = 0;
/**
* Includes or excludes the line number of where the log message came from. A new instance
* will by default exclude this information.
*
* @param included Whether the line number information should be included in the log message
*/
virtual void setLineNumberIncluded(bool included) = 0;
/**
* Includes or excludes the function name of where the log message came from. A new instance
* will by default exclude this information.
*
* @param included Whether the function name information should be included in the log message
*/
virtual void setFunctionNameIncluded(bool included) = 0;
/**
* Includes or excludes the timestamp of when the log message was issued. A new instance
* will by default exclude this information. The time is in UTC format.
*
* @param included Whether the timestamp information should be included in the log message
*/
virtual void setTimestampIncluded(bool included) = 0;
/**
* Includes or excludes the id of a thread from which the log message was issued. A new instance
* will by default exclude this information.
*
* @param included Whether the thread id should be included in the log message
*/
virtual void setThreadIdIncluded(bool included) = 0;
/**
* Includes or excludes the source (module) of where the log message came from. A new instance
* will by default include this information.
*
* @param included Whether the source (module) information should be included in the log message
*/
virtual void setSourceIncluded(bool included) = 0;
/**
* Enables (or disables) standard stream output (stdout and stderr) for the logger. Error messages are written
* to stderr, all other messages to stdout. A new FrameworkLogger will have this output enabled.
*
* @param enabled Whether log output should go to standard streams (stdout and stderr)
*/
virtual void setStandardStreamOutput(bool enabled) = 0;
/**
* (Windows only) Enables (or disables) debug console output for the logger via `OutputDebugStringW()`. By default,
* debug output is only supplied if a debugger is attached (via `IsDebuggerPresent()`). Calling this with @p enabled
* as `true` will always produce debug output which is useful for non-debugger tools such as SysInternals DebugView.
*
* @param enabled Whether log output should be sent to the debug console.
*/
virtual void setDebugConsoleOutput(bool enabled) = 0;
/** sets the path to the log file to open.
*
* @param[in] filePath the local file path to write the log file to. This may be a
* relative or absolute path. Relative paths will be resolved
* relative to the process's current working directory at the time
* of the call. This may be nullptr to not write to a log file at
* all or to close the current log file. If a log file was
* previously open during this call, it will be closed first. If
* nullptr is passed in here, logging to a file will effectively
* be disabled. This path must be UTF-8 encoded. See the remarks
* below for more information on formatting of the log file path.
* @returns no return value.
*
* @remarks This sets the path to the log file to write to for the given instance of a
* standard logger object. The log file name may contain the string "${pid}" to
* have the process ID inserted in its place. By default, a new standard logger
* will disable logging to a file.
*
* @note Setting the log file name with this function will preserve the previous log file
* configuration. If the configuration needs to changes as well (ie: change the
* 'append' state of the log file), setFileConfiguration() should be used instead.
*/
virtual void setFileOutput(const char* filePath) = 0;
/**
* Enables flushing on every log message to file specified severity or higher.
* A new instance will have this set to flush starting from kLevelVerbose, so that file logging will be
* reliable out of the box. The idea is that file logging will be used for debugging purposes by default, with a
* price of significant performance penalty.
*
* @param level The starting log level to flush file log output at.
*/
virtual void setFileOuputFlushLevel(int32_t level) = 0;
/**
* Enables flushing of stdout after each message is printed to it.
* By default, this option will be disabled. The default behavior will be to only flush stdout just before
* writing a message to stderr.
*
* @param enabled Set to true to cause stdout to be flushed after each message is written. Set to false to
* use the default behavior of only flushing stdout before writing to stderr.
*/
virtual void setFlushStandardStreamOutput(bool enabled) = 0;
/**
* Enables a high resolution time index to be printed with each message.
* By default, this option is disabled (ie: no time index printed). When enabled, the current time index
* (since the first message was printed) will be printed with each message. The time index may be in
* milliseconds, microseconds, or nanoseconds depending on the string @p units. The printing of the time
* index may be enabled at the same time as the timestamp.
*
* @param[in] units the units that the time index should be printed in. This can be one of the following
* supported unit names:
* * nullptr, "", or "none": the time index printing is disabled (default state).
* * "ms", "milli", or "milliseconds": print the time index in milliseconds.
* * "us", "µs", "micro", or "microseconds": print the time index in microseconds.
* * "ns", "nano", or "nanoseconds": print the time index in nanoseconds.
*/
virtual void setElapsedTimeUnits(const char* units) = 0;
/**
* Includes or excludes the id of the process from which the log message was issued. A new instance
* will by default exclude this information.
*
* @param enabled Whether the process id should be included in the log message
*/
virtual void setProcessIdIncluded(bool enabled) = 0;
/**
* sets the process group ID for the logger. If a non-zero identifier is given, inter-process
* locking will be enabled on both the log file and the stdout/stderr streams. This will prevent
* simultaneous messages from multiple processes in the logs from becoming interleaved within
* each other. If a zero identifier is given, inter-process locking will be disabled.
*
* @param[in] id an arbitrary process group identifier to set.
*/
virtual void setMultiProcessGroupId(int32_t id) = 0;
/**
* Enables (or disables) color codes output for the logger. A new instance will have this output enabled
* unless the output is piped to a file, in which case this will be disabled.
*
* @param enabled Whether log output should include color codes
*/
virtual void setColorOutputIncluded(bool enabled) = 0;
/**
* Specify the output stream that logging should go to.
* By default, messages are sent to stdout and errors are sent to stderr.
*
* @param[in] outputStream The output stream setting to use.
* If this is OutputStream::eStderr, all logging
* output will be sent to stderr.
* If this is OutputStream::eDefault, the default
* logging behavior will be used.
*/
virtual void setOutputStream(OutputStream outputStream) = 0;
/**
* Sets the log level threshold for the messages going to the standard stream. Messages below this threshold will be
* dropped.
*
* @param level The log level to set.
*/
virtual void setStandardStreamOutputLevelThreshold(int32_t level) = 0;
/**
* Sets the log level threshold for the messages going to the debug console output. Messages below this threshold
* will be dropped.
*
* @param level The log level to set.
*/
virtual void setDebugConsoleOutputLevelThreshold(int32_t level) = 0;
/**
* Sets the log level threshold for the messages going to the file output. Messages below this threshold
* will be dropped.
*
* @param level The log level to set.
*/
virtual void setFileOutputLevelThreshold(int32_t level) = 0;
/**
* Sets the file path and configuration for file logging. If nullptr is provided the file logging is disabled. A new
* instance will by default disable file output.
*
* @param filePath The local file path to write to or nullptr, if you want to disable logging to file.
* Parameter is encoded as UTF8 character string with forward slashes as path separator. The path
* should include the extension .log but this is not a requirement. If a relative path is provided
* it is interpreted to be relative to the current working directory for the application. Can be kKeepSameFile to
* keep logging to the same file but set a new LogFileConfiguration.
* @param config The LogFileConfiguration structure with parameters to use for the file configuration. Required.
*/
virtual void setFileConfiguration(const char* filePath, const LogFileConfiguration* config) = 0;
/**
* Returns the file path (in buffer) and configuration for file logging.
*
* @param buffer The buffer that will receive the UTF-8 file name that is being logged to. May be nullptr.
* @param bufferSize The maximum number of bytes available in \p buffer.
* @param config The LogFileConfiguration to receive the current configuration. May be nullptr.
* @returns If successful, the number of non-NUL bytes written to \p buffer. If not successful, contains the
* required size of a buffer to receive the filename (not including the NUL terminator).
*/
virtual size_t getFileConfiguration(char* buffer, size_t bufferSize, LogFileConfiguration* config) = 0;
/**
* Pauses file logging (and closes the file) until resumeFileLogging() is called.
*
* @note This is a counted call. Each call to pauseFileLogging() must have a matching call to resumeFileLogging()
*
*/
virtual void pauseFileLogging() = 0;
/**
* Resumes file logging (potentially reopening the file)
*
* @note This is a counted call. Each call to pauseFileLogging() must have a matching call to resumeFileLogging()
*
*/
virtual void resumeFileLogging() = 0;
/**
* Forces the logger to use ANSI escape code's to annotate the log with color.
*
* By default, on Windows ANSI escape codes will never be used, rather the Console API will be used to place
* colors in a console. Linux uses the isatty() to determine if the terminal supports ANSI escape codes. However,
* the isatty check doesn't work in all cases. One notable case where this doesn't work is running a process in a
* CI/CD that returns false from isatty() yet still supports ANSI escape codes.
*
* See: https://en.wikipedia.org/wiki/ANSI_escape_code for more information about ANSI escape codes.
*
* @param forceAnsiColor if true forces terminal to use ANSI escape codes for color
*/
virtual void setForceAnsiColor(bool forceAnsiColor) = 0;
/**
* Overrides the current log level, for the given stream, only for the calling thread.
*
* Call \ref clearLevelThresholdThreadOverride() to clear the override.
* @param type The \ref OutputType to override.
* @param level The \ref loglevel to use for override.
*/
virtual void setLevelThresholdThreadOverride(OutputType type, int32_t level) = 0;
/**
* Clears any override for the given stream, only for the calling thread.
*
* The override was previously set with \ref setLevelThresholdThreadOverride().
* @param type The \ref OutputType to override.
*/
virtual void clearLevelThresholdThreadOverride(OutputType type) = 0;
// Functions may be added to this class as long as it is not inherited from (as an interface) and ILogging's minor
// version is incremented.
};
} // namespace logging
} // namespace carb
| 14,293 | C | 44.814102 | 120 | 0.676205 |
omniverse-code/kit/include/carb/logging/StandardLogger.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief carb.logging StandardLogger definitions
#pragma once
#include "Logger.h"
#include "StandardLogger2.h"
namespace carb
{
namespace logging
{
/**
* The default logger provided by the Framework. It is quite flexible and you can use multiple
* instances if you want different configurations for different output destinations. It can
* also be safely called from multiple threads.
*
* @see ILogging::getDefaultLogger
* @see ILogging::createStandardLogger
* @see ILogging::destroyStandardLogger
*/
#if CARB_PLATFORM_WINDOWS && !defined(DOXYGEN_BUILD)
struct CARB_DEPRECATED("Use StandardLogger2 instead") StandardLogger : public Logger
#else // Linux is very warning-heavy about [[deprecated]]
struct StandardLogger : public Logger
#endif
{
//! \copydoc StandardLogger2::setFilenameIncluded
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`. May not be
//! `nullptr`.
void(CARB_ABI* setFilenameIncluded)(StandardLogger* instance, bool included);
//! \copydoc StandardLogger2::setLineNumberIncluded
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setLineNumberIncluded)(StandardLogger* instance, bool included);
//! \copydoc StandardLogger2::setFunctionNameIncluded
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setFunctionNameIncluded)(StandardLogger* instance, bool included);
//! \copydoc StandardLogger2::setTimestampIncluded
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setTimestampIncluded)(StandardLogger* instance, bool included);
//! \copydoc StandardLogger2::setThreadIdIncluded
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setThreadIdIncluded)(StandardLogger* instance, bool included);
//! \copydoc StandardLogger2::setSourceIncluded
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setSourceIncluded)(StandardLogger* instance, bool included);
//! \copydoc StandardLogger2::setStandardStreamOutput
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setStandardStreamOutput)(StandardLogger* instance, bool enabled);
//! \copydoc StandardLogger2::setDebugConsoleOutput
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setDebugConsoleOutput)(StandardLogger* instance, bool enabled);
//! \copydoc StandardLogger2::setFileOutput
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setFileOutput)(StandardLogger* instance, const char* filePath);
//! \copydoc StandardLogger2::setFileOuputFlushLevel
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setFileOuputFlushLevel)(StandardLogger* instance, int32_t level);
//! \copydoc StandardLogger2::setFlushStandardStreamOutput
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setFlushStandardStreamOutput)(StandardLogger* instance, bool enabled);
//! \copydoc StandardLogger2::setElapsedTimeUnits
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setElapsedTimeUnits)(StandardLogger* instance, const char* units);
//! \copydoc StandardLogger2::setProcessIdIncluded
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setProcessIdIncluded)(StandardLogger* instance, bool enabled);
//! \copydoc StandardLogger2::setMultiProcessGroupId
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setMultiProcessGroupId)(StandardLogger* instance, int32_t id);
//! \copydoc StandardLogger2::setColorOutputIncluded
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setColorOutputIncluded)(StandardLogger* instance, bool enabled);
//! \copydoc StandardLogger2::setOutputStream
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setOutputStream)(StandardLogger* instance, OutputStream outputStream);
//! \copydoc StandardLogger2::setStandardStreamOutputLevelThreshold
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setStandardStreamOutputLevelThreshold)(StandardLogger* instance, int32_t level);
//! \copydoc StandardLogger2::setDebugConsoleOutputLevelThreshold
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setDebugConsoleOutputLevelThreshold)(StandardLogger* instance, int32_t level);
//! \copydoc StandardLogger2::setFileOutputLevelThreshold
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setFileOutputLevelThreshold)(StandardLogger* instance, int32_t level);
//! \copydoc StandardLogger2::setFileConfiguration
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setFileConfiguration)(StandardLogger* instance,
const char* filePath,
const LogFileConfiguration* config);
//! \copydoc StandardLogger2::getFileConfiguration
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
size_t(CARB_ABI* getFileConfiguration)(StandardLogger* instance,
char* buffer,
size_t bufferSize,
LogFileConfiguration* config);
//! \copydoc StandardLogger2::pauseFileLogging
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* pauseFileLogging)(StandardLogger* instance);
//! \copydoc StandardLogger2::resumeFileLogging
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* resumeFileLogging)(StandardLogger* instance);
//! \copydoc StandardLogger2::setForceAnsiColor
//! \param instance The instance of the StandardLogger interface being used. May not be `nullptr`.
void(CARB_ABI* setForceAnsiColor)(StandardLogger* instance, bool forceAnsiColor);
// NOTE: This interface, because it is inherited from, is CLOSED and may not have any additional functions added
// without an ILogging major version increase. See StandardLogger2 for adding additional functionality.
};
} // namespace logging
} // namespace carb
| 7,677 | C | 51.951724 | 116 | 0.740003 |
omniverse-code/kit/include/carb/logging/LoggingTypes.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Type definitions for carb.logging
#pragma once
#include "../Defines.h"
namespace carb
{
namespace logging
{
//! Enumerations of output stream types
enum class OutputStream
{
eDefault, //!< Default selection, stdout for \ref kLevelWarn and below, stderr for \ref kLevelError and above.
eStderr, //!< Force all output to stderr.
};
//! Can be used by setFileConfiguration
const char* const kKeepSameFile = (const char*)size_t(-1);
/**
* Describes the configuration for logging to a file for setFileConfiguration
*
* @note Do not rearrange below members as it disrupts @rstref{ABI compatibility <abi-compatibility>}. Add members at
* the bottom.
*/
struct LogFileConfiguration
{
/// Size of the struct used for versioning. Adding members to this struct will change the size and therefore act as
/// a version for the struct.
size_t size{ sizeof(LogFileConfiguration) };
/// Indicates whether opening the file should append to it. If false, file is overwritten.
///
/// @note Setting (boolean): "/log/fileAppend"
/// @note Default = false
bool append{ false };
};
//! StandardLogger2 output types
enum class OutputType
{
eFile, //!< Output to log file.
eDebugConsole, //!< Output to debug console.
eStandardStream, //!< Output to standard stream (i.e. stdout/stderr).
eCount //!< Number of OutputTypes
};
} // namespace logging
} // namespace carb
| 1,870 | C | 29.177419 | 119 | 0.721925 |
omniverse-code/kit/include/carb/logging/Logger.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief carb.logging Logger definition
#pragma once
#include "../Defines.h"
#include <cstdint>
// example-begin Logger
namespace carb
{
//! Namespace for logging interfaces and utilities
namespace logging
{
/**
* Defines an extension interface for logging backends to register with the ILogging system.
*
* @see ILogging::addLogger
* @see ILogging::removeLogger
*/
struct Logger
{
/**
* Handler for a formatted log message.
*
* This function is called by @ref ILogging if the Logger has
* been registered via @ref ILogging::addLogger(), log level passes the threshold (for module or
* globally if not set for module), and logging is enabled (for module or globally if not set
* for module).
*
* @param logger The logger interface - can be nullptr if not used by handleMessage
* @param source The source of the message in UTF8 character encoding - commonly plugin name
* @param level The severity level of the message
* @param filename The file name where the message originated from.
* @param functionName The name of the function where the message originated from.
* @param lineNumber The line number where the message originated from
* @param message The formatted message in UTF8 character encoding
*
* @thread_safety this function will potentially be called simultaneously from multiple threads.
*/
void(CARB_ABI* handleMessage)(Logger* logger,
const char* source,
int32_t level,
const char* filename,
const char* functionName,
int lineNumber,
const char* message);
// NOTE: This interface, because it is inherited from, is CLOSED and may not have any additional functions added
// without an ILogging major version increase.
};
} // namespace logging
} // namespace carb
// example-end
| 2,460 | C | 36.287878 | 116 | 0.672764 |
omniverse-code/kit/include/carb/logging/ILogging.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief carb.logging interface definition
#pragma once
#include "../Interface.h"
#include "../IObject.h"
#include "StandardLogger2.h"
namespace carb
{
namespace logging
{
struct StandardLogger;
class StandardLogger2;
struct Logger;
/**
* Defines a callback type for setting log level for every source.
*/
typedef void(CARB_ABI* SetLogLevelFn)(int32_t logLevel);
/**
* Defines a log setting behavior.
*/
enum class LogSettingBehavior
{
eInherit,
eOverride
};
/**
* Function pointer typedef for a logging function
*
* @note Typically this is not used directly. It exists solely for \ref g_carbLogFn and represents the type of
* \ref carb::logging::ILogging::log().
* @param source The log source (typically client or plugin)
* @param level The log level, such as \ref kLevelInfo
* @param fileName The name of the source file that generated the log message (typically from `__FILE__`)
* @param functionName The name of the source function that generated the log message (such as via
* \ref CARB_PRETTY_FUNCTION)
* @param lineNumber The line number of \p filename that generated the log message (typically from `__LINE__`)
* @param fmt A printf format string
* @param ... varargs for \p fmt
*/
typedef void (*LogFn)(const char* source,
int32_t level,
const char* fileName,
const char* functionName,
int lineNumber,
const char* fmt,
...);
/**
* Defines the log system that is associated with the Framework.
*
* This interface defines the log system, which is a singleton object. It can be used at any moment, including
* before the startup of the Framework and after the Framework was shutdown. It allows a user to setup the logging
* behavior in advance and allows the Framework to log during its initialization.
*
* Logger - is an interface for logging backend. ILogging can contain multiple Loggers and every message will be passed
* to every logger. There is one implementation of a Logger provided - StandardLogger. It can log into file, console and
* debug window. ILogging starts up with one instance of \ref StandardLogger2, which can be retrieved by calling
* getDefaultLogger(). It is added by default, but can be removed with
* `getLogging()->removeLogger(getLogging()->getDefaultLogger()->getLogger())`.
*
* ILogging supports multiple sources of log messages. Source is just a name to differentiate the origins of a message.
* Every plugin, application and Framework itself are different sources. However user can add more custom sources if
* needed.
*
* Use the logging macros from Log.h for all logging in applications and plugins.
*
* There are 2 log settings: log level (to control log severity threshold) and log enabled (to toggle whole logging).
* Both of them can be set globally and per source.
*/
struct ILogging
{
CARB_PLUGIN_INTERFACE("carb::logging::ILogging", 1, 1)
/**
* Logs a formatted message to the specified log source and log level.
*
* This API is used primarily by the CARB_LOG_XXXX macros.
*
* @param source The log source to log the message to.
* @param level The level to log the message at.
* @param fileName The file name to log to.
* @param functionName The name of the function where the message originated from.
* @param lineNumber The line number
* @param fmt The print formatted message.
* @param ... The variable arguments for the formatted message variables.
*/
void(CARB_ABI* log)(const char* source,
int32_t level,
const char* fileName,
const char* functionName,
int lineNumber,
const char* fmt,
...) CARB_PRINTF_FUNCTION(6, 7);
/**
* Sets global log level threshold. Messages below this threshold will be dropped.
*
* @param level The log level to set.
*/
void(CARB_ABI* setLevelThreshold)(int32_t level);
/**
* Gets global log level threshold. Messages below this threshold will be dropped.
*
* @return Global log level.
*/
int32_t(CARB_ABI* getLevelThreshold)();
/**
* Sets global log enabled setting.
*
* @param enabled Global log enabled setting.
*/
void(CARB_ABI* setLogEnabled)(bool enabled);
/**
* If global log is enabled.
*
* @return Global log enabled.
*/
bool(CARB_ABI* isLogEnabled)();
/**
* Sets log level threshold for the specified source. Messages below this threshold will be dropped.
* Per source log settings can either inherit global or override it, it is configured with
* LogSettingBehavior::eInherit and LogSettingBehavior::eOverride accordingly.
*
* @param source The source to set log level setting for. Must not be nullptr.
* @param behavior The log setting behavior for the source.
* @param level The log level to set. This param is ignored if behavior is set to LogSettingBehavior::eInherit.
*/
void(CARB_ABI* setLevelThresholdForSource)(const char* source, LogSettingBehavior behavior, int32_t level);
/**
* Sets log enabled setting for the specified source.
* Per source log settings can either inherit global or override it, it is configured with
* LogSettingBehavior::eInherit and LogSettingBehavior::eOverride accordingly.
*
* @param source The source to set log enabled setting for. Must not be nullptr.
* @param behavior The log setting behavior for the source.
* @param enabled The log enabled setting. This param is ignored if behavior is set to LogSettingBehavior::eInherit.
*/
void(CARB_ABI* setLogEnabledForSource)(const char* source, LogSettingBehavior behavior, bool enabled);
/**
* Reset all log settings set both globally and per source.
* Log system resets to the defaults: log is enabled and log level is 'warn'.
*/
void(CARB_ABI* reset)();
/**
* Adds a logger to the ILogging.
* @see StandardLogger2::getLogger()
* @param logger The logger to be added.
*/
void(CARB_ABI* addLogger)(Logger* logger);
/**
* Removes the logger from the ILogging.
* @see StandardLogger2::getLogger()
* @param logger The logger to be removed.
*/
void(CARB_ABI* removeLogger)(Logger* logger);
/**
* Accesses the default logger.
*
* This logger can be disabled by passing it to \ref removeLogger(). This logger is owned by the logging system and
* cannot be destroyed by passing it to \ref destroyStandardLoggerOld().
*
* @rst
* .. deprecated:: 156.0
* Use getDefaultLogger() instead
* @endrst
*
* @returns the default logger.
*/
CARB_DEPRECATED("Use getDefaultLogger() instead") StandardLogger*(CARB_ABI* getDefaultLoggerOld)();
/**
* Creates a new \ref StandardLogger instance.
*
* Use this method to create additional \ref StandardLogger instances. This can be useful when you want to log
* to multiple output destinations but want different configuration for each. Use \ref addLogger() to make it
* active. When finished with the \ref StandardLogger pass it to \ref destroyStandardLoggerOld().
*
* @rst
* .. deprecated:: 156.0
* Use createStandardLogger() instead
* @endrst
*
* @returns A new \ref StandardLogger.
*/
CARB_DEPRECATED("Use createStandardLogger() instead") StandardLogger*(CARB_ABI* createStandardLoggerOld)();
/**
* Use this method to destroy a \ref StandardLogger that was created via \ref createStandardLogger().
*
* @rst
* .. deprecated:: 156.0
* The ``StandardLogger2`` that replaces ``StandardLogger`` can be destroyed by calling ``release()``.
* @endrst
*
* @param logger The logger to be destroyed.
*/
CARB_DEPRECATED("Use StandardLogger2::release() instead")
void(CARB_ABI* destroyStandardLoggerOld)(StandardLogger* logger);
/**
* Register new logging source.
* This function is mainly automatically used by plugins, application and the Framework itself to create
* their own logging sources.
*
* Custom logging source can also be created if needed. It is the user's responsibility to call
* ILogging::unregisterSource in that case.
*
* It is the source responsibility to track its log level. The reason is that it allows to filter out
* logging before calling into the logging system, thus making the performance cost for the disabled logging
* negligible. It is done by providing a callback `setLevelThreshold` to be called by ILogging when any setting
* which influences this source is changed.
*
* @param source The source name. Must not be nullptr.
* @param setLevelThreshold The callback to be called to update log level. ILogging::unregisterSource must be called
* when the callback is no longer valid.
*/
void(CARB_ABI* registerSource)(const char* source, SetLogLevelFn setLevelThreshold);
/**
* Unregister logging source.
*
* @param source The source name. Must not be nullptr.
*/
void(CARB_ABI* unregisterSource)(const char* source);
/**
* Instructs the logging system to deliver all log messages to the Logger backends asynchronously. Async logging is
* OFF by default.
*
* This causes log() calls to be buffered so that log() may return as quickly as possible. A background thread then
* issues these buffered log messages to the registered Logger backend objects.
*
* @param logAsync True to use async logging; false to disable async logging.
* @return true if was previously using async logging; false if was previously using synchronous logging.
*/
bool(CARB_ABI* setLogAsync)(bool logAsync);
/**
* Returns whether the ILogging system is using async logging.
* @return true if currently using async logging; false if currently using synchronous logging
*/
bool(CARB_ABI* getLogAsync)();
/**
* When ILogging is in async mode, wait until all log messages have flushed out to the various loggers.
*/
void(CARB_ABI* flushLogs)();
/**
* Retrieves the extended StandardLogger2 interface from an old \ref StandardLogger instance.
* @param logger The logger to retrieve the instance from. If `nullptr` then `nullptr` will be returned.
* @returns The \ref StandardLogger2 interface for \p logger, or `nullptr`.
*/
StandardLogger2*(CARB_ABI* getStandardLogger2)(StandardLogger* logger);
/**
* Accesses the default logger.
*
* This logger can be disabled by passing the underlying logger (from \ref StandardLogger2::getLogger()) to
* \ref removeLogger(). This logger is owned by the logging system and calling \ref StandardLogger2::release() has
* no effect.
*
* @returns the default \ref StandardLogger2.
*/
StandardLogger2*(CARB_ABI* getDefaultLogger)();
//! @private
StandardLogger2*(CARB_ABI* createStandardLoggerInternal)();
/**
* Creates a new \ref StandardLogger2 instance.
*
* Use this method to create additional \ref StandardLogger2 instances. This can be useful when you want to log
* to multiple output destinations but want different configuration for each. Pass the value from
* \ref StandardLogger2::getLogger() to \ref addLogger() to make it active. When finished with the
* \ref StandardLogger2 call \ref StandardLogger2::release().
*
* @returns A new \ref StandardLogger2.
*/
ObjectPtr<StandardLogger2> createStandardLogger()
{
using Ptr = ObjectPtr<StandardLogger2>;
return Ptr(createStandardLoggerInternal(), Ptr::InitPolicy::eSteal);
}
};
} // namespace logging
} // namespace carb
| 12,452 | C | 38.659236 | 120 | 0.682059 |
omniverse-code/kit/include/carb/logging/LoggingUtils.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Utilities for carb.logging
#pragma once
#include "Log.h"
#if CARB_ASSERT_ENABLED
# include "../thread/Util.h"
#endif
namespace carb
{
namespace logging
{
/**
* A class that pauses logging to a file when constructed and resumes logging to a file when destroyed.
*/
class ScopedFilePause
{
public:
/**
* RAII Constructor.
*
* @param inst The StandardLogger to pause file logging for.
*/
CARB_DEPRECATED("Use StandardLogger2 instead")
ScopedFilePause(StandardLogger* inst) : ScopedFilePause(g_carbLogging->getStandardLogger2(inst))
{
}
/**
* RAII Constructor.
*
* @param inst The \ref StandardLogger2 to pause file logging for.
*/
ScopedFilePause(StandardLogger2* inst) : m_inst(inst)
{
if (m_inst)
{
m_inst->addRef();
m_inst->pauseFileLogging();
}
}
/**
* RAII Destructor.
*
* Restarts file logging on the StandardLogger that was given to the constructor.
*/
~ScopedFilePause()
{
if (m_inst)
{
m_inst->resumeFileLogging();
m_inst->release();
}
}
CARB_PREVENT_COPY_AND_MOVE(ScopedFilePause);
private:
StandardLogger2* m_inst;
};
/**
* A RAII object for overriding a thread's log level for a given type in \ref StandardLogger while in scope.
*
* When this object is constructed, \ref StandardLogger2::setLevelThresholdThreadOverride() is called as long as the
* given logger object is not `nullptr`. Upon destruction, \ref StandardLogger2::clearLevelThresholdThreadOverride() is
* called.
*/
class ScopedLevelThreadOverride
{
public:
/**
* Converting constructor for StandardLogger.
* @warning It is not recommended to use this from within a \a carb.tasking task across context switches.
* @param logger The \ref StandardLogger instance to override. If `nullptr` no action is taken.
* @param type The \ref OutputType to override.
* @param level The overriding \ref loglevel.
*/
CARB_DEPRECATED("Use StandardLogger2 instead")
ScopedLevelThreadOverride(StandardLogger* logger, OutputType type, int32_t level)
: ScopedLevelThreadOverride(g_carbLogging->getStandardLogger2(logger), type, level)
{
}
/**
* Constructor for overriding a log level for the calling thread.
* @warning It is not recommended to use this from within a \a carb.tasking task across context switches.
* @param logger The \ref StandardLogger2 instance to override. If `nullptr` no action is taken.
* @param type The \ref OutputType to override.
* @param level The overriding \ref loglevel.
*/
ScopedLevelThreadOverride(StandardLogger2* logger, OutputType type, int32_t level)
: m_logger(logger),
m_type(type)
#if CARB_ASSERT_ENABLED
,
m_threadId(carb::this_thread::getId())
#endif
{
if (m_logger)
{
m_logger->addRef();
m_logger->setLevelThresholdThreadOverride(m_type, level);
}
}
/**
* Destructor which clears the override for the current thread.
*/
~ScopedLevelThreadOverride()
{
// Make sure we are on the same thread
CARB_ASSERT(m_threadId == carb::this_thread::getId());
if (m_logger)
{
m_logger->clearLevelThresholdThreadOverride(m_type);
m_logger->release();
}
}
CARB_PREVENT_COPY_AND_MOVE(ScopedLevelThreadOverride);
private:
StandardLogger2* m_logger;
OutputType m_type;
#if CARB_ASSERT_ENABLED
thread::ThreadId m_threadId;
#endif
};
} // namespace logging
} // namespace carb
| 4,142 | C | 27.376712 | 119 | 0.660792 |
omniverse-code/kit/include/carb/logging/Log.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief carb.logging utilities
#pragma once
#include "../Framework.h"
#include "ILogging.h"
#include "../../omni/log/ILog.h"
#include <cctype>
#include <cstdint>
#include <cstdio>
// example-begin Log levels
namespace carb
{
namespace logging
{
//! \defgroup loglevel Log Levels
//! @{
/**
* Verbose level, this is for detailed diagnostics messages. Expect to see some verbose messages on every frame under
* certain conditions.
*/
const int32_t kLevelVerbose = -2;
/**
* Info level, this is for informational messages. They are usually triggered on state changes and typically we should
* not see the same message on every frame.
*/
const int32_t kLevelInfo = -1;
/**
* Warning level, this is for warning messages. Something could be wrong but not necessarily an error. Therefore
* anything that could be a problem but cannot be determined to be an error should fall into this category. This is the
* default log level threshold, if nothing else was specified via configuration or startup arguments. This is also the
* reason why it has a value of 0 (default as zero).
*/
const int32_t kLevelWarn = 0;
/**
* Error level, this is for error messages. An error has occurred but the program can continue.
*/
const int32_t kLevelError = 1;
/**
* Fatal level, this is for messages on unrecoverable errors. An error has occurred and the program cannot continue.
* After logging such a message the caller should take immediate action to exit the program or unload the module.
*/
const int32_t kLevelFatal = 2;
//! @}
} // namespace logging
} // namespace carb
// example-end
//! A global weak variable representing the current log level.
//! @note This variable is registered by \ref carb::logging::registerLoggingForClient() and is updated whenever the
//! logging level changes.
//! @warning If \ref carb::logging::deregisterLoggingForClient() is not called before a module is unloaded, changing the
//! log level can result in a crash since \ref carb::logging::ILogging retains a pointer to this variable.
CARB_WEAKLINK int32_t g_carbLogLevel = carb::logging::kLevelWarn;
//! A global weak variable cache of the logging function.
//!
//! This variable is initialized by \ref carb::logging::registerLoggingForClient() and stores a pointer to
//! \ref carb::logging::ILogging::log() for performance, so that the interface does not have to constantly be acquired
//! (even via \ref carb::getCachedInterface()).
CARB_WEAKLINK carb::logging::LogFn g_carbLogFn CARB_PRINTF_FUNCTION(6, 7);
//! A global weak variable cache of the logging interface.
//!
//! This variable is initialized by \ref carb::logging::registerLoggingForClient(). As \ref carb::logging::ILogging is a
//! built-in interface from the Carbonite Framework, this variable can be safely cached without
//! \ref carb::getCachedInterface().
CARB_WEAKLINK carb::logging::ILogging* g_carbLogging;
#if CARB_COMPILER_GNUC || defined(DOXYGEN_BUILD)
/**
* A printf that will never be executed but allows the compiler to test if there are format errors.
*
* This is a no-op on GCC and Clang because they support `__attribute__((format))`.
* @param fmt The printf format specifier
* @param ... Optional arguments
*/
# define CARB_FAKE_PRINTF(fmt, ...) \
do \
{ \
} while (0)
#else
# define CARB_FAKE_PRINTF(fmt, ...) \
do \
{ \
if (false) \
::printf(fmt, ##__VA_ARGS__); \
} while (0)
#endif
//! \defgroup logmacros Logging Macros
//! @{
//! Logging macro if the level is dynamic.
//!
//! Prefer using @ref CARB_LOG_VERBOSE, @ref CARB_LOG_INFO, etc. if the level is static.
//! @param level The \ref loglevel
//! @param fmt The printf format specifier string
//! @param ... Optional arguments
#define CARB_LOG(level, fmt, ...) \
do \
{ \
auto lvl = (level); \
if (g_carbLogFn && g_carbLogLevel <= lvl) \
{ \
CARB_FAKE_PRINTF(fmt, ##__VA_ARGS__); \
g_carbLogFn(g_carbClientName, lvl, __FILE__, __func__, __LINE__, fmt, ##__VA_ARGS__); \
} \
} while (0)
//! Logging macro for static log level.
//! @param fmt The printf format specifier string
//! @param ... Optional arguments
#define CARB_LOG_VERBOSE(fmt, ...) CARB_LOG(carb::logging::kLevelVerbose, fmt, ##__VA_ARGS__)
//! @copydoc CARB_LOG_VERBOSE
#define CARB_LOG_INFO(fmt, ...) CARB_LOG(carb::logging::kLevelInfo, fmt, ##__VA_ARGS__)
//! @copydoc CARB_LOG_VERBOSE
#define CARB_LOG_WARN(fmt, ...) CARB_LOG(carb::logging::kLevelWarn, fmt, ##__VA_ARGS__)
//! @copydoc CARB_LOG_VERBOSE
#define CARB_LOG_ERROR(fmt, ...) CARB_LOG(carb::logging::kLevelError, fmt, ##__VA_ARGS__)
//! @copydoc CARB_LOG_VERBOSE
#define CARB_LOG_FATAL(fmt, ...) CARB_LOG(carb::logging::kLevelFatal, fmt, ##__VA_ARGS__)
//! Single-time logging macro if the level is dynamic.
//!
//! Prefer using @ref CARB_LOG_VERBOSE_ONCE, @ref CARB_LOG_INFO_ONCE, etc. if the level is static.
//! @note This logs a single time by using `static` initialization.
//! @param level The \ref loglevel
//! @param fmt The print format specifier string
//! @param ... Optional arguments
#define CARB_LOG_ONCE(level, fmt, ...) \
do \
{ \
static bool CARB_JOIN(logged_, __LINE__) = \
(g_carbLogFn && g_carbLogLevel <= (level)) ? \
(false ? \
(::printf(fmt, ##__VA_ARGS__), true) : \
(g_carbLogFn(g_carbClientName, (level), __FILE__, __func__, __LINE__, fmt, ##__VA_ARGS__), true)) : \
false; \
CARB_UNUSED(CARB_JOIN(logged_, __LINE__)); \
} while (0)
//! Single-time logging macro for static log level.
//! @note This logs a single time by using `static` initialization.
//! @param fmt The print format specifier string
//! @param ... Optional arguments
#define CARB_LOG_VERBOSE_ONCE(fmt, ...) CARB_LOG_ONCE(carb::logging::kLevelVerbose, fmt, ##__VA_ARGS__)
//! @copydoc CARB_LOG_VERBOSE_ONCE
#define CARB_LOG_INFO_ONCE(fmt, ...) CARB_LOG_ONCE(carb::logging::kLevelInfo, fmt, ##__VA_ARGS__)
//! @copydoc CARB_LOG_VERBOSE_ONCE
#define CARB_LOG_WARN_ONCE(fmt, ...) CARB_LOG_ONCE(carb::logging::kLevelWarn, fmt, ##__VA_ARGS__)
//! @copydoc CARB_LOG_VERBOSE_ONCE
#define CARB_LOG_ERROR_ONCE(fmt, ...) CARB_LOG_ONCE(carb::logging::kLevelError, fmt, ##__VA_ARGS__)
//! @copydoc CARB_LOG_VERBOSE_ONCE
#define CARB_LOG_FATAL_ONCE(fmt, ...) CARB_LOG_ONCE(carb::logging::kLevelFatal, fmt, ##__VA_ARGS__)
//! @}
//! Placeholder macro for any globals that must be declared for the logging system.
//! @note This is typically not used as it is included in the @ref CARB_GLOBALS_EX macro.
#define CARB_LOG_GLOBALS()
namespace carb
{
namespace logging
{
//! Accessor for logging interface.
//! @returns \ref ILogging interface as read from \ref g_carbLogging
inline ILogging* getLogging()
{
return g_carbLogging;
}
//! Acquires the default ILogging interface and registers log channels.
//!
//! This acquires the \ref ILogging interface and assigns it to a special \ref g_carbLogging variable. The
//! \ref g_carbLogLevel variable is registered with \ref ILogging so that it is kept up to date when log level changes.
//! The \ref g_carbLogFn variable is also initialized. Finally \ref omni::log::addModulesChannels() is called to
//! register log channels.
//! @note It is typically not necessary to call this function. It is automatically called for plugins by
//! \ref carb::pluginInitialize() (in turn called by \ref CARB_PLUGIN_IMPL). For script bindings it is called by
//! \ref carb::acquireFrameworkForBindings(). For applications it is called by
//! \ref carb::acquireFrameworkAndRegisterBuiltins() (typically called by \ref OMNI_CORE_INIT).
//! @see deregisterLoggingForClient()
inline void registerLoggingForClient() noexcept
{
g_carbLogging = getFramework()->tryAcquireInterface<ILogging>();
if (g_carbLogging)
{
g_carbLogging->registerSource(g_carbClientName, [](int32_t logLevel) { g_carbLogLevel = logLevel; });
g_carbLogFn = g_carbLogging->log;
}
omni::log::addModulesChannels();
}
//! Unregisters the log channels and the logger interface.
//!
//! @note It is typically not necessary to call this function as it is automatically called in similar situations to
//! those described in @ref registerLoggingForClient().
inline void deregisterLoggingForClient() noexcept
{
omni::log::removeModulesChannels();
if (g_carbLogging)
{
g_carbLogFn = nullptr;
if (getFramework() && getFramework()->verifyInterface<ILogging>(g_carbLogging))
{
g_carbLogging->unregisterSource(g_carbClientName);
}
g_carbLogging = nullptr;
}
}
//! A struct that describes level name to integer value
struct StringToLogLevelMapping
{
const char* name; //!< Log level name
int32_t level; //!< Log level integer value (see \ref loglevel)
};
//! A mapping of log level names to integer value
//! @see loglevel
const StringToLogLevelMapping kStringToLevelMappings[] = { { "verbose", kLevelVerbose },
{ "info", kLevelInfo },
{ "warning", kLevelWarn },
{ "error", kLevelError },
{ "fatal", kLevelFatal } };
//! The number of items in \ref kStringToLevelMappings.
const size_t kStringToLevelMappingsCount = CARB_COUNTOF(kStringToLevelMappings);
/**
* Convert a given string to a log level.
*
* Compares the given \p levelString against \ref kStringToLevelMappings to find a match. Only the first character is
* checked in a case insensitive manner.
* @param levelString A string representing the name of a log level. `nullptr` is interpreted as \ref kLevelFatal. Only
* the first character of the string is checked in a case insensitive manner.
* @returns The integer \ref loglevel determined from \p levelString. If a level could not be determined,
* \ref kLevelFatal is returned after an error log is issued.
*/
inline int32_t stringToLevel(const char* levelString)
{
const int32_t kFallbackLevel = kLevelFatal;
if (!levelString)
return kFallbackLevel;
// Since our log level identifiers start with different characters, we're allowed to just compare the first one.
// However, whether the need arises, it is worth making a score-based system, where full match will win over
// partial match, if there are similarly starting log levels.
int lcLevelChar = tolower((int)levelString[0]);
for (size_t lm = 0; lm < kStringToLevelMappingsCount; ++lm)
{
int lcMappingChar = tolower((int)kStringToLevelMappings[lm].name[0]);
if (lcLevelChar == lcMappingChar)
return kStringToLevelMappings[lm].level;
}
// Ideally, this should never happen if level string is valid.
CARB_ASSERT(false);
CARB_LOG_ERROR("Unknown log level string: %s", levelString);
return kFallbackLevel;
}
} // namespace logging
} // namespace carb
| 13,867 | C | 48.003533 | 122 | 0.565155 |
omniverse-code/kit/include/carb/simplegui/ISimpleGui.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief *carb.simplegui* interface definition file.
#pragma once
#include "SimpleGuiTypes.h"
#include "../Interface.h"
namespace carb
{
//! Namespace for *carb.simplegui* plugin.
namespace simplegui
{
/**
* Defines the simplegui interface.
*
* Based on: ImGui 1.70
*/
struct ISimpleGui
{
CARB_PLUGIN_INTERFACE("carb::simplegui::ISimpleGui", 1, 2)
/**
* Creates a new immediate mode GUI context.
*
* @param desc Context descriptor.
* @return The context used for the current state of the GUI.
*/
Context*(CARB_ABI* createContext)(const ContextDesc& desc);
/**
* Destroys an immediate mode GUI context.
*
* @param ctx The context to be destroyed.
*/
void(CARB_ABI* destroyContext)(Context* ctx);
/**
* Sets the current immediate mode GUI context to be used.
*/
void(CARB_ABI* setCurrentContext)(Context* ctx);
/**
* Gets the current immediate mode GUI context that is used.
* @return returns current immediate GUI mode context.
*/
Context*(CARB_ABI* getCurrentContext)();
/**
* Start rendering a new immediate mode GUI frame.
*/
void(CARB_ABI* newFrame)();
/**
* Render the immediate mode GUI frame.
*
* @param elapsedTime The amount of elapsed time since the last render() call.
*/
void(CARB_ABI* render)(float elapsedTime);
/**
* Sets the display size.
*
* @param size The display size to be set.
*/
void(CARB_ABI* setDisplaySize)(Float2 size);
/**
* Gets the display size.
*
* @return The display size.
*/
Float2(CARB_ABI* getDisplaySize)();
/**
* Gets the style struct.
*
* @return The style struct.
*/
Style*(CARB_ABI* getStyle)();
/**
* Shows a demo window of all features supported.
*
* @param open Is window opened, can be changed after the call.
*/
void(CARB_ABI* showDemoWindow)(bool* open);
/**
* Create metrics window.
*
* Display simplegui internals: draw commands (with individual draw calls and vertices), window list, basic internal
* state, etc.
*
* @param open Is window opened, can be changed after the call.
*/
void(CARB_ABI* showMetricsWindow)(bool* open);
/**
* Add style editor block (not a window).
*
* You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default
* style)
*
* @param style Style to edit. Pass nullptr to edit the default one.
*/
void(CARB_ABI* showStyleEditor)(Style* style);
/**
* Add style selector block (not a window).
*
* Essentially a combo listing the default styles.
*
* @param label Label.
*/
bool(CARB_ABI* showStyleSelector)(const char* label);
/**
* Add font selector block (not a window).
*
* Essentially a combo listing the loaded fonts.
*
* @param label Label.
*/
void(CARB_ABI* showFontSelector)(const char* label);
/**
* Add basic help/info block (not a window): how to manipulate simplegui as a end-user (mouse/keyboard controls).
*/
void(CARB_ABI* showUserGuide)();
/**
* Get underlying ImGui library version string.
*
* @return The version string e.g. "1.70".
*/
const char*(CARB_ABI* getImGuiVersion)();
/**
* Set style colors from one of the predefined presets:
*
* @param style Style to change. Pass nullptr to change the default one.
* @param preset Colors preset.
*/
void(CARB_ABI* setStyleColors)(Style* style, StyleColorsPreset preset);
/**
* Begins defining a new immediate mode GUI (window).
*
* @param label The window label.
* @param open Returns if the window was active.
* @param windowFlags The window flags to be used.
* @return return false to indicate the window is collapsed or fully clipped,
* so you may early out and omit submitting anything to the window.
*/
bool(CARB_ABI* begin)(const char* label, bool* open, WindowFlags flags);
/**
* Ends defining a immediate mode.
*/
void(CARB_ABI* end)();
/**
* Begins a scrolling child region.
*
* @param strId The string identifier for the child region.
* @param size The size of the region.
* size==0.0f: use remaining window size, size<0.0f: use remaining window.
* @param border Draw border.
* @param flags Sets any WindowFlags for the dialog.
* @return true if the region change, false if not.
*/
bool(CARB_ABI* beginChild)(const char* strId, Float2 size, bool border, WindowFlags flags);
/**
* Begins a scrolling child region.
*
* @param id The identifier for the child region.
* @param size The size of the region.
* size==0.0f: use remaining window size, size<0.0f: use remaining window.
* @param border Draw border.
* @param flags Sets any WindowFlags for the dialog.
* @return true if the region change, false if not.
*/
bool(CARB_ABI* beginChildId)(uint32_t id, Float2 size, bool border, WindowFlags flags);
/**
* Ends a child region.
*/
void(CARB_ABI* endChild)();
/**
* Is window appearing?
*
* @return true if window is appearing, false if not.
*/
bool(CARB_ABI* isWindowAppearing)();
/**
* Is window collapsed?
*
* @return true if window is collapsed, false is not.
*/
bool(CARB_ABI* isWindowCollapsed)();
/**
* Is current window focused? or its root/child, depending on flags. see flags for options.
*
* @param flags The focused flags to use.
* @return true if window is focused, false if not.
*/
bool(CARB_ABI* isWindowFocused)(FocusedFlags flags);
/**
* Is current window hovered (and typically: not blocked by a popup/modal)? see flags for options.
*
* If you are trying to check whether your mouse should be dispatched to simplegui or to your app, you should use
* the 'io.WantCaptureMouse' boolean for that! Please read the FAQ!
*
* @param flags The hovered flags to use.
* @return true if window is currently hovered over, false if not.
*/
bool(CARB_ABI* isWindowHovered)(HoveredFlags flags);
/**
* Get the draw list associated to the window, to append your own drawing primitives.
*
* @return The draw list associated to the window, to append your own drawing primitives.
*/
DrawList*(CARB_ABI* getWindowDrawList)();
/**
* Gets the DPI scale currently associated to the current window's viewport.
*
* @return The DPI scale currently associated to the current window's viewport.
*/
float(CARB_ABI* getWindowDpiScale)();
/**
* Get current window position in screen space
*
* This is useful if you want to do your own drawing via the DrawList API.
*
* @return The current window position in screen space.
*/
Float2(CARB_ABI* getWindowPos)();
/**
* Gets the current window size.
*
* @return The current window size
*/
Float2(CARB_ABI* getWindowSize)();
/**
* Gets the current window width.
*
* @return The current window width.
*/
float(CARB_ABI* getWindowWidth)();
/**
* Gets the current window height.
*
* @return The current window height.
*/
float(CARB_ABI* getWindowHeight)();
/**
* Gets the current content boundaries.
*
* This is typically window boundaries including scrolling,
* or current column boundaries, in windows coordinates.
*
* @return The current content boundaries.
*/
Float2(CARB_ABI* getContentRegionMax)();
/**
* Gets the current content region available.
*
* This is: getContentRegionMax() - getCursorPos()
*
* @return The current content region available.
*/
Float2(CARB_ABI* getContentRegionAvail)();
/**
* Gets the width of the current content region available.
*
* @return The width of the current content region available.
*/
float(CARB_ABI* ContentRegionAvailWidth)();
/**
* Content boundaries min (roughly (0,0)-Scroll), in window coordinates
*/
Float2(CARB_ABI* getWindowContentRegionMin)();
/**
* Gets the maximum content boundaries.
*
* This is roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(),
* in window coordinates.
*
* @return The maximum content boundaries.
*/
Float2(CARB_ABI* getWindowContentRegionMax)();
/**
* Content region width.
*/
float(CARB_ABI* getWindowContentRegionWidth)();
/**
* Sets the next window position.
*
* Call before begin(). use pivot=(0.5f,0.5f) to center on given point, etc.
*
* @param position The position to set.
* @param pivot The offset pivot.
*/
void(CARB_ABI* setNextWindowPos)(Float2 position, Condition cond, Float2 pivot);
/**
* Set next window size.
*
* Set axis to 0.0f to force an auto-fit on this axis. call before begin()
*
* @param size The next window size.
*/
void(CARB_ABI* setNextWindowSize)(Float2 size, Condition cond);
/**
* Set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply
* non-trivial programmatic constraints.
*/
void(CARB_ABI* setNextWindowSizeConstraints)(const Float2& sizeMin, const Float2& sizeMax);
/**
* Set next window content size (~ enforce the range of scrollbars). not including window decorations (title bar,
* menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin()
*/
void(CARB_ABI* setNextWindowContentSize)(const Float2& size);
/**
* Set next window collapsed state. call before Begin()
*/
void(CARB_ABI* setNextWindowCollapsed)(bool collapsed, Condition cond);
/**
* Set next window to be focused / front-most. call before Begin()
*/
void(CARB_ABI* setNextWindowFocus)();
/**
* Set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg.
*/
void(CARB_ABI* setNextWindowBgAlpha)(float alpha);
/**
* Set font scale. Adjust IO.FontGlobalScale if you want to scale all windows
*/
void(CARB_ABI* setWindowFontScale)(float scale);
/**
* Set named window position.
*/
void(CARB_ABI* setWindowPos)(const char* name, const Float2& pos, Condition cond);
/**
* Set named window size. set axis to 0.0f to force an auto-fit on this axis.
*/
void(CARB_ABI* setWindowSize)(const char* name, const Float2& size, Condition cond);
/**
* Set named window collapsed state
*/
void(CARB_ABI* setWindowCollapsed)(const char* name, bool collapsed, Condition cond);
/**
* Set named window to be focused / front-most. use NULL to remove focus.
*/
void(CARB_ABI* setWindowFocus)(const char* name);
/**
* Get scrolling amount [0..GetScrollMaxX()]
*/
float(CARB_ABI* getScrollX)();
/**
* Get scrolling amount [0..GetScrollMaxY()]
*/
float(CARB_ABI* getScrollY)();
/**
* Get maximum scrolling amount ~~ ContentSize.X - WindowSize.X
*/
float(CARB_ABI* getScrollMaxX)();
/**
* Get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y
*/
float(CARB_ABI* getScrollMaxY)();
/**
* Set scrolling amount [0..GetScrollMaxX()]
*/
void(CARB_ABI* setScrollX)(float scrollX);
/**
* Set scrolling amount [0..GetScrollMaxY()]
*/
void(CARB_ABI* setScrollY)(float scrollY);
/**
* Adjust scrolling amount to make current cursor position visible.
*
* @param centerYRatio Center y ratio: 0.0: top, 0.5: center, 1.0: bottom.
*/
void(CARB_ABI* setScrollHereY)(float centerYRatio);
/**
* Adjust scrolling amount to make given position valid. use getCursorPos() or getCursorStartPos()+offset to get
* valid positions. default: centerYRatio = 0.5f
*/
void(CARB_ABI* setScrollFromPosY)(float posY, float centerYRatio);
/**
* Use NULL as a shortcut to push default font
*/
void(CARB_ABI* pushFont)(Font* font);
/**
* Pop font from the stack
*/
void(CARB_ABI* popFont)();
/**
* Pushes and applies a style color for the current widget.
*
* @param styleColorIndex The style color index.
* @param color The color to be applied for the style color being pushed.
*/
void(CARB_ABI* pushStyleColor)(StyleColor styleColorIndex, Float4 color);
/**
* Pops off and stops applying the style color for the current widget.
*/
void(CARB_ABI* popStyleColor)();
/**
* Pushes a style variable(property) with a float value.
*
* @param styleVarIndex The style variable(property) index.
* @param value The value to be applied.
*/
void(CARB_ABI* pushStyleVarFloat)(StyleVar styleVarIndex, float value);
/**
* Pushes a style variable(property) with a Float2 value.
*
* @param styleVarIndex The style variable(property) index.
* @param value The value to be applied.
*/
void(CARB_ABI* pushStyleVarFloat2)(StyleVar styleVarIndex, Float2 value);
/**
* Pops off and stops applying the style variable(property) for the current widget.
*/
void(CARB_ABI* popStyleVar)();
/**
* Retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use
* GetColorU32() to get style color with style alpha baked in.
*/
const Float4&(CARB_ABI* getStyleColorVec4)(StyleColor colorIndex);
/**
* Get current font
*/
Font*(CARB_ABI* getFont)();
/**
* Get current font size (= height in pixels) of current font with current scale applied
*/
float(CARB_ABI* getFontSize)();
/**
* Get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API
*/
Float2(CARB_ABI* getFontTexUvWhitePixel)();
/**
* Retrieve given style color with style alpha applied and optional extra alpha multiplier
*/
uint32_t(CARB_ABI* getColorU32StyleColor)(StyleColor colorIndex, float alphaMul);
/**
* Retrieve given color with style alpha applied
*/
uint32_t(CARB_ABI* getColorU32Vec4)(Float4 color);
/**
* Retrieve given color with style alpha applied
*/
uint32_t(CARB_ABI* getColorU32)(uint32_t color);
/**
* Push an item width for next widgets.
* In pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of
* window (so -1.0f always align width to the right side).
*
* @param width The width.
*/
void(CARB_ABI* pushItemWidth)(float width);
/**
* Pops an item width.
*/
void(CARB_ABI* popItemWidth)();
/**
* Size of item given pushed settings and current cursor position
* NOTE: This is not the same as calcItemWidth
*/
carb::Float2(CARB_ABI* calcItemSize)(carb::Float2 size, float defaultX, float defaultY);
/**
* Width of item given pushed settings and current cursor position
*/
float(CARB_ABI* calcItemWidth)();
//! @private Unknown/Undocumented
void(CARB_ABI* pushItemFlag)(ItemFlags option, bool enabled);
//! @private Unknown/Undocumented
void(CARB_ABI* popItemFlag)();
/**
* Word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at
* 'wrapPosX' position in window local space
*/
void(CARB_ABI* pushTextWrapPos)(float wrapPosX);
/**
* Pop text wrap pos form the stack
*/
void(CARB_ABI* popTextWrapPos)();
/**
* Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
*/
void(CARB_ABI* pushAllowKeyboardFocus)(bool allow);
/**
* Pop allow keyboard focus
*/
void(CARB_ABI* popAllowKeyboardFocus)();
/**
* In 'repeat' mode, Button*() functions return repeated true in a typematic manner (using
* io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if
* the button is held in the current frame.
*/
void(CARB_ABI* pushButtonRepeat)(bool repeat);
/**
* Pop button repeat
*/
void(CARB_ABI* popButtonRepeat)();
/**
* Adds a widget separator.
*/
void(CARB_ABI* separator)();
/**
* Tell the widget to stay on the same line.
*/
void sameLine();
/**
* Tell the widget to stay on the same line with parameters.
*/
void(CARB_ABI* sameLineEx)(float posX, float spacingW);
/**
* Undo sameLine()
*/
void(CARB_ABI* newLine)();
/**
* Adds widget spacing.
*/
void(CARB_ABI* spacing)();
/**
* Adds a dummy element of a given size
*
* @param size The size of a dummy element.
*/
void(CARB_ABI* dummy)(Float2 size);
/**
* Indents.
*/
void(CARB_ABI* indent)();
/**
* Indents with width indent spacing.
*/
void(CARB_ABI* indentEx)(float indentWidth);
/**
* Undo indent.
*/
void(CARB_ABI* unindent)();
/**
* Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or
* layout primitives such as () on whole group, etc.)
*/
void(CARB_ABI* beginGroup)();
/**
* End group
*/
void(CARB_ABI* endGroup)();
/**
* Cursor position is relative to window position
*/
Float2(CARB_ABI* getCursorPos)();
//! @private Unknown/Undocumented
float(CARB_ABI* getCursorPosX)();
//! @private Unknown/Undocumented
float(CARB_ABI* getCursorPosY)();
//! @private Unknown/Undocumented
void(CARB_ABI* setCursorPos)(const Float2& localPos);
//! @private Unknown/Undocumented
void(CARB_ABI* setCursorPosX)(float x);
//! @private Unknown/Undocumented
void(CARB_ABI* setCursorPosY)(float y);
/**
* Initial cursor position
*/
Float2(CARB_ABI* getCursorStartPos)();
/**
* Cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API)
*/
Float2(CARB_ABI* getCursorScreenPos)();
/**
* Cursor position in absolute screen coordinates [0..io.DisplaySize]
*/
void(CARB_ABI* setCursorScreenPos)(const Float2& pos);
/**
* Vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed
* items (call if you have text on a line before a framed item)
*/
void(CARB_ABI* alignTextToFramePadding)();
/**
* ~ FontSize
*/
float(CARB_ABI* getTextLineHeight)();
/**
* ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)
*/
float(CARB_ABI* getTextLineHeightWithSpacing)();
/**
* ~ FontSize + style.FramePadding.y * 2
*/
float(CARB_ABI* getFrameHeight)();
/**
* ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of
* framed widgets)
*/
float(CARB_ABI* getFrameHeightWithSpacing)();
/**
* Push a string id for next widgets.
*
* If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop
* index) so simplegui can differentiate them. popId() must be called later.
* @param id The string id.
*/
void(CARB_ABI* pushIdString)(const char* id);
/**
* Push a string id for next widgets.
*
* If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop
* index) so simplegui can differentiate them. popId() must be called later.
* @param id The string id.
*/
void(CARB_ABI* pushIdStringBeginEnd)(const char* idBegin, const char* idEnd);
/**
* Push an integer id for next widgets.
*
* If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop
* index) so simplegui can differentiate them. popId() must be called later.
* @param id The integer id.
*/
void(CARB_ABI* pushIdInt)(int id);
/**
* Push pointer id for next widgets.
*/
void(CARB_ABI* pushIdPtr)(const void* id);
/**
* Pops an id.
*/
void(CARB_ABI* popId)();
/**
* Calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage
* yourself.
*/
uint32_t(CARB_ABI* getIdString)(const char* id);
/**
* Calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage
* yourself.
*/
uint32_t(CARB_ABI* getIdStringBeginEnd)(const char* idBegin, const char* idEnd);
//! @private Unknown/Undocumented
uint32_t(CARB_ABI* getIdPtr)(const void* id);
/**
* Shows a text widget, without text formatting. Faster version, use for big texts.
*
* @param text The null terminated text string.
*/
void(CARB_ABI* textUnformatted)(const char* text);
/**
* Shows a text widget.
*
* @param fmt The formatted label for the text.
* @param ... The variable arguments for the label.
*/
void(CARB_ABI* text)(const char* fmt, ...);
/**
* Shows a colored text widget.
*
* @param fmt The formatted label for the text.
* @param ... The variable arguments for the label.
*/
void(CARB_ABI* textColored)(const Float4& color, const char* fmt, ...);
/**
* Shows a disabled text widget.
*
* @param fmt The formatted label for the text.
* @param ... The variable arguments for the label.
*/
void(CARB_ABI* textDisabled)(const char* fmt, ...);
/**
* Shows a wrapped text widget.
*
* @param fmt The formatted label for the text.
* @param ... The variable arguments for the label.
*/
void(CARB_ABI* textWrapped)(const char* fmt, ...);
/**
* Display text+label aligned the same way as value+label widgets.
*/
void(CARB_ABI* labelText)(const char* label, const char* fmt, ...);
/**
* Shortcut for Bullet()+Text()
*/
void(CARB_ABI* bulletText)(const char* fmt, ...);
/**
* Shows a button widget.
*
* @param label The label for the button.
* @return true if the button was pressed, false if not.
*/
bool(CARB_ABI* buttonEx)(const char* label, const Float2& size);
//! @private Unknown/Undocumented
bool button(const char* label);
/**
* Shows a smallButton widget.
*
* @param label The label for the button.
* @return true if the button was pressed, false if not.
*/
bool(CARB_ABI* smallButton)(const char* label);
/**
* Button behavior without the visuals.
*
* Useful to build custom behaviors using the public api (along with isItemActive, isItemHovered, etc.)
*/
bool(CARB_ABI* invisibleButton)(const char* id, const Float2& size);
/**
* Arrow-like button with specified direction.
*/
bool(CARB_ABI* arrowButton)(const char* id, Direction dir);
/**
* Image with user texture id
* defaults:
* uv0 = Float2(0,0)
* uv1 = Float2(1,1)
* tintColor = Float4(1,1,1,1)
* borderColor = Float4(0,0,0,0)
*/
void(CARB_ABI* image)(TextureId userTextureId,
const Float2& size,
const Float2& uv0,
const Float2& uv1,
const Float4& tintColor,
const Float4& borderColor);
/**
* Image as a button. <0 framePadding uses default frame padding settings. 0 for no padding
* defaults:
* uv0 = Float2(0,0)
* uv1 = Float2(1,1)
* framePadding = -1
* bgColor = Float4(0,0,0,0)
* tintColor = Float4(1,1,1,1)
*/
bool(CARB_ABI* imageButton)(TextureId userTextureId,
const Float2& size,
const Float2& uv0,
const Float2& uv1,
int framePadding,
const Float4& bgColor,
const Float4& tintColor);
/**
* Adds a checkbox widget.
*
* @param label The checkbox label.
* @param value The current value of the checkbox
*
* @return true if the checkbox was pressed, false if not.
*/
bool(CARB_ABI* checkbox)(const char* label, bool* value);
/**
* Flags checkbox
*/
bool(CARB_ABI* checkboxFlags)(const char* label, uint32_t* flags, uint32_t flagsValue);
/**
* Radio button
*/
bool(CARB_ABI* radioButton)(const char* label, bool active);
/**
* Radio button
*/
bool(CARB_ABI* radioButtonEx)(const char* label, int* v, int vButton);
/**
* Adds a progress bar widget.
*
* @param fraction The progress value (0-1).
* @param size The widget size.
* @param overlay The text overlay, if nullptr the default with percents is displayed.
*/
void(CARB_ABI* progressBar)(float fraction, Float2 size, const char* overlay);
/**
* Draws a small circle.
*/
void(CARB_ABI* bullet)();
/**
* The new beginCombo()/endCombo() api allows you to manage your contents and selection state however you want it.
* The old Combo() api are helpers over beginCombo()/endCombo() which are kept available for convenience purpose.
*/
bool(CARB_ABI* beginCombo)(const char* label, const char* previewValue, ComboFlags flags);
/**
* only call endCombo() if beginCombo() returns true!
*/
void(CARB_ABI* endCombo)();
/**
* Adds a combo box widget.
*
* @param label The label for the combo box.
* @param currentItem The current (selected) element index.
* @param items The array of items.
* @param itemCount The number of items.
*
* @return true if the selected item value has changed, false if not.
*/
bool(CARB_ABI* combo)(const char* label, int* currentItem, const char* const* items, int itemCount);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds). If vMin >= vMax we have no bound. For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of
* every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a
* way to document the number of elements that are expected to be accessible. You can pass address of your first
* element out of a contiguous set, e.g. &myvector.x. Speed are per-pixel of mouse movement (vSpeed=0.2f: mouse
* needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(vSpeed,
* minimum_step_at_given_precision). Defaults: float vSpeed = 1.0f, float vMin = 0.0f, float vMax = 0.0f, const
* char* displayFormat = "%.3f", float power = 1.0f)
*/
bool(CARB_ABI* dragFloat)(
const char* label, float* v, float vSpeed, float vMin, float vMax, const char* displayFormat, float power);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds) Defaults: float vSpeed = 1.0f, float vMin = 0.0f, float vMax = 0.0f, const char* displayFormat =
* "%.3f", float power = 1.0f)
*/
bool(CARB_ABI* dragFloat2)(
const char* label, float v[2], float vSpeed, float vMin, float vMax, const char* displayFormat, float power);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds) Defaults: float vSpeed = 1.0f, float vMin = 0.0f, float vMax = 0.0f, const char* displayFormat =
* "%.3f", float power = 1.0f)
*/
bool(CARB_ABI* dragFloat3)(
const char* label, float v[3], float vSpeed, float vMin, float vMax, const char* displayFormat, float power);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds) Defaults: float vSpeed = 1.0f, float vMin = 0.0f, float vMax = 0.0f, const char* displayFormat =
* "%.3f", float power = 1.0f)
*/
bool(CARB_ABI* dragFloat4)(
const char* label, float v[4], float vSpeed, float vMin, float vMax, const char* displayFormat, float power);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: float vSpeed = 1.0f, float vMin = 0.0f, float vMax = 0.0f, const char* displayFormat =
* "%.3f", const char* displayFormatMax = NULL, float power = 1.0f
*/
bool(CARB_ABI* dragFloatRange2)(const char* label,
float* vCurrentMin,
float* vCurrentMax,
float vSpeed,
float vMin,
float vMax,
const char* displayFormat,
const char* displayFormatMax,
float power);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds). If vMin >= vMax we have no bound.. Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0,
* const char* displayFormat = "%.0f"
*/
bool(CARB_ABI* dragInt)(const char* label, int* v, float vSpeed, int vMin, int vMax, const char* displayFormat);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, const char* displayFormat = "%.0f"
*/
bool(CARB_ABI* dragInt2)(const char* label, int v[2], float vSpeed, int vMin, int vMax, const char* displayFormat);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, const char* displayFormat = "%.0f"
*/
bool(CARB_ABI* dragInt3)(const char* label, int v[3], float vSpeed, int vMin, int vMax, const char* displayFormat);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, const char* displayFormat = "%.0f"
*/
bool(CARB_ABI* dragInt4)(const char* label, int v[4], float vSpeed, int vMin, int vMax, const char* displayFormat);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, const char* displayFormat = "%.0f",
* const char* displayFormatMax = NULL
*/
bool(CARB_ABI* dragIntRange2)(const char* label,
int* vCurrentMin,
int* vCurrentMax,
float vSpeed,
int vMin,
int vMax,
const char* displayFormat,
const char* displayFormatMax);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds). If vMin >= vMax we have no bound.. Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0,
* const char* displayFormat = "%.0f", power = 1.0f
*/
bool(CARB_ABI* dragScalar)(const char* label,
DataType dataType,
void* v,
float vSpeed,
const void* vMin,
const void* vMax,
const char* displayFormat,
float power);
/**
* Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can
* go off-bounds). If vMin >= vMax we have no bound.. Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0,
* const char* displayFormat = "%.0f", power = 1.0f
*/
bool(CARB_ABI* dragScalarN)(const char* label,
DataType dataType,
void* v,
int components,
float vSpeed,
const void* vMin,
const void* vMax,
const char* displayFormat,
float power);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Adjust displayFormat to decorate the value with a prefix or a suffix for in-slider labels or unit
* display. Use power!=1.0 for logarithmic sliders . Defaults: const char* displayFormat = "%.3f", float power
* = 1.0f
*/
bool(CARB_ABI* sliderFloat)(const char* label, float* v, float vMin, float vMax, const char* displayFormat, float power);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.3f", float power = 1.0f
*/
bool(CARB_ABI* sliderFloat2)(
const char* label, float v[2], float vMin, float vMax, const char* displayFormat, float power);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.3f", float power = 1.0f
*/
bool(CARB_ABI* sliderFloat3)(
const char* label, float v[3], float vMin, float vMax, const char* displayFormat, float power);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.3f", float power = 1.0f
*/
bool(CARB_ABI* sliderFloat4)(
const char* label, float v[4], float vMin, float vMax, const char* displayFormat, float power);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: float vDegreesMin = -360.0f, float vDegreesMax = +360.0f
*/
bool(CARB_ABI* sliderAngle)(const char* label, float* vRad, float vDegreesMin, float vDegreesMax);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.0f"
*/
bool(CARB_ABI* sliderInt)(const char* label, int* v, int vMin, int vMax, const char* displayFormat);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.0f"
*/
bool(CARB_ABI* sliderInt2)(const char* label, int v[2], int vMin, int vMax, const char* displayFormat);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.0f"
*/
bool(CARB_ABI* sliderInt3)(const char* label, int v[3], int vMin, int vMax, const char* displayFormat);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.0f"
*/
bool(CARB_ABI* sliderInt4)(const char* label, int v[4], int vMin, int vMax, const char* displayFormat);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.0f", power = 1.0f
*/
bool(CARB_ABI* sliderScalar)(const char* label,
DataType dataType,
void* v,
const void* vMin,
const void* vMax,
const char* displayFormat,
float power);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.0f", power = 1.0f
*/
bool(CARB_ABI* sliderScalarN)(const char* label,
DataType dataType,
void* v,
int components,
const void* vMin,
const void* vMax,
const char* displayFormat,
float power);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.3f", float power = 1.0f
*/
bool(CARB_ABI* vSliderFloat)(
const char* label, const Float2& size, float* v, float vMin, float vMax, const char* displayFormat, float power);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.0f"
*/
bool(CARB_ABI* vSliderInt)(const char* label, const Float2& size, int* v, int vMin, int vMax, const char* displayFormat);
/**
* Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can
* go off-bounds). Defaults: const char* displayFormat = "%.0f", power = 1.0f
*/
bool(CARB_ABI* vSliderScalar)(const char* label,
const Float2& size,
DataType dataType,
void* v,
const void* vMin,
const void* vMax,
const char* displayFormat,
float power);
/**
* Widgets: Input with Keyboard
*/
bool(CARB_ABI* inputText)(
const char* label, char* buf, size_t bufSize, InputTextFlags flags, TextEditCallback callback, void* userData);
/**
* Widgets: Input with Keyboard
*/
bool(CARB_ABI* inputTextMultiline)(const char* label,
char* buf,
size_t bufSize,
const Float2& size,
InputTextFlags flags,
TextEditCallback callback,
void* userData);
/**
* Widgets: Input with Keyboard. Defaults: float step = 0.0f, float stepFast = 0.0f, int decimalPrecision = -1,
* InputTextFlags extraFlags = 0
*/
bool(CARB_ABI* inputFloat)(
const char* label, float* v, float step, float stepFast, int decimalPrecision, InputTextFlags extraFlags);
/**
* Widgets: Input with Keyboard. Defaults: int decimalPrecision = -1, InputTextFlags extraFlags = 0
*/
bool(CARB_ABI* inputFloat2)(const char* label, float v[2], int decimalPrecision, InputTextFlags extraFlags);
/**
* Widgets: Input with Keyboard. Defaults: int decimalPrecision = -1, InputTextFlags extraFlags = 0
*/
bool(CARB_ABI* inputFloat3)(const char* label, float v[3], int decimalPrecision, InputTextFlags extraFlags);
/**
* Widgets: Input with Keyboard. Defaults: int decimalPrecision = -1, InputTextFlags extraFlags = 0
*/
bool(CARB_ABI* inputFloat4)(const char* label, float v[4], int decimalPrecision, InputTextFlags extraFlags);
/**
* Widgets: Input with Keyboard. Defaults: int step = 1, int stepFast = 100, InputTextFlags extraFlags = 0
*/
bool(CARB_ABI* inputInt)(const char* label, int* v, int step, int stepFast, InputTextFlags extraFlags);
/**
* Widgets: Input with Keyboard
*/
bool(CARB_ABI* inputInt2)(const char* label, int v[2], InputTextFlags extraFlags);
/**
* Widgets: Input with Keyboard
*/
bool(CARB_ABI* inputInt3)(const char* label, int v[3], InputTextFlags extraFlags);
/**
* Widgets: Input with Keyboard
*/
bool(CARB_ABI* inputInt4)(const char* label, int v[4], InputTextFlags extraFlags);
/**
* Widgets: Input with Keyboard. Defaults: double step = 0.0f, double stepFast = 0.0f, const char* displayFormat =
* "%.6f", InputTextFlags extraFlags = 0
*/
bool(CARB_ABI* inputDouble)(
const char* label, double* v, double step, double stepFast, const char* displayFormat, InputTextFlags extraFlags);
/**
* Widgets: Input with Keyboard. Defaults: double step = 0.0f, double stepFast = 0.0f, const char* displayFormat =
* "%.6f", InputTextFlags extraFlags = 0
*/
bool(CARB_ABI* inputScalar)(const char* label,
DataType dataType,
void* v,
const void* step,
const void* stepFast,
const char* displayFormat,
InputTextFlags extraFlags);
/**
* Widgets: Input with Keyboard. Defaults: double step = 0.0f, double stepFast = 0.0f, const char* displayFormat =
* "%.6f", InputTextFlags extraFlags = 0
*/
bool(CARB_ABI* inputScalarN)(const char* label,
DataType dataType,
void* v,
int components,
const void* step,
const void* stepFast,
const char* displayFormat,
InputTextFlags extraFlags);
/**
* Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be
* left-clicked to open a picker, and right-clicked to open an option menu.)
*/
bool(CARB_ABI* colorEdit3)(const char* label, float col[3], ColorEditFlags flags);
/**
* Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be
* left-clicked to open a picker, and right-clicked to open an option menu.)
*/
bool(CARB_ABI* colorEdit4)(const char* label, float col[4], ColorEditFlags flags);
/**
* Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be
* left-clicked to open a picker, and right-clicked to open an option menu.)
*/
bool(CARB_ABI* colorPicker3)(const char* label, float col[3], ColorEditFlags flags);
/**
* Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be
* left-clicked to open a picker, and right-clicked to open an option menu.)
*/
bool(CARB_ABI* colorPicker4)(const char* label, float col[4], ColorEditFlags flags, const float* refCol);
/**
* display a colored square/button, hover for details, return true when pressed.
*/
bool(CARB_ABI* colorButton)(const char* descId, const Float4& col, ColorEditFlags flags, Float2 size);
/**
* initialize current options (generally on application startup) if you want to select a default format, picker
* type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls.
*/
void(CARB_ABI* setColorEditOptions)(ColorEditFlags flags);
/**
* Tree node. if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible
* for calling TreePop().
*/
bool(CARB_ABI* treeNode)(const char* label);
/**
* Tree node with string id. read the FAQ about why and how to use ID. to align arbitrary text at the same level as
* a TreeNode() you can use Bullet().
*/
bool(CARB_ABI* treeNodeString)(const char* strId, const char* fmt, ...);
/**
* Tree node with ptr id.
*/
bool(CARB_ABI* treeNodePtr)(const void* ptrId, const char* fmt, ...);
/**
* Tree node with flags.
*/
bool(CARB_ABI* treeNodeEx)(const char* label, TreeNodeFlags flags);
/**
* Tree node with flags and string id.
*/
bool(CARB_ABI* treeNodeStringEx)(const char* strId, TreeNodeFlags flags, const char* fmt, ...);
/**
* Tree node with flags and ptr id.
*/
bool(CARB_ABI* treeNodePtrEx)(const void* ptrId, TreeNodeFlags flags, const char* fmt, ...);
/**
* ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for
* layout purpose
*/
void(CARB_ABI* treePushString)(const char* strId);
//! @private Unknown/Undocumented
void(CARB_ABI* treePushPtr)(const void* ptrId);
/**
* ~ Unindent()+PopId()
*/
void(CARB_ABI* treePop)();
/**
* Advance cursor x position by GetTreeNodeToLabelSpacing()
*/
void(CARB_ABI* treeAdvanceToLabelPos)();
/**
* Horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2)
* for a regular unframed TreeNode
*/
float(CARB_ABI* getTreeNodeToLabelSpacing)();
/**
* Set next TreeNode/CollapsingHeader open state.
*/
void(CARB_ABI* setNextTreeNodeOpen)(bool isOpen, Condition cond);
/**
* If returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop().
*/
bool(CARB_ABI* collapsingHeader)(const char* label, TreeNodeFlags flags);
/**
* When 'open' isn't NULL, display an additional small close button on upper right of the header
*/
bool(CARB_ABI* collapsingHeaderEx)(const char* label, bool* open, TreeNodeFlags flags);
/**
* Selectable. "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you
* can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use
* label height, size.y>0.0: specify height.
*/
bool(CARB_ABI* selectable)(const char* label,
bool selected /* = false*/,
SelectableFlags flags /* = 0*/,
const Float2& size /* = Float2(0,0)*/);
/**
* Selectable. "bool* selected" point to the selection state (read-write), as a convenient helper.
*/
bool(CARB_ABI* selectableEx)(const char* label,
bool* selected,
SelectableFlags flags /* = 0*/,
const Float2& size /* = Float2(0,0)*/);
/**
* ListBox.
*/
bool(CARB_ABI* listBox)(
const char* label, int* currentItem, const char* const items[], int itemCount, int heightInItems /* = -1*/);
/**
* ListBox.
*/
bool(CARB_ABI* listBoxEx)(const char* label,
int* currentItem,
bool (*itemsGetterFn)(void* data, int idx, const char** out_text),
void* data,
int itemCount,
int heightInItems /* = -1*/);
/**
* ListBox Header. use if you want to reimplement ListBox() will custom data or interactions. make sure to call
* ListBoxFooter() afterwards.
*/
bool(CARB_ABI* listBoxHeader)(const char* label, const Float2& size /* = Float2(0,0)*/);
/**
* ListBox Header.
*/
bool(CARB_ABI* listBoxHeaderEx)(const char* label, int itemCount, int heightInItems /* = -1*/);
/**
* Terminate the scrolling region
*/
void(CARB_ABI* listBoxFooter)();
/**
* Plot
* defaults:
* valuesOffset = 0
* overlayText = nullptr
* scaleMin = FLT_MAX
* scaleMax = FLT_MAX
* graphSize = Float2(0,0)
* stride = sizeof(float)
*/
void(CARB_ABI* plotLines)(const char* label,
const float* values,
int valuesCount,
int valuesOffset,
const char* overlayText,
float scaleMin,
float scaleMax,
Float2 graphSize,
int stride);
/**
* Plot
* defaults:
* valuesOffset = 0
* overlayText = nullptr
* scaleMin = FLT_MAX
* scaleMax = FLT_MAX
* graphSize = Float2(0,0)
*/
void(CARB_ABI* plotLinesEx)(const char* label,
float (*valuesGetterFn)(void* data, int idx),
void* data,
int valuesCount,
int valuesOffset,
const char* overlayText,
float scaleMin,
float scaleMax,
Float2 graphSize);
/**
* Histogram
* defaults:
* valuesOffset = 0
* overlayText = nullptr
* scaleMin = FLT_MAX
* scaleMax = FLT_MAX
* graphSize = Float2(0,0)
* stride = sizeof(float)
*/
void(CARB_ABI* plotHistogram)(const char* label,
const float* values,
int valuesCount,
int valuesOffset,
const char* overlayText,
float scaleMin,
float scaleMax,
Float2 graphSize,
int stride);
/**
* Histogram
* defaults:
* valuesOffset = 0
* overlayText = nullptr
* scaleMin = FLT_MAX
* scaleMax = FLT_MAX
* graphSize = Float2(0,0)
*/
void(CARB_ABI* plotHistogramEx)(const char* label,
float (*valuesGetterFn)(void* data, int idx),
void* data,
int valuesCount,
int valuesOffset,
const char* overlayText,
float scaleMin,
float scaleMax,
Float2 graphSize);
/**
* Widgets: Value() Helpers. Output single value in "name: value" format.
*/
void(CARB_ABI* valueBool)(const char* prefix, bool b);
/**
* Widgets: Value() Helpers. Output single value in "name: value" format.
*/
void(CARB_ABI* valueInt)(const char* prefix, int v);
/**
* Widgets: Value() Helpers. Output single value in "name: value" format.
*/
void(CARB_ABI* valueUInt32)(const char* prefix, uint32_t v);
/**
* Widgets: Value() Helpers. Output single value in "name: value" format.
*/
void(CARB_ABI* valueFloat)(const char* prefix, float v, const char* floatFormat /* = nullptr*/);
/**
* Create and append to a full screen menu-bar.
*/
bool(CARB_ABI* beginMainMenuBar)();
/**
* Only call EndMainMenuBar() if BeginMainMenuBar() returns true!
*/
void(CARB_ABI* endMainMenuBar)();
/**
* Append to menu-bar of current window (requires WindowFlags_MenuBar flag set on parent window).
*/
bool(CARB_ABI* beginMenuBar)();
/**
* Only call EndMenuBar() if BeginMenuBar() returns true!
*/
void(CARB_ABI* endMenuBar)();
/**
* Create a sub-menu entry. only call EndMenu() if this returns true!
*/
bool(CARB_ABI* beginMenu)(const char* label, bool enabled /* = true*/);
/**
* Only call EndMenu() if BeginMenu() returns true!
*/
void(CARB_ABI* endMenu)();
/**
* Return true when activated. shortcuts are displayed for convenience but not processed by simplegui at the moment
*/
bool(CARB_ABI* menuItem)(const char* label,
const char* shortcut /* = NULL*/,
bool selected /* = false*/,
bool enabled /* = true*/);
/**
* Return true when activated + toggle (*pSelected) if pSelected != NULL
*/
bool(CARB_ABI* menuItemEx)(const char* label, const char* shortcut, bool* pSelected, bool enabled /* = true*/);
/**
* Set text tooltip under mouse-cursor, typically use with ISimpleGui::IsItemHovered(). Overrides any previous call
* to SetTooltip().
*/
void(CARB_ABI* setTooltip)(const char* fmt, ...);
/**
* Begin/append a tooltip window. to create full-featured tooltip (with any kind of contents).
*/
void(CARB_ABI* beginTooltip)();
/**
* End tooltip
*/
void(CARB_ABI* endTooltip)();
/**
* Call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if
* CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are
* calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup
* needs to be at the same level).
*/
void(CARB_ABI* openPopup)(const char* strId);
/**
* Return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup()
* returns true!
*/
bool(CARB_ABI* beginPopup)(const char* strId, WindowFlags flags /* = 0*/);
/**
* Helper to open and begin popup when clicked on last item. if you can pass a NULL strId only if the previous item
* had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID
* here. read comments in .cpp!
*/
bool(CARB_ABI* beginPopupContextItem)(const char* strId /* = NULL*/, int mouseButton /* = 1*/);
/**
* Helper to open and begin popup when clicked on current window.
*/
bool(CARB_ABI* beginPopupContextWindow)(const char* strId /* = NULL*/,
int mouseButton /* = 1*/,
bool alsoOverItems /* = true*/);
/**
* Helper to open and begin popup when clicked in void (where there are no simplegui windows).
*/
bool(CARB_ABI* beginPopupContextVoid)(const char* strId /* = NULL*/, int mouseButton /* = 1*/);
/**
* Modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal
* window by clicking outside)
*/
bool(CARB_ABI* beginPopupModal)(const char* name, bool* open /* = NULL*/, WindowFlags flags /* = 0*/);
/**
* Only call EndPopup() if BeginPopupXXX() returns true!
*/
void(CARB_ABI* endPopup)();
/**
* Helper to open popup when clicked on last item. return true when just opened.
*/
bool(CARB_ABI* openPopupOnItemClick)(const char* strId /* = NULL*/, int mouseButton /* = 1*/);
/**
* Return true if the popup is open
*/
bool(CARB_ABI* isPopupOpen)(const char* strId);
/**
* Close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current
* popup.
*/
void(CARB_ABI* closeCurrentPopup)();
/**
* Columns. You can also use SameLine(pos_x) for simplified columns. The columns API is still work-in-progress and
* rather lacking.
*/
void(CARB_ABI* columns)(int count /* = 1*/, const char* id /* = NULL*/, bool border /* = true*/);
/**
* Next column, defaults to current row or next row if the current row is finished
*/
void(CARB_ABI* nextColumn)();
/**
* Get current column index
*/
int(CARB_ABI* getColumnIndex)();
/**
* Get column width (in pixels). pass -1 to use current column
*/
float(CARB_ABI* getColumnWidth)(int columnIndex /* = -1*/);
/**
* Set column width (in pixels). pass -1 to use current column
*/
void(CARB_ABI* setColumnWidth)(int columnIndex, float width);
/**
* Get position of column line (in pixels, from the left side of the contents region). pass -1 to use current
* column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f
*/
float(CARB_ABI* getColumnOffset)(int columnIndex /* = -1*/);
/**
* Set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column
*/
void(CARB_ABI* setColumnOffset)(int columnIndex, float offsetX);
/**
* Columns count.
*/
int(CARB_ABI* getColumnsCount)();
/**
* Create and append into a TabBar.
* defaults:
* flags = 0
*/
bool(CARB_ABI* beginTabBar)(const char* strId, TabBarFlags flags);
/**
* End TabBar.
*/
void(CARB_ABI* endTabBar)();
/**
* Create a Tab. Returns true if the Tab is selected.
* defaults:
* open = nullptr
* flags = 0
*/
bool(CARB_ABI* beginTabItem)(const char* label, bool* open, TabItemFlags flags);
/**
* Only call endTabItem() if beginTabItem() returns true!
*/
void(CARB_ABI* endTabItem)();
/**
* Notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable
* tab bars). For tab-bar: call after beginTabBar() and before Tab submissions. Otherwise call with a window name.
*/
void(CARB_ABI* setTabItemClosed)(const char* tabOrDockedWindowLabel);
/**
* defaults:
* size = Float2(0, 0),
* flags = 0,
* windowClass = nullptr
*/
void(CARB_ABI* dockSpace)(uint32_t id, const Float2& size, DockNodeFlags flags, const WindowClass* windowClass);
/**
* defaults:
* viewport = nullptr,
* dockspaceFlags = 0,
* windowClass = nullptr
*/
uint32_t(CARB_ABI* dockSpaceOverViewport)(Viewport* viewport,
DockNodeFlags dockspaceFlags,
const WindowClass* windowClass);
/**
* Set next window dock id (FIXME-DOCK).
*/
void(CARB_ABI* setNextWindowDockId)(uint32_t dockId, Condition cond);
/**
* Set next window user type (docking filters by same user_type).
*/
void(CARB_ABI* setNextWindowClass)(const WindowClass* windowClass);
/**
* Get window dock Id.
*/
uint32_t(CARB_ABI* getWindowDockId)();
/**
* Return is window Docked.
*/
bool(CARB_ABI* isWindowDocked)();
/**
* Call when the current item is active. If this return true, you can call setDragDropPayload() +
* endDragDropSource()
*/
bool(CARB_ABI* beginDragDropSource)(DragDropFlags flags);
/**
* Type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for simplegui
* internal types. Data is copied and held by simplegui. Defaults: cond = 0
*/
bool(CARB_ABI* setDragDropPayload)(const char* type, const void* data, size_t size, Condition cond);
/**
* Only call endDragDropSource() if beginDragDropSource() returns true!
*/
void(CARB_ABI* endDragDropSource)();
/**
* Call after submitting an item that may receive a payload. If this returns true, you can call
* acceptDragDropPayload() + endDragDropTarget()
*/
bool(CARB_ABI* beginDragDropTarget)();
/**
* Accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload
* before the mouse button is released.
*/
const Payload*(CARB_ABI* acceptDragDropPayload)(const char* type, DragDropFlags flags);
/**
* Only call endDragDropTarget() if beginDragDropTarget() returns true!
*/
void(CARB_ABI* endDragDropTarget)();
/**
* Peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for
* the payload type.
*/
const Payload*(CARB_ABI* getDragDropPayload)();
/**
* Clipping.
*/
void(CARB_ABI* pushClipRect)(const Float2& clipRectMin, const Float2& clipRectMax, bool intersectWithCurrentClipRect);
/**
* Clipping.
*/
void(CARB_ABI* popClipRect)();
/**
* Make last item the default focused item of a window. Please use instead of "if (IsWindowAppearing())
* SetScrollHere()" to signify "default item".
*/
void(CARB_ABI* setItemDefaultFocus)();
/**
* Focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget.
* Use -1 to access previous widget.
*/
void(CARB_ABI* setKeyboardFocusHere)(int offset /* = 0*/);
/**
* Clears the active element id in the internal state.
*/
void(CARB_ABI* clearActiveId)();
/**
* Is the last item hovered? (and usable, aka not blocked by a popup, etc.). See HoveredFlags for more options.
*/
bool(CARB_ABI* isItemHovered)(HoveredFlags flags /* = 0*/);
/**
* Is the last item active? (e.g. button being held, text field being edited- items that don't interact will always
* return false)
*/
bool(CARB_ABI* isItemActive)();
/**
* Is the last item focused for keyboard/gamepad navigation?
*/
bool(CARB_ABI* isItemFocused)();
/**
* Is the last item clicked? (e.g. button/node just clicked on)
*/
bool(CARB_ABI* isItemClicked)(int mouseButton /* = 0*/);
/**
* Is the last item visible? (aka not out of sight due to clipping/scrolling.)
*/
bool(CARB_ABI* isItemVisible)();
/**
* Is the last item visible? (items may be out of sight because of clipping/scrolling)
*/
bool(CARB_ABI* isItemEdited)();
/**
* Was the last item just made inactive (item was previously active).
*
* Useful for Undo/Redo patterns with widgets that requires continuous editing.
*/
bool(CARB_ABI* isItemDeactivated)();
/**
* Was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved).
*
* Useful for Undo/Redo patterns with widgets that requires continuous editing.
* Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable()
will return true even when clicking an already selected item).
*/
bool(CARB_ABI* isItemDeactivatedAfterEdit)();
//! @private Unknown/Undocumented
bool(CARB_ABI* isAnyItemHovered)();
//! @private Unknown/Undocumented
bool(CARB_ABI* isAnyItemActive)();
//! @private Unknown/Undocumented
bool(CARB_ABI* isAnyItemFocused)();
/**
* Is specific item active?
*/
bool(CARB_ABI* isItemIdActive)(uint32_t id);
/**
* Get bounding rectangle of last item, in screen space
*/
Float2(CARB_ABI* getItemRectMin)();
//! @private Unknown/Undocumented
Float2(CARB_ABI* getItemRectMax)();
/**
* Get size of last item, in screen space
*/
Float2(CARB_ABI* getItemRectSize)();
/**
* Allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc.
* to catch unused area.
*/
void(CARB_ABI* setItemAllowOverlap)();
/**
* Test if rectangle (of given size, starting from cursor position) is visible / not clipped.
*/
bool(CARB_ABI* isRectVisible)(const Float2& size);
/**
* Test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side.
*/
bool(CARB_ABI* isRectVisibleEx)(const Float2& rectMin, const Float2& rectMax);
/**
* Time.
*/
float(CARB_ABI* getTime)();
/**
* Frame Count.
*/
int(CARB_ABI* getFrameCount)();
/**
* This draw list will be the last rendered one, useful to quickly draw overlays shapes/text
*/
DrawList*(CARB_ABI* getOverlayDrawList)();
//! @private Unknown/Undocumented
const char*(CARB_ABI* getStyleColorName)(StyleColor color);
//! @private Unknown/Undocumented
Float2(CARB_ABI* calcTextSize)(const char* text,
const char* textEnd /* = nullptr*/,
bool hideTextAfterDoubleHash /* = false*/,
float wrap_width /* = -1.0f*/);
/**
* Calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level
* helper if you can.
*/
void(CARB_ABI* calcListClipping)(int itemCount, float itemsHeight, int* outItemsDisplayStart, int* outItemsDisplayEnd);
/**
* Helper to create a child window / scrolling region that looks like a normal widget frame
*/
bool(CARB_ABI* beginChildFrame)(uint32_t id, const Float2& size, WindowFlags flags /* = 0*/);
/**
* Always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped
* window)
*/
void(CARB_ABI* endChildFrame)();
//! @private Unknown/Undocumented
Float4(CARB_ABI* colorConvertU32ToFloat4)(uint32_t in);
//! @private Unknown/Undocumented
uint32_t(CARB_ABI* colorConvertFloat4ToU32)(const Float4& in);
//! @private Unknown/Undocumented
void(CARB_ABI* colorConvertRGBtoHSV)(float r, float g, float b, float& outH, float& outS, float& outV);
//! @private Unknown/Undocumented
void(CARB_ABI* colorConvertHSVtoRGB)(float h, float s, float v, float& outR, float& outG, float& outB);
/**
* Map ImGuiKey_* values into user's key index. == io.KeyMap[key]
*/
int(CARB_ABI* getKeyIndex)(int imguiKey);
/**
* Is key being held. == io.KeysDown[userKeyIndex]. note that simplegui doesn't know the semantic of each entry of
* io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]!
*/
bool(CARB_ABI* isKeyDown)(int userKeyIndex);
/**
* Was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
*/
bool(CARB_ABI* isKeyPressed)(int userKeyIndex, bool repeat /* = true*/);
/**
* Was key released (went from Down to !Down).
*/
bool(CARB_ABI* isKeyReleased)(int userKeyIndex);
/**
* Uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough
* that DeltaTime > RepeatRate
*/
int(CARB_ABI* getKeyPressedAmount)(int keyIndex, float repeatDelay, float rate);
/**
* Gets the key modifiers for each frame.
*
* Shortcut to bitwise modifier from ImGui::GetIO().KeyCtrl + .KeyShift + .KeyAlt + .KeySuper
*
* @return The key modifiers for each frame.
*/
KeyModifiers(CARB_ABI* getKeyModifiers)();
/**
* Is mouse button held
*/
bool(CARB_ABI* isMouseDown)(int button);
/**
* Is any mouse button held
*/
bool(CARB_ABI* isAnyMouseDown)();
/**
* Did mouse button clicked (went from !Down to Down)
*/
bool(CARB_ABI* isMouseClicked)(int button, bool repeat /* = false*/);
/**
* Did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime.
*/
bool(CARB_ABI* isMouseDoubleClicked)(int button);
/**
* Did mouse button released (went from Down to !Down)
*/
bool(CARB_ABI* isMouseReleased)(int button);
/**
* Is mouse dragging. if lockThreshold < -1.0f uses io.MouseDraggingThreshold
*/
bool(CARB_ABI* isMouseDragging)(int button /* = 0*/, float lockThreshold /* = -1.0f*/);
/**
* Is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of
* consideration of focus/window ordering/blocked by a popup.
*/
bool(CARB_ABI* isMouseHoveringRect)(const Float2& rMin, const Float2& rMax, bool clip /* = true*/);
//! @private Unknown/Undocumented
bool(CARB_ABI* isMousePosValid)(const Float2* mousePos /* = nullptr*/);
/**
* Shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls
*/
Float2(CARB_ABI* getMousePos)();
/**
* Retrieve backup of mouse position at the time of opening popup we have BeginPopup() into
*/
Float2(CARB_ABI* getMousePosOnOpeningCurrentPopup)();
/**
* Dragging amount since clicking. if lockThreshold < -1.0f uses io.MouseDraggingThreshold
*/
Float2(CARB_ABI* getMouseDragDelta)(int button /* = 0*/, float lockThreshold /* = -1.0f*/);
//! @private Unknown/Undocumented
void(CARB_ABI* resetMouseDragDelta)(int button /* = 0*/);
/**
* Gets the mouse wheel delta for each frame.
*
* Shortcut to ImGui::GetIO().MouseWheel + .MouseWheelH.
*
* @return The mouse wheel delta for each frame.
*/
carb::Float2(CARB_ABI* getMouseWheel)();
/**
* Get desired cursor type, reset in ISimpleGui::newFrame(), this is updated during the frame. valid before
* Render(). If you use software rendering by setting io.MouseDrawCursor simplegui will render those for you
*/
MouseCursor(CARB_ABI* getMouseCursor)();
/**
* Set desired cursor type
*/
void(CARB_ABI* setMouseCursor)(MouseCursor type);
/**
* Manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to
* handle). e.g. force capture keyboard when your widget is being hovered.
*/
void(CARB_ABI* captureKeyboardFromApp)(bool capture /* = true*/);
/**
* Manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to
* handle).
*/
void(CARB_ABI* captureMouseFromApp)(bool capture /* = true*/);
/**
* Used to capture text data to the clipboard.
*
* @return The text captures from the clipboard
*/
const char*(CARB_ABI* getClipboardText)();
/**
* Used to apply text into the clipboard.
*
* @param text The text to be set into the clipboard.
*/
void(CARB_ABI* setClipboardText)(const char* text);
/**
* Shortcut to ImGui::GetIO().WantSaveIniSettings provided by user, to be consistent with other calls
*/
bool(CARB_ABI* getWantSaveIniSettings)();
/**
* Shortcut to ImGui::GetIO().WantSaveIniSettings provided by user, to be consistent with other calls
*/
void(CARB_ABI* setWantSaveIniSettings)(bool wantSaveIniSettings);
/**
* Manually load the previously saved setting from memory loaded from an .ini settings file.
*
* @param iniData The init data to be loaded.
* @param initSize The size of the ini data to be loaded.
*/
void(CARB_ABI* loadIniSettingsFromMemory)(const char* iniData, size_t iniSize);
/**
* Manually save settings to a ini memory as a string.
*
* @param iniSize[out] The ini size of memory to be saved.
* @return The memory
*/
const char*(CARB_ABI* saveIniSettingsToMemory)(size_t* iniSize);
/**
* Main viewport. Same as GetPlatformIO().MainViewport == GetPlatformIO().Viewports[0]
*/
Viewport*(CARB_ABI* getMainViewport)();
/**
* Associates a windowName to a dock node id.
*
* @param windowName The name of the window.
* @param nodeId The dock node id.
*/
void(CARB_ABI* dockBuilderDockWindow)(const char* windowName, uint32_t nodeId);
/**
* DO NOT HOLD ON ImGuiDockNode* pointer, will be invalided by any split/merge/remove operation.
*/
DockNode*(CARB_ABI* dockBuilderGetNode)(uint32_t nodeId);
/**
* Defaults:
* flags = 0
*/
void(CARB_ABI* dockBuilderAddNode)(uint32_t nodeId, DockNodeFlags flags);
/**
* Remove node and all its child, undock all windows
*/
void(CARB_ABI* dockBuilderRemoveNode)(uint32_t nodeId);
/**
* Defaults:
* clearPersistentDockingReferences = true
*/
void(CARB_ABI* dockBuilderRemoveNodeDockedWindows)(uint32_t nodeId, bool clearPersistentDockingReferences);
/**
* Remove all split/hierarchy. All remaining docked windows will be re-docked to the root.
*/
void(CARB_ABI* dockBuilderRemoveNodeChildNodes)(uint32_t nodeId);
/**
* Dock building split node.
*/
uint32_t(CARB_ABI* dockBuilderSplitNode)(
uint32_t nodeId, Direction splitDir, float sizeRatioForNodeAtDir, uint32_t* outIdDir, uint32_t* outIdOther);
/**
* Dock building finished.
*/
void(CARB_ABI* dockBuilderFinish)(uint32_t nodeId);
/**
* Adds a font from a given font config.
* @param fontConfig The font config struct.
* @returns A valid font, or `nullptr` if an error occurred.
*/
Font*(CARB_ABI* addFont)(const FontConfig* fontConfig);
/**
* Adds a default font from a given font config.
* @param fontConfig The font config struct.
* @returns A valid font, or `nullptr` if an error occurred.
*/
Font*(CARB_ABI* addFontDefault)(const FontConfig* fontConfig /* = NULL */);
/**
* Adds a TTF font from a file.
* @param filename The path to the file.
* @param sizePixels The size of the font in pixels.
* @param fontCfg (Optional) The font config struct.
* @param glyphRanges (Optional) The range of glyphs.
* @returns A valid font, or `nullptr` if an error occurred.
*/
Font*(CARB_ABI* addFontFromFileTTF)(const char* filename,
float sizePixels,
const FontConfig* fontCfg /*= NULL */,
const Wchar* glyphRanges /*= NULL*/);
/**
* Adds a TTF font from a memory region.
* @param fontData The font data in memory.
* @param fontSize The number of bytes of the font data in memory.
* @param sizePixels The size of the font in pixels.
* @param fontCfg (Optional) The font config struct.
* @param glyphRanges (Optional) The range of glyphs.
* @returns A valid font, or `nullptr` if an error occurred.
*/
Font*(CARB_ABI* addFontFromMemoryTTF)(void* fontData,
int fontSize,
float sizePixels,
const FontConfig* fontCfg /* = NULL */,
const Wchar* glyphRanges /* = NULL */);
/**
* Adds a compressed TTF font from a memory region.
* @param compressedFontData The font data in memory.
* @param compressedFontSize The number of bytes of the font data in memory.
* @param sizePixels The size of the font in pixels.
* @param fontCfg (Optional) The font config struct.
* @param glyphRanges (Optional) The range of glyphs.
* @returns A valid font, or `nullptr` if an error occurred.
*/
Font*(CARB_ABI* addFontFromMemoryCompressedTTF)(const void* compressedFontData,
int compressedFontSize,
float sizePixels,
const FontConfig* fontCfg /* = NULL */,
const Wchar* glyphRanges /*= NULL */);
/**
* Adds a compressed base-85 TTF font from a memory region.
* @param compressedFontDataBase85 The font data in memory.
* @param sizePixels The size of the font in pixels.
* @param fontCfg (Optional) The font config struct.
* @param glyphRanges (Optional) The range of glyphs.
* @returns A valid font, or `nullptr` if an error occurred.
*/
Font*(CARB_ABI* addFontFromMemoryCompressedBase85TTF)(const char* compressedFontDataBase85,
float sizePixels,
const FontConfig* fontCfg /* = NULL */,
const Wchar* glyphRanges /* = NULL */);
/**
* Add a custom rect glyph that can be built into the font atlas. Call buildFont after.
*
* @param font The font to add to.
* @param id The Unicode point to add for.
* @param width The width of the glyph.
* @param height The height of the glyph
* @param advanceX The advance x for the glyph.
* @param offset The glyph offset.
* @return The glyph index.
*/
int(CARB_ABI* addFontCustomRectGlyph)(
Font* font, Wchar id, int width, int height, float advanceX, const carb::Float2& offset /* (0, 0) */);
/**
* Gets the font custom rect by glyph index.
*
* @param index The glyph index to get the custom rect information for.
* @return The font glyph custom rect information.
*/
const FontCustomRect*(CARB_ABI* getFontCustomRectByIndex)(int index);
/**
* Builds the font atlas.
*
* @return true if the font atlas was built successfully.
*/
bool(CARB_ABI* buildFont)();
/**
* Determines if changes have been made to font atlas
*
* @return true if the font atlas is built.
*/
bool(CARB_ABI* isFontBuilt)();
/**
* Gets the font texture data.
*
* @param outPixel The pixel texture data in A8 format.
* @param outWidth The texture width.
* @param outPixel The texture height.
*/
void(CARB_ABI* getFontTexDataAsAlpha8)(unsigned char** outPixels, int* outWidth, int* outHeight);
/**
* Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used
* to build the texture and fonts.
*/
void(CARB_ABI* clearFontInputData)();
/**
* Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory.
*/
void(CARB_ABI* clearFontTexData)();
/**
* Clear output font data (glyphs storage, UV coordinates).
*/
void(CARB_ABI* clearFonts)();
/**
* Clear all input and output.
*/
void(CARB_ABI* clearFontInputOutput)();
/**
* Basic Latin, Extended Latin
*/
const Wchar*(CARB_ABI* getFontGlyphRangesDefault)();
/**
* Default + Korean characters
*/
const Wchar*(CARB_ABI* getFontGlyphRangesKorean)();
/**
* Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
*/
const Wchar*(CARB_ABI* getFontGlyphRangesJapanese)();
/**
* Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs
*/
const Wchar*(CARB_ABI* getFontGlyphRangesChineseFull)();
/**
* Default + Half-Width + Japanese Hiragana/Katakana + set
* of 2500 CJK Unified Ideographs for common simplified Chinese
*/
const Wchar*(CARB_ABI* getGlyphRangesChineseSimplifiedCommon)();
/**
* Default + about 400 Cyrillic characters
*/
const Wchar*(CARB_ABI* getFontGlyphRangesCyrillic)();
/**
* Default + Thai characters
*/
const Wchar*(CARB_ABI* getFontGlyphRangesThai)();
/**
* set Global Font Scale
*/
void(CARB_ABI* setFontGlobalScale)(float scale);
/**
* Shortcut for getWindowDrawList() + DrawList::AddCallback()
*/
void(CARB_ABI* addWindowDrawCallback)(DrawCallback callback, void* userData);
/**
* Adds a line to the draw list.
*/
void(CARB_ABI* addLine)(DrawList* drawList, const carb::Float2& a, const carb::Float2& b, uint32_t col, float thickness);
/**
* Adds a rect to the draw list.
*
* @param a Upper-left.
* @param b Lower-right.
* @param col color.
* @param rounding Default = 0.f;
* @param roundingCornersFlags 4-bits corresponding to which corner to round. Default = kDrawCornerFlagAll
* @param thickness Default = 1.0f
*/
void(CARB_ABI* addRect)(DrawList* drawList,
const carb::Float2& a,
const carb::Float2& b,
uint32_t col,
float rounding,
DrawCornerFlags roundingCornersFlags,
float thickness);
/**
* Adds a filled rect to the draw list.
*
* @param a Upper-left.
* @param b Lower-right.
* @param col color.
* @param rounding Default = 0.f;
* @param roundingCornersFlags 4-bits corresponding to which corner to round. Default = kDrawCornerFlagAll
*/
void(CARB_ABI* addRectFilled)(DrawList* drawList,
const carb::Float2& a,
const carb::Float2& b,
uint32_t col,
float rounding,
DrawCornerFlags roundingCornersFlags);
/**
* Adds a filled multi-color rect to the draw list.
*/
void(CARB_ABI* addRectFilledMultiColor)(DrawList* drawList,
const carb::Float2& a,
const carb::Float2& b,
uint32_t colUprLeft,
uint32_t colUprRight,
uint32_t colBotRight,
uint32_t colBotLeft);
/**
* Adds a quad to the draw list.
* Default: thickness = 1.0f.
*/
void(CARB_ABI* addQuad)(DrawList* drawList,
const carb::Float2& a,
const carb::Float2& b,
const carb::Float2& c,
const carb::Float2& d,
uint32_t col,
float thickness);
/**
* Adds a filled quad to the draw list.
*/
void(CARB_ABI* addQuadFilled)(DrawList* drawList,
const carb::Float2& a,
const carb::Float2& b,
const carb::Float2& c,
const carb::Float2& d,
uint32_t col);
/**
* Adds a triangle to the draw list.
* Defaults: thickness = 1.0f.
*/
void(CARB_ABI* addTriangle)(DrawList* drawList,
const carb::Float2& a,
const carb::Float2& b,
const carb::Float2& c,
uint32_t col,
float thickness);
/**
* Adds a filled triangle to the draw list.
*/
void(CARB_ABI* addTriangleFilled)(
DrawList* drawList, const carb::Float2& a, const carb::Float2& b, const carb::Float2& c, uint32_t col);
/**
* Adds a circle to the draw list.
* Defaults: numSegments = 12, thickness = 1.0f.
*/
void(CARB_ABI* addCircle)(
DrawList* drawList, const carb::Float2& centre, float radius, uint32_t col, int32_t numSegments, float thickness);
/**
* Adds a filled circle to the draw list.
* Defaults: numSegments = 12, thickness = 1.0f.
*/
void(CARB_ABI* addCircleFilled)(
DrawList* drawList, const carb::Float2& centre, float radius, uint32_t col, int32_t numSegments);
/**
* Adds text to the draw list.
*/
void(CARB_ABI* addText)(
DrawList* drawList, const carb::Float2& pos, uint32_t col, const char* textBegin, const char* textEnd);
/**
* Adds text to the draw list.
* Defaults: textEnd = nullptr, wrapWidth = 0.f, cpuFineClipRect = nullptr.
*/
void(CARB_ABI* addTextEx)(DrawList* drawList,
const Font* font,
float fontSize,
const carb::Float2& pos,
uint32_t col,
const char* textBegin,
const char* textEnd,
float wrapWidth,
const carb::Float4* cpuFineClipRect);
/**
* Adds an image to the draw list.
*/
void(CARB_ABI* addImage)(DrawList* drawList,
TextureId textureId,
const carb::Float2& a,
const carb::Float2& b,
const carb::Float2& uvA,
const carb::Float2& uvB,
uint32_t col);
/**
* Adds an image quad to the draw list.
* defaults: uvA = (0, 0), uvB = (1, 0), uvC = (1, 1), uvD = (0, 1), col = 0xFFFFFFFF.
*/
void(CARB_ABI* addImageQuad)(DrawList* drawList,
TextureId textureId,
const carb::Float2& a,
const carb::Float2& b,
const carb::Float2& c,
const carb::Float2& d,
const carb::Float2& uvA,
const carb::Float2& uvB,
const carb::Float2& uvC,
const carb::Float2& uvD,
uint32_t col);
/**
* Adds an rounded image to the draw list.
* defaults: roundingCorners = kDrawCornerFlagAll
*/
void(CARB_ABI* addImageRounded)(DrawList* drawList,
TextureId textureId,
const carb::Float2& a,
const carb::Float2& b,
const carb::Float2& uvA,
const carb::Float2& uvB,
uint32_t col,
float rounding,
DrawCornerFlags roundingCorners);
/**
* Adds a polygon line to the draw list.
*/
void(CARB_ABI* addPolyline)(DrawList* drawList,
const carb::Float2* points,
const int32_t numPoints,
uint32_t col,
bool closed,
float thickness);
/**
* Adds a filled convex polygon to draw list.
* Note: Anti-aliased filling requires points to be in clockwise order.
*/
void(CARB_ABI* addConvexPolyFilled)(DrawList* drawList,
const carb::Float2* points,
const int32_t numPoints,
uint32_t col);
/**
* Adds a Bezier curve to draw list.
* defaults: numSegments = 0.
*/
void(CARB_ABI* addBezierCurve)(DrawList* drawList,
const carb::Float2& pos0,
const carb::Float2& cp0,
const carb::Float2& cp1,
const carb::Float2& pos1,
uint32_t col,
float thickness,
int32_t numSegments);
/**
* Creates a ListClipper to clip large list of items.
*
* @param itemsCount Number of items to clip. Use INT_MAX if you don't know how many items you have (in which case
* the cursor won't be advanced in the final step)
* @param float itemsHeight Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance
* between your items, typically getTextLineHeightWithSpacing() or getFrameHeightWithSpacing().
*
* @return returns the created ListClipper instance.
*/
ListClipper*(CARB_ABI* createListClipper)(int32_t itemsCount, float itemsHeight);
/**
* Call until it returns false. The displayStart/displayEnd fields will be set and you can process/draw those items.
*
* @param listClipper The listClipper instance to advance.
*/
bool(CARB_ABI* stepListClipper)(ListClipper* listClipper);
/**
* Destroys a listClipper instance.
*
* @param listClipper The listClipper instance to destroy.
*/
void(CARB_ABI* destroyListClipper)(ListClipper* listClipper);
/**
* Feed the keyboard event into the simplegui.
*
* @param ctx The context to be fed input event to.
* @param event Keyboard event description.
*/
bool(CARB_ABI* feedKeyboardEvent)(Context* ctx, const input::KeyboardEvent& event);
/**
* Feed the mouse event into the simplegui.
*
* @param ctx The context to be fed input event to.
* @param event Mouse event description.
*/
bool(CARB_ABI* feedMouseEvent)(Context* ctx, const input::MouseEvent& event);
/**
* Walks all of the currently loaded fonts and calls a callback for each.
* @param func The function to call for each loaded font.
* @param user The user data to pass to \p func.
*/
void(CARB_ABI* enumerateFonts)(FontEnumFn func, void* user);
/**
* Returns the name of a loaded font.
* @param font The font to retrieve the name of.
* @returns The font name, or "<unknown>" if not known.
*/
const char*(CARB_ABI* getFontName)(const Font* font);
/**
* Returns the default font for the current context.
* @returns The default font for the current context.
*/
Font*(CARB_ABI* getDefaultFont)();
/**
* Sets the default font for the current context.
* @param font The font to use as the default.
* @returns The previous default font.
*/
Font*(CARB_ABI* setDefaultFont)(Font* font);
};
inline void ISimpleGui::sameLine()
{
sameLineEx(0, -1.0f);
}
inline bool ISimpleGui::button(const char* label)
{
return buttonEx(label, { 0, 0 });
}
} // namespace simplegui
} // namespace carb
| 92,149 | C | 34.144928 | 125 | 0.588373 |
omniverse-code/kit/include/carb/simplegui/SimpleGuiTypes.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief carb.simplegui type definitions.
#pragma once
#include "../Types.h"
namespace carb
{
//! Namespace for Carbonite Input system.
namespace input
{
struct Keyboard;
struct Mouse;
struct Gamepad;
struct KeyboardEvent;
struct MouseEvent;
} // namespace input
//! Namespace for Carbonite Windowing system.
namespace windowing
{
struct Window;
}
namespace simplegui
{
//! An opaque type representing a SimpleGui "context," or instance of a GUI.
struct Context;
//! An opaque type representing a SimpleGui font.
struct Font;
//! An opaque type returned by ISimpleGui::dockBuilderGetNode().
struct DockNode;
/**
* Defines a descriptor for simplegui context.
*/
struct ContextDesc
{
Float2 displaySize; //!< The display size.
windowing::Window* window; //!< The Window to use.
input::Keyboard* keyboard; //!< The Keyboard to listen for events. Can be nullptr.
input::Mouse* mouse; //!< The Mouse to listen for events. Can be nullptr.
input::Gamepad* gamepad; //!< The Gamepad to listen for events. Can be nullptr.
};
/**
* Key modifiers returned by ISimpleGui::getKeyModifiers().
*/
typedef uint32_t KeyModifiers;
const KeyModifiers kKeyModifierNone = 0; //!< Indicates no key modifiers.
const KeyModifiers kKeyModifierCtrl = 1 << 0; //!< Indicates CTRL is held.
const KeyModifiers kKeyModifierShift = 1 << 1; //!< Indicates SHIFT is held.
const KeyModifiers kKeyModifierAlt = 1 << 2; //!< Indicates ALT is held.
const KeyModifiers kKeyModifierSuper = 1 << 3; //!< Indicates a "super key" is held (Cmd/Windows/etc.).
/**
* Defines window flags for simplegui::begin()
*/
typedef uint32_t WindowFlags;
const WindowFlags kWindowFlagNone = 0; //!< Indicates the absence of all other window flags.
const WindowFlags kWindowFlagNoTitleBar = 1 << 0; //!< Window Flag to disable the title bar.
const WindowFlags kWindowFlagNoResize = 1 << 1; //!< Window Flag to disable user resizing with the lower-right grip.
const WindowFlags kWindowFlagNoMove = 1 << 2; //!< Window Flag to disable user moving the window.
const WindowFlags kWindowFlagNoScrollbar = 1 << 3; //!< Window Flag to disable user moving the window.
const WindowFlags kWindowFlagNoScrollWithMouse = 1 << 4; //!< Window Flag to disable user vertically scrolling with
//!< mouse wheel. On child window, mouse wheel will be
//!< forwarded to the parent unless NoScrollbar is also set..
const WindowFlags kWindowFlagNoCollapse = 1 << 5; //!< Window Flag to disable user collapsing window by double-clicking
//!< on it.
const WindowFlags kWindowFlagAlwaysAutoResize = 1 << 6; //!< Window Flag to resize every window to its content every
//!< frame.
const WindowFlags kWindowFlagNoBackground = 1 << 7; //!< Window Flag to disable drawing background color (WindowBg,
//!< etc.) and outside border. Similar as using
//!< SetNextWindowBgAlpha(0.0f).
const WindowFlags kWindowFlagNoSavedSettings = 1 << 8; //!< Window Flag to never load/save settings in .ini file
const WindowFlags kWindowFlagNoMouseInputs = 1 << 9; //!< Window Flag to disable catching mouse, hovering test with pass
//!< through.
const WindowFlags kWindowFlagMenuBar = 1 << 10; //!< Window Flag to state that this has a menu-bar.
const WindowFlags kWindowFlagHorizontalScrollbar = 1 << 11; //!< Window Flag to allow horizontal scrollbar to appear
//!< (off by default). You may use
//!< `SetNextWindowContentSize(Float2(width,0.0f))`, prior
//!< to calling Begin() to specify width.
const WindowFlags kWindowFlagNoFocusOnAppearing = 1 << 12; //!< Window Flag to disable taking focus when transitioning
//!< from hidden to visible state.
const WindowFlags kWindowFlagNoBringToFrontOnFocus = 1 << 13; //!< Window Flag to disable bringing window to front when
//!< taking focus. (Ex. clicking on it or programmatically
//!< giving it focus).
const WindowFlags kWindowFlagAlwaysVerticalScrollbar = 1 << 14; //!< Window Flag to always show vertical scrollbar (even
//!< if content Size.y < Size.y).
const WindowFlags kWindowFlagAlwaysHorizontalScrollbar = 1 << 15; //!< Window Flag to always show horizontal scrollbar
//!< (even if content Size.x < Size.x).
const WindowFlags kWindowFlagAlwaysUseWindowPadding = 1 << 16; //!< Window Flag to ensure child windows without border
//!< uses style.WindowPadding. Ignored by default for
//!< non-bordered child windows, because more convenient.
const WindowFlags kWindowFlagNoNavInputs = 1 << 18; //!< No gamepad/keyboard navigation within the window
const WindowFlags kWindowFlagNoNavFocus = 1 << 19; //!< No focusing toward this window with gamepad/keyboard navigation
//!< (e.g. skipped by CTRL+TAB)
const WindowFlags kWindowFlagUnsavedDocument = 1 << 20; //!< Append '*' to title without affecting the ID, as a
//!< convenience to avoid using the ### operator. When used in a
//!< tab/docking context, tab is selected on closure and closure
//!< is deferred by one frame to allow code to cancel the
//!< closure (with a confirmation popup, etc.) without flicker.
const WindowFlags kWindowFlagNoDocking = 1 << 21; //!< Disable docking of this window
//! Special composed Window Flag to disable navigation.
const WindowFlags kWindowFlagNoNav = kWindowFlagNoNavInputs | kWindowFlagNoNavFocus;
//! Special composed Window Flag to disable all decorative elements.
const WindowFlags kWindowFlagNoDecoration =
kWindowFlagNoTitleBar | kWindowFlagNoResize | kWindowFlagNoScrollbar | kWindowFlagNoCollapse;
//! Special composed Window Flag to disable input.
const WindowFlags kWindowFlagNoInput = kWindowFlagNoMouseInputs | kWindowFlagNoNavInputs | kWindowFlagNoNavFocus;
/**
* Defines item flags for simplegui::pushItemFlags().
*
* Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first
* Begin().
*/
typedef uint32_t ItemFlags;
const ItemFlags kItemFlagDefault = 0; //!< Absence of other item flags.
const ItemFlags kItemFlagsNoTabStop = 1 << 0; //!< No tab stop.
const ItemFlags kItemFlagButtonRepeat = 1 << 1; //!< Button repeat.
const ItemFlags kItemFlagDisabled = 1 << 2; //!< Disable interactions.
const ItemFlags kItemFlagNoNav = 1 << 3; //!< No Navigation
const ItemFlags kItemFlagNoNavDefaultFocus = 1 << 4; //!< No Navigation Default Focus.
const ItemFlags kItemFlagSelectableDontClosePopup = 1 << 5; //!< MenuItem/Selectable() automatically closes current
//!< Popup window.
/**
* Defines input text flags for simplegui::inputText()
*/
typedef uint32_t InputTextFlags;
const InputTextFlags kInputTextFlagNone = 0; //!< Absence of other input text flags.
const InputTextFlags kInputTextFlagCharsDecimal = 1 << 0; //!< Allow `0123456789.+-*/`
const InputTextFlags kInputTextFlagCharsHexadecimal = 1 << 1; //!< Allow `0123456789ABCDEFabcdef`
const InputTextFlags kInputTextFlagCharsUppercase = 1 << 2; //!< Turn `a..z` into `A..Z`
const InputTextFlags kInputTextFlagCharsNoBlank = 1 << 3; //!< Filter out spaces, tabs
const InputTextFlags kInputTextFlagAutoSelectAll = 1 << 4; //!< Select entire text when first taking mouse focus
const InputTextFlags kInputTextFlagEnterReturnsTrue = 1 << 5; //!< Return 'true' when Enter is pressed (as opposed to
//!< when the value was modified)
const InputTextFlags kInputTextFlagCallbackCompletion = 1 << 6; //!< Call user function on pressing TAB (for completion
//!< handling)
const InputTextFlags kInputTextFlagCallbackHistory = 1 << 7; //!< Call user function on pressing Up/Down arrows (for
//!< history handling)
const InputTextFlags kInputTextFlagCallbackAlways = 1 << 8; //!< Call user function every time. User code may query
//!< cursor position, modify text buffer.
const InputTextFlags kInputTextFlagCallbackCharFilter = 1 << 9; //!< Call user function to filter character. Modify
//!< data->EventChar to replace/filter input, or return
//!< 1 to discard character.
const InputTextFlags kInputTextFlagAllowTabInput = 1 << 10; //!< Pressing TAB input a `\t` character into the text field
const InputTextFlags kInputTextFlagCtrlEnterForNewLine = 1 << 11; //!< In multi-line mode, unfocus with Enter, add new
//!< line with Ctrl+Enter (default is opposite:
//!< unfocus with Ctrl+Enter, add line with Enter).
const InputTextFlags kInputTextFlagNoHorizontalScroll = 1 << 12; //!< Disable following the cursor horizontally
const InputTextFlags kInputTextFlagAlwaysInsertMode = 1 << 13; //!< Insert mode
const InputTextFlags kInputTextFlagReadOnly = 1 << 14; //!< Read-only mode
const InputTextFlags kInputTextFlagPassword = 1 << 15; //!< Password mode, display all characters as '*'
const InputTextFlags kInputTextFlagNoUndoRedo = 1 << 16; //!< Disable undo/redo. Note that input text owns the text data
//!< while active, if you want to provide your own undo/redo
//!< stack you need e.g. to call ClearActiveID().
const InputTextFlags kInputTextFlagCharsScientific = 1 << 17; //!< Allow `0123456789.+-*/eE` (Scientific notation input)
const InputTextFlags kInputTextFlagCallbackResize = 1 << 18; //!< Callback on buffer capacity changes request (beyond
//!< `buf_size` parameter value)
/**
* Defines tree node flags to be used in simplegui::collapsingHeader(), simplegui::treeNodeEx()
*/
typedef uint32_t TreeNodeFlags;
const TreeNodeFlags kTreeNodeFlagNone = 0; //!< Absence of other tree node flags.
const TreeNodeFlags kTreeNodeFlagSelected = 1 << 0; //!< Draw as selected
const TreeNodeFlags kTreeNodeFlagFramed = 1 << 1; //!< Full colored frame (e.g. for CollapsingHeader)
const TreeNodeFlags kTreeNodeFlagAllowItemOverlap = 1 << 2; //!< Hit testing to allow subsequent widgets to overlap this
//!< one
const TreeNodeFlags kTreeNodeFlagNoTreePushOnOpen = 1 << 3; //!< Don't do a TreePush() when open (e.g. for
//!< CollapsingHeader) = no extra indent nor pushing on ID
//!< stack
const TreeNodeFlags kTreeNodeFlagNoAutoOpenOnLog = 1 << 4; //!< Don't automatically and temporarily open node when
//!< Logging is active (by default logging will automatically
//!< open tree nodes)
const TreeNodeFlags kTreeNodeFlagDefaultOpen = 1 << 5; //!< Default node to be open
const TreeNodeFlags kTreeNodeFlagOpenOnDoubleClick = 1 << 6; //!< Need double-click to open node
const TreeNodeFlags kTreeNodeFlagOpenOnArrow = 1 << 7; //!< Only open when clicking on the arrow part. If
//!< kTreeNodeFlagOpenOnDoubleClick is also set, single-click
//!< arrow or double-click all box to open.
const TreeNodeFlags kTreeNodeFlagLeaf = 1 << 8; //!< No collapsing, no arrow (use as a convenience for leaf nodes).
const TreeNodeFlags kTreeNodeFlagBullet = 1 << 9; //!< Display a bullet instead of arrow
const TreeNodeFlags kTreeNodeFlagFramePadding = 1 << 10; //!< Use FramePadding (even for an unframed text node) to
//!< vertically align text baseline to regular widget
const TreeNodeFlags kTreeNodeFlagNavLeftJumpsBackHere = 1 << 13; //!< (WIP) Nav: left direction may move to this
//!< TreeNode() from any of its child (items submitted
//!< between TreeNode and TreePop)
//! Composed flag indicating collapsing header.
const TreeNodeFlags kTreeNodeFlagCollapsingHeader =
kTreeNodeFlagFramed | kTreeNodeFlagNoTreePushOnOpen | kTreeNodeFlagNoAutoOpenOnLog;
/**
* Defines flags to be used in simplegui::selectable()
*/
typedef uint32_t SelectableFlags;
const SelectableFlags kSelectableFlagNone = 0; //!< Absence of other selectable flags.
const SelectableFlags kSelectableFlagDontClosePopups = 1 << 0; //!< Clicking this don't close parent popup window
const SelectableFlags kSelectableFlagSpanAllColumns = 1 << 1; //!< Selectable frame can span all columns (text will
//!< still fit in current column)
const SelectableFlags kSelectableFlagAllowDoubleClick = 1 << 2; //!< Generate press events on double clicks too
const SelectableFlags kSelectableFlagDisabled = 1 << 3; //!< Cannot be selected, display grayed out text
/**
* Defines flags to be used in simplegui::beginCombo()
*/
typedef uint32_t ComboFlags;
const ComboFlags kComboFlagNone = 0; //!< Absence of other combo flags.
const ComboFlags kComboFlagPopupAlignLeft = 1 << 0; //!< Align the popup toward the left by default
const ComboFlags kComboFlagHeightSmall = 1 << 1; //!< Max ~4 items visible. Tip: If you want your combo popup to be a
//!< specific size you can use SetNextWindowSizeConstraints() prior to
//!< calling BeginCombo()
const ComboFlags kComboFlagHeightRegular = 1 << 2; //!< Max ~8 items visible (default)
const ComboFlags kComboFlagHeightLarge = 1 << 3; //!< Max ~20 items visible
const ComboFlags kComboFlagHeightLargest = 1 << 4; //!< As many fitting items as possible
const ComboFlags kComboFlagNoArrowButton = 1 << 5; //!< Display on the preview box without the square arrow button
const ComboFlags kComboFlagNoPreview = 1 << 6; //!< Display only a square arrow button
const ComboFlags kComboFlagHeightMask =
kComboFlagHeightSmall | kComboFlagHeightRegular | kComboFlagHeightLarge | kComboFlagHeightLargest; //!< Composed
//!< flag.
/**
* Defines flags to be used in simplegui::beginTabBar()
*/
typedef uint32_t TabBarFlags;
const TabBarFlags kTabBarFlagNone = 0; //!< Absence of other tab bar flags.
const TabBarFlags kTabBarFlagReorderable = 1 << 0; //!< Allow manually dragging tabs to re-order them + New tabs are
//!< appended at the end of list
const TabBarFlags kTabBarFlagAutoSelectNewTabs = 1 << 1; //!< Automatically select new tabs when they appear
const TabBarFlags kTabBarFlagTabListPopupButton = 1 << 2; //!< Tab list popup button.
const TabBarFlags kTabBarFlagNoCloseWithMiddleMouseButton = 1 << 3; //!< Disable behavior of closing tabs (that are
//!< submitted with `p_open != NULL`) with middle
//!< mouse button. You can still repro this behavior
//!< on user's side with if (IsItemHovered() &&
//!< IsMouseClicked(2)) `*p_open = false`.
const TabBarFlags kTabBarFlagNoTabListScrollingButtons = 1 << 4; //!< No scrolling buttons.
const TabBarFlags kTabBarFlagNoTooltip = 1 << 5; //!< Disable tooltips when hovering a tab
const TabBarFlags kTabBarFlagFittingPolicyResizeDown = 1 << 6; //!< Resize tabs when they don't fit
const TabBarFlags kTabBarFlagFittingPolicyScroll = 1 << 7; //!< Add scroll buttons when tabs don't fit
const TabBarFlags kTabBarFlagFittingPolicyMask =
kTabBarFlagFittingPolicyResizeDown | kTabBarFlagFittingPolicyScroll; //!< Composed flag.
const TabBarFlags kTabBarFlagFittingPolicyDefault = kTabBarFlagFittingPolicyResizeDown; //!< Composed flag.
/**
* Defines flags to be used in simplegui::beginTabItem()
*/
typedef uint32_t TabItemFlags;
const TabItemFlags kTabItemFlagNone = 0; //!< Absence of other tab item flags.
const TabItemFlags kTabItemFlagUnsavedDocument = 1 << 0; //!< Append '*' to title without affecting the ID; as a
//!< convenience to avoid using the ### operator. Also: tab is
//!< selected on closure and closure is deferred by one frame
//!< to allow code to undo it without flicker.
const TabItemFlags kTabItemFlagSetSelected = 1 << 1; //!< Trigger flag to programmatically make the tab selected when
//!< calling BeginTabItem()
const TabItemFlags kTabItemFlagNoCloseWithMiddleMouseButton = 1 << 2; //!< Disable behavior of closing tabs (that are
//!< submitted with `p_open != NULL`) with middle
//!< mouse button. You can still repro this
//!< behavior on user's side with if
//!< (IsItemHovered() && IsMouseClicked(2))
//!< `*p_open = false`.
const TabItemFlags kTabItemFlagNoPushId = 1 << 3; //!< Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem()
/**
* Defines flags to be used in simplegui::dockSpace()
*/
typedef uint32_t DockNodeFlags;
const DockNodeFlags kDockNodeFlagNone = 0; //!< Absence of other dock node flags.
const DockNodeFlags kDockNodeFlagKeepAliveOnly = 1 << 0; //!< Don't display the dockspace node but keep it alive.
//!< Windows docked into this dockspace node won't be undocked.
// const DockNodeFlags kDockNodeFlagNoCentralNode = 1 << 1; //!< Disable Central Node (the node which can stay empty)
const DockNodeFlags kDockNodeFlagNoDockingInCentralNode = 1 << 2; //!< Disable docking inside the Central Node, which
//!< will be always kept empty.
const DockNodeFlags kDockNodeFlagPassthruCentralNode = 1 << 3; //!< Enable passthru dockspace: 1) DockSpace() will
//!< render a ImGuiCol_WindowBg background covering
//!< everything excepted the Central Node when empty.
//!< Meaning the host window should probably use
//!< SetNextWindowBgAlpha(0.0f) prior to Begin() when
//!< using this. 2) When Central Node is empty: let
//!< inputs pass-through + won't display a DockingEmptyBg
//!< background. See demo for details.
const DockNodeFlags kDockNodeFlagNoSplit = 1 << 4; //!< Disable splitting the node into smaller nodes. Useful e.g. when
//!< embedding dockspaces into a main root one (the root one may have
//!< splitting disabled to reduce confusion)
const DockNodeFlags kDockNodeFlagNoResize = 1 << 5; //!< Disable resizing child nodes using the splitter/separators.
//!< Useful with programmatically setup dockspaces.
const DockNodeFlags kDockNodeFlagAutoHideTabBar = 1 << 6; //!< Tab bar will automatically hide when there is a single
//!< window in the dock node.
/**
* Defines flags to be used in simplegui::isWindowFocused()
*/
typedef uint32_t FocusedFlags;
const FocusedFlags kFocusedFlagNone = 0; //!< Absence of other focused flags.
const FocusedFlags kFocusedFlagChildWindows = 1 << 0; //!< IsWindowFocused(): Return true if any children of the window
//!< is focused
const FocusedFlags kFocusedFlagRootWindow = 1 << 1; //!< IsWindowFocused(): Test from root window (top most parent of
//!< the current hierarchy)
const FocusedFlags kFocusedFlagAnyWindow = 1 << 2; //!< IsWindowFocused(): Return true if any window is focused
const FocusedFlags kFocusedFlagRootAndChildWindows = kFocusedFlagRootWindow | kFocusedFlagChildWindows; //!< Composed
//!< flag.
/**
* Defines flags to be used in simplegui::isItemHovered(), simplegui::isWindowHovered()
*/
typedef uint32_t HoveredFlags;
const HoveredFlags kHoveredFlagNone = 0; //!< Return true if directly over the item/window, not obstructed by another
//!< window, not obstructed by an active popup or modal blocking inputs under
//!< them.
const HoveredFlags kHoveredFlagChildWindows = 1 << 0; //!< IsWindowHovered() only: Return true if any children of the
//!< window is hovered
const HoveredFlags kHoveredFlagRootWindow = 1 << 1; //!< IsWindowHovered() only: Test from root window (top most parent
//!< of the current hierarchy)
const HoveredFlags kHoveredFlagAnyWindow = 1 << 2; //!< IsWindowHovered() only: Return true if any window is hovered
const HoveredFlags kHoveredFlagAllowWhenBlockedByPopup = 1 << 3; //!< Return true even if a popup window is normally
//!< blocking access to this item/window
const HoveredFlags kHoveredFlagAllowWhenBlockedByActiveItem = 1 << 5; //!< Return true even if an active item is
//!< blocking access to this item/window. Useful
//!< for Drag and Drop patterns.
const HoveredFlags kHoveredFlagAllowWhenOverlapped = 1 << 6; //!< Return true even if the position is overlapped by
//!< another window
const HoveredFlags kHoveredFlagAllowWhenDisabled = 1 << 7; //!< Return true even if the item is disabled
const HoveredFlags kHoveredFlagRectOnly = kHoveredFlagAllowWhenBlockedByPopup | kHoveredFlagAllowWhenBlockedByActiveItem |
kHoveredFlagAllowWhenOverlapped; //!< Composed flag.
const HoveredFlags kHoveredFlagRootAndChildWindows = kHoveredFlagRootWindow | kHoveredFlagChildWindows; //!< Composed
//!< flag.
/**
* Defines flags to be used in simplegui::beginDragDropSource(), simplegui::acceptDragDropPayload()
*/
typedef uint32_t DragDropFlags;
const DragDropFlags kDragDropFlagNone = 0; //!< Absence of other drag/drop flags.
// BeginDragDropSource() flags
const DragDropFlags kDragDropFlagSourceNoPreviewTooltip = 1 << 0; //!< By default, a successful call to
//!< BeginDragDropSource opens a tooltip so you can
//!< display a preview or description of the source
//!< contents. This flag disable this behavior.
const DragDropFlags kDragDropFlagSourceNoDisableHover = 1 << 1; //!< By default, when dragging we clear data so that
//!< IsItemHovered() will return true, to avoid
//!< subsequent user code submitting tooltips. This flag
//!< disable this behavior so you can still call
//!< IsItemHovered() on the source item.
const DragDropFlags kDragDropFlagSourceNoHoldToOpenOthers = 1 << 2; //!< Disable the behavior that allows to open tree
//!< nodes and collapsing header by holding over
//!< them while dragging a source item.
const DragDropFlags kDragDropFlagSourceAllowNullID = 1 << 3; //!< Allow items such as Text(), Image() that have no
//!< unique identifier to be used as drag source, by
//!< manufacturing a temporary identifier based on their
//!< window-relative position. This is extremely unusual
//!< within the simplegui ecosystem and so we made it
//!< explicit.
const DragDropFlags kDragDropFlagSourceExtern = 1 << 4; //!< External source (from outside of simplegui), won't attempt
//!< to read current item/window info. Will always return true.
//!< Only one Extern source can be active simultaneously.
const DragDropFlags kDragDropFlagSourceAutoExpirePayload = 1 << 5; //!< Automatically expire the payload if the source
//!< cease to be submitted (otherwise payloads are
//!< persisting while being dragged)
// AcceptDragDropPayload() flags
const DragDropFlags kDragDropFlagAcceptBeforeDelivery = 1 << 10; //!< AcceptDragDropPayload() will returns true even
//!< before the mouse button is released. You can then
//!< call IsDelivery() to test if the payload needs to
//!< be delivered.
const DragDropFlags kDragDropFlagAcceptNoDrawDefaultRect = 1 << 11; //!< Do not draw the default highlight rectangle
//!< when hovering over target.
const DragDropFlags kDragDropFlagAcceptNoPreviewTooltip = 1 << 12; //!< Request hiding the BeginDragDropSource tooltip
//!< from the BeginDragDropTarget site.
const DragDropFlags kDragDropFlagAcceptPeekOnly =
kDragDropFlagAcceptBeforeDelivery | kDragDropFlagAcceptNoDrawDefaultRect; //!< For peeking ahead and inspecting the
//!< payload before delivery.
/**
* A primary data type
*/
enum class DataType
{
eS8, //!< char
eU8, //!< unsigned char
eS16, //!< short
eU16, //!< unsigned short
eS32, //!< int
eU32, //!< unsigned int
eS64, //!< long long, __int64
eU64, //!< unsigned long long, unsigned __int64
eFloat, //!< float
eDouble, //!< double
eCount //!< Number of items.
};
/**
* A cardinal direction
*/
enum class Direction
{
eNone = -1, //!< None
eLeft = 0, //!< Left
eRight = 1, //!< Right
eUp = 2, //<! Up
eDown = 3, //!< Down
eCount //!< Number of items.
};
/**
* Enumeration for pushStyleColor() / popStyleColor()
*/
enum class StyleColor
{
eText, //!< Text
eTextDisabled, //!< Disabled text
eWindowBg, //!< Background of normal windows
eChildBg, //!< Background of child windows
ePopupBg, //!< Background of popups, menus, tooltips windows
eBorder, //!< Border
eBorderShadow, //!< Border Shadow
eFrameBg, //!< Background of checkbox, radio button, plot, slider, text input
eFrameBgHovered, //!< Hovered background
eFrameBgActive, //!< Active background
eTitleBg, //!< Title background
eTitleBgActive, //!< Active title background
eTitleBgCollapsed, //!< Collapsed title background
eMenuBarBg, //!< Menu bar background
eScrollbarBg, //!< Scroll bar background
eScrollbarGrab, //!< Grabbed scroll bar
eScrollbarGrabHovered, //!< Hovered grabbed scroll bar
eScrollbarGrabActive, //!< Active grabbed scroll bar
eCheckMark, //!< Check box
eSliderGrab, //!< Grabbed slider
eSliderGrabActive, //!< Active grabbed slider
eButton, //!< Button
eButtonHovered, //!< Hovered button
eButtonActive, //!< Active button
eHeader, //!< Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem
eHeaderHovered, //!< Hovered header
eHeaderActive, //!< Active header
eSeparator, //!< Separator
eSeparatorHovered, //!< Hovered separator
eSeparatorActive, //!< Active separator
eResizeGrip, //!< Resize grip
eResizeGripHovered, //!< Hovered resize grip
eResizeGripActive, //!< Active resize grip
eTab, //!< Tab
eTabHovered, //!< Hovered tab
eTabActive, //!< Active tab
eTabUnfocused, //!< Unfocused tab
eTabUnfocusedActive, //!< Active unfocused tab
eDockingPreview, //!< Preview overlay color when about to docking something
eDockingEmptyBg, //!< Background color for empty node (e.g. CentralNode with no window docked into it)
ePlotLines, //!< Plot lines
ePlotLinesHovered, //!< Hovered plot lines
ePlotHistogram, //!< Histogram
ePlotHistogramHovered, //!< Hovered histogram
eTableHeaderBg, //!< Table header background
eTableBorderStrong, //!< Table outer and header borders (prefer using Alpha=1.0 here)
eTableBorderLight, //!< Table inner borders (prefer using Alpha=1.0 here)
eTableRowBg, //!< Table row background (even rows)
eTableRowBgAlt, //!< Table row background (odd rows)
eTextSelectedBg, //!< Selected text background
eDragDropTarget, //!< Drag/drop target
eNavHighlight, //!< Gamepad/keyboard: current highlighted item
eNavWindowingHighlight, //!< Highlight window when using CTRL+TAB
eNavWindowingDimBg, //!< Darken/colorize entire screen behind the CTRL+TAB window list, when active
eModalWindowDimBg, //!< Darken/colorize entire screen behind a modal window, when one is active
eWindowShadow, //!< Window shadows
#ifdef IMGUI_NVIDIA
eCustomChar, //!< Color to render custom char
#endif
eCount //!< Number of items
};
/**
* Defines style variable (properties) that can be used
* to temporarily modify UI styles.
*
* The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. During
* initialization, feel free to just poke into ImGuiStyle directly.
*
* @see pushStyleVarFloat
* @see pushStyleVarFloat2
* @see popStyleVar
*/
enum class StyleVar
{
eAlpha, //!< (float, Style::alpha)
eWindowPadding, //!< (Float2, Style::windowPadding)
eWindowRounding, //!< (float, Style::windowRounding)
eWindowBorderSize, //!< (float, Style::windowBorderSize)
eWindowMinSize, //!< (Float2, Style::windowMinSize)
eWindowTitleAlign, //!< (Float2, Style::windowTitleAlign)
eChildRounding, //!< (float, Style::childRounding)
eChildBorderSize, //!< (float, Style::childBorderSize)
ePopupRounding, //!< (float, Style::popupRounding)
ePopupBorderSize, //!< (float, Style::popupBorderSize)
eFramePadding, //!< (Float2, Style::framePadding)
eFrameRounding, //!< (float, Style::frameRounding)
eFrameBorderSize, //!< (float, Style::frameBorderSize)
eItemSpacing, //!< (Float2, Style::itemSpacing)
eItemInnerSpacing, //!< (Float2, Style::itemInnerSpacing)
eIndentSpacing, //!< (float, Style::indentSpacing)
eCellPadding, //!< (Float2, Style::cellPadding)
eScrollbarSize, //!< (float, Style::scrollbarSize)
eScrollbarRounding, //!< (float, Style::scrollbarRounding)
eGrabMinSize, //!< (float, Style::grabMinSize)
eGrabRounding, //!< (float, Style::grabRounding)
eTabRounding, //!< (float, Style::tabRounding)
eButtonTextAlign, //!< (Float2, Style::buttonTextAlign)
eSelectableTextAlign, //!< (Float2, Style::selectableTextAlign)
#ifdef IMGUI_NVIDIA
eDockSplitterSize, //!< (float, Style::dockSplitterSize)
#endif
eCount //!< Number of items
};
/**
* Defines flags to be used in colorEdit3() / colorEdit4() / colorPicker3() / colorPicker4() / colorButton()
*/
typedef uint32_t ColorEditFlags;
const ColorEditFlags kColorEditFlagNone = 0; //!< Absence of other color edit flags.
const ColorEditFlags kColorEditFlagNoAlpha = 1 << 1; //!< ColorEdit, ColorPicker, ColorButton: ignore Alpha component
//!< (read 3 components from the input pointer).
const ColorEditFlags kColorEditFlagNoPicker = 1 << 2; //!< ColorEdit: disable picker when clicking on colored square.
const ColorEditFlags kColorEditFlagNoOptions = 1 << 3; //!< ColorEdit: disable toggling options menu when right-clicking
//!< on inputs/small preview.
const ColorEditFlags kColorEditFlagNoSmallPreview = 1 << 4; //!< ColorEdit, ColorPicker: disable colored square preview
//!< next to the inputs. (e.g. to show only the inputs)
const ColorEditFlags kColorEditFlagNoInputs = 1 << 5; //!< ColorEdit, ColorPicker: disable inputs sliders/text widgets
//!< (e.g. to show only the small preview colored square).
const ColorEditFlags kColorEditFlagNoTooltip = 1 << 6; //!< ColorEdit, ColorPicker, ColorButton: disable tooltip when
//!< hovering the preview.
const ColorEditFlags kColorEditFlagNoLabel = 1 << 7; //!< ColorEdit, ColorPicker: disable display of inline text label
//!< (the label is still forwarded to the tooltip and picker).
const ColorEditFlags kColorEditFlagNoSidePreview = 1 << 8; //!< ColorPicker: disable bigger color preview on right side
//!< of the picker, use small colored square preview instead.
// User Options (right-click on widget to change some of them). You can set application defaults using
// SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user
// choose and/or call SetColorEditOptions() during startup.
const ColorEditFlags kColorEditFlagAlphaBar = 1 << 9; //!< ColorEdit, ColorPicker: show vertical alpha bar/gradient in
//!< picker.
const ColorEditFlags kColorEditFlagAlphaPreview = 1 << 10; //!< ColorEdit, ColorPicker, ColorButton: display preview as
//!< a transparent color over a checkerboard, instead of
//!< opaque.
const ColorEditFlags kColorEditFlagAlphaPreviewHalf = 1 << 11; //!< ColorEdit, ColorPicker, ColorButton: display half
//!< opaque / half checkerboard, instead of opaque.
const ColorEditFlags kColorEditFlagHDR = 1 << 12; //!< (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA
//!< edition (note: you probably want to use ImGuiColorEditFlags_Float
//!< flag as well).
const ColorEditFlags kColorEditFlagRGB = 1 << 13; //!< [Inputs] ColorEdit: choose one among RGB/HSV/HEX. ColorPicker:
//!< choose any combination using RGB/HSV/HEX.
const ColorEditFlags kColorEditFlagHSV = 1 << 14; //!< [Inputs]
const ColorEditFlags kColorEditFlagHEX = 1 << 15; //!< [Inputs]
const ColorEditFlags kColorEditFlagUint8 = 1 << 16; //!< [DataType] ColorEdit, ColorPicker, ColorButton: _display_
//!< values formatted as 0..255.
const ColorEditFlags kColorEditFlagFloat = 1 << 17; //!< [DataType] ColorEdit, ColorPicker, ColorButton: _display_
//!< values formatted as 0.0f..1.0f floats instead of 0..255
//!< integers. No round-trip of value via integers.
const ColorEditFlags kColorEditFlagPickerHueBar = 1 << 18; //!< [PickerMode] // ColorPicker: bar for Hue, rectangle for
//!< Sat/Value.
const ColorEditFlags kColorEditFlagPickerHueWheel = 1 << 19; //!< [PickerMode] // ColorPicker: wheel for Hue, triangle
//!< for Sat/Value.
/**
* Defines DrawCornerFlags.
*/
typedef uint32_t DrawCornerFlags;
const DrawCornerFlags kDrawCornerFlagTopLeft = 1 << 0; //!< Top left
const DrawCornerFlags kDrawCornerFlagTopRight = 1 << 1; //!< Top right
const DrawCornerFlags kDrawCornerFlagBotLeft = 1 << 2; //!< Bottom left
const DrawCornerFlags kDrawCornerFlagBotRight = 1 << 3; //!< Bottom right
const DrawCornerFlags kDrawCornerFlagTop = kDrawCornerFlagTopLeft | kDrawCornerFlagTopRight; //!< Top
const DrawCornerFlags kDrawCornerFlagBot = kDrawCornerFlagBotLeft | kDrawCornerFlagBotRight; //!< Bottom
const DrawCornerFlags kDrawCornerFlagLeft = kDrawCornerFlagTopLeft | kDrawCornerFlagBotLeft; //!< Left
const DrawCornerFlags kDrawCornerFlagRight = kDrawCornerFlagTopRight | kDrawCornerFlagBotRight; //!< Right
const DrawCornerFlags kDrawCornerFlagAll = 0xF; //!< All corners
/**
* Enumeration for GetMouseCursor()
* User code may request binding to display given cursor by calling SetMouseCursor(), which is why we have some cursors
* that are marked unused here
*/
enum class MouseCursor
{
eNone = -1, //!< No mouse cursor.
eArrow = 0, //!< Arrow
eTextInput, //!< When hovering over InputText, etc.
eResizeAll, //!< Unused by simplegui functions
eResizeNS, //!< When hovering over an horizontal border
eResizeEW, //!< When hovering over a vertical border or a column
eResizeNESW, //!< When hovering over the bottom-left corner of a window
eResizeNWSE, //!< When hovering over the bottom-right corner of a window
eHand, //!< Unused by simplegui functions. Use for e.g. hyperlinks
eNotAllowed, //!< When hovering something with disallowed interaction. Usually a crossed circle.
eCount //!< Number of items
};
/**
* Condition for simplegui::setWindow***(), setNextWindow***(), setNextTreeNode***() functions
*/
enum class Condition
{
eAlways = 1 << 0, //!< Set the variable
eOnce = 1 << 1, //!< Set the variable once per runtime session (only the first call with succeed)
eFirstUseEver = 1 << 2, //!< Set the variable if the object/window has no persistently saved data (no entry in .ini
//!< file)
eAppearing = 1 << 3, //!< Set the variable if the object/window is appearing after being hidden/inactive (or the
//!< first time)
};
/**
* Struct with all style variables
*
* You may modify the simplegui::getStyle() main instance during initialization and before newFrame().
* During the frame, use simplegui::pushStyleVar()/popStyleVar() to alter the main style values, and
* simplegui::pushStyleColor()/popStyleColor() for colors.
*/
struct Style
{
float alpha; //!< Global alpha applies to everything in simplegui.
Float2 windowPadding; //!< Padding within a window.
float windowRounding; //!< Radius of window corners rounding. Set to 0.0f to have rectangular windows.
float windowBorderSize; //!< Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are
//!< not well tested and more CPU/GPU costly).
Float2 windowMinSize; //!< Minimum window size. This is a global setting. If you want to constraint individual
//!< windows, use SetNextWindowSizeConstraints().
Float2 windowTitleAlign; //!< Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically
//!< centered.
Direction windowMenuButtonPosition; //!< Side of the collapsing/docking button in the title bar (None/Left/Right).
//!< Defaults to ImGuiDir_Left.
float childRounding; //!< Radius of child window corners rounding. Set to 0.0f to have rectangular windows.
float childBorderSize; //!< Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values
//!< are not well tested and more CPU/GPU costly).
float popupRounding; //!< Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding)
float popupBorderSize; //!< Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other
//!< values are not well tested and more CPU/GPU costly).
Float2 framePadding; //!< Padding within a framed rectangle (used by most widgets).
float frameRounding; //!< Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most
//!< widgets).
float frameBorderSize; //!< Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not
//!< well tested and more CPU/GPU costly).
Float2 itemSpacing; //!< Horizontal and vertical spacing between widgets/lines.
Float2 itemInnerSpacing; //!< Horizontal and vertical spacing between within elements of a composed widget (e.g. a
//!< slider and its label).
Float2 cellPadding; //!< Padding within a table cell
Float2 touchExtraPadding; //!< Expand reactive bounding box for touch-based system where touch position is not
//!< accurate enough. Unfortunately we don't sort widgets so priority on overlap will
//!< always be given to the first widget. So don't grow this too much!
float indentSpacing; //!< Horizontal indentation when e.g. entering a tree node. Generally == (FontSize +
//!< FramePadding.x*2).
float columnsMinSpacing; //!< Minimum horizontal spacing between two columns.
float scrollbarSize; //!< Width of the vertical scrollbar, Height of the horizontal scrollbar.
float scrollbarRounding; //!< Radius of grab corners for scrollbar.
float grabMinSize; //!< Minimum width/height of a grab box for slider/scrollbar.
float grabRounding; //!< Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
float tabRounding; //!< Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
float tabBorderSize; //!< Thickness of border around tabs.
float tabMinWidthForUnselectedCloseButton; //!< Minimum width for close button to appears on an unselected tab when
//!< hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to
//!< never show close button unless selected.
Direction colorButtonPosition; //!< Side of the color button in the ColorEdit4 widget (left/right). Defaults to
//!< ImGuiDir_Right.
Float2 buttonTextAlign; //!< Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for
//!< horizontally+vertically centered.
Float2 selectableTextAlign; //!< Alignment of selectable text when selectable is larger than text. Defaults to
//!< (0.0f, 0.0f) (top-left aligned).
Float2 displayWindowPadding; //!< Window positions are clamped to be visible within the display area by at least
//!< this amount. Only covers regular windows.
Float2 displaySafeAreaPadding; //!< If you cannot see the edge of your screen (e.g. on a TV) increase the safe area
//!< padding. Covers popups/tooltips as well regular windows.
float mouseCursorScale; //!< Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be
//!< removed later.
bool antiAliasedLines; //!< Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU.
bool antiAliasedFill; //!< Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
float curveTessellationTol; //!< Tessellation tolerance when using PathBezierCurveTo() without a specific number of
//!< segments. Decrease for highly tessellated curves (higher quality, more polygons),
//!< increase to reduce quality.
float circleSegmentMaxError; //!< Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or
//!< drawing rounded corner rectangles with no explicit segment count specified.
//!< Decrease for higher quality but more geometry.
float windowShadowSize; //!< Size (in pixels) of window shadows. Set this to zero to disable shadows.
float windowShadowOffsetDist; //!< Offset distance (in pixels) of window shadows from casting window.
float windowShadowOffsetAngle; //!< Offset angle of window shadows from casting window (0.0f = left, 0.5f*PI =
//!< bottom, 1.0f*PI = right, 1.5f*PI = top).
Float4 colors[(size_t)StyleColor::eCount]; //!< Color by style.
#ifdef IMGUI_NVIDIA
float dockSplitterSize; //!< Thickness of border around docking window. Set to 0.0f to no splitter.
uint16_t customCharBegin; //!< Code of first custom char. Custom char will be rendered with ImGuiCol_CustomChar.
//!< 0xFFFF means no custom char.
#endif
//! Constructor.
Style()
{
}
};
/**
* Predefined Style Colors presets.
*/
enum class StyleColorsPreset
{
eNvidiaDark, //!< NVIDIA Dark colors.
eNvidiaLight, //!< NVIDIA Light colors.
eDark, //!< New Dear ImGui style
eLight, //!< Best used with borders and a custom, thicker font
eClassic, //!< Classic Dear ImGui style
eCount //!< Number of items.
};
struct DrawCommand;
struct DrawData;
/**
* User data to identify a texture.
*/
typedef void* TextureId;
/**
* Draw callbacks for advanced uses.
*/
typedef void (*DrawCallback)(const DrawData* drawData, const DrawCommand* cmd);
/**
* Font enumeration function.
*
* A return of \c false stops iteration.
*/
typedef bool (*FontEnumFn)(Font* font, void* user);
/**
* Defines a drawing command.
*/
struct DrawCommand
{
/**
* The number of indices (multiple of 3) to be rendered as triangles.
* The vertices are stored in the callee DrawList::vertexBuffer array,
* indices in IdxBuffer.
*/
uint32_t elementCount;
/**
* The clipping rectangle (x1, y1, x2, y2).
*/
carb::Float4 clipRect;
/**
* User provided texture ID.
*/
TextureId textureId;
/**
* If != NULL, call the function instead of rendering the vertices.
*/
DrawCallback userCallback;
/**
* The draw callback code can access this.
*/
void* userCallbackData;
};
/**
* Defines a vertex used for drawing lists.
*/
struct DrawVertex
{
Float2 position; //!< Position
Float2 texCoord; //!< Texture Coordinate
uint32_t color; //!< Color
};
/**
* Defines a list of draw commands.
*/
struct DrawList
{
uint32_t commandBufferCount; //!< The number of command in the command buffers.
DrawCommand* commandBuffers; //!< Draw commands. (Typically 1 command = 1 GPU draw call)
uint32_t indexBufferSize; //!< The number of index buffers.
uint32_t* indexBuffer; //!< The index buffers. (Each command consumes command)
uint32_t vertexBufferSize; //!< The number of vertex buffers.
DrawVertex* vertexBuffer; //!< The vertex buffers.
};
/**
* Defines the data used for drawing back-ends
*/
struct DrawData
{
uint32_t commandListCount; //!< Number of command lists
DrawList* commandLists; //!< Command lists
uint32_t vertexCount; //!< Count of vertexes.
uint32_t indexCount; //!< Count of indexes.
};
//! SimpleGui-specific definition of a wide character.
typedef unsigned short Wchar;
/**
* Structure defining the configuration for a font.
*/
struct FontConfig
{
void* fontData; //!< TTF/OTF data
int fontDataSize; //!< TTF/OTF data size
bool fontDataOwnedByAtlas; //!< `true` - TTF/OTF data ownership taken by the container ImFontAtlas (will delete
//!< memory itself).
int fontNo; //!< 0 - Index of font within TTF/OTF file
float sizePixels; //!< Size in pixels for rasterizer (more or less maps to the resulting font height).
int oversampleH; //!< 3 - Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on
//!< the Y axis.
int oversampleV; //!< 1 - Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on
//!< the Y axis.
bool pixelSnapH; //!< false - Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel
//!< aligned font with the default font. If enabled, you can set OversampleH/V to 1.
Float2 glyphExtraSpacing; //!< 0, 0 - Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
Float2 glyphOffset; //!< 0, 0 - Offset all glyphs from this font input.
const Wchar* glyphRanges; //!< NULL - Pointer to a user-provided list of Unicode range (2 value per range, values
//!< are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE
//!< FONT IS ALIVE.
float glyphMinAdvanceX; //!< 0 - Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to
//!< enforce mono-space font
float glyphMaxAdvanceX; //!< FLT_MAX - Maximum AdvanceX for glyphs
bool mergeMode; //!< false - Merge into previous ImFont, so you can combine multiple inputs font into one ImFont
//!< (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font
//!< of different heights.
uint32_t rasterizerFlags; //!< 0x00 - Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you
//!< aren't using one.
float rasterizerMultiply; //!< 1.0f - Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be
//!< a good workaround to make them more readable.
char name[40]; //!< (internal) Name (strictly to ease debugging)
Font* dstFont; //!< (internal)
//! Constructor.
FontConfig()
{
fontData = nullptr;
fontDataSize = 0;
fontDataOwnedByAtlas = true;
fontNo = 0;
sizePixels = 0.0f;
oversampleH = 3;
oversampleV = 1;
pixelSnapH = false;
glyphExtraSpacing = Float2{ 0.0f, 0.0f };
glyphOffset = Float2{ 0.0f, 0.0f };
glyphRanges = nullptr;
glyphMinAdvanceX = 0.0f;
glyphMaxAdvanceX = CARB_FLOAT_MAX;
mergeMode = false;
rasterizerFlags = 0x00;
rasterizerMultiply = 1.0f;
memset(name, 0, sizeof(name));
dstFont = nullptr;
}
};
/**
* Structure of a custom rectangle for a font definition.
*/
struct FontCustomRect
{
uint32_t id; //!< [input] User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom
//!< texture data.
uint16_t width; //!< [input] Desired rectangle dimension
uint16_t height; //!< [input] Desired rectangle dimension
uint16_t x; //!< [output] Packed position in Atlas
uint16_t y; //!< [output] Packed position in Atlas
float glyphAdvanceX; //!< [input] For custom font glyphs only (ID<0x10000): glyph xadvance
carb::Float2 glyphOffset; //!< [input] For custom font glyphs only (ID<0x10000): glyph display offset
Font* font; //!< [input] For custom font glyphs only (ID<0x10000): target font
//! Constructor.
FontCustomRect()
{
id = 0xFFFFFFFF;
width = height = 0;
x = y = 0xFFFF;
glyphAdvanceX = 0.0f;
glyphOffset = { 0.0f, 0.0f };
font = nullptr;
}
//! Checks if the font custom rect is packed or not.
//! @returns `true` if the font is packed; `false` otherwise.
bool isPacked() const
{
return x != 0xFFFF;
}
};
/**
* Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the
* corresponding callback is triggered.
*/
struct TextEditCallbackData
{
InputTextFlags eventFlag; //!< One of ImGuiInputTextFlags_Callback* - Read-only
InputTextFlags flags; //!< What user passed to InputText() - Read-only
void* userData; //!< What user passed to InputText() - Read-only
uint16_t eventChar; //!< Character input - Read-write (replace character or set to zero)
int eventKey; //!< Key pressed (Up/Down/TAB) - Read-only
char* buf; //!< Current text buffer - Read-write (pointed data only, can't replace the actual pointer)
int bufTextLen; //!< Current text length in bytes - Read-write
int bufSize; //!< Maximum text length in bytes - Read-only
bool bufDirty; //!< Set if you modify Buf/BufTextLen - Write
int cursorPos; //!< Read-write
int selectionStart; //!< Read-write (== to SelectionEnd when no selection)
int selectionEnd; //!< Read-write
};
//! Definition of callback from InputText().
typedef int (*TextEditCallback)(TextEditCallbackData* data);
/**
* Data payload for Drag and Drop operations: acceptDragDropPayload(), getDragDropPayload()
*/
struct Payload
{
// Members
void* data; //!< Data (copied and owned by simplegui)
int dataSize; //!< Data size
// [Internal]
uint32_t sourceId; //!< Source item id
uint32_t sourceParentId; //!< Source parent id (if available)
int dataFrameCount; //!< Data timestamp
char dataType[32 + 1]; //!< Data type tag (short user-supplied string, 32 characters max)
bool preview; //!< Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb:
//!< handle overlapping drag targets)
bool delivery; //!< Set when AcceptDragDropPayload() was called and mouse button is released over the target item.
//! Constructor.
Payload()
{
clear();
}
//! Resets the state to cleared.
void clear()
{
sourceId = sourceParentId = 0;
data = nullptr;
dataSize = 0;
memset(dataType, 0, sizeof(dataType));
dataFrameCount = -1;
preview = delivery = false;
}
//! Checks if the Payload matches the given type.
//! @param type The type that should be checked against the `dataType` member.
//! @returns `true` if the type matches `dataType`; `false` otherwise.
bool isDataType(const char* type) const
{
return dataFrameCount != -1 && strcmp(type, dataType) == 0;
}
//! Returns the state of the `preview` member.
//! @returns The state of the `preview` member.
bool isPreview() const
{
return preview;
}
//! Returns the state of the `delivery` member.
//! @returns The state of the `delivery` member.
bool isDelivery() const
{
return delivery;
}
};
/**
* Flags stored in ImGuiViewport::Flags, giving indications to the platform back-ends
*/
typedef uint32_t ViewportFlags;
const ViewportFlags kViewportFlagNone = 0; //!< Absence of other viewport flags.
const ViewportFlags kViewportFlagNoDecoration = 1 << 0; //!< Platform Window: Disable platform decorations: title bar;
//!< borders; etc.
const ViewportFlags kViewportFlagNoTaskBarIcon = 1 << 1; //!< Platform Window: Disable platform task bar icon (for
//!< popups; menus; or all windows if
//!< ImGuiConfigFlags_ViewportsNoTaskBarIcons if set)
const ViewportFlags kViewportFlagNoFocusOnAppearing = 1 << 2; //!< Platform Window: Don't take focus when created.
const ViewportFlags kViewportFlagNoFocusOnClick = 1 << 3; //!< Platform Window: Don't take focus when clicked on.
const ViewportFlags kViewportFlagNoInputs = 1 << 4; //!< Platform Window: Make mouse pass through so we can drag this
//!< window while peaking behind it.
const ViewportFlags kViewportFlagNoRendererClear = 1 << 5; //!< Platform Window: Renderer doesn't need to clear the
//!< framebuffer ahead.
const ViewportFlags kViewportFlagTopMost = 1 << 6; //!< Platform Window: Display on top (for tooltips only)
/**
* The viewports created and managed by simplegui. The role of the platform back-end is to create the platform/OS
* windows corresponding to each viewport.
*/
struct Viewport
{
uint32_t id; //!< Unique identifier.
ViewportFlags flags; //!< Flags describing this viewport.
Float2 pos; //!< Position of viewport both in simplegui space and in OS desktop/native space
Float2 size; //!< Size of viewport in pixel
Float2 workOffsetMin; //!< Work Area: Offset from Pos to top-left corner of Work Area. Generally (0,0) or
//!< (0,+main_menu_bar_height). Work Area is Full Area but without menu-bars/status-bars (so
//!< WorkArea always fit inside Pos/Size!)
Float2 workOffsetMax; //!< Work Area: Offset from Pos+Size to bottom-right corner of Work Area. Generally (0,0) or
//!< (0,-status_bar_height).
float dpiScale; //!< 1.0f = 96 DPI = No extra scale
DrawData* drawData; //!< The ImDrawData corresponding to this viewport. Valid after Render() and until the next call
//!< to NewFrame().
uint32_t parentViewportId; //!< (Advanced) 0: no parent. Instruct the platform back-end to setup a parent/child
//!< relationship between platform windows.
void* rendererUserData; //!< void* to hold custom data structure for the renderer (e.g. swap chain, frame-buffers
//!< etc.)
void* platformUserData; //!< void* to hold custom data structure for the platform (e.g. windowing info, render
//!< context)
void* platformHandle; //!< void* for FindViewportByPlatformHandle(). (e.g. suggested to use natural platform handle
//!< such as HWND, GlfwWindow*, SDL_Window*)
void* platformHandleRaw; //!< void* to hold lower-level, platform-native window handle (e.g. the HWND) when using an
//!< abstraction layer like GLFW or SDL (where PlatformHandle would be a SDL_Window*)
bool platformRequestMove; //!< Platform window requested move (e.g. window was moved by the OS / host window
//!< manager, authoritative position will be OS window position)
bool platformRequestResize; //!< Platform window requested resize (e.g. window was resized by the OS / host window
//!< manager, authoritative size will be OS window size)
bool platformRequestClose; //!< Platform windows requested closure (e.g. window was moved by the OS / host window
//!< manager, e.g. pressing ALT-F4)
//! Constructor.
Viewport()
{
id = 0;
flags = 0;
dpiScale = 0.0f;
drawData = NULL;
parentViewportId = 0;
rendererUserData = platformUserData = platformHandle = platformHandleRaw = nullptr;
platformRequestMove = platformRequestResize = platformRequestClose = false;
}
//! Destructor.
~Viewport()
{
CARB_ASSERT(platformUserData == nullptr && rendererUserData == nullptr);
}
};
//! [BETA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions.
//! Provide hints to the platform back-end via altered viewport flags (enable/disable OS decoration, OS task bar icons,
//! etc.) and OS level parent/child relationships.
struct WindowClass
{
uint32_t classId; //!< User data. 0 = Default class (unclassed)
uint32_t parentViewportId; //!< Hint for the platform back-end. If non-zero, the platform back-end can create a
//!< parent<>child relationship between the platform windows. Not conforming back-ends
//!< are free to e.g. parent every viewport to the main viewport or not.
ViewportFlags viewportFlagsOverrideSet; //!< Viewport flags to set when a window of this class owns a viewport. This
//!< allows you to enforce OS decoration or task bar icon, override the
//!< defaults on a per-window basis.
ViewportFlags viewportFlagsOverrideClear; //!< Viewport flags to clear when a window of this class owns a viewport.
//!< This allows you to enforce OS decoration or task bar icon, override
//!< the defaults on a per-window basis.
DockNodeFlags dockNodeFlagsOverrideSet; //!< [EXPERIMENTAL] Dock node flags to set when a window of this class is
//!< hosted by a dock node (it doesn't have to be selected!)
DockNodeFlags dockNodeFlagsOverrideClear; //!< [EXPERIMENTAL]
bool dockingAlwaysTabBar; //!< Set to true to enforce single floating windows of this class always having their own
//!< docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar)
bool dockingAllowUnclassed; //!< Set to true to allow windows of this class to be docked/merged with an unclassed
//!< window. // FIXME-DOCK: Move to DockNodeFlags override?
//! Constructor.
WindowClass()
{
classId = 0;
parentViewportId = 0;
viewportFlagsOverrideSet = viewportFlagsOverrideClear = 0x00;
dockNodeFlagsOverrideSet = dockNodeFlagsOverrideClear = 0x00;
dockingAlwaysTabBar = false;
dockingAllowUnclassed = true;
}
};
/**
* Helper: Manually clip large list of items.
* If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse
* clipping based on visibility to save yourself from processing those items at all. The clipper calculates the range of
* visible items and advance the cursor to compensate for the non-visible items we have skipped.
*/
struct ListClipper
{
float startPosY; //!< Start Y coordinate position;
float itemsHeight; //!< Height of items.
int32_t itemsCount; //!< Number of items.
int32_t stepNo; //!< Stepping
int32_t displayStart; //!< Display start index.
int32_t displayEnd; //!< Display end index.
};
} // namespace simplegui
} // namespace carb
| 65,995 | C | 57.248897 | 122 | 0.611137 |
omniverse-code/kit/include/carb/simplegui/SimpleGuiBindingsPython.h | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../BindingsPythonUtils.h"
#include "../BindingsPythonTypes.h"
#include "ISimpleGui.h"
#include <algorithm>
#include <string>
#include <vector>
namespace carb
{
namespace simplegui
{
inline void definePythonModule(py::module& m)
{
using namespace carb;
using namespace carb::simplegui;
m.doc() = "pybind11 carb.simplegui bindings";
py::enum_<Condition>(m, "Condition")
.value("ALWAYS", Condition::eAlways)
.value("APPEARING", Condition::eAppearing)
.value("FIRST_USE_EVER", Condition::eFirstUseEver)
.value("ONCE", Condition::eOnce);
defineInterfaceClass<ISimpleGui>(m, "ISimpleGui", "acquire_simplegui")
//.def("create_context", wrapInterfaceFunction(&ISimpleGui::createContext))
//.def("destroy_context", wrapInterfaceFunction(&ISimpleGui::destroyContext))
//.def("set_current_context", wrapInterfaceFunction(&ISimpleGui::setCurrentContext))
//.def("new_frame", wrapInterfaceFunction(&ISimpleGui::newFrame))
//.def("render", wrapInterfaceFunction(&ISimpleGui::render))
.def("set_display_size", wrapInterfaceFunction(&ISimpleGui::setDisplaySize))
.def("get_display_size", wrapInterfaceFunction(&ISimpleGui::getDisplaySize))
.def("show_demo_window", wrapInterfaceFunction(&ISimpleGui::showDemoWindow))
.def("set_next_window_pos", wrapInterfaceFunction(&ISimpleGui::setNextWindowPos))
.def("set_next_window_size", wrapInterfaceFunction(&ISimpleGui::setNextWindowSize))
.def("begin",
[](const ISimpleGui* iface, const char* label, bool opened, carb::simplegui::WindowFlags flags) {
bool visible = iface->begin(label, &opened, flags);
return py::make_tuple(visible, opened);
})
.def("end", wrapInterfaceFunction(&ISimpleGui::end))
.def("collapsing_header", wrapInterfaceFunction(&ISimpleGui::collapsingHeader))
.def("text", [](const ISimpleGui* iface, const char* text) { iface->text(text); })
.def("text_unformatted", wrapInterfaceFunction(&ISimpleGui::textUnformatted))
.def("text_wrapped", [](const ISimpleGui* iface, const char* text) { iface->textWrapped(text); })
.def("button", &ISimpleGui::button)
.def("small_button", wrapInterfaceFunction(&ISimpleGui::smallButton))
.def("same_line", &ISimpleGui::sameLine)
.def("same_line_ex", wrapInterfaceFunction(&ISimpleGui::sameLineEx), py::arg("pos_x") = 0.0f,
py::arg("spacing_w") = -1.0f)
.def("separator", wrapInterfaceFunction(&ISimpleGui::separator))
.def("spacing", wrapInterfaceFunction(&ISimpleGui::spacing))
.def("indent", wrapInterfaceFunction(&ISimpleGui::indent))
.def("unindent", wrapInterfaceFunction(&ISimpleGui::unindent))
.def("dummy", wrapInterfaceFunction(&ISimpleGui::dummy))
.def("bullet", wrapInterfaceFunction(&ISimpleGui::bullet))
.def("checkbox",
[](const ISimpleGui* iface, const char* label, bool value) {
bool clicked = iface->checkbox(label, &value);
return py::make_tuple(clicked, value);
})
.def("input_float",
[](const ISimpleGui* iface, const char* label, float value, float step) {
bool clicked = iface->inputFloat(label, &value, step, 0.0f, -1, 0);
return py::make_tuple(clicked, value);
})
.def("input_int",
[](const ISimpleGui* iface, const char* label, int value, int step) {
bool clicked = iface->inputInt(label, &value, step, 0, 0);
return py::make_tuple(clicked, value);
})
.def("input_text",
[](const ISimpleGui* iface, const char* label, const std::string& str, size_t size) {
std::vector<char> buf(str.begin(), str.end());
buf.resize(size);
bool clicked = iface->inputText(label, buf.data(), size, 0, nullptr, nullptr);
return py::make_tuple(clicked, buf.data());
})
.def("slider_float",
[](const ISimpleGui* iface, const char* label, float value, float vMin, float vMax) {
bool clicked = iface->sliderFloat(label, &value, vMin, vMax, "%.3f", 1.0f);
return py::make_tuple(clicked, value);
})
.def("slider_int",
[](const ISimpleGui* iface, const char* label, int value, int vMin, int vMax) {
bool clicked = iface->sliderInt(label, &value, vMin, vMax, "%.0f");
return py::make_tuple(clicked, value);
})
.def("combo",
[](const ISimpleGui* iface, const char* label, int selectedItem, std::vector<std::string> items) {
std::vector<const char*> itemPtrs(items.size());
std::transform(
items.begin(), items.end(), itemPtrs.begin(), [](const std::string& s) { return s.c_str(); });
bool clicked = iface->combo(label, &selectedItem, itemPtrs.data(), (int)itemPtrs.size());
return py::make_tuple(clicked, selectedItem);
})
.def("progress_bar", wrapInterfaceFunction(&ISimpleGui::progressBar))
.def("color_edit3",
[](const ISimpleGui* iface, const char* label, Float3 color) {
bool clicked = iface->colorEdit3(label, &color.x, 0);
return py::make_tuple(clicked, color);
})
.def("color_edit4",
[](const ISimpleGui* iface, const char* label, Float4 color) {
bool clicked = iface->colorEdit4(label, &color.x, 0);
return py::make_tuple(clicked, color);
})
.def("push_id_string", wrapInterfaceFunction(&ISimpleGui::pushIdString))
.def("push_id_int", wrapInterfaceFunction(&ISimpleGui::pushIdInt))
.def("pop_id", wrapInterfaceFunction(&ISimpleGui::popId))
.def("push_item_width", wrapInterfaceFunction(&ISimpleGui::pushItemWidth))
.def("pop_item_width", wrapInterfaceFunction(&ISimpleGui::popItemWidth))
.def("tree_node_ptr",
[](const ISimpleGui* iface, int64_t id, const char* text) { return iface->treeNodePtr((void*)id, text); })
.def("tree_pop", wrapInterfaceFunction(&ISimpleGui::treePop))
.def("begin_child", wrapInterfaceFunction(&ISimpleGui::beginChild))
.def("end_child", wrapInterfaceFunction(&ISimpleGui::endChild))
.def("set_scroll_here_y", wrapInterfaceFunction(&ISimpleGui::setScrollHereY))
.def("open_popup", wrapInterfaceFunction(&ISimpleGui::openPopup))
.def("begin_popup_modal", wrapInterfaceFunction(&ISimpleGui::beginPopupModal))
.def("end_popup", wrapInterfaceFunction(&ISimpleGui::endPopup))
.def("close_current_popup", wrapInterfaceFunction(&ISimpleGui::closeCurrentPopup))
.def("push_style_color", wrapInterfaceFunction(&ISimpleGui::pushStyleColor))
.def("pop_style_color", wrapInterfaceFunction(&ISimpleGui::popStyleColor))
.def("push_style_var_float", wrapInterfaceFunction(&ISimpleGui::pushStyleVarFloat))
.def("push_style_var_float2", wrapInterfaceFunction(&ISimpleGui::pushStyleVarFloat2))
.def("pop_style_var", wrapInterfaceFunction(&ISimpleGui::popStyleVar))
.def("menu_item_ex",
[](const ISimpleGui* iface, const char* label, const char* shortcut, bool selected, bool enabled) {
bool activated = iface->menuItemEx(label, shortcut, &selected, enabled);
return py::make_tuple(activated, selected);
})
.def("dock_builder_dock_window", wrapInterfaceFunction(&ISimpleGui::dockBuilderDockWindow))
.def("plot_lines", [](const ISimpleGui* self, const char* label, const std::vector<float>& values,
int valuesCount, int valuesOffset, const char* overlayText, float scaleMin,
float scaleMax, Float2 graphSize, int stride) {
self->plotLines(
label, values.data(), valuesCount, valuesOffset, overlayText, scaleMin, scaleMax, graphSize, stride);
});
m.attr("WINDOW_FLAG_NO_TITLE_BAR") = py::int_(kWindowFlagNoTitleBar);
m.attr("WINDOW_FLAG_NO_RESIZE") = py::int_(kWindowFlagNoResize);
m.attr("WINDOW_FLAG_NO_MOVE") = py::int_(kWindowFlagNoMove);
m.attr("WINDOW_FLAG_NO_SCROLLBAR") = py::int_(kWindowFlagNoScrollbar);
m.attr("WINDOW_FLAG_NO_SCROLL_WITH_MOUSE") = py::int_(kWindowFlagNoScrollWithMouse);
m.attr("WINDOW_FLAG_NO_COLLAPSE") = py::int_(kWindowFlagNoCollapse);
m.attr("WINDOW_FLAG_ALWAYS_AUTO_RESIZE") = py::int_(kWindowFlagAlwaysAutoResize);
m.attr("WINDOW_FLAG_NO_BACKGROUND") = py::int_(kWindowFlagNoBackground);
m.attr("WINDOW_FLAG_NO_SAVED_SETTINGS") = py::int_(kWindowFlagNoSavedSettings);
m.attr("WINDOW_FLAG_NO_MOUSE_INPUTS") = py::int_(kWindowFlagNoMouseInputs);
m.attr("WINDOW_FLAG_MENU_BAR") = py::int_(kWindowFlagMenuBar);
m.attr("WINDOW_FLAG_HORIZONTAL_SCROLLBAR") = py::int_(kWindowFlagHorizontalScrollbar);
m.attr("WINDOW_FLAG_NO_FOCUS_ON_APPEARING") = py::int_(kWindowFlagNoFocusOnAppearing);
m.attr("WINDOW_FLAG_NO_BRING_TO_FRONT_ON_FOCUS") = py::int_(kWindowFlagNoBringToFrontOnFocus);
m.attr("WINDOW_FLAG_ALWAYS_VERTICAL_SCROLLBAR") = py::int_(kWindowFlagAlwaysVerticalScrollbar);
m.attr("WINDOW_FLAG_ALWAYS_HORIZONTAL_SCROLLBAR") = py::int_(kWindowFlagAlwaysHorizontalScrollbar);
m.attr("WINDOW_FLAG_ALWAYS_USE_WINDOW_PADDING") = py::int_(kWindowFlagAlwaysUseWindowPadding);
m.attr("WINDOW_FLAG_NO_NAV_INPUTS") = py::int_(kWindowFlagNoNavFocus);
m.attr("WINDOW_FLAG_NO_NAV_FOCUS") = py::int_(kWindowFlagNoNavInputs);
m.attr("WINDOW_FLAG_UNSAVED_DOCUMENT") = py::int_(kWindowFlagUnsavedDocument);
m.attr("WINDOW_FLAG_NO_DOCKING") = py::int_(kWindowFlagNoDocking);
}
} // namespace simplegui
} // namespace carb
| 10,474 | C | 57.848314 | 119 | 0.643307 |
omniverse-code/kit/include/carb/scripting/IScripting.h | // Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../Interface.h"
namespace carb
{
namespace scripting
{
/**
* Defines a scripting return code.
*/
enum class ExecutionErrorCode
{
eOk,
eError
};
using OutputFlags = uint32_t;
const OutputFlags kOutputFlagCaptureStdout = 1;
const OutputFlags kOutputFlagCaptureStderr = (1 << 1);
struct ExecutionError
{
ExecutionErrorCode code;
const char* message;
};
/**
* Scripting plugin description
*/
struct ScriptingDesc
{
const char* languageName;
const char* const* fileExtensions; ///! File extensions list, each prefixed with period. E.g. ".py"
size_t fileExtensionCount;
};
/**
* Context of execution.
*
* Context keeps all shared data between executions. For example global state (variables, functions etc.) in python.
*/
struct Context;
/**
* Script is an execution unit.
*
* By making a Script from a code you give an opportunity to plugin to preload and compile the code once.
*/
struct Script;
/**
* Opaque container to pass and retrieve data with Scripting interface.
*/
struct Object;
/**
* Defines a generic scripting interface.
*
* Specific implementations such as Python realize this simple interface
* and allow access to the Carbonite framework through run-time scripts and not
* just compiled code.
*/
struct IScripting
{
CARB_PLUGIN_INTERFACE("carb::scripting::IScripting", 1, 0)
/**
* Add raw module search path, this path will be added to the list unmodified, potentially requiring
* language-specific search patterns.
*/
void(CARB_ABI* addSearchPath)(const char* path);
/**
* Remove raw module search path.
*/
void(CARB_ABI* removeSearchPath)(const char* path);
/**
* Create an execution context.
*
* Context:
* 1. Keeps execution result: errors, stdout, stderr.
* 2. Stores globals between execution calls.
*/
Context*(CARB_ABI* createContext)();
/**
* Destroy an execution context.
*/
void(CARB_ABI* destroyContext)(Context* context);
/**
* Get a global execution context.
* This context uses interpreter global state for globals.
*/
Context*(CARB_ABI* getGlobalContext)();
/**
* Execute code from a file on a Context.
*
* @return false iff execution produced an error. Use getLastExecutionError(context) to get more details.
*/
bool(CARB_ABI* executeFile)(Context* context, const char* path, OutputFlags outputCaptureFlags);
/**
* Execute a string of code on a Context.
*
* @param sourceFile Set as __file__ in python. Can be nullptr, will default to executable name then.
*
* @return false iff execution produced an error. Use getLastExecutionError(context) to get more details.
*/
bool(CARB_ABI* executeString)(Context* context, const char* str, OutputFlags outputCaptureFlags, const char* sourceFile);
/**
* Execute a Script on a Context.
*
* @return false iff execution produced an error. Use getLastExecutionError(context) to get more details.
*/
bool(CARB_ABI* executeScript)(Context* context, Script* script, OutputFlags outputCaptureFlags);
/**
* Execute a Script with arguments on a Context.
*
* @return false iff execution produced an error. Use getLastExecutionError(context) to get more details.
*/
bool(CARB_ABI* executeScriptWithArgs)(
Context* context, Script* script, const char* const* argv, size_t argc, OutputFlags outputCaptureFlags);
/**
* Check if context has a function.
*/
bool(CARB_ABI* hasFunction)(Context* context, const char* functionName);
/**
* Execute a function on a Context.
*
* @param returnObject Pass an object to store returned data, if any. Can be nullptr.
* @return false iff execution produced an error. Use getLastExecutionError(context) to get more details.
*/
bool(CARB_ABI* executeFunction)(Context* context,
const char* functionName,
Object* returnObject,
OutputFlags outputCaptureFlags);
/**
* Check if object has a method
*/
bool(CARB_ABI* hasMethod)(Context* context, Object* self, const char* methodName);
/**
* Execute Object method on a Context.
*
* @param returnObject Pass an object to store returned data, if any. Can be nullptr.
* @return false iff execution produced an error. Use getLastExecutionError(context) to get more details.
*/
bool(CARB_ABI* executeMethod)(
Context* context, Object* self, const char* methodName, Object* returnObject, OutputFlags outputCaptureFlags);
/**
* Get last stdout, if stdout from the execute within the given context.
*/
const char*(CARB_ABI* getLastStdout)(Context* context);
/**
* Get last stderr, if stdout from the execute within the given context.
*/
const char*(CARB_ABI* getLastStderr)(Context* context);
/**
* Get last execution error from last execute within the given context call if any.
*/
const ExecutionError&(CARB_ABI* getLastExecutionError)(Context* context);
/**
* Create a script instance from an explicit string.
*
* @param str The full script as a string.
* @return The script.
*/
Script*(CARB_ABI* createScriptFromString)(const char* str);
/**
* Create a script instance from a file path.
*
* @param path The file path such as "assets/scripts/hello.py"
* @return The script.
*/
Script*(CARB_ABI* createScriptFromFile)(const char* path);
/**
* Destroys the script and releases all resources from a previously created script.
*
* @param script The previously created script.
*/
void(CARB_ABI* destroyScript)(Script* script);
/**
* Create an object to hold scripting data.
*/
Object*(CARB_ABI* createObject)();
/**
* Destroy an object.
*/
void(CARB_ABI* destroyObject)(Object* object);
/**
* Is object empty?
*/
bool(CARB_ABI* isObjectNone)(Object* object);
/**
* Get a object data as string.
*
* Returned string is internally buffered and valid until next call.
* If an object is not of a string type, nullptr is returned.
*/
const char*(CARB_ABI* getObjectAsString)(Object* object);
/**
* Get a object data as integer.
*
* If an object is not of an int type, 0 is returned.
*/
int(CARB_ABI* getObjectAsInt)(Object* object);
/**
* Gets the Scripting plugin desc.
*
* @return The desc.
*/
const ScriptingDesc&(CARB_ABI* getDesc)();
/**
* Collects all plugin folders (by asking the Framework), appends language specific subfolder and adds them to
* search path.
*/
void(CARB_ABI* addPluginBindingFoldersToSearchPath)();
/**
* Temp helper to scope control GIL
*/
void(CARB_ABI* releaseGIL)();
void(CARB_ABI* acquireGIL)();
};
} // namespace scripting
} // namespace carb
| 7,548 | C | 28.25969 | 125 | 0.659512 |
omniverse-code/kit/include/carb/messaging/MessagingTypes.h | // Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <cstdint>
namespace carb
{
namespace messaging
{
struct Channel;
/**
* Defines type on message.
*/
enum class Type
{
eError,
eMessage,
eHello,
eJoin,
eLeft,
eDeleted,
};
/**
* Response results for messaging.
*/
enum class Status
{
eOk,
eErrorUnknown
};
/**
* Callback return type.
*/
enum class CallbackReturnType : uint64_t
{
eContinue = 0, ///! Continue callback subscription.
eStop = 1 ///! Stop callback subscription.
};
/**
* Description of Listen channel parameters.
*/
struct ListenChannelDesc
{
void* connection; ///! Native connection handle for message channel.
const char* path; ///! Path of message channel to listen to.
};
/**
* Defines a message body.
*/
struct MessageResult
{
carb::messaging::Status status; ///! Status of the message
const char* statusDescription; ///! Status in a more descriptive string.
Channel* channel; ///! Channel where the message is received from.
const char* from; ///! The sender id of this message.
const uint8_t* ptr; ///! Payload of the message.
uint64_t size; ///! Size of the payload.
Type type; ///! Type of message.
};
/**
* Description of message to be sent.
*/
struct SendMessageDesc
{
Channel* channel; ///! Channel to send this message to.
const char* to; ///! Recipient of the message. use nullptr to broadcast.
const uint8_t* ptr; ///! Payload of the message. A copy will be made internally.
uint64_t size; ///! Size of the message.
bool waitForAnswer; ///! Whether to wait for answer or not.
};
/**
* Callback function when a message is sent or received.
*
* @param result The message body.
* @param userPtr The custom user data to be passed into callback function.
* @return if to continue or stop callback subscription.
*/
typedef CallbackReturnType (*OnMessageFn)(const MessageResult* result, void* userPtr);
}
}
| 2,361 | C | 23.604166 | 86 | 0.695044 |
omniverse-code/kit/include/carb/messaging/IMessaging.h | // Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "MessagingTypes.h"
#include <carb/Interface.h>
namespace carb
{
namespace messaging
{
/**
* Defines a messaging interface.
*/
struct IMessaging
{
CARB_PLUGIN_INTERFACE("carb::messaging::IMessaging", 0, 3)
/**
* Listens to a channel and keep receiving message from it until @ref stopChannel is called.
* This also creates the channel, if it doesn't already exist.
*
* @param desc The description of listen settings.
* @param onMessage Callback function to be called when a message is received.
* @param userData Custom user data to be passed back in callback function.
* @return the channel joined.
*/
Channel*(CARB_ABI* joinChannel)(const ListenChannelDesc* desc, OnMessageFn onMessage, void* userData);
/**
* Stops listening to a channel.
*
* @param channel The Channel to stop listening to.
* @param connectionLost Whether the stop request is due to a connection lose.
*/
void(CARB_ABI* leaveChannel)(const Channel* channel, bool connectionLost);
/**
* Sends a message.
*
* @param desc The description of the message.
* @param onMessage Callback function to be called when a message is sent.
* @param userData Custom user data to be passed back in callback function.
*/
void(CARB_ABI* sendMessage)(const SendMessageDesc* desc, OnMessageFn onMessage, void* userData);
};
}
}
| 1,869 | C | 32.392857 | 106 | 0.713216 |
omniverse-code/kit/include/usdrt/gf/vec.h | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
//! @file
//!
//! @brief TODO
#include <carb/Defines.h>
#include <usdrt/gf/half.h>
#include <usdrt/gf/math.h>
#include <cmath>
#include <initializer_list>
#include <stdint.h>
#include <type_traits>
#ifndef __CUDACC__
# define CUDA_SAFE_ASSERT(cond, ...) CARB_ASSERT(cond, ##__VA_ARGS__)
# define CUDA_CALLABLE
#else
# define CUDA_SAFE_ASSERT(cond, ...)
# define CUDA_CALLABLE __device__ __host__
#endif
namespace omni
{
namespace math
{
namespace linalg
{
// Forward declaration, just for the using statements, below.
class half;
template <typename T, size_t N>
class base_vec
{
public:
// Some standard types, similar to std::array and std::vector.
using value_type = T;
using size_type = size_t;
using difference_type = ptrdiff_t;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
using iterator = pointer;
using const_iterator = const_pointer;
// static constexpr variable to be able to refer to the tuple size from the type,
// from outside this class definition.
static constexpr size_t tuple_size = N;
using ScalarType = T;
static const size_t dimension = N;
base_vec() = default;
constexpr base_vec(const base_vec<T, N>&) = default;
constexpr explicit CUDA_CALLABLE base_vec(T value) : v{}
{
for (size_t i = 0; i < N; ++i)
{
v[i] = value;
}
}
// NOTE: The static_cast is to avoid issues with other not being accepted as being the
// base class type, presumably because of the base class type conversion constructor
// being marked as explicit.
template <typename OTHER_T>
constexpr explicit CUDA_CALLABLE base_vec(const base_vec<OTHER_T, N>& other) : v{}
{
for (size_t i = 0; i < N; ++i)
{
v[i] = T(other[i]);
}
}
template <typename OTHER_T0, typename OTHER_T1, typename... Args>
constexpr CUDA_CALLABLE base_vec(OTHER_T0 a, OTHER_T1 b, Args... args) noexcept : v{}
{
v[0] = a;
initHelper<1>(b, args...);
}
template <typename OTHER_T>
CUDA_CALLABLE base_vec(const std::initializer_list<OTHER_T>& other) noexcept : v{}
{
CUDA_SAFE_ASSERT(other.size() == N);
for (size_t i = 0; i < N && i < other.size(); ++i)
{
// NOTE: This intentionally doesn't have an explicit cast, so that
// the compiler will warn on invalid implicit casts, since this
// constructor isn't marked explicit.
v[i] = other.begin()[i];
}
}
// Access a single component of this base_vec.
constexpr CUDA_CALLABLE T& operator[](size_t i) noexcept
{
// Ensure that this type is a POD type if T is a POD type.
// This check is unrelated to this operator, but the static_assert
// must be inside some function that is likely to be called.
static_assert(std::is_pod<base_vec<T, N>>::value == std::is_pod<T>::value,
"base_vec<T,N> should be a POD type iff T is a POD type.");
CUDA_SAFE_ASSERT(i < N);
return v[i];
}
constexpr CUDA_CALLABLE const T& operator[](size_t i) const noexcept
{
CUDA_SAFE_ASSERT(i < N);
return v[i];
}
// Get a pointer to the data of this tuple.
constexpr CUDA_CALLABLE T* data() noexcept
{
return v;
}
constexpr CUDA_CALLABLE const T* data() const noexcept
{
return v;
}
static CUDA_CALLABLE base_vec<T, N> Axis(size_t axis)
{
base_vec<T, N> v(T(0));
if (axis < dimension)
{
v[axis] = T(1);
}
return v;
}
const CUDA_CALLABLE T* GetArray() const
{
return data();
}
constexpr CUDA_CALLABLE T Dot(const base_vec<T, N>& other) const
{
T d = v[0] * other[0];
for (size_t i = 1; i < N; ++i)
{
d += v[i] * other[i];
}
return d;
}
constexpr CUDA_CALLABLE T GetLengthSq() const
{
return this->Dot(*this);
}
CUDA_CALLABLE auto GetLength() const
{
return std::sqrt(GetLengthSq());
}
CUDA_CALLABLE auto Normalize()
{
const T length2 = GetLengthSq();
decltype(std::sqrt(length2)) length;
decltype(length) scale;
if (length2 != T(0))
{
length = std::sqrt(length2);
scale = T(1) / length;
}
else
{
// If close enough to zero that the length squared is zero,
// make it exactly zero, for consistency.
length = 0;
scale = 0;
}
(*this) *= scale;
return length;
}
#ifndef DOXYGEN_BUILD
CUDA_CALLABLE base_vec<T, N> GetNormalized() const
{
base_vec<T, N> copy(*this);
copy.Normalize();
return copy;
}
#endif // DOXYGEN_BUILD
// NOTE: This is the dot product, NOT the component-wise product!
constexpr CUDA_CALLABLE T operator*(const base_vec<T, N>& other) const
{
return Dot(other);
}
constexpr CUDA_CALLABLE base_vec<T, N>& operator+=(const base_vec<T, N>& that) noexcept
{
for (size_t i = 0; i < N; ++i)
{
v[i] += that[i];
}
return *this;
}
constexpr CUDA_CALLABLE base_vec<T, N>& operator-=(const base_vec<T, N>& that) noexcept
{
for (size_t i = 0; i < N; ++i)
{
v[i] -= that[i];
}
return *this;
}
constexpr CUDA_CALLABLE base_vec<T, N>& operator*=(const T that) noexcept
{
for (size_t i = 0; i < N; ++i)
{
v[i] *= that;
}
return *this;
}
constexpr CUDA_CALLABLE base_vec<T, N>& operator/=(const T that) noexcept
{
for (size_t i = 0; i < N; ++i)
{
v[i] /= that;
}
return *this;
}
#ifndef DOXYGEN_BUILD
friend CUDA_CALLABLE base_vec<T, N> operator*(const T& multiplier, base_vec<T, N> rhs)
{
rhs *= multiplier;
return rhs;
}
friend CUDA_CALLABLE base_vec<T, N> operator*(base_vec<T, N> lhs, const T& multiplier)
{
lhs *= multiplier;
return lhs;
}
friend CUDA_CALLABLE base_vec<T, N> operator/(base_vec<T, N> lhs, const T& divisor)
{
lhs /= divisor;
return lhs;
}
friend CUDA_CALLABLE base_vec<T, N> operator+(base_vec<T, N> lhs, const base_vec<T, N>& rhs)
{
lhs += rhs;
return lhs;
}
friend CUDA_CALLABLE base_vec<T, N> operator-(base_vec<T, N> lhs, const base_vec<T, N>& rhs)
{
lhs -= rhs;
return lhs;
}
#endif
protected:
T v[N];
private:
template <size_t i, typename OTHER_T>
constexpr CUDA_CALLABLE void initHelper(OTHER_T a)
{
static_assert(i == N - 1, "Variadic constructor of base_vec<T, N> requires N arguments");
v[i] = T(a);
}
template <size_t i, typename OTHER_T, typename... Args>
constexpr CUDA_CALLABLE void initHelper(OTHER_T a, Args... args)
{
v[i] = T(a);
initHelper<i + 1>(args...);
}
};
template <typename T, size_t N>
CUDA_CALLABLE T GfDot(const base_vec<T, N>& a, const base_vec<T, N>& b)
{
return a.Dot(b);
}
template <typename T, size_t N>
CUDA_CALLABLE auto GfGetLength(const base_vec<T, N>& v)
{
return v.GetLength();
}
template <typename T, size_t N>
CUDA_CALLABLE auto GfNormalize(base_vec<T, N>* p)
{
return p->Normalize();
}
template <typename T, size_t N>
CUDA_CALLABLE bool GfIsClose(const base_vec<T, N>& a, const base_vec<T, N>& b, double tolerance)
{
auto distanceSq = (a - b).GetLengthSq();
return distanceSq <= tolerance * tolerance;
}
#ifndef DOXYGEN_BUILD
template <>
inline auto base_vec<half, 2>::GetLength() const
{
return std::sqrt((float)GetLengthSq());
}
template <>
inline auto base_vec<half, 2>::Normalize()
{
const float length2 = (float)GetLengthSq();
float length;
float scale;
if (length2 != 0.0)
{
length = std::sqrt(length2);
scale = 1.0f / length;
}
else
{
// If close enough to zero that the length squared is zero,
// make it exactly zero, for consistency.
length = 0;
scale = 0;
}
(*this) *= scale;
return length;
}
template <>
inline auto base_vec<half, 3>::GetLength() const
{
return std::sqrt((float)GetLengthSq());
}
template <>
inline auto base_vec<half, 3>::Normalize()
{
const float length2 = (float)GetLengthSq();
float length;
float scale;
if (length2 != 0.0)
{
length = std::sqrt(length2);
scale = 1.0f / length;
}
else
{
// If close enough to zero that the length squared is zero,
// make it exactly zero, for consistency.
length = 0;
scale = 0;
}
(*this) *= scale;
return length;
}
template <>
inline auto base_vec<half, 4>::GetLength() const
{
return std::sqrt((float)GetLengthSq());
}
template <>
inline auto base_vec<half, 4>::Normalize()
{
const float length2 = (float)GetLengthSq();
float length;
float scale;
if (length2 != 0.0)
{
length = std::sqrt(length2);
scale = 1.0f / length;
}
else
{
// If close enough to zero that the length squared is zero,
// make it exactly zero, for consistency.
length = 0;
scale = 0;
}
(*this) *= scale;
return length;
}
#endif // DOXYGEN_BUILD
template <typename T>
class vec2 : public base_vec<T, 2>
{
public:
using base_type = base_vec<T, 2>;
using this_type = vec2<T>;
using base_type::operator[];
using base_type::data;
using base_type::operator+=;
using base_type::operator-=;
using base_type::operator*=;
using base_type::operator/=;
using base_type::GetArray;
using base_type::GetLength;
using base_type::GetLengthSq;
using base_type::Normalize;
using ScalarType = T;
using base_type::dimension;
vec2() = default;
constexpr vec2(const vec2<T>&) = default;
// Implicit conversion from base class, to avoid issues on that front.
constexpr CUDA_CALLABLE vec2(const base_type& other) : base_type(other)
{
}
constexpr explicit CUDA_CALLABLE vec2(T value) : base_type(value, value)
{
}
constexpr CUDA_CALLABLE vec2(T v0, T v1) : base_type(v0, v1)
{
}
template <typename OTHER_T>
constexpr explicit CUDA_CALLABLE vec2(const OTHER_T* p) : base_type(p[0], p[1])
{
}
template <typename OTHER_T>
explicit CUDA_CALLABLE vec2(const vec2<OTHER_T>& other) : base_type(other)
{
}
template <typename OTHER_T>
explicit CUDA_CALLABLE vec2(const base_vec<OTHER_T, 2>& other) : base_type(other)
{
}
template <typename OTHER_T>
CUDA_CALLABLE vec2(const std::initializer_list<OTHER_T>& other) : base_type(other)
{
}
static constexpr CUDA_CALLABLE vec2<T> XAxis()
{
return vec2<T>(T(1), T(0));
}
static constexpr CUDA_CALLABLE vec2<T> YAxis()
{
return vec2<T>(T(0), T(1));
}
static CUDA_CALLABLE vec2<T> Axis(size_t axis)
{
return base_type::Axis(axis);
}
CUDA_CALLABLE this_type& Set(T v0, T v1)
{
v[0] = v0;
v[1] = v1;
return *this;
}
CUDA_CALLABLE this_type& Set(T* p)
{
return Set(p[0], p[1]);
}
// NOTE: To avoid including Boost unless absolutely necessary, hash_value() is not defined here.
template <typename OTHER_T>
CUDA_CALLABLE bool operator==(const vec2<OTHER_T>& other) const
{
return (v[0] == other[0]) && (v[1] == other[1]);
}
template <typename OTHER_T>
CUDA_CALLABLE bool operator!=(const vec2<OTHER_T>& other) const
{
return !(*this == other);
}
// Returns the portion of this that is parallel to unitVector.
// NOTE: unitVector must have length 1 for this to produce a meaningful result.
CUDA_CALLABLE this_type GetProjection(const this_type& unitVector) const
{
return unitVector * (this->Dot(unitVector));
}
// Returns the portion of this that is orthogonal to unitVector.
// NOTE: unitVector must have length 1 for this to produce a meaningful result.
CUDA_CALLABLE this_type GetComplement(const this_type& unitVector) const
{
return *this - GetProjection(unitVector);
}
CUDA_CALLABLE this_type GetNormalized() const
{
return base_type::GetNormalized();
}
private:
using base_type::v;
};
template <typename T>
CUDA_CALLABLE vec2<T> operator-(const vec2<T>& v)
{
return vec2<T>(-v[0], -v[1]);
}
template <typename T>
CUDA_CALLABLE vec2<T> GfCompMult(const vec2<T>& a, const vec2<T>& b)
{
return vec2<T>(a[0] * b[0], a[1] * b[1]);
}
template <typename T>
CUDA_CALLABLE vec2<T> GfCompDiv(const vec2<T>& a, const vec2<T>& b)
{
return vec2<T>(a[0] / b[0], a[1] / b[1]);
}
template <typename T>
CUDA_CALLABLE vec2<T> GfGetNormalized(const vec2<T>& v)
{
return v.GetNormalized();
}
template <typename T>
CUDA_CALLABLE vec2<T> GfGetProjection(const vec2<T>& v, const vec2<T>& unitVector)
{
return v.GetProjection(unitVector);
}
template <typename T>
CUDA_CALLABLE vec2<T> GfGetComplement(const vec2<T>& v, const vec2<T>& unitVector)
{
return v.GetComplement(unitVector);
}
template <typename T>
class vec3 : public base_vec<T, 3>
{
public:
using base_type = base_vec<T, 3>;
using this_type = vec3<T>;
using base_type::operator[];
using base_type::data;
using base_type::operator+=;
using base_type::operator-=;
using base_type::operator*=;
using base_type::operator/=;
using base_type::GetArray;
using base_type::GetLength;
using base_type::GetLengthSq;
using base_type::Normalize;
using ScalarType = T;
using base_type::dimension;
vec3() = default;
constexpr vec3(const this_type&) = default;
// Implicit conversion from base class, to avoid issues on that front.
constexpr CUDA_CALLABLE vec3(const base_type& other) : base_type(other)
{
}
constexpr explicit CUDA_CALLABLE vec3(T value) : base_type(value, value, value)
{
}
constexpr CUDA_CALLABLE vec3(T v0, T v1, T v2) : base_type(v0, v1, v2)
{
}
template <typename OTHER_T>
constexpr explicit CUDA_CALLABLE vec3(const OTHER_T* p) : base_type(p[0], p[1], p[2])
{
}
template <typename OTHER_T>
explicit CUDA_CALLABLE vec3(const vec3<OTHER_T>& other) : base_type(other)
{
}
template <typename OTHER_T>
explicit CUDA_CALLABLE vec3(const base_vec<OTHER_T, 3>& other) : base_type(other)
{
}
template <typename OTHER_T>
CUDA_CALLABLE vec3(const std::initializer_list<OTHER_T>& other) : base_type(other)
{
}
static constexpr CUDA_CALLABLE vec3<T> XAxis()
{
return vec3<T>(T(1), T(0), T(0));
}
static constexpr CUDA_CALLABLE vec3<T> YAxis()
{
return vec3<T>(T(0), T(1), T(0));
}
static constexpr CUDA_CALLABLE vec3<T> ZAxis()
{
return vec3<T>(T(0), T(0), T(1));
}
static CUDA_CALLABLE vec3<T> Axis(size_t axis)
{
return base_type::Axis(axis);
}
CUDA_CALLABLE this_type& Set(T v0, T v1, T v2)
{
v[0] = v0;
v[1] = v1;
v[2] = v2;
return *this;
}
CUDA_CALLABLE this_type& Set(T* p)
{
return Set(p[0], p[1], p[2]);
}
// NOTE: To avoid including Boost unless absolutely necessary, hash_value() is not defined here.
template <typename OTHER_T>
CUDA_CALLABLE bool operator==(const vec3<OTHER_T>& other) const
{
return (v[0] == other[0]) && (v[1] == other[1]) && (v[2] == other[2]);
}
template <typename OTHER_T>
CUDA_CALLABLE bool operator!=(const vec3<OTHER_T>& other) const
{
return !(*this == other);
}
// Returns the portion of this that is parallel to unitVector.
// NOTE: unitVector must have length 1 for this to produce a meaningful result.
CUDA_CALLABLE this_type GetProjection(const this_type& unitVector) const
{
return unitVector * (this->Dot(unitVector));
}
// Returns the portion of this that is orthogonal to unitVector.
// NOTE: unitVector must have length 1 for this to produce a meaningful result.
CUDA_CALLABLE this_type GetComplement(const this_type& unitVector) const
{
return *this - GetProjection(unitVector);
}
CUDA_CALLABLE this_type GetNormalized() const
{
return base_type::GetNormalized();
}
static CUDA_CALLABLE bool OrthogonalizeBasis(vec3<T>* pa, vec3<T>* pb, vec3<T>* pc, bool normalize = true);
CUDA_CALLABLE void BuildOrthonormalFrame(vec3<T>* v1, vec3<T>* v2, float eps = 1e-10) const;
private:
using base_type::v;
};
template <typename T>
CUDA_CALLABLE vec3<T> operator-(const vec3<T>& v)
{
return vec3<T>(-v[0], -v[1], -v[2]);
}
template <typename T>
CUDA_CALLABLE vec3<T> GfCompMult(const vec3<T>& a, const vec3<T>& b)
{
return vec3<T>(a[0] * b[0], a[1] * b[1], a[2] * b[2]);
}
template <typename T>
CUDA_CALLABLE vec3<T> GfCompDiv(const vec3<T>& a, const vec3<T>& b)
{
return vec3<T>(a[0] / b[0], a[1] / b[1], a[2] / b[2]);
}
template <typename T>
CUDA_CALLABLE vec3<T> GfGetNormalized(const vec3<T>& v)
{
return v.GetNormalized();
}
template <typename T>
CUDA_CALLABLE vec3<T> GfGetProjection(const vec3<T>& v, const vec3<T>& unitVector)
{
return v.GetProjection(unitVector);
}
template <typename T>
CUDA_CALLABLE vec3<T> GfGetComplement(const vec3<T>& v, const vec3<T>& unitVector)
{
return v.GetComplement(unitVector);
}
template <typename T>
CUDA_CALLABLE vec3<T> GfRadiansToDegrees(const vec3<T>& radians)
{
return radians * T(180.0 / M_PI);
}
template <typename T>
CUDA_CALLABLE vec3<T> GfDegreesToRadians(const vec3<T>& degrees)
{
return degrees * T(M_PI / 180.0);
}
template <typename T>
CUDA_CALLABLE vec3<T> GfCross(const base_vec<T, 3>& a, const base_vec<T, 3>& b)
{
return vec3<T>(a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]);
}
// NOTE: This is the cross product, NOT the XOR operator!
template <typename T>
CUDA_CALLABLE vec3<T> operator^(const vec3<T>& a, const vec3<T>& b)
{
return GfCross(a, b);
}
template <typename T>
class vec4 : public base_vec<T, 4>
{
public:
using base_type = base_vec<T, 4>;
using this_type = vec4<T>;
using base_type::operator[];
using base_type::data;
using base_type::operator+=;
using base_type::operator-=;
using base_type::operator*=;
using base_type::operator/=;
using base_type::GetArray;
using base_type::GetLength;
using base_type::GetLengthSq;
using base_type::Normalize;
using ScalarType = T;
using base_type::dimension;
vec4() = default;
constexpr vec4(const vec4<T>&) = default;
// Implicit conversion from base class, to avoid issues on that front.
constexpr CUDA_CALLABLE vec4(const base_type& other) : base_type(other)
{
}
constexpr explicit CUDA_CALLABLE vec4(T value) : base_type(value, value, value, value)
{
}
constexpr CUDA_CALLABLE vec4(T v0, T v1, T v2, T v3) : base_type(v0, v1, v2, v3)
{
}
template <typename OTHER_T>
constexpr explicit CUDA_CALLABLE vec4(const OTHER_T* p) : base_type(p[0], p[1], p[2], p[3])
{
}
template <typename OTHER_T>
explicit CUDA_CALLABLE vec4(const vec4<OTHER_T>& other) : base_type(other)
{
}
template <typename OTHER_T>
explicit CUDA_CALLABLE vec4(const base_vec<OTHER_T, 4>& other) : base_type(other)
{
}
template <typename OTHER_T>
CUDA_CALLABLE vec4(const std::initializer_list<OTHER_T>& other) : base_type(other)
{
}
static constexpr CUDA_CALLABLE vec4<T> XAxis()
{
return vec4<T>(T(1), T(0), T(0), T(0));
}
static constexpr CUDA_CALLABLE vec4<T> YAxis()
{
return vec4<T>(T(0), T(1), T(0), T(0));
}
static constexpr CUDA_CALLABLE vec4<T> ZAxis()
{
return vec4<T>(T(0), T(0), T(1), T(0));
}
static constexpr CUDA_CALLABLE vec4<T> WAxis()
{
return vec4<T>(T(0), T(0), T(0), T(1));
}
static CUDA_CALLABLE vec4<T> Axis(size_t axis)
{
return base_type::Axis(axis);
}
CUDA_CALLABLE this_type& Set(T v0, T v1, T v2, T v3)
{
v[0] = v0;
v[1] = v1;
v[2] = v2;
v[3] = v3;
return *this;
}
CUDA_CALLABLE this_type& Set(T* p)
{
return Set(p[0], p[1], p[2], p[3]);
}
// NOTE: To avoid including Boost unless absolutely necessary, hash_value() is not defined here.
template <typename OTHER_T>
CUDA_CALLABLE bool operator==(const vec4<OTHER_T>& other) const
{
return (v[0] == other[0]) && (v[1] == other[1]) && (v[2] == other[2]) && (v[3] == other[3]);
}
template <typename OTHER_T>
CUDA_CALLABLE bool operator!=(const vec4<OTHER_T>& other) const
{
return !(*this == other);
}
// Returns the portion of this that is parallel to unitVector.
// NOTE: unitVector must have length 1 for this to produce a meaningful result.
CUDA_CALLABLE this_type GetProjection(const this_type& unitVector) const
{
return unitVector * (this->Dot(unitVector));
}
// Returns the portion of this that is orthogonal to unitVector.
// NOTE: unitVector must have length 1 for this to produce a meaningful result.
CUDA_CALLABLE this_type GetComplement(const this_type& unitVector) const
{
return *this - GetProjection(unitVector);
}
CUDA_CALLABLE this_type GetNormalized() const
{
return base_type::GetNormalized();
}
CUDA_CALLABLE vec3<T> Project() const
{
T w = v[3];
w = (w != T(0)) ? T(1) / w : T(1);
return w * vec3<T>(v[0], v[1], v[2]);
}
private:
using base_type::v;
};
template <typename T>
CUDA_CALLABLE vec4<T> operator-(const vec4<T>& v)
{
return vec4<T>(-v[0], -v[1], -v[2], -v[3]);
}
template <typename T>
CUDA_CALLABLE vec4<T> GfCompMult(const vec4<T>& a, const vec4<T>& b)
{
return vec4<T>(a[0] * b[0], a[1] * b[1], a[2] * b[2], a[3] * b[3]);
}
template <typename T>
CUDA_CALLABLE vec4<T> GfCompDiv(const vec4<T>& a, const vec4<T>& b)
{
return vec4<T>(a[0] / b[0], a[1] / b[1], a[2] / b[2], a[3] / b[3]);
}
template <typename T>
CUDA_CALLABLE vec4<T> GfGetNormalized(const vec4<T>& v)
{
return v.GetNormalized();
}
template <typename T>
CUDA_CALLABLE vec4<T> GfGetProjection(const vec4<T>& v, const vec4<T>& unitVector)
{
return v.GetProjection(unitVector);
}
template <typename T>
CUDA_CALLABLE vec4<T> GfGetComplement(const vec4<T>& v, const vec4<T>& unitVector)
{
return v.GetComplement(unitVector);
}
template <typename T>
CUDA_CALLABLE bool GfOrthogonalizeBasis(vec3<T>* pa, vec3<T>* pb, vec3<T>* pc, bool normalize = true)
{
// Compute using at least single-precision, to avoid issues with half-precision floating-point values.
using S = typename std::conditional<std::is_same<T, float>::value || std::is_same<T, double>::value, T, float>::type;
vec3<S> a(pa->GetNormalized());
vec3<S> b(pb->GetNormalized());
vec3<S> c(pc->GetNormalized());
if (normalize)
{
pa->Normalize();
pb->Normalize();
pc->Normalize();
}
// This is an arbitrary tolerance that's about 8 ulps in single-precision floating-point.
const double tolerance = 4.8e-7;
const double toleranceSq = tolerance * tolerance;
// This max iteration count is also somewhat arbitrary.
const size_t maxIterations = 32;
size_t iteration;
for (iteration = 0; iteration < maxIterations; ++iteration)
{
vec3<S> newA(a.GetComplement(b));
newA = newA.GetComplement(c);
vec3<S> newB(b.GetComplement(c));
newB = newB.GetComplement(a);
vec3<S> newC(c.GetComplement(a));
newC = newC.GetComplement(b);
if (iteration == 0)
{
// Should only need to check for coplanar vectors on the first iteration.
auto lengthSqA = newA.GetLengthSq();
auto lengthSqB = newB.GetLengthSq();
auto lengthSqC = newC.GetLengthSq();
// The unusual condition form is to catch NaNs.
if (!(lengthSqA >= toleranceSq) || !(lengthSqB >= toleranceSq) || !(lengthSqC >= toleranceSq))
{
return false;
}
}
// Only move a half-step at a time, to avoid instability and improve convergence.
newA = S(0.5) * (a + newA);
newB = S(0.5) * (b + newB);
newC = S(0.5) * (c + newC);
if (normalize)
{
newA.Normalize();
newB.Normalize();
newC.Normalize();
}
S changeSq = (newA - a).GetLengthSq() + (newB - b).GetLengthSq() + (newC - c).GetLengthSq();
if (changeSq < toleranceSq)
{
break;
}
a = newA;
b = newB;
c = newC;
*pa = vec3<T>(a);
*pb = vec3<T>(b);
*pc = vec3<T>(c);
if (!normalize)
{
a.Normalize();
b.Normalize();
c.Normalize();
}
}
return iteration < maxIterations;
}
template <typename T>
CUDA_CALLABLE void GfBuildOrthonormalFrame(const vec3<T>& v0, vec3<T>* v1, vec3<T>* v2, float eps)
{
float length = v0.GetLength();
if (length == 0)
{
*v1 = vec3<T>(0);
*v2 = vec3<T>(0);
}
else
{
vec3<T> unitDir = v0 / length;
*v1 = GfCross(vec3<T>::XAxis(), unitDir);
if (v1->GetLengthSq() < 1e-8)
{
*v1 = GfCross(vec3<T>::YAxis(), unitDir);
}
GfNormalize(v1);
*v2 = GfCross(unitDir, *v1);
if (length < eps)
{
double desiredLen = length / eps;
*v1 *= desiredLen;
*v2 *= desiredLen;
}
}
}
template <typename T>
CUDA_CALLABLE bool vec3<T>::OrthogonalizeBasis(vec3<T>* pa, vec3<T>* pb, vec3<T>* pc, bool normalize)
{
return GfOrthogonalizeBasis(pa, pb, pc, normalize);
}
template <typename T>
CUDA_CALLABLE void vec3<T>::BuildOrthonormalFrame(vec3<T>* v1, vec3<T>* v2, float eps) const
{
return GfBuildOrthonormalFrame(*this, v1, v2, eps);
}
template <typename T, size_t N>
CUDA_CALLABLE base_vec<T, N> GfSlerp(const base_vec<T, N>& a, const base_vec<T, N>& b, double t)
{
const base_vec<double, N> ad(a);
base_vec<double, N> bd(b);
double d = ad.Dot(bd);
const double arbitraryThreshold = (1.0 - 1e-5);
if (d < arbitraryThreshold)
{
const double angle = t * acos(d);
base_vec<double, N> complement;
if (d > -arbitraryThreshold)
{
// Common case: large enough angle between a and b for stable angle from acos and stable complement
complement = bd - d * ad;
}
else
{
// Angle is almost 180 degrees, so pick an arbitrary vector perpendicular to ad
size_t minAxis = 0;
for (size_t axis = 1; axis < N; ++axis)
minAxis = (abs(ad[axis]) < abs(ad[minAxis])) ? axis : minAxis;
base_vec<double, N> complement(0.0);
complement[minAxis] = 1;
complement -= ad.Dot(complement) * ad;
}
complement.Normalize();
return base_vec<T, N>(cos(angle) * ad + sin(angle) * complement);
}
// For small angles, just linearly interpolate.
return base_vec<T, N>(ad + t * (bd - ad));
}
template <typename T>
CUDA_CALLABLE vec2<T> GfSlerp(const vec2<T>& a, const vec2<T>& b, double t)
{
return vec2<T>(GfSlerp((const base_vec<T, 2>&)a, (const base_vec<T, 2>&)b, t));
}
template <typename T>
CUDA_CALLABLE vec3<T> GfSlerp(const vec3<T>& a, const vec3<T>& b, double t)
{
const vec3<double> ad(a);
vec3<double> bd(b);
double d = ad.Dot(bd);
const double arbitraryThreshold = (1.0 - 1e-5);
if (d < arbitraryThreshold)
{
const double angle = t * acos(d);
vec3<double> complement;
if (d > -arbitraryThreshold)
{
// Common case: large enough angle between a and b for stable angle from acos and stable complement
complement = bd - d * ad;
}
else
{
// Angle is almost 180 degrees, so pick an arbitrary vector perpendicular to ad
vec3<double> ofa(0);
vec3<double> unit = ad / ad.GetLength();
vec3<double> xaxis(0);
xaxis[0] = 1;
ofa = GfCross(xaxis, unit);
if (ofa.GetLength() < 1e-8)
{
vec3<double> yaxis(0);
yaxis[1] = 1;
ofa = GfCross(yaxis, unit);
}
ofa.Normalize();
return vec3<T>(cos(t * M_PI) * ad + sin(t * M_PI) * ofa);
}
complement.Normalize();
return vec3<T>(cos(angle) * ad + sin(angle) * complement);
}
// For small angles, just linearly interpolate.
return vec3<T>(ad + t * (bd - ad));
}
template <typename T>
CUDA_CALLABLE vec4<T> GfSlerp(const vec4<T>& a, const vec4<T>& b, double t)
{
return vec4<T>(GfSlerp((const base_vec<T, 4>&)a, (const base_vec<T, 4>&)b, t));
}
// Different parameter order, for compatibility.
template <typename VECTOR_T>
CUDA_CALLABLE VECTOR_T GfSlerp(double t, const VECTOR_T& a, const VECTOR_T& b)
{
return GfSlerp(a, b, t);
}
using vec2h = vec2<half>;
using vec2f = vec2<float>;
using vec2d = vec2<double>;
using vec2i = vec2<int>;
using vec3h = vec3<half>;
using vec3f = vec3<float>;
using vec3d = vec3<double>;
using vec3i = vec3<int>;
using vec4h = vec4<half>;
using vec4f = vec4<float>;
using vec4d = vec4<double>;
using vec4i = vec4<int>;
}
}
}
namespace usdrt
{
using omni::math::linalg::GfBuildOrthonormalFrame;
using omni::math::linalg::GfCompDiv;
using omni::math::linalg::GfCompMult;
using omni::math::linalg::GfCross;
using omni::math::linalg::GfDot;
using omni::math::linalg::GfGetComplement;
using omni::math::linalg::GfGetLength;
using omni::math::linalg::GfGetNormalized;
using omni::math::linalg::GfGetProjection;
using omni::math::linalg::GfIsClose;
using omni::math::linalg::GfNormalize;
using omni::math::linalg::GfOrthogonalizeBasis;
using omni::math::linalg::GfSlerp;
using GfVec2d = omni::math::linalg::vec2<double>;
using GfVec2f = omni::math::linalg::vec2<float>;
using GfVec2h = omni::math::linalg::vec2<omni::math::linalg::half>;
using GfVec2i = omni::math::linalg::vec2<int>;
using GfVec3d = omni::math::linalg::vec3<double>;
using GfVec3f = omni::math::linalg::vec3<float>;
using GfVec3h = omni::math::linalg::vec3<omni::math::linalg::half>;
using GfVec3i = omni::math::linalg::vec3<int>;
using GfVec4d = omni::math::linalg::vec4<double>;
using GfVec4f = omni::math::linalg::vec4<float>;
using GfVec4h = omni::math::linalg::vec4<omni::math::linalg::half>;
using GfVec4i = omni::math::linalg::vec4<int>;
}
| 31,710 | C | 25.536402 | 121 | 0.59363 |
omniverse-code/kit/include/usdrt/gf/half.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
//! @file
//!
//! @brief TODO
#include <usdrt/gf/defines.h>
#include <stdint.h>
#include <type_traits>
namespace omni
{
namespace math
{
namespace linalg
{
class half
{
public:
half() noexcept = default;
constexpr half(const half&) noexcept = default;
constexpr half& operator=(const half&) noexcept = default;
// TODO: Change this to be explicit, once OGN default value code supports explicit conversions.
// Converting to half-precision can be dangerous if unintentional, so make sure it's intentional.
CUDA_CALLABLE half(float f) noexcept : v(floatToHalf(f))
{
static_assert(std::is_pod<half>::value, "half should be a POD type.");
}
// NOTE: This is two roundings, so could occasionally produce a suboptimal rounded value.
explicit CUDA_CALLABLE half(double f) noexcept : v(floatToHalf(float(f)))
{
}
explicit CUDA_CALLABLE half(int i) noexcept : v(floatToHalf(float(i)))
{
}
explicit CUDA_CALLABLE operator float() const noexcept
{
return halfToFloat(v);
}
explicit CUDA_CALLABLE operator double() const noexcept
{
return double(halfToFloat(v));
}
explicit CUDA_CALLABLE operator int() const noexcept
{
return int(halfToFloat(v));
}
CUDA_CALLABLE bool operator<(const half& rhs) const noexcept
{
return halfToFloat(v) < halfToFloat(rhs.bits());
}
CUDA_CALLABLE bool operator<=(const half& rhs) const noexcept
{
return halfToFloat(v) <= halfToFloat(rhs.bits());
}
CUDA_CALLABLE bool operator>(const half& rhs) const noexcept
{
return halfToFloat(v) > halfToFloat(rhs.bits());
}
CUDA_CALLABLE bool operator>=(const half& rhs) const noexcept
{
return halfToFloat(v) >= halfToFloat(rhs.bits());
}
CUDA_CALLABLE bool operator==(const half& rhs) const noexcept
{
return bits() == rhs.bits();
}
CUDA_CALLABLE bool operator!=(const half& rhs) const noexcept
{
return bits() != rhs.bits();
}
CUDA_CALLABLE half operator-() const noexcept
{
half result(-halfToFloat(v));
return result;
}
CUDA_CALLABLE half& operator+=(const half& rhs) noexcept
{
v = floatToHalf(halfToFloat(v) + halfToFloat(rhs.bits()));
return *this;
}
CUDA_CALLABLE half& operator-=(const half& rhs) noexcept
{
v = floatToHalf(halfToFloat(v) - halfToFloat(rhs.bits()));
return *this;
}
CUDA_CALLABLE half& operator*=(const half& rhs) noexcept
{
v = floatToHalf(halfToFloat(v) * halfToFloat(rhs.bits()));
return *this;
}
CUDA_CALLABLE half& operator/=(const half& rhs) noexcept
{
v = floatToHalf(halfToFloat(v) / halfToFloat(rhs.bits()));
return *this;
}
#ifndef DOXYGEN_BUILD
friend CUDA_CALLABLE half operator+(half lhs, const half& rhs)
{
lhs += rhs;
return lhs;
}
friend CUDA_CALLABLE half operator-(half lhs, const half& rhs)
{
lhs -= rhs;
return lhs;
}
friend CUDA_CALLABLE half operator*(half lhs, const half& rhs)
{
lhs *= rhs;
return lhs;
}
friend CUDA_CALLABLE half operator/(half lhs, const half& rhs)
{
lhs /= rhs;
return lhs;
}
#endif // DOXYGEN_BUILD
CUDA_CALLABLE uint16_t& bits() noexcept
{
return v;
}
CUDA_CALLABLE const uint16_t& bits() const noexcept
{
return v;
}
#ifndef DOXYGEN_BUILD
constexpr static uint32_t s_floatMantissaBitCount = 23;
constexpr static uint32_t s_floatMantissaMask = (uint32_t(1) << s_floatMantissaBitCount) - 1;
constexpr static uint32_t s_floatExponentBitCount = 8;
constexpr static uint32_t s_floatShiftedExponentMask = (uint32_t(1) << s_floatExponentBitCount) - 1;
constexpr static uint32_t s_floatExponentExcess = 0x7F;
constexpr static uint32_t s_floatInfExpWithExcess = s_floatShiftedExponentMask;
constexpr static uint16_t s_halfMantissaBitCount = 10;
constexpr static uint16_t s_halfMantissaMask = (uint16_t(1) << s_halfMantissaBitCount) - 1;
constexpr static uint16_t s_halfExponentBitCount = 5;
constexpr static uint16_t s_halfShiftedExponentMask = (uint16_t(1) << s_halfExponentBitCount) - 1;
constexpr static uint16_t s_halfExponentExcess = 0xF;
constexpr static uint16_t s_halfInfExpWithExcess = s_halfShiftedExponentMask;
constexpr static uint32_t s_mantissaBitCountDiff = s_floatMantissaBitCount - s_halfMantissaBitCount;
constexpr static uint32_t s_exponentExcessDiff = s_floatExponentExcess - s_halfExponentExcess;
#endif // DOXYGEN_BUILD
static CUDA_CALLABLE float halfToFloat(uint16_t i) noexcept
{
// Extract parts
uint32_t sign = uint32_t(i >> 15);
uint16_t exponent = (i >> s_halfMantissaBitCount) & s_halfShiftedExponentMask;
uint16_t mantissa = (i & s_halfMantissaMask);
// Shift parts
uint32_t newExponent = (uint32_t(exponent) + s_exponentExcessDiff);
uint32_t newMantissa = (mantissa << s_mantissaBitCountDiff);
if (exponent == s_halfInfExpWithExcess)
{
// Infinity or NaN
newExponent = s_floatInfExpWithExcess;
}
else if (exponent == 0)
{
// Denormal
if (mantissa == 0)
{
// Zero
newExponent = 0;
}
else
{
// Non-zero denormal
++newExponent;
do
{
newMantissa <<= 1;
--newExponent;
} while (!(newMantissa & (s_floatMantissaMask + 1)));
newMantissa &= s_floatMantissaMask;
}
}
uint32_t result = (sign << 31) | (newExponent << s_floatMantissaBitCount) | newMantissa;
static_assert(sizeof(uint32_t) == sizeof(float),
"The following union requires that uint32_t and float are the same size.");
union
{
uint32_t result_i;
float result_f;
};
result_i = result;
return result_f;
}
static CUDA_CALLABLE uint16_t floatToHalf(float f) noexcept
{
static_assert(sizeof(uint32_t) == sizeof(float),
"The following union requires that uint32_t and float are the same size.");
union
{
uint32_t input_i;
float input_f;
};
input_f = f;
uint32_t i = input_i;
// Extract parts
uint32_t sign = uint32_t(i >> 31);
uint32_t exponent = (i >> s_floatMantissaBitCount) & s_floatShiftedExponentMask;
uint32_t mantissa = (i & s_floatMantissaMask);
bool atLeastHalf = false;
bool nonZeroLowBits = false;
uint16_t newExponent;
uint16_t newMantissa;
if (exponent >= (s_exponentExcessDiff + s_halfInfExpWithExcess))
{
// New value will be infinity or NaN
newExponent = s_halfInfExpWithExcess;
if (exponent == s_floatInfExpWithExcess)
{
// Old value was infinity or NaN
newMantissa = (mantissa >> s_mantissaBitCountDiff);
if (mantissa != 0 && newMantissa == 0)
{
// Preserve NaN
newMantissa = 1;
}
}
else
{
// New infinity
newMantissa = 0;
}
}
// NOTE: s_exponentExcessDiff is the smallest half-precision exponent with single-precision's excess.
else if (exponent <= s_exponentExcessDiff)
{
// New value will be denormal (unless rounded up to normal)
newExponent = 0;
if (exponent < (s_exponentExcessDiff - s_halfMantissaBitCount))
{
// Zero
newMantissa = 0;
}
else
{
// Non-zero denormal
mantissa += (s_floatMantissaMask + 1);
std::size_t shift = (s_exponentExcessDiff + 1) + s_mantissaBitCountDiff - exponent;
newMantissa = (mantissa >> shift);
atLeastHalf = ((mantissa >> (shift - 1)) & 1);
nonZeroLowBits = (mantissa & ((1 << (shift - 1)) - 1)) != 0;
}
}
else
{
// New value will be normal (unless rounded up to infinity)
newMantissa = (mantissa >> s_mantissaBitCountDiff);
newExponent = exponent - s_exponentExcessDiff;
atLeastHalf = ((mantissa >> (s_mantissaBitCountDiff - 1)) & 1);
nonZeroLowBits = (mantissa & ((1 << (s_mantissaBitCountDiff - 1)) - 1)) != 0;
}
// Round half to even
bool odd = (newMantissa & 1);
newMantissa += atLeastHalf && (nonZeroLowBits || odd);
if (newMantissa == (s_halfMantissaMask + 1))
{
newMantissa = 0;
++newExponent;
}
uint16_t result = (sign << 15) | (newExponent << s_halfMantissaBitCount) | newMantissa;
return result;
}
private:
uint16_t v;
};
}
}
}
namespace usdrt
{
using GfHalf = omni::math::linalg::half;
}
| 9,814 | C | 29.386997 | 109 | 0.58549 |
omniverse-code/kit/include/usdrt/gf/quat.h | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
//! @file
//!
//! @brief TODO
#include <usdrt/gf/defines.h>
#include <usdrt/gf/math.h>
#include <usdrt/gf/vec.h>
#include <initializer_list>
namespace omni
{
namespace math
{
namespace linalg
{
// Forward declaration, just for the using statement, below.
class half;
template <typename T>
class quat : private base_vec<T, 4>
{
public:
using base_type = base_vec<T, 4>;
// usdrt edit
using typename base_type::const_iterator;
using typename base_type::const_pointer;
using typename base_type::const_reference;
using typename base_type::difference_type;
using typename base_type::iterator;
using typename base_type::pointer;
using typename base_type::reference;
using typename base_type::size_type;
using typename base_type::value_type;
// end usdrt edit
using ScalarType = T;
using ImaginaryType = vec3<T>;
#ifndef DOXYGEN_BUILD
constexpr static size_t dimension = 4;
constexpr static size_t real_index = 3;
constexpr static size_t imaginary_index = 0;
#endif // DOXYGEN_BUILD
quat() = default;
constexpr quat(const quat<T>&) = default;
// Explicit conversion from base class, to avoid issues on that front.
constexpr explicit CUDA_CALLABLE quat(const base_type& other) : base_type(other)
{
}
// NOTE: This usually only makes sense for real being -1, 0, or 1.
constexpr explicit CUDA_CALLABLE quat(T real) : base_type(T(0), T(0), T(0), real)
{
}
// NOTE: The order of the arguments is different from the order in memory!
constexpr CUDA_CALLABLE quat(T real, T i, T j, T k) : base_type(i, j, k, real)
{
}
// NOTE: The order of the arguments is different from the order in memory!
constexpr CUDA_CALLABLE quat(T real, vec3<T> imaginary) : base_type(imaginary[0], imaginary[1], imaginary[2], real)
{
}
template <typename OTHER_T>
explicit CUDA_CALLABLE quat(const quat<OTHER_T>& other) : quat(T(other.GetReal()), vec3<T>(other.GetImaginary()))
{
}
// NOTE: The order of the arguments is different from the order in memory,
// so we can't delegate directly to the base class constructor.
template <typename OTHER_T>
CUDA_CALLABLE quat(const std::initializer_list<OTHER_T>& other) noexcept : base_type(T(0), T(0), T(0), T(0))
{
CUDA_SAFE_ASSERT(other.size() == 4);
if (other.size() != 4)
return;
// Order change as above
base_type::operator[](0) = other.begin()[1];
base_type::operator[](1) = other.begin()[2];
base_type::operator[](2) = other.begin()[3];
base_type::operator[](3) = other.begin()[0];
}
static CUDA_CALLABLE quat<T> GetIdentity()
{
return quat<T>(T(1));
}
CUDA_CALLABLE T GetReal() const
{
return base_type::operator[](real_index);
}
CUDA_CALLABLE void SetReal(T real)
{
base_type::operator[](real_index) = real;
}
CUDA_CALLABLE vec3<T> GetImaginary() const
{
return vec3<T>(base_type::operator[](imaginary_index), base_type::operator[](imaginary_index + 1),
base_type::operator[](imaginary_index + 2));
}
CUDA_CALLABLE void SetImaginary(const vec3<T>& imaginary)
{
base_type::operator[](imaginary_index) = imaginary[0];
base_type::operator[](imaginary_index + 1) = imaginary[1];
base_type::operator[](imaginary_index + 2) = imaginary[2];
}
CUDA_CALLABLE void SetImaginary(T i, T j, T k)
{
base_type::operator[](imaginary_index) = i;
base_type::operator[](imaginary_index + 1) = j;
base_type::operator[](imaginary_index + 2) = k;
}
constexpr CUDA_CALLABLE T Dot(const quat<T>& other) const
{
return base_type::Dot(other);
// return GetImaginary().Dot(other.GetImaginary()) + GetReal() * other.GetReal();
}
using base_type::data;
using base_type::GetLength;
using base_type::GetLengthSq;
using base_type::Normalize;
#ifndef DOXYGEN_BUILD
CUDA_CALLABLE quat<T> GetNormalized() const
{
return quat<T>(base_type::GetNormalized());
}
#endif // DOXYGEN_BUILD
CUDA_CALLABLE quat<T> GetConjugate() const
{
return quat<T>(GetReal(), -GetImaginary());
}
CUDA_CALLABLE quat<T> GetInverse() const
{
return GetConjugate() / GetLengthSq();
}
CUDA_CALLABLE vec3<T> Transform(const vec3<T>& point) const
{
const auto& cosTheta = GetReal();
const T cosTheta2 = GetReal() * GetReal();
const vec3<T> sinThetas = GetImaginary();
const T sinTheta2 = sinThetas.GetLengthSq();
const T length2 = cosTheta2 + sinTheta2;
const T cos2Theta = cosTheta2 - sinTheta2;
return (cos2Theta * point +
((2 * GfDot(sinThetas, point)) * sinThetas + (2 * cosTheta) * GfCross(sinThetas, point))) /
length2;
}
// NOTE: To avoid including Boost unless absolutely necessary, hash_value() is not defined here.
CUDA_CALLABLE quat<T> operator-() const
{
return quat<T>(-GetReal(), -GetImaginary());
}
CUDA_CALLABLE bool operator==(const quat<T>& other) const
{
return (GetImaginary() == other.GetImaginary()) && (GetReal() == other.GetReal());
}
CUDA_CALLABLE bool operator!=(const quat<T>& other) const
{
return !(*this == other);
}
CUDA_CALLABLE quat<T>& operator*=(const quat<T>& other)
{
const T r0 = GetReal();
const T r1 = other.GetReal();
const vec3<T> i0 = GetImaginary();
const vec3<T> i1 = other.GetImaginary();
// TODO: This isn't the most efficient way to multiply two quaternions.
SetImaginary(r0 * i1 + r1 * i0 + GfCross(i0, i1));
SetReal(r0 * r1 - i0.Dot(i1));
return *this;
}
CUDA_CALLABLE quat<T>& operator*=(T scalar)
{
base_type::operator*=(scalar);
return *this;
}
CUDA_CALLABLE quat<T>& operator/=(T scalar)
{
base_type::operator/=(scalar);
return *this;
}
CUDA_CALLABLE quat<T>& operator+=(const quat<T>& other)
{
base_type::operator+=(other);
return *this;
}
CUDA_CALLABLE quat<T>& operator-=(const quat<T>& other)
{
base_type::operator-=(other);
return *this;
}
#ifndef DOXYGEN_BUILD
friend CUDA_CALLABLE quat<T> operator+(const quat<T>& a, const quat<T>& b)
{
return quat<T>(((const base_type&)a) + ((const base_type&)b));
}
friend CUDA_CALLABLE quat<T> operator-(const quat<T>& a, const quat<T>& b)
{
return quat<T>(((const base_type&)a) - ((const base_type&)b));
}
friend CUDA_CALLABLE quat<T> operator*(const quat<T>& a, const quat<T>& b)
{
quat<T> product(a);
product *= b;
return product;
}
friend CUDA_CALLABLE quat<T> operator*(const quat<T>& q, T scalar)
{
return quat<T>(((const base_type&)q) * scalar);
}
friend CUDA_CALLABLE quat<T> operator*(T scalar, const quat<T>& q)
{
return quat<T>(((const base_type&)q) * scalar);
}
friend CUDA_CALLABLE quat<T> operator/(const quat<T>& q, T scalar)
{
return quat<T>(((const base_type&)q) / scalar);
}
#endif
};
template <typename T>
CUDA_CALLABLE T GfDot(const quat<T>& a, const quat<T>& b)
{
return a.Dot(b);
}
template <typename T>
CUDA_CALLABLE bool GfIsClose(const quat<T>& a, const quat<T>& b, double tolerance)
{
auto distanceSq = (a - b).GetLengthSq();
return distanceSq <= tolerance * tolerance;
}
template <typename T>
CUDA_CALLABLE quat<T> GfSlerp(const quat<T>& a, const quat<T>& b, double t)
{
const quat<double> ad(a);
quat<double> bd(b);
double d = ad.Dot(bd);
// NOTE: Although a proper slerp wouldn't flip b on negative dot, this flips b
// for compatibility. Quaternions cover the space of orientations twice, so this
// avoids interpolating between orientations that are more than 180 degrees apart.
if (d < 0)
{
bd = -bd;
d = -d;
}
const double arbitraryThreshold = (1.0 - 1e-5);
if (d < arbitraryThreshold)
{
// Common case: large enough angle between a and b for stable angle from acos and stable complement
const double angle = t * std::acos(d);
quat<double> complement = bd - d * ad;
complement.Normalize();
return quat<T>(std::cos(angle) * ad + std::sin(angle) * complement);
}
// For small angles, just linearly interpolate.
return quat<T>(ad + t * (bd - ad));
}
using quath = quat<half>;
using quatf = quat<float>;
using quatd = quat<double>;
// Alphabetical order (same order as pxr::UsdGeomXformCommonAPI::RotationOrder)
enum class EulerRotationOrder
{
XYZ,
XZY,
YXZ,
YZX,
ZXY,
ZYX
};
static constexpr size_t s_eulerRotationOrderAxes[6][3] = {
{ 0, 1, 2 }, // XYZ
{ 0, 2, 1 }, // XZY
{ 1, 0, 2 }, // YXZ
{ 1, 2, 0 }, // YZX
{ 2, 0, 1 }, // ZXY
{ 2, 1, 0 } // ZYX
};
// eulerAngles is in radians. You can use GfDegreesToRadians to convert.
template <typename T>
CUDA_CALLABLE quatd eulerAnglesToQuaternion(const vec3<T>& eulerAngles, EulerRotationOrder order)
{
// There's almost certainly a more efficient way to do this, but this should work,
// (unless the quaternion order is backward from what's needed, but then
// choosing the reverse rotation order should address that.)
// Quaternions are applied "on both sides", so each contains half the rotation,
// or at least that's a mnemonic to remember to half it.
const vec3d halfAngles = 0.5 * vec3d(eulerAngles);
const double cx = std::cos(halfAngles[0]);
const double sx = std::sin(halfAngles[0]);
const double cy = std::cos(halfAngles[1]);
const double sy = std::sin(halfAngles[1]);
const double cz = std::cos(halfAngles[2]);
const double sz = std::sin(halfAngles[2]);
const quatd qs[3] = { quatd(cx, vec3d(sx, 0, 0)), quatd(cy, vec3d(0, sy, 0)), quatd(cz, vec3d(0, 0, sz)) };
// Apply the quaternions in the specified order
// NOTE: Even though USD matrix transformations are applied to row vectors from left to right,
// quaternions are still applied from right to left, like standard quaternions.
const size_t* const orderAxes = s_eulerRotationOrderAxes[size_t(order)];
const quatd q = qs[orderAxes[2]] * qs[orderAxes[1]] * qs[orderAxes[0]];
return q;
}
}
}
}
namespace usdrt
{
using omni::math::linalg::GfDot;
using omni::math::linalg::GfIsClose;
using omni::math::linalg::GfSlerp;
using GfQuatd = omni::math::linalg::quat<double>;
using GfQuatf = omni::math::linalg::quat<float>;
using GfQuath = omni::math::linalg::quat<omni::math::linalg::half>;
}
| 11,278 | C | 29.483784 | 119 | 0.625288 |
omniverse-code/kit/include/usdrt/gf/rect.h | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
//! @file
//!
//! @brief TODO
#include <carb/Defines.h>
#include <usdrt/gf/vec.h>
#include <float.h>
namespace usdrt
{
struct GfRect2i
{
public:
// In order to make GfRect2i a POD type we need to give up on non-default constructor
// pxr::GfRect2i initializes to empty, so we're not 100% compatible here!
GfRect2i() = default;
constexpr GfRect2i(const GfRect2i&) = default;
/// Helper typedef.
using MinMaxType = GfVec2i;
static const size_t dimension = MinMaxType::dimension;
using ScalarType = MinMaxType::ScalarType;
/// Constructs a rectangle with \p min and \p max corners.
constexpr GfRect2i(const GfVec2i& min, const GfVec2i& max) : _min(min), _max(max)
{
}
/// Constructs a rectangle with \p min corner and the indicated \p width
/// and \p height.
GfRect2i(const GfVec2i& min, int width, int height) : _min(min), _max(min + GfVec2i(width - 1, height - 1))
{
}
/// Returns true if the rectangle is a null rectangle.
///
/// A null rectangle has both the width and the height set to 0, that is
/// \code
/// GetMaxX() == GetMinX() - 1
/// \endcode
/// and
/// \code
/// GetMaxY() == GetMinY() - 1
/// \endcode
/// Remember that if \c GetMinX() and \c GetMaxX() return the same value
/// then the rectangle has width 1, and similarly for the height.
///
/// A null rectangle is both empty, and not valid.
bool IsNull() const
{
return GetWidth() == 0 && GetHeight() == 0;
}
/// Returns true if the rectangle is empty.
///
/// An empty rectangle has one or both of its min coordinates strictly
/// greater than the corresponding max coordinate.
///
/// An empty rectangle is not valid.
bool IsEmpty() const
{
return GetWidth() <= 0 || GetHeight() <= 0;
}
/// Return true if the rectangle is valid (equivalently, not empty).
bool IsValid() const
{
return !IsEmpty();
}
/// Returns a normalized rectangle, i.e. one that has a non-negative width
/// and height.
///
/// \c GetNormalized() swaps the min and max x-coordinates to
/// ensure a non-negative width, and similarly for the
/// y-coordinates.
GfRect2i GetNormalized() const
{
GfVec2i min, max;
if (_max[0] < _min[0])
{
min[0] = _max[0];
max[0] = _min[0];
}
else
{
min[0] = _min[0];
max[0] = _max[0];
}
if (_max[1] < _min[1])
{
min[1] = _max[1];
max[1] = _min[1];
}
else
{
min[1] = _min[1];
max[1] = _max[1];
}
return GfRect2i(min, max);
}
/// Returns the min corner of the rectangle.
const GfVec2i& GetMin() const
{
return _min;
}
/// Returns the max corner of the rectangle.
const GfVec2i& GetMax() const
{
return _max;
}
/// Return the X value of min corner.
///
int GetMinX() const
{
return _min[0];
}
/// Set the X value of the min corner.
///
void SetMinX(int x)
{
_min[0] = x;
}
/// Return the X value of the max corner.
///
int GetMaxX() const
{
return _max[0];
}
/// Set the X value of the max corner
void SetMaxX(int x)
{
_max[0] = x;
}
/// Return the Y value of the min corner
///
int GetMinY() const
{
return _min[1];
}
/// Set the Y value of the min corner.
///
void SetMinY(int y)
{
_min[1] = y;
}
/// Return the Y value of the max corner
int GetMaxY() const
{
return _max[1];
}
/// Set the Y value of the max corner
void SetMaxY(int y)
{
_max[1] = y;
}
/// Sets the min corner of the rectangle.
void SetMin(const GfVec2i& min)
{
_min = min;
}
/// Sets the max corner of the rectangle.
void SetMax(const GfVec2i& max)
{
_max = max;
}
/// Returns the center point of the rectangle.
GfVec2i GetCenter() const
{
return (_min + _max) / 2;
}
/// Move the rectangle by \p displ.
void Translate(const GfVec2i& displacement)
{
_min += displacement;
_max += displacement;
}
/// Return the area of the rectangle.
unsigned long GetArea() const
{
return (unsigned long)GetWidth() * (unsigned long)GetHeight();
}
/// Returns the size of the rectangle as a vector (width,height).
GfVec2i GetSize() const
{
return GfVec2i(GetWidth(), GetHeight());
}
/// Returns the width of the rectangle.
///
/// \note If the min and max x-coordinates are coincident, the width is
/// one.
int GetWidth() const
{
return (_max[0] - _min[0]) + 1;
}
/// Returns the height of the rectangle.
///
/// \note If the min and max y-coordinates are coincident, the height is
/// one.
int GetHeight() const
{
return (_max[1] - _min[1]) + 1;
}
/// Computes the intersection of two rectangles.
GfRect2i GetIntersection(const GfRect2i& that) const
{
if (IsEmpty())
return *this;
else if (that.IsEmpty())
return that;
else
return GfRect2i(GfVec2i(GfMax(_min[0], that._min[0]), GfMax(_min[1], that._min[1])),
GfVec2i(GfMin(_max[0], that._max[0]), GfMin(_max[1], that._max[1])));
}
/// Computes the intersection of two rectangles.
/// \deprecated Use GetIntersection() instead
GfRect2i Intersect(const GfRect2i& that) const
{
return GetIntersection(that);
}
/// Computes the union of two rectangles.
GfRect2i GetUnion(const GfRect2i& that) const
{
if (IsEmpty())
return that;
else if (that.IsEmpty())
return *this;
else
return GfRect2i(GfVec2i(GfMin(_min[0], that._min[0]), GfMin(_min[1], that._min[1])),
GfVec2i(GfMax(_max[0], that._max[0]), GfMax(_max[1], that._max[1])));
}
/// Computes the union of two rectangles
/// \deprecated Use GetUnion() instead.
GfRect2i Union(const GfRect2i& that) const
{
return GetUnion(that);
}
/// Returns true if the specified point in the rectangle.
bool Contains(const GfVec2i& p) const
{
return ((p[0] >= _min[0]) && (p[0] <= _max[0]) && (p[1] >= _min[1]) && (p[1] <= _max[1]));
}
/// Returns true if \p r1 and \p r2 are equal.
friend bool operator==(const GfRect2i& r1, const GfRect2i& r2)
{
return r1._min == r2._min && r1._max == r2._max;
}
/// Returns true if \p r1 and \p r2 are different.
friend bool operator!=(const GfRect2i& r1, const GfRect2i& r2)
{
return !(r1 == r2);
}
/// Computes the union of two rectangles.
/// \see GetUnion()
GfRect2i operator+=(const GfRect2i& that)
{
*this = GetUnion(that);
return *this;
}
friend GfRect2i operator+(const GfRect2i r1, const GfRect2i& r2)
{
GfRect2i tmp(r1);
tmp += r2;
return tmp;
}
private:
GfVec2i _min = { 0, 0 };
GfVec2i _max = { -1, -1 };
};
}
| 7,830 | C | 23.70347 | 111 | 0.554023 |
omniverse-code/kit/include/usdrt/gf/math.h | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
//! @file
//!
//! @brief TODO
#ifdef _MSC_VER
// This is for M_PI
# define _USE_MATH_DEFINES
# include <math.h>
#endif
#include <usdrt/gf/defines.h>
#include <cmath>
namespace omni
{
namespace math
{
namespace linalg
{
// WARNING: Non-standard parameter order, for compatibility!
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfLerp(double t, const VALUE_T& a, const VALUE_T& b)
{
// Always use the difference, so that if a==b, a value equal to both
// will be returned, instead of one that might have roundoff error.
return a + t * (b - a);
}
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfRadiansToDegrees(VALUE_T radians)
{
return radians * VALUE_T(180.0 / M_PI);
}
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfDegreesToRadians(VALUE_T degrees)
{
return degrees * VALUE_T(M_PI / 180.0);
}
CUDA_CALLABLE inline bool GfIsClose(double a, double b, double epsilon)
{
return fabs(a - b) < epsilon;
}
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfMin(VALUE_T a1, VALUE_T a2)
{
return (a1 < a2 ? a1 : a2);
}
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfMin(VALUE_T a1, VALUE_T a2, VALUE_T a3)
{
return GfMin(GfMin(a1, a2), a3);
}
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfMin(VALUE_T a1, VALUE_T a2, VALUE_T a3, VALUE_T a4)
{
return GfMin(GfMin(a1, a2, a3), a4);
}
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfMin(VALUE_T a1, VALUE_T a2, VALUE_T a3, VALUE_T a4, VALUE_T a5)
{
return GfMin(GfMin(a1, a2, a3, a4), a5);
}
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfMax(VALUE_T a1, VALUE_T a2)
{
return (a1 < a2 ? a2 : a1);
}
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfMax(VALUE_T a1, VALUE_T a2, VALUE_T a3)
{
return GfMax(GfMax(a1, a2), a3);
}
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfMax(VALUE_T a1, VALUE_T a2, VALUE_T a3, VALUE_T a4)
{
return GfMax(GfMax(a1, a2, a3), a4);
}
template <typename VALUE_T>
CUDA_CALLABLE VALUE_T GfMax(VALUE_T a1, VALUE_T a2, VALUE_T a3, VALUE_T a4, VALUE_T a5)
{
return GfMax(GfMax(a1, a2, a3, a4), a5);
}
template <class VALUE_T>
inline double GfSqr(const VALUE_T& x)
{
return x * x;
}
}
}
}
namespace usdrt
{
using omni::math::linalg::GfDegreesToRadians;
using omni::math::linalg::GfIsClose;
using omni::math::linalg::GfLerp;
using omni::math::linalg::GfMax;
using omni::math::linalg::GfMin;
using omni::math::linalg::GfRadiansToDegrees;
using omni::math::linalg::GfSqr;
}
| 2,917 | C | 21.796875 | 87 | 0.699349 |
omniverse-code/kit/include/usdrt/gf/range.h | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
//! @file
//!
//! @brief TODO
#include <carb/Defines.h>
#include <usdrt/gf/vec.h>
namespace omni
{
namespace math
{
namespace linalg
{
// specializing range for 1 dimensions to use float and match GfRange1(d|f)
template <typename T>
class range1
{
public:
static const size_t dimension = 1;
using MinMaxType = T;
using ScalarType = T;
using ThisType = range1<T>;
/// Sets the range to an empty interval
// TODO check whether this can be deprecated.
void inline SetEmpty()
{
_min = std::numeric_limits<ScalarType>::max();
_max = -std::numeric_limits<ScalarType>::max();
}
/// The default constructor creates an empty range.
range1() = default;
constexpr range1(const ThisType&) = default;
constexpr explicit range1(ScalarType size) : _min(-size), _max(size)
{
}
/// This constructor initializes the minimum and maximum points.
constexpr range1(ScalarType min, ScalarType max) : _min(min), _max(max)
{
}
/// Returns the minimum value of the range.
ScalarType GetMin() const
{
return _min;
}
/// Returns the maximum value of the range.
ScalarType GetMax() const
{
return _max;
}
/// Returns the size of the range.
ScalarType GetSize() const
{
return _max - _min;
}
/// Returns the midpoint of the range, that is, 0.5*(min+max).
/// Note: this returns zero in the case of default-constructed ranges,
/// or ranges set via SetEmpty().
ScalarType GetMidpoint() const
{
return static_cast<ScalarType>(0.5) * _min + static_cast<ScalarType>(0.5) * _max;
}
/// Sets the minimum value of the range.
void SetMin(ScalarType min)
{
_min = min;
}
/// Sets the maximum value of the range.
void SetMax(ScalarType max)
{
_max = max;
}
/// Returns whether the range is empty (max < min).
bool IsEmpty() const
{
return _min > _max;
}
/// Modifies the range if necessary to surround the given value.
/// \deprecated Use UnionWith() instead.
void ExtendBy(ScalarType point)
{
UnionWith(point);
}
/// Modifies the range if necessary to surround the given range.
/// \deprecated Use UnionWith() instead.
void ExtendBy(const ThisType& range)
{
UnionWith(range);
}
/// Returns true if the \p point is located inside the range. As with all
/// operations of this type, the range is assumed to include its extrema.
bool Contains(const ScalarType& point) const
{
return (point >= _min && point <= _max);
}
/// Returns true if the \p range is located entirely inside the range. As
/// with all operations of this type, the ranges are assumed to include
/// their extrema.
bool Contains(const ThisType& range) const
{
return Contains(range._min) && Contains(range._max);
}
/// Returns true if the \p point is located inside the range. As with all
/// operations of this type, the range is assumed to include its extrema.
/// \deprecated Use Contains() instead.
bool IsInside(ScalarType point) const
{
return Contains(point);
}
/// Returns true if the \p range is located entirely inside the range. As
/// with all operations of this type, the ranges are assumed to include
/// their extrema.
/// \deprecated Use Contains() instead.
bool IsInside(const ThisType& range) const
{
return Contains(range);
}
/// Returns true if the \p range is located entirely outside the range. As
/// with all operations of this type, the ranges are assumed to include
/// their extrema.
bool IsOutside(const ThisType& range) const
{
return (range._max < _min || range._min > _max);
}
/// Returns the smallest \c GfRange1f which contains both \p a and \p b.
static ThisType GetUnion(const ThisType& a, const ThisType& b)
{
auto res = a;
_FindMin(res._min, b._min);
_FindMax(res._max, b._max);
return res;
}
/// Extend \p this to include \p b.
const ThisType& UnionWith(const ThisType& b)
{
_FindMin(_min, b._min);
_FindMax(_max, b._max);
return *this;
}
/// Extend \p this to include \p b.
const ThisType& UnionWith(const ScalarType& b)
{
_FindMin(_min, b);
_FindMax(_max, b);
return *this;
}
/// Returns the smallest \c GfRange1f which contains both \p a and \p b
/// \deprecated Use GetUnion() instead.
static ThisType Union(const ThisType& a, const ThisType& b)
{
return GetUnion(a, b);
}
/// Extend \p this to include \p b.
/// \deprecated Use UnionWith() instead.
const ThisType& Union(const ThisType& b)
{
return UnionWith(b);
}
/// Extend \p this to include \p b.
/// \deprecated Use UnionWith() instead.
const ThisType& Union(ScalarType b)
{
return UnionWith(b);
}
/// Returns a \c GfRange1f that describes the intersection of \p a and \p b.
static ThisType GetIntersection(const ThisType& a, const ThisType& b)
{
auto res = a;
_FindMax(res._min, b._min);
_FindMin(res._max, b._max);
return res;
}
/// Returns a \c GfRange1f that describes the intersection of \p a and \p b.
/// \deprecated Use GetIntersection() instead.
static ThisType Intersection(const ThisType& a, const ThisType& b)
{
return GetIntersection(a, b);
}
/// Modifies this range to hold its intersection with \p b and returns the
/// result
const ThisType& IntersectWith(const ThisType& b)
{
_FindMax(_min, b._min);
_FindMin(_max, b._max);
return *this;
}
/// Modifies this range to hold its intersection with \p b and returns the
/// result.
/// \deprecated Use IntersectWith() instead.
const ThisType& Intersection(const ThisType& b)
{
return IntersectWith(b);
}
/// unary sum.
ThisType operator+=(const ThisType& b)
{
_min += b._min;
_max += b._max;
return *this;
}
/// unary difference.
ThisType operator-=(const ThisType& b)
{
_min -= b._max;
_max -= b._min;
return *this;
}
/// unary multiply.
ThisType operator*=(double m)
{
if (m > 0)
{
_min *= m;
_max *= m;
}
else
{
float tmp = _min;
_min = _max * m;
_max = tmp * m;
}
return *this;
}
/// unary division.
ThisType operator/=(double m)
{
return *this *= (1.0 / m);
}
/// binary sum.
ThisType operator+(const ThisType& b) const
{
return ThisType(_min + b._min, _max + b._max);
}
/// binary difference.
ThisType operator-(const ThisType& b) const
{
return ThisType(_min - b._max, _max - b._min);
}
/// scalar multiply.
friend ThisType operator*(double m, const ThisType& r)
{
return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m));
}
/// scalar multiply.
friend ThisType operator*(const ThisType& r, double m)
{
return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m));
}
/// scalar divide.
friend ThisType operator/(const ThisType& r, double m)
{
return r * (1.0 / m);
}
inline bool operator==(const ThisType& other) const
{
return _min == static_cast<ScalarType>(other.GetMin()) && _max == static_cast<ScalarType>(other.GetMax());
}
inline bool operator!=(const ThisType& other) const
{
return !(*this == other);
}
/// Compute the squared distance from a point to the range.
double GetDistanceSquared(ScalarType p) const
{
double dist = 0.0;
if (p < _min)
{
// p is left of box
dist += GfSqr(_min - p);
}
else if (p > _max)
{
// p is right of box
dist += GfSqr(p - _max);
}
return dist;
}
private:
/// Minimum and maximum points.
ScalarType _min, _max;
/// Extends minimum point if necessary to contain given point.
static void _FindMin(ScalarType& dest, ScalarType point)
{
if (point < dest)
{
dest = point;
}
}
/// Extends maximum point if necessary to contain given point.
static void _FindMax(ScalarType& dest, ScalarType point)
{
if (point > dest)
{
dest = point;
}
}
};
template <typename T>
class range2
{
public:
static const size_t dimension = 2;
using ScalarType = T;
using MinMaxType = omni::math::linalg::vec2<T>;
using ThisType = range2<T>;
range2() = default;
constexpr range2(const ThisType&) = default;
constexpr explicit range2(ScalarType size) : _min(-size), _max(size)
{
}
/// Sets the range to an empty interval
// TODO check whether this can be deprecated.
constexpr void inline SetEmpty()
{
_min = { std::numeric_limits<ScalarType>::max() };
_max = { -std::numeric_limits<ScalarType>::max() };
}
/// This constructor initializes the minimum and maximum points.
constexpr range2(const MinMaxType& min, const MinMaxType& max) : _min(min), _max(max)
{
}
/// Returns the minimum value of the range.
const MinMaxType& GetMin() const
{
return _min;
}
/// Returns the maximum value of the range.
const MinMaxType& GetMax() const
{
return _max;
}
/// Returns the size of the range.
MinMaxType GetSize() const
{
return _max - _min;
}
/// Returns the midpoint of the range, that is, 0.5*(min+max).
/// Note: this returns zero in the case of default-constructed ranges,
/// or ranges set via SetEmpty().
MinMaxType GetMidpoint() const
{
return static_cast<ScalarType>(0.5) * _min + static_cast<ScalarType>(0.5) * _max;
}
/// Sets the minimum value of the range.
void SetMin(const MinMaxType& min)
{
_min = min;
}
/// Sets the maximum value of the range.
void SetMax(const MinMaxType& max)
{
_max = max;
}
/// Returns whether the range is empty (max < min).
bool IsEmpty() const
{
return _min[0] > _max[0] || _min[1] > _max[1];
}
/// Modifies the range if necessary to surround the given value.
/// \deprecated Use UnionWith() instead.
void ExtendBy(const MinMaxType& point)
{
UnionWith(point);
}
/// Modifies the range if necessary to surround the given range.
/// \deprecated Use UnionWith() instead.
void ExtendBy(const ThisType& range)
{
UnionWith(range);
}
/// Returns true if the \p point is located inside the range. As with all
/// operations of this type, the range is assumed to include its extrema.
bool Contains(const MinMaxType& point) const
{
return (point[0] >= _min[0] && point[0] <= _max[0] && point[1] >= _min[1] && point[1] <= _max[1]);
}
/// Returns true if the \p range is located entirely inside the range. As
/// with all operations of this type, the ranges are assumed to include
/// their extrema.
bool Contains(const ThisType& range) const
{
return Contains(range._min) && Contains(range._max);
}
/// Returns true if the \p point is located inside the range. As with all
/// operations of this type, the range is assumed to include its extrema.
/// \deprecated Use Contains() instead.
bool IsInside(const MinMaxType& point) const
{
return Contains(point);
}
/// Returns true if the \p range is located entirely inside the range. As
/// with all operations of this type, the ranges are assumed to include
/// their extrema.
/// \deprecated Use Contains() instead.
bool IsInside(const ThisType& range) const
{
return Contains(range);
}
/// Returns true if the \p range is located entirely outside the range. As
/// with all operations of this type, the ranges are assumed to include
/// their extrema.
bool IsOutside(const ThisType& range) const
{
return ((range._max[0] < _min[0] || range._min[0] > _max[0]) ||
(range._max[1] < _min[1] || range._min[1] > _max[1]));
}
/// Returns the smallest \c ThisType which contains both \p a and \p b.
static ThisType GetUnion(const ThisType& a, const ThisType& b)
{
auto res = a;
_FindMin(res._min, b._min);
_FindMax(res._max, b._max);
return res;
}
/// Extend \p this to include \p b.
const ThisType& UnionWith(const ThisType& b)
{
_FindMin(_min, b._min);
_FindMax(_max, b._max);
return *this;
}
/// Extend \p this to include \p b.
const ThisType& UnionWith(const MinMaxType& b)
{
_FindMin(_min, b);
_FindMax(_max, b);
return *this;
}
/// Returns the smallest \c ThisType which contains both \p a and \p b
/// \deprecated Use GetUnion() instead.
static ThisType Union(const ThisType& a, const ThisType& b)
{
return GetUnion(a, b);
}
/// Extend \p this to include \p b.
/// \deprecated Use UnionWith() instead.
const ThisType& Union(const ThisType& b)
{
return UnionWith(b);
}
/// Extend \p this to include \p b.
/// \deprecated Use UnionWith() instead.
const ThisType& Union(const MinMaxType& b)
{
return UnionWith(b);
}
/// Returns a \c ThisType that describes the intersection of \p a and \p b.
static ThisType GetIntersection(const ThisType& a, const ThisType& b)
{
auto res = a;
_FindMax(res._min, b._min);
_FindMin(res._max, b._max);
return res;
}
/// Returns a \c ThisType that describes the intersection of \p a and \p b.
/// \deprecated Use GetIntersection() instead.
static ThisType Intersection(const ThisType& a, const ThisType& b)
{
return GetIntersection(a, b);
}
/// Modifies this range to hold its intersection with \p b and returns the
/// result
const ThisType& IntersectWith(const ThisType& b)
{
_FindMax(_min, b._min);
_FindMin(_max, b._max);
return *this;
}
/// Modifies this range to hold its intersection with \p b and returns the
/// result.
/// \deprecated Use IntersectWith() instead.
const ThisType& Intersection(const ThisType& b)
{
return IntersectWith(b);
}
/// unary sum.
ThisType& operator+=(const ThisType& b)
{
_min += b._min;
_max += b._max;
return *this;
}
/// unary difference.
ThisType& operator-=(const ThisType& b)
{
_min -= b._max;
_max -= b._min;
return *this;
}
/// unary multiply.
ThisType& operator*=(double m)
{
if (m > 0)
{
_min *= m;
_max *= m;
}
else
{
auto tmp = _min;
_min = _max * m;
_max = tmp * m;
}
return *this;
}
/// unary division.
ThisType& operator/=(double m)
{
return *this *= (1.0 / m);
}
/// binary sum.
ThisType operator+(const ThisType& b) const
{
return ThisType(_min + b._min, _max + b._max);
}
/// binary difference.
ThisType operator-(const ThisType& b) const
{
return ThisType(_min - b._max, _max - b._min);
}
/// scalar multiply.
friend ThisType operator*(double m, const ThisType& r)
{
return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m));
}
/// scalar multiply.
friend ThisType operator*(const ThisType& r, double m)
{
return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m));
}
/// scalar divide.
friend ThisType operator/(const ThisType& r, double m)
{
return r * (1.0 / m);
}
/// The min and max points must match exactly for equality.
bool operator==(const ThisType& b) const
{
return (_min == b._min && _max == b._max);
}
bool operator!=(const ThisType& b) const
{
return !(*this == b);
}
/// Compute the squared distance from a point to the range.
double GetDistanceSquared(const MinMaxType& p) const
{
double dist = 0.0;
if (p[0] < _min[0])
{
// p is left of box
dist += GfSqr(_min[0] - p[0]);
}
else if (p[0] > _max[0])
{
// p is right of box
dist += GfSqr(p[0] - _max[0]);
}
if (p[1] < _min[1])
{
// p is front of box
dist += GfSqr(_min[1] - p[1]);
}
else if (p[1] > _max[1])
{
// p is back of box
dist += GfSqr(p[1] - _max[1]);
}
return dist;
}
/// Returns the ith corner of the range, in the following order:
/// SW, SE, NW, NE.
MinMaxType GetCorner(size_t i) const
{
if (i > 3)
{
return _min;
}
return MinMaxType((i & 1 ? _max : _min)[0], (i & 2 ? _max : _min)[1]);
}
/// Returns the ith quadrant of the range, in the following order:
/// SW, SE, NW, NE.
ThisType GetQuadrant(size_t i) const
{
if (i > 3)
{
return {};
}
auto a = GetCorner(i);
auto b = .5 * (_min + _max);
return ThisType(
MinMaxType(GfMin(a[0], b[0]), GfMin(a[1], b[1])), MinMaxType(GfMax(a[0], b[0]), GfMax(a[1], b[1])));
}
/// The unit square.
static constexpr ThisType UnitSquare()
{
return ThisType(MinMaxType(0), MinMaxType(1));
}
private:
/// Minimum and maximum points.
MinMaxType _min, _max;
/// Extends minimum point if necessary to contain given point.
static void _FindMin(MinMaxType& dest, const MinMaxType& point)
{
if (point[0] < dest[0])
{
dest[0] = point[0];
}
if (point[1] < dest[1])
{
dest[1] = point[1];
}
}
/// Extends maximum point if necessary to contain given point.
static void _FindMax(MinMaxType& dest, const MinMaxType& point)
{
if (point[0] > dest[0])
{
dest[0] = point[0];
}
if (point[1] > dest[1])
{
dest[1] = point[1];
}
}
};
template <typename T>
class range3
{
public:
static const size_t dimension = 3;
using ScalarType = T;
using MinMaxType = omni::math::linalg::vec3<T>;
using ThisType = range3<T>;
range3() = default;
constexpr range3(const ThisType&) = default;
constexpr explicit range3(ScalarType size) : _min(-size), _max(size)
{
}
/// Sets the range to an empty interval
// TODO check whether this can be deprecated.
constexpr void inline SetEmpty()
{
_min = { std::numeric_limits<ScalarType>::max() };
_max = { -std::numeric_limits<ScalarType>::max() };
}
/// This constructor initializes the minimum and maximum points.
constexpr range3(const MinMaxType& min, const MinMaxType& max) : _min(min), _max(max)
{
}
/// Returns the minimum value of the range.
const MinMaxType& GetMin() const
{
return _min;
}
/// Returns the maximum value of the range.
const MinMaxType& GetMax() const
{
return _max;
}
/// Returns the size of the range.
MinMaxType GetSize() const
{
return _max - _min;
}
/// Returns the midpoint of the range, that is, 0.5*(min+max).
/// Note: this returns zero in the case of default-constructed ranges,
/// or ranges set via SetEmpty().
MinMaxType GetMidpoint() const
{
return static_cast<ScalarType>(0.5) * _min + static_cast<ScalarType>(0.5) * _max;
}
/// Sets the minimum value of the range.
void SetMin(const MinMaxType& min)
{
_min = min;
}
/// Sets the maximum value of the range.
void SetMax(const MinMaxType& max)
{
_max = max;
}
/// Returns whether the range is empty (max < min).
bool IsEmpty() const
{
return _min[0] > _max[0] || _min[1] > _max[1] || _min[2] > _max[2];
}
/// Modifies the range if necessary to surround the given value.
/// \deprecated Use UnionWith() instead.
void ExtendBy(const MinMaxType& point)
{
UnionWith(point);
}
/// Modifies the range if necessary to surround the given range.
/// \deprecated Use UnionWith() instead.
void ExtendBy(const ThisType& range)
{
UnionWith(range);
}
/// Returns true if the \p point is located inside the range. As with all
/// operations of this type, the range is assumed to include its extrema.
bool Contains(const MinMaxType& point) const
{
return (point[0] >= _min[0] && point[0] <= _max[0] && point[1] >= _min[1] && point[1] <= _max[1] &&
point[2] >= _min[2] && point[2] <= _max[2]);
}
/// Returns true if the \p range is located entirely inside the range. As
/// with all operations of this type, the ranges are assumed to include
/// their extrema.
bool Contains(const ThisType& range) const
{
return Contains(range._min) && Contains(range._max);
}
/// Returns true if the \p point is located inside the range. As with all
/// operations of this type, the range is assumed to include its extrema.
/// \deprecated Use Contains() instead.
bool IsInside(const MinMaxType& point) const
{
return Contains(point);
}
/// Returns true if the \p range is located entirely inside the range. As
/// with all operations of this type, the ranges are assumed to include
/// their extrema.
/// \deprecated Use Contains() instead.
bool IsInside(const ThisType& range) const
{
return Contains(range);
}
/// Returns true if the \p range is located entirely outside the range. As
/// with all operations of this type, the ranges are assumed to include
/// their extrema.
bool IsOutside(const ThisType& range) const
{
return ((range._max[0] < _min[0] || range._min[0] > _max[0]) ||
(range._max[1] < _min[1] || range._min[1] > _max[1]) ||
(range._max[2] < _min[2] || range._min[2] > _max[2]));
}
/// Returns the smallest \c ThisType which contains both \p a and \p b.
static ThisType GetUnion(const ThisType& a, const ThisType& b)
{
ThisType res = a;
_FindMin(res._min, b._min);
_FindMax(res._max, b._max);
return res;
}
/// Extend \p this to include \p b.
const ThisType& UnionWith(const ThisType& b)
{
_FindMin(_min, b._min);
_FindMax(_max, b._max);
return *this;
}
/// Extend \p this to include \p b.
const ThisType& UnionWith(const MinMaxType& b)
{
_FindMin(_min, b);
_FindMax(_max, b);
return *this;
}
/// Returns the smallest \c ThisType which contains both \p a and \p b
/// \deprecated Use GetUnion() instead.
static ThisType Union(const ThisType& a, const ThisType& b)
{
return GetUnion(a, b);
}
/// Extend \p this to include \p b.
/// \deprecated Use UnionWith() instead.
const ThisType& Union(const ThisType& b)
{
return UnionWith(b);
}
/// Extend \p this to include \p b.
/// \deprecated Use UnionWith() instead.
const ThisType& Union(const MinMaxType& b)
{
return UnionWith(b);
}
/// Returns a \c ThisType that describes the intersection of \p a and \p b.
static ThisType GetIntersection(const ThisType& a, const ThisType& b)
{
ThisType res = a;
_FindMax(res._min, b._min);
_FindMin(res._max, b._max);
return res;
}
/// Returns a \c ThisType that describes the intersection of \p a and \p b.
/// \deprecated Use GetIntersection() instead.
static ThisType Intersection(const ThisType& a, const ThisType& b)
{
return GetIntersection(a, b);
}
/// Modifies this range to hold its intersection with \p b and returns the
/// result
const ThisType& IntersectWith(const ThisType& b)
{
_FindMax(_min, b._min);
_FindMin(_max, b._max);
return *this;
}
/// Modifies this range to hold its intersection with \p b and returns the
/// result.
/// \deprecated Use IntersectWith() instead.
const ThisType& Intersection(const ThisType& b)
{
return IntersectWith(b);
}
/// unary sum.
ThisType& operator+=(const ThisType& b)
{
_min += b._min;
_max += b._max;
return *this;
}
/// unary difference.
ThisType& operator-=(const ThisType& b)
{
_min -= b._max;
_max -= b._min;
return *this;
}
/// unary multiply.
ThisType& operator*=(double m)
{
if (m > 0)
{
_min *= m;
_max *= m;
}
else
{
MinMaxType tmp = _min;
_min = _max * m;
_max = tmp * m;
}
return *this;
}
/// unary division.
ThisType& operator/=(double m)
{
return *this *= (1.0 / m);
}
/// binary sum.
ThisType operator+(const ThisType& b) const
{
return ThisType(_min + b._min, _max + b._max);
}
/// binary difference.
ThisType operator-(const ThisType& b) const
{
return ThisType(_min - b._max, _max - b._min);
}
/// scalar multiply.
friend ThisType operator*(double m, const ThisType& r)
{
return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m));
}
/// scalar multiply.
friend ThisType operator*(const ThisType& r, double m)
{
return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m));
}
/// scalar divide.
friend ThisType operator/(const ThisType& r, double m)
{
return r * (1.0 / m);
}
/// The min and max points must match exactly for equality.
bool operator==(const ThisType& b) const
{
return (_min == b._min && _max == b._max);
}
bool operator!=(const ThisType& b) const
{
return !(*this == b);
}
/// Compute the squared distance from a point to the range.
double GetDistanceSquared(const MinMaxType& p) const
{
double dist = 0.0;
if (p[0] < _min[0])
{
// p is left of box
dist += GfSqr(_min[0] - p[0]);
}
else if (p[0] > _max[0])
{
// p is right of box
dist += GfSqr(p[0] - _max[0]);
}
if (p[1] < _min[1])
{
// p is front of box
dist += GfSqr(_min[1] - p[1]);
}
else if (p[1] > _max[1])
{
// p is back of box
dist += GfSqr(p[1] - _max[1]);
}
if (p[2] < _min[2])
{
// p is below of box
dist += GfSqr(_min[2] - p[2]);
}
else if (p[2] > _max[2])
{
// p is above of box
dist += GfSqr(p[2] - _max[2]);
}
return dist;
}
/// Returns the ith corner of the range, in the following order:
/// LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF. Where L/R is left/right,
/// D/U is down/up, and B/F is back/front.
MinMaxType GetCorner(size_t i) const
{
if (i > 7)
{
return _min;
}
return MinMaxType((i & 1 ? _max : _min)[0], (i & 2 ? _max : _min)[1], (i & 4 ? _max : _min)[2]);
}
/// Returns the ith octant of the range, in the following order:
/// LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF. Where L/R is left/right,
/// D/U is down/up, and B/F is back/front.
ThisType GetOctant(size_t i) const
{
if (i > 7)
{
return {};
}
auto a = GetCorner(i);
auto b = .5 * (_min + _max);
return ThisType(MinMaxType(GfMin(a[0], b[0]), GfMin(a[1], b[1]), GfMin(a[2], b[2])),
MinMaxType(GfMax(a[0], b[0]), GfMax(a[1], b[1]), GfMax(a[2], b[2])));
}
/// The unit cube.
static constexpr const ThisType UnitCube()
{
return ThisType(MinMaxType(0), MinMaxType(1));
}
private:
/// Minimum and maximum points.
MinMaxType _min, _max;
/// Extends minimum point if necessary to contain given point.
static void _FindMin(MinMaxType& dest, const MinMaxType& point)
{
if (point[0] < dest[0])
{
dest[0] = point[0];
}
if (point[1] < dest[1])
{
dest[1] = point[1];
}
if (point[2] < dest[2])
{
dest[2] = point[2];
}
}
/// Extends maximum point if necessary to contain given point.
static void _FindMax(MinMaxType& dest, const MinMaxType& point)
{
if (point[0] > dest[0])
{
dest[0] = point[0];
}
if (point[1] > dest[1])
{
dest[1] = point[1];
}
if (point[2] > dest[2])
{
dest[2] = point[2];
}
}
};
}
}
}
namespace usdrt
{
using GfRange1d = omni::math::linalg::range1<double>;
using GfRange1f = omni::math::linalg::range1<float>;
using GfRange2d = omni::math::linalg::range2<double>;
using GfRange2f = omni::math::linalg::range2<float>;
using GfRange3d = omni::math::linalg::range3<double>;
using GfRange3f = omni::math::linalg::range3<float>;
}
| 30,553 | C | 25.339655 | 114 | 0.553923 |
omniverse-code/kit/include/usdrt/gf/matrix.h | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
//! @file
//!
//! @brief TODO
#include <carb/Defines.h>
#include <usdrt/gf/defines.h>
#include <usdrt/gf/quat.h>
#include <usdrt/gf/vec.h>
#include <initializer_list>
namespace omni
{
namespace math
{
namespace linalg
{
template <typename T, size_t N>
class base_matrix
{
public:
using ScalarType = T;
static const size_t numRows = N;
static const size_t numColumns = N;
base_matrix() = default;
constexpr base_matrix(const base_matrix<T, N>&) = default;
constexpr base_matrix<T, N>& operator=(const base_matrix<T, N>&) = default;
// NOTE: Hopefully the compiler can identify that the initializer for v is redundant,
// since this constructor is quite useful for constexpr cases.
explicit constexpr CUDA_CALLABLE base_matrix(const T m[N][N]) : v{}
{
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
v[i][j] = m[i][j];
}
}
}
explicit CUDA_CALLABLE base_matrix(T scalar)
{
SetDiagonal(scalar);
}
explicit CUDA_CALLABLE base_matrix(const base_vec<T, N>& diagonal)
{
SetDiagonal(diagonal);
}
template <typename OTHER_T>
explicit CUDA_CALLABLE base_matrix(const base_matrix<OTHER_T, N>& other)
{
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
v[i][j] = T(other[i][j]);
}
}
}
template <typename OTHER_T>
CUDA_CALLABLE base_matrix(const std::initializer_list<std::initializer_list<OTHER_T>>& other) : v{}
{
CUDA_SAFE_ASSERT(other.size() == N);
for (size_t i = 0; i < N && i < other.size(); ++i)
{
CUDA_SAFE_ASSERT(other.begin()[i].size() == N);
for (size_t j = 0; j < N && j < other.begin()[i].size(); ++j)
{
// NOTE: This intentionally doesn't have an explicit cast, so that
// the compiler will warn on invalid implicit casts, since this
// constructor isn't marked explicit.
v[i][j] = other.begin()[i].begin()[j];
}
}
}
CUDA_CALLABLE void SetRow(size_t rowIndex, const base_vec<T, N>& rowValues)
{
for (size_t col = 0; col < N; ++col)
{
v[rowIndex][col] = rowValues[col];
}
}
CUDA_CALLABLE void SetColumn(size_t colIndex, const base_vec<T, N>& colValues)
{
for (size_t row = 0; row < N; ++row)
{
v[row][colIndex] = colValues[row];
}
}
CUDA_CALLABLE base_vec<T, N> GetRow(size_t rowIndex) const
{
base_vec<T, N> rowValues;
for (size_t col = 0; col < N; ++col)
{
rowValues[col] = v[rowIndex][col];
}
return rowValues;
}
CUDA_CALLABLE base_vec<T, N> GetColumn(size_t colIndex) const
{
base_vec<T, N> colValues;
for (size_t row = 0; row < N; ++row)
{
colValues[row] = v[row][colIndex];
}
return colValues;
}
CUDA_CALLABLE base_matrix<T, N>& Set(const T m[N][N])
{
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
v[i][j] = m[i][j];
}
}
return *this;
}
CUDA_CALLABLE base_matrix<T, N>& SetIdentity()
{
return SetDiagonal(T(1));
}
CUDA_CALLABLE base_matrix<T, N>& SetZero()
{
return SetDiagonal(T(0));
}
CUDA_CALLABLE base_matrix<T, N>& SetDiagonal(T scalar)
{
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
v[i][j] = (i == j) ? scalar : T(0);
}
}
return *this;
}
CUDA_CALLABLE base_matrix<T, N>& SetDiagonal(const base_vec<T, N>& diagonal)
{
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
v[i][j] = (i == j) ? diagonal[i] : T(0);
}
}
return *this;
}
CUDA_CALLABLE T* Get(T m[N][N]) const
{
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
m[i][j] = v[i][j];
}
}
return &m[0][0];
}
CUDA_CALLABLE T* data()
{
return &v[0][0];
}
CUDA_CALLABLE const T* data() const
{
return &v[0][0];
}
CUDA_CALLABLE T* GetArray()
{
return &v[0][0];
}
CUDA_CALLABLE const T* GetArray() const
{
return &v[0][0];
}
CUDA_CALLABLE T* operator[](size_t row)
{
return v[row];
}
CUDA_CALLABLE const T* operator[](size_t row) const
{
return v[row];
}
// NOTE: To avoid including Boost unless absolutely necessary, hash_value() is not defined here.
CUDA_CALLABLE bool operator==(const base_matrix<T, N>& other) const
{
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
if (v[i][j] != other[i][j])
{
return false;
}
}
}
return true;
}
CUDA_CALLABLE bool operator!=(const base_matrix<T, N>& other) const
{
return !(*this == other);
}
template <typename OTHER_T>
CUDA_CALLABLE bool operator==(const base_matrix<OTHER_T, N>& other) const
{
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
if (v[i][j] != other[i][j])
{
return false;
}
}
}
return true;
}
template <typename OTHER_T>
CUDA_CALLABLE bool operator!=(const base_matrix<OTHER_T, N>& other) const
{
return !(*this == other);
}
#ifndef DOXYGEN_BUILD
CUDA_CALLABLE base_matrix<T, N> GetTranspose() const
{
base_matrix<T, N> result;
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
result[i][j] = v[j][i];
}
}
return result;
}
#endif // DOXYGEN_BUILD
CUDA_CALLABLE base_matrix<T, N>& operator*=(const base_matrix<T, N>& other)
{
T result[N][N];
for (size_t row = 0; row < N; ++row)
{
for (size_t col = 0; col < N; ++col)
{
T sum = v[row][0] * other[0][col];
for (size_t i = 1; i < N; ++i)
{
sum += v[row][i] * other[i][col];
}
result[row][col] = sum;
}
}
Set(result);
return *this;
}
CUDA_CALLABLE base_matrix<T, N>& operator*=(T scalar)
{
for (size_t row = 0; row < N; ++row)
{
for (size_t col = 0; col < N; ++col)
{
v[row][col] *= scalar;
}
}
return *this;
}
#ifndef DOXYGEN_BUILD
friend CUDA_CALLABLE base_matrix<T, N> operator*(const base_matrix<T, N>& matrix, T scalar)
{
base_matrix<T, N> result;
for (size_t row = 0; row < N; ++row)
{
for (size_t col = 0; col < N; ++col)
{
result[row][col] = matrix[row][col] * scalar;
}
}
return result;
}
friend CUDA_CALLABLE base_matrix<T, N> operator*(T scalar, const base_matrix<T, N>& matrix)
{
return matrix * scalar;
}
#endif
CUDA_CALLABLE base_matrix<T, N>& operator+=(const base_matrix<T, N>& other)
{
for (size_t row = 0; row < N; ++row)
{
for (size_t col = 0; col < N; ++col)
{
v[row][col] += other[row][col];
}
}
return *this;
}
CUDA_CALLABLE base_matrix<T, N>& operator-=(const base_matrix<T, N>& other)
{
for (size_t row = 0; row < N; ++row)
{
for (size_t col = 0; col < N; ++col)
{
v[row][col] -= other[row][col];
}
}
return *this;
}
#ifndef DOXYGEN_BUILD
CUDA_CALLABLE base_matrix<T, N> operator-() const
{
base_matrix<T, N> result;
for (size_t row = 0; row < N; ++row)
{
for (size_t col = 0; col < N; ++col)
{
result[row][col] = -v[row][col];
}
}
return result;
}
#endif // DOXYGEN_BUILD
#ifndef DOXYGEN_BUILD
friend CUDA_CALLABLE base_matrix<T, N> operator+(const base_matrix<T, N>& a, const base_matrix<T, N>& b)
{
base_matrix<T, N> result;
for (size_t row = 0; row < N; ++row)
{
for (size_t col = 0; col < N; ++col)
{
result[row][col] = a[row][col] + b[row][col];
}
}
return result;
}
friend CUDA_CALLABLE base_matrix<T, N> operator-(const base_matrix<T, N>& a, const base_matrix<T, N>& b)
{
base_matrix<T, N> result;
for (size_t row = 0; row < N; ++row)
{
for (size_t col = 0; col < N; ++col)
{
result[row][col] = a[row][col] - b[row][col];
}
}
return result;
}
friend CUDA_CALLABLE base_matrix<T, N> operator*(const base_matrix<T, N>& a, const base_matrix<T, N>& b)
{
base_matrix<T, N> result(a);
result *= b;
return result;
}
// Matrix times column vector
friend CUDA_CALLABLE base_vec<T, N> operator*(const base_matrix<T, N>& matrix, const base_vec<T, N>& vec)
{
base_vec<T, N> result;
for (size_t row = 0; row < N; ++row)
{
T sum = matrix[row][0] * vec[0];
for (size_t col = 1; col < N; ++col)
{
sum += matrix[row][col] * vec[col];
}
result[row] = sum;
}
return result;
}
// Row vector times matrix
friend CUDA_CALLABLE base_vec<T, N> operator*(const base_vec<T, N>& vec, const base_matrix<T, N>& matrix)
{
base_vec<T, N> result;
T scale = vec[0];
for (size_t col = 0; col < N; ++col)
{
result[col] = matrix[0][col] * scale;
}
for (size_t row = 1; row < N; ++row)
{
T scale = vec[row];
for (size_t col = 0; col < N; ++col)
{
result[col] += matrix[row][col] * scale;
}
}
return result;
}
// Matrix times column vector
template <typename OTHER_T>
friend CUDA_CALLABLE base_vec<OTHER_T, N> operator*(const base_matrix<T, N>& matrix, const base_vec<OTHER_T, N>& vec)
{
base_vec<OTHER_T, N> result;
for (size_t row = 0; row < N; ++row)
{
OTHER_T sum = matrix[row][0] * vec[0];
for (size_t col = 1; col < N; ++col)
{
sum += matrix[row][col] * vec[col];
}
result[row] = sum;
}
return result;
}
// Row vector times matrix
template <typename OTHER_T>
friend CUDA_CALLABLE base_vec<OTHER_T, N> operator*(const base_vec<OTHER_T, N>& vec, const base_matrix<T, N>& matrix)
{
base_vec<OTHER_T, N> result;
OTHER_T scale = vec[0];
for (size_t col = 0; col < N; ++col)
{
result[col] = matrix[0][col] * scale;
}
for (size_t row = 1; row < N; ++row)
{
OTHER_T scale = vec[row];
for (size_t col = 0; col < N; ++col)
{
result[col] += matrix[row][col] * scale;
}
}
return result;
}
#endif
protected:
T v[N][N];
};
template <typename T, size_t N>
CUDA_CALLABLE bool GfIsClose(const base_matrix<T, N>& a, const base_matrix<T, N>& b, double tolerance)
{
for (size_t row = 0; row < N; ++row)
{
for (size_t col = 0; col < N; ++col)
{
const T diff = a[row][col] - b[row][col];
const T absDiff = (diff < T(0)) ? -diff : diff;
// NOTE: This condition looks weird, but it's so that NaN values in
// either matrix will yield false.
if (!(absDiff <= tolerance))
{
return false;
}
}
}
return true;
}
template <typename T>
class matrix2 : public base_matrix<T, 2>
{
public:
using base_type = base_matrix<T, 2>;
using this_type = matrix2<T>;
using base_matrix<T, 2>::base_matrix;
using base_type::operator[];
using base_type::operator==;
using base_type::operator!=;
using base_type::data;
using base_type::Get;
using base_type::GetArray;
using base_type::SetColumn;
using base_type::SetRow;
using ScalarType = T;
using base_type::numColumns;
using base_type::numRows;
matrix2() = default;
constexpr matrix2(const this_type&) = default;
constexpr this_type& operator=(const this_type&) = default;
// Implicit conversion from base_type
CUDA_CALLABLE matrix2(const base_type& other) : base_type(other)
{
}
template <typename OTHER_T>
explicit CUDA_CALLABLE matrix2(const matrix2<OTHER_T>& other)
: base_type(static_cast<const base_matrix<OTHER_T, numRows>&>(other))
{
}
CUDA_CALLABLE matrix2(T v00, T v01, T v10, T v11)
{
Set(v00, v01, v10, v11);
}
CUDA_CALLABLE this_type& Set(const T m[numRows][numColumns])
{
base_type::Set(m);
return *this;
}
CUDA_CALLABLE this_type& Set(T v00, T v01, T v10, T v11)
{
T v[2][2] = { { v00, v01 }, { v10, v11 } };
return Set(v);
}
CUDA_CALLABLE this_type& SetIdentity()
{
base_type::SetIdentity();
return *this;
}
CUDA_CALLABLE this_type& SetZero()
{
base_type::SetZero();
return *this;
}
CUDA_CALLABLE this_type& SetDiagonal(T scalar)
{
base_type::SetDiagonal(scalar);
return *this;
}
CUDA_CALLABLE this_type& SetDiagonal(const base_vec<T, numRows>& diagonal)
{
base_type::SetDiagonal(diagonal);
return *this;
}
CUDA_CALLABLE this_type GetTranspose() const
{
return this_type(base_type::GetTranspose());
}
CUDA_CALLABLE this_type GetInverse(T* det = nullptr, T epsilon = T(0)) const
{
T determinant = GetDeterminant();
if (det != nullptr)
{
*det = determinant;
}
T absDeterminant = (determinant < 0) ? -determinant : determinant;
// This unusual writing of the condition should catch NaNs.
if (!(absDeterminant > epsilon))
{
// Return the zero matrix, instead of a huge matrix,
// so that multiplying by this is less likely to be catastrophic.
return this_type(T(0));
}
T inverse[2][2] = { { v[1][1] / determinant, -v[0][1] / determinant },
{ -v[1][0] / determinant, v[0][0] / determinant } };
return this_type(inverse);
}
CUDA_CALLABLE T GetDeterminant() const
{
return v[0][0] * v[1][1] - v[0][1] * v[1][0];
}
CUDA_CALLABLE this_type& operator*=(const base_type& other)
{
base_type::operator*=(other);
return *this;
}
CUDA_CALLABLE this_type& operator*=(T scalar)
{
base_type::operator*=(scalar);
return *this;
}
CUDA_CALLABLE this_type& operator+=(const base_type& other)
{
base_type::operator+=(other);
return *this;
}
CUDA_CALLABLE this_type& operator-=(const base_type& other)
{
base_type::operator-=(other);
return *this;
}
CUDA_CALLABLE this_type operator-() const
{
return this_type(base_type::operator-());
}
#ifndef DOXYGEN_BUILD
friend CUDA_CALLABLE this_type operator/(const this_type& a, const this_type& b)
{
return a * b.GetInverse();
}
#endif // DOXYGEN_BUILD
private:
using base_type::v;
};
template <typename T>
class matrix3 : public base_matrix<T, 3>
{
public:
using base_type = base_matrix<T, 3>;
using this_type = matrix3<T>;
using base_matrix<T, 3>::base_matrix;
using base_type::operator[];
using base_type::operator==;
using base_type::operator!=;
using base_type::data;
using base_type::Get;
using base_type::GetArray;
using base_type::SetColumn;
using base_type::SetRow;
using ScalarType = T;
using base_type::numColumns;
using base_type::numRows;
matrix3() = default;
constexpr matrix3(const this_type&) = default;
constexpr this_type& operator=(const this_type&) = default;
// Implicit conversion from base_type
CUDA_CALLABLE matrix3(const base_type& other) : base_type(other)
{
}
template <typename OTHER_T>
explicit CUDA_CALLABLE matrix3(const matrix3<OTHER_T>& other)
: base_type(static_cast<const base_matrix<OTHER_T, numRows>&>(other))
{
}
CUDA_CALLABLE matrix3(T v00, T v01, T v02, T v10, T v11, T v12, T v20, T v21, T v22)
{
Set(v00, v01, v02, v10, v11, v12, v20, v21, v22);
}
CUDA_CALLABLE this_type& Set(const T m[numRows][numColumns])
{
base_type::Set(m);
return *this;
}
CUDA_CALLABLE this_type& Set(T v00, T v01, T v02, T v10, T v11, T v12, T v20, T v21, T v22)
{
T v[3][3] = { { v00, v01, v02 }, { v10, v11, v12 }, { v20, v21, v22 } };
return Set(v);
}
CUDA_CALLABLE this_type& SetIdentity()
{
base_type::SetIdentity();
return *this;
}
CUDA_CALLABLE this_type& SetZero()
{
base_type::SetZero();
return *this;
}
CUDA_CALLABLE this_type& SetDiagonal(T scalar)
{
base_type::SetDiagonal(scalar);
return *this;
}
CUDA_CALLABLE this_type& SetDiagonal(const base_vec<T, numRows>& diagonal)
{
base_type::SetDiagonal(diagonal);
return *this;
}
CUDA_CALLABLE this_type GetTranspose() const
{
return this_type(base_type::GetTranspose());
}
CUDA_CALLABLE this_type GetInverse(T* det = nullptr, T epsilon = T(0)) const
{
T determinant = GetDeterminant();
if (det != nullptr)
{
*det = determinant;
}
T absDeterminant = (determinant < 0) ? -determinant : determinant;
// This unusual writing of the condition should catch NaNs.
if (!(absDeterminant > epsilon))
{
// Return the zero matrix, instead of a huge matrix,
// so that multiplying by this is less likely to be catastrophic.
return this_type(T(0));
}
// TODO: If compilers have difficulty optimizing this, inline the calculations.
const vec3<T> row0 = GfCross(vec3<T>(v[1]), vec3<T>(v[2]));
const vec3<T> row1 = GfCross(vec3<T>(v[2]), vec3<T>(v[0]));
const vec3<T> row2 = GfCross(vec3<T>(v[0]), vec3<T>(v[1]));
const T recip = T(1) / determinant;
return this_type(row0[0], row0[1], row0[2], row1[0], row1[1], row1[2], row2[0], row2[1], row2[2]) * recip;
}
CUDA_CALLABLE T GetDeterminant() const
{
// Scalar triple product
// TODO: If compilers have difficulty optimizing this, inline the calculations.
return vec3<T>(v[0]).Dot(GfCross(vec3<T>(v[1]), vec3<T>(v[2])));
}
CUDA_CALLABLE bool Orthonormalize()
{
vec3<T> rows[3] = { vec3<T>(v[0]), vec3<T>(v[1]), vec3<T>(v[2]) };
bool success = GfOrthogonalizeBasis(&rows[0], &rows[1], &rows[2]);
if (success)
{
// TODO: Should this check for a negative determinant and flip 1 or all 3 axes,
// to force this to be a rotation matrix?
for (size_t i = 0; i < 3; ++i)
{
for (size_t j = 0; j < 3; ++j)
{
v[i][j] = rows[i][j];
}
}
}
return success;
}
CUDA_CALLABLE this_type GetOrthonormalized() const
{
this_type result(*this);
result.Orthonormalize();
return result;
}
CUDA_CALLABLE int GetHandedness() const
{
T det = GetDeterminant();
return (det < T(0)) ? -1 : ((det > T(0)) ? 1 : 0);
}
CUDA_CALLABLE bool IsRightHanded() const
{
return GetHandedness() == 1;
}
CUDA_CALLABLE bool IsLeftHanded() const
{
return GetHandedness() == -1;
}
CUDA_CALLABLE this_type& operator*=(const base_type& other)
{
base_type::operator*=(other);
return *this;
}
CUDA_CALLABLE this_type& operator*=(T scalar)
{
base_type::operator*=(scalar);
return *this;
}
CUDA_CALLABLE this_type& operator+=(const base_type& other)
{
base_type::operator+=(other);
return *this;
}
CUDA_CALLABLE this_type& operator-=(const base_type& other)
{
base_type::operator-=(other);
return *this;
}
CUDA_CALLABLE this_type operator-() const
{
return this_type(base_type::operator-());
}
#ifndef DOXYGEN_BUILD
friend CUDA_CALLABLE this_type operator/(const this_type& a, const this_type& b)
{
return a * b.GetInverse();
}
#endif // DOXYGEN_BUILD
CUDA_CALLABLE this_type& SetScale(T scale)
{
return SetDiagonal(scale);
}
CUDA_CALLABLE this_type& SetScale(const base_vec<T, numRows>& scales)
{
return SetDiagonal(scales);
}
// NOTE: The input quaternion must be normalized (length 1).
// NOTE: This may or may not represent the rotation matrix for the opposite rotation,
// due to interpretations of left-to-right vs. right-to-left multiplication.
CUDA_CALLABLE this_type& SetRotate(const quat<double>& rotation)
{
const double w = rotation.GetReal();
const vec3<double> xyz = rotation.GetImaginary();
const double x = xyz[0];
const double y = xyz[1];
const double z = xyz[2];
const double x2 = x * x;
const double y2 = y * y;
const double z2 = z * z;
const double xy = x * y;
const double xz = x * z;
const double yz = y * z;
const double xw = x * w;
const double yw = y * w;
const double zw = z * w;
const T m[3][3] = { { T(1 - 2 * (y2 + z2)), 2 * T(xy + zw), 2 * T(xz - yw) },
{ 2 * T(xy - zw), T(1 - 2 * (x2 + z2)), 2 * T(yz + xw) },
{ 2 * T(xz + yw), 2 * T(yz - xw), T(1 - 2 * (x2 + y2)) } };
return Set(m);
}
// NOTE: This must already be a rotation matrix (i.e. orthonormal rows and columns,
// and positive determinant.)
// NOTE: This may or may not represent the quaternion for the transpose,
// due to interpretations of left-to-right vs. right-to-left multiplication.
CUDA_CALLABLE quat<double> ExtractRotation() const
{
double diag[3] = { v[0][0], v[1][1], v[2][2] };
double trace = diag[0] + diag[1] + diag[2];
double real;
vec3d imaginary;
if (trace >= 0)
{
// Non-negative trace corresponds with a rotation of at most 120 degrees.
real = 0.5 * sqrt(1.0 + trace);
double scale = 0.25 / real;
imaginary = scale * vec3d(v[1][2] - v[2][1], v[2][0] - v[0][2], v[0][1] - v[1][0]);
}
else
{
// Negative trace corresponds with a rotation of more than 120 degrees.
// Use a different approach to reduce instability and risk of dividing by something near or equal zero.
// Find the largest diagonal value.
size_t index0 = (diag[0] >= diag[1]) ? 0 : 1;
index0 = (diag[index0] >= diag[2]) ? index0 : 2;
size_t index1 = (index0 == 2) ? 0 : (index0 + 1);
size_t index2 = (index1 == 2) ? 0 : (index1 + 1);
double large = 0.5 * sqrt(1 + diag[index0] - diag[index1] - diag[index2]);
double scale = 0.25 / large;
real = scale * (v[index1][index2] - v[index2][index1]);
imaginary[index0] = large;
imaginary[index1] = scale * (v[index0][index1] + v[index1][index0]);
imaginary[index2] = scale * (v[index0][index2] + v[index2][index0]);
}
return quat<double>(real, imaginary);
}
private:
using base_type::v;
};
template <typename T>
class matrix4 : public base_matrix<T, 4>
{
public:
using base_type = base_matrix<T, 4>;
using this_type = matrix4<T>;
using base_matrix<T, 4>::base_matrix;
using base_type::operator[];
using base_type::operator==;
using base_type::operator!=;
using base_type::data;
using base_type::Get;
using base_type::GetArray;
using base_type::SetColumn;
using base_type::SetRow;
using ScalarType = T;
using base_type::numColumns;
using base_type::numRows;
matrix4() = default;
constexpr matrix4(const this_type&) = default;
constexpr this_type& operator=(const this_type&) = default;
// Implicit conversion from base_type
CUDA_CALLABLE matrix4(const base_type& other) : base_type(other)
{
}
template <typename OTHER_T>
explicit CUDA_CALLABLE matrix4(const matrix4<OTHER_T>& other)
: base_type(static_cast<const base_matrix<OTHER_T, numRows>&>(other))
{
}
CUDA_CALLABLE matrix4(
T v00, T v01, T v02, T v03, T v10, T v11, T v12, T v13, T v20, T v21, T v22, T v23, T v30, T v31, T v32, T v33)
{
Set(v00, v01, v02, v03, v10, v11, v12, v13, v20, v21, v22, v23, v30, v31, v32, v33);
}
CUDA_CALLABLE this_type& Set(const T m[numRows][numColumns])
{
base_type::Set(m);
return *this;
}
CUDA_CALLABLE this_type& Set(
T v00, T v01, T v02, T v03, T v10, T v11, T v12, T v13, T v20, T v21, T v22, T v23, T v30, T v31, T v32, T v33)
{
T v[4][4] = { { v00, v01, v02, v03 }, { v10, v11, v12, v13 }, { v20, v21, v22, v23 }, { v30, v31, v32, v33 } };
return Set(v);
}
CUDA_CALLABLE this_type& SetIdentity()
{
base_type::SetIdentity();
return *this;
}
CUDA_CALLABLE this_type& SetZero()
{
base_type::SetZero();
return *this;
}
CUDA_CALLABLE this_type& SetDiagonal(T scalar)
{
base_type::SetDiagonal(scalar);
return *this;
}
CUDA_CALLABLE this_type& SetDiagonal(const base_vec<T, numRows>& diagonal)
{
base_type::SetDiagonal(diagonal);
return *this;
}
CUDA_CALLABLE this_type GetTranspose() const
{
return this_type(base_type::GetTranspose());
}
// TODO: Optimize this. The implementation is not as efficient as it could be.
// For example, it computes the 4x4 determinant separately from the rest.
CUDA_CALLABLE this_type GetInverse(T* det = nullptr, T epsilon = T(0)) const
{
T determinant = GetDeterminant();
if (det != nullptr)
{
*det = determinant;
}
T absDeterminant = (determinant < 0) ? -determinant : determinant;
// This unusual writing of the condition should catch NaNs.
if (!(absDeterminant > epsilon))
{
// Return the zero matrix, instead of a huge matrix,
// so that multiplying by this is less likely to be catastrophic.
return this_type(T(0));
}
// Compute all 2x2 determinants.
// There are only actually 6x6 of them: (0,1), (0,2), (0,3), (1,2), (1,3), (2,3) for row pairs and col pairs.
constexpr size_t pairIndices[6][2] = { { 0, 1 }, { 0, 2 }, { 0, 3 }, { 1, 2 }, { 1, 3 }, { 2, 3 } };
T det2x2[6][6];
// NOTE: The first 3 row pairs are never used, below, so we can skip computing them.
for (size_t rowpair = 3; rowpair < 6; ++rowpair)
{
const size_t row0 = pairIndices[rowpair][0];
const size_t row1 = pairIndices[rowpair][1];
for (size_t colpair = 0; colpair < 6; ++colpair)
{
const size_t col0 = pairIndices[colpair][0];
const size_t col1 = pairIndices[colpair][1];
det2x2[rowpair][colpair] = v[row0][col0] * v[row1][col1] - v[row0][col1] * v[row1][col0];
}
}
// Compute all 3x3 determinants.
// There is one for every row-col pair.
constexpr size_t oneIndexRemoved4[4][3] = { { 1, 2, 3 }, { 0, 2, 3 }, { 0, 1, 3 }, { 0, 1, 2 } };
constexpr size_t twoIndicesRemovedToPair[4][3] = { { 5, 4, 3 }, { 5, 2, 1 }, { 4, 2, 0 }, { 3, 1, 0 } };
T adjugate[4][4];
for (size_t omittedRow = 0; omittedRow < 4; ++omittedRow)
{
for (size_t omittedCol = 0; omittedCol < 4; ++omittedCol)
{
size_t iterationRow = oneIndexRemoved4[omittedRow][0];
// The first entry in each subarray of twoIndicesRemovedToPair is 3, 4, or 5,
// regardless of omittedRow, which is why we didn't need to compute det2x2 for
// any rowpair less than 3, above.
size_t rowpair = twoIndicesRemovedToPair[omittedRow][0];
T sum = T(0);
for (size_t subCol = 0; subCol < 3; ++subCol)
{
size_t iterationCol = oneIndexRemoved4[omittedCol][subCol];
size_t colpair = twoIndicesRemovedToPair[omittedCol][subCol];
const T& factor = v[iterationRow][iterationCol];
T value = factor * det2x2[rowpair][colpair];
sum += (subCol & 1) ? -value : value;
}
// The adjugate matrix is the transpose of the cofactor matrix, so row and col are swapped here.
adjugate[omittedCol][omittedRow] = ((omittedRow ^ omittedCol) & 1) ? -sum : sum;
}
}
// Divide by the 4x4 determinant.
for (size_t row = 0; row < 4; ++row)
{
for (size_t col = 0; col < 4; ++col)
{
adjugate[row][col] /= determinant;
}
}
return this_type(adjugate);
}
CUDA_CALLABLE T GetDeterminant() const
{
T sum = 0;
// It's *very* common that the first 3 components of the last column are all zero,
// so skip over them.
if (v[0][3] != 0)
{
sum -= v[0][3] * vec3<T>(v[1]).Dot(GfCross(vec3<T>(v[2]), vec3<T>(v[3])));
}
if (v[1][3] != 0)
{
sum += v[1][3] * vec3<T>(v[0]).Dot(GfCross(vec3<T>(v[2]), vec3<T>(v[3])));
}
if (v[2][3] != 0)
{
sum -= v[2][3] * vec3<T>(v[0]).Dot(GfCross(vec3<T>(v[1]), vec3<T>(v[3])));
}
if (v[3][3] != 0)
{
sum += v[3][3] * vec3<T>(v[0]).Dot(GfCross(vec3<T>(v[1]), vec3<T>(v[2])));
}
return sum;
}
CUDA_CALLABLE T GetDeterminant3() const
{
// Scalar triple product
return vec3<T>(v[0]).Dot(GfCross(vec3<T>(v[1]), vec3<T>(v[2])));
}
CUDA_CALLABLE int GetHandedness() const
{
T det = GetDeterminant3();
return (det < T(0)) ? -1 : ((det > T(0)) ? 1 : 0);
}
CUDA_CALLABLE bool Orthonormalize()
{
vec3<T> rows[3] = { vec3<T>(v[0][0], v[0][1], v[0][2]), vec3<T>(v[1][0], v[1][1], v[1][2]),
vec3<T>(v[2][0], v[2][1], v[2][2]) };
bool success = GfOrthogonalizeBasis(&rows[0], &rows[1], &rows[2]);
// TODO: Should this check for a negative determinant and flip 1 or all 3 axes,
// to force this to be a rotation matrix?
for (size_t i = 0; i < 3; ++i)
{
for (size_t j = 0; j < 3; ++j)
{
v[i][j] = rows[i][j];
}
}
const double minVectorLength = 1e-10;
if (v[3][3] != 1.0 && !GfIsClose(v[3][3], 0.0, minVectorLength))
{
v[3][0] /= v[3][3];
v[3][1] /= v[3][3];
v[3][2] /= v[3][3];
v[3][3] = 1.0;
}
return success;
}
CUDA_CALLABLE this_type GetOrthonormalized() const
{
this_type result(*this);
result.Orthonormalize();
return result;
}
CUDA_CALLABLE this_type& operator*=(const base_type& other)
{
base_type::operator*=(other);
return *this;
}
CUDA_CALLABLE this_type& operator*=(T scalar)
{
base_type::operator*=(scalar);
return *this;
}
CUDA_CALLABLE this_type& operator+=(const base_type& other)
{
base_type::operator+=(other);
return *this;
}
CUDA_CALLABLE this_type& operator-=(const base_type& other)
{
base_type::operator-=(other);
return *this;
}
CUDA_CALLABLE this_type operator-() const
{
return this_type(base_type::operator-());
}
#ifndef DOXYGEN_BUILD
friend CUDA_CALLABLE this_type operator/(const this_type& a, const this_type& b)
{
return a * b.GetInverse();
}
#endif // DOXYGEN_BUILD
CUDA_CALLABLE this_type& SetScale(T scale)
{
return SetDiagonal(vec4<T>(scale, scale, scale, T(1)));
}
CUDA_CALLABLE this_type& SetScale(const vec3<T>& scales)
{
return SetDiagonal(vec4<T>(scales[0], scales[1], scales[2], T(1)));
}
CUDA_CALLABLE this_type RemoveScaleShear() const
{
vec3<T> rows[3] = { vec3<T>(v[0]), vec3<T>(v[1]), vec3<T>(v[2]) };
bool success = GfOrthogonalizeBasis(&rows[0], &rows[1], &rows[2]);
if (!success)
{
return *this;
}
// Scalar triple product is determinant of 3x3 matrix, (which should be about -1 or 1
// after orthonormalizing the vectors.)
if (rows[0].Dot(GfCross(rows[1], rows[2])) < 0)
{
// Negative determinant, so invert one of the axes.
// TODO: Is it better to invert all 3 axes?
rows[2] = -rows[2];
}
return matrix4<T>(rows[0][0], rows[0][1], rows[0][2], 0.0f, rows[1][0], rows[1][1], rows[1][2], 0.0f,
rows[2][0], rows[2][1], rows[2][2], 0.0f, v[3][0], v[3][1], v[3][2], 1.0f);
}
CUDA_CALLABLE this_type& SetRotate(const quat<double>& rotation)
{
matrix3<T> m3;
m3.SetRotate(rotation);
return SetRotate(m3);
}
CUDA_CALLABLE this_type& SetRotateOnly(const quat<double>& rotation)
{
matrix3<T> m3;
m3.SetRotate(rotation);
return SetRotateOnly(m3);
}
// NOTE: Contrary to the name, this sets the full 3x3 portion of the matrix,
// i.e. it also sets scales and shears.
// NOTE: This clears any translations.
CUDA_CALLABLE this_type& SetRotate(const matrix3<T>& m3)
{
for (size_t i = 0; i < 3; ++i)
{
for (size_t j = 0; j < 3; ++j)
{
v[i][j] = m3[i][j];
}
v[i][3] = T(0);
}
v[3][0] = T(0);
v[3][1] = T(0);
v[3][2] = T(0);
v[3][3] = T(1);
return *this;
}
// NOTE: Contrary to the name, this sets the full 3x3 portion of the matrix,
// i.e. it also sets scales and shears.
// NOTE: This does NOT clear any translations.
CUDA_CALLABLE this_type& SetRotateOnly(const matrix3<T>& m3)
{
for (size_t i = 0; i < 3; ++i)
{
for (size_t j = 0; j < 3; ++j)
{
v[i][j] = m3[i][j];
}
}
return *this;
}
CUDA_CALLABLE this_type& SetTranslate(const vec3<T>& translation)
{
for (size_t i = 0; i < 3; ++i)
{
for (size_t j = 0; j < 4; ++j)
{
v[i][j] = (i == j) ? T(1) : T(0);
}
}
v[3][0] = translation[0];
v[3][1] = translation[1];
v[3][2] = translation[2];
v[3][3] = T(1);
return *this;
}
CUDA_CALLABLE this_type& SetTranslateOnly(const vec3<T>& translation)
{
v[3][0] = translation[0];
v[3][1] = translation[1];
v[3][2] = translation[2];
v[3][3] = T(1);
return *this;
}
CUDA_CALLABLE void SetRow3(size_t rowIndex, const vec3<T>& rowValues)
{
v[rowIndex][0] = rowValues[0];
v[rowIndex][1] = rowValues[1];
v[rowIndex][2] = rowValues[2];
}
CUDA_CALLABLE vec3<T> GetRow3(size_t rowIndex)
{
return vec3<T>(v[rowIndex][0], v[rowIndex][1], v[rowIndex][2]);
}
CUDA_CALLABLE this_type& SetLookAt(const vec3<T>& cameraPosition,
const vec3<T>& focusPosition,
const vec3<T>& upDirection)
{
// NOTE: forward is the negative z direction.
vec3<T> forward = (focusPosition - cameraPosition).GetNormalized();
// Force up direction to be orthogonal to forward.
// NOTE: up is the positive y direction.
vec3<T> up = upDirection.GetComplement(forward).GetNormalized();
// NOTE: right is the positive x direction.
vec3<T> right = GfCross(forward, up);
// Pre-translation by -cameraPosition
vec3<T> translation(-right.Dot(cameraPosition), -up.Dot(cameraPosition), forward.Dot(cameraPosition));
T m[4][4] = { { right[0], up[0], -forward[0], T(0) },
{ right[1], up[1], -forward[1], T(0) },
{ right[2], up[2], -forward[2], T(0) },
{ translation[0], translation[1], translation[2], T(1) } };
return Set(m);
}
CUDA_CALLABLE this_type& SetLookAt(const vec3<T>& cameraPosition, const quat<double>& orientation)
{
matrix4<T> translation;
translation.SetTranslate(-cameraPosition);
matrix4<T> rotation;
rotation.SetRotate(orientation.GetInverse());
*this = translation * rotation;
return *this;
}
CUDA_CALLABLE vec3<T> ExtractTranslation() const
{
return vec3<T>(v[3][0], v[3][1], v[3][2]);
}
CUDA_CALLABLE quat<double> ExtractRotation() const
{
return ExtractRotationMatrix().ExtractRotation();
}
// NOTE: Contrary to the name, this extracts the full 3x3 portion of the matrix,
// i.e. it also includes scales and shears.
CUDA_CALLABLE matrix3<T> ExtractRotationMatrix() const
{
return matrix3<T>(v[0][0], v[0][1], v[0][2], v[1][0], v[1][1], v[1][2], v[2][0], v[2][1], v[2][2]);
}
template <typename OTHER_T>
CUDA_CALLABLE vec3<OTHER_T> Transform(const vec3<OTHER_T>& u) const
{
return vec3<OTHER_T>(vec4<T>(u[0] * v[0][0] + u[1] * v[1][0] + u[2] * v[2][0] + v[3][0],
u[0] * v[0][1] + u[1] * v[1][1] + u[2] * v[2][1] + v[3][1],
u[0] * v[0][2] + u[1] * v[1][2] + u[2] * v[2][2] + v[3][2],
u[0] * v[0][3] + u[1] * v[1][3] + u[2] * v[2][3] + v[3][3])
.Project());
}
template <typename OTHER_T>
CUDA_CALLABLE vec3<OTHER_T> TransformDir(const vec3<OTHER_T>& u) const
{
return vec3<OTHER_T>(OTHER_T(u[0] * v[0][0] + u[1] * v[1][0] + u[2] * v[2][0]),
OTHER_T(u[0] * v[0][1] + u[1] * v[1][1] + u[2] * v[2][1]),
OTHER_T(u[0] * v[0][2] + u[1] * v[1][2] + u[2] * v[2][2]));
}
template <typename OTHER_T>
CUDA_CALLABLE vec3<OTHER_T> TransformAffine(const vec3<OTHER_T>& u) const
{
return vec3<OTHER_T>(OTHER_T(u[0] * v[0][0] + u[1] * v[1][0] + u[2] * v[2][0] + v[3][0]),
OTHER_T(u[0] * v[0][1] + u[1] * v[1][1] + u[2] * v[2][1] + v[3][1]),
OTHER_T(u[0] * v[0][2] + u[1] * v[1][2] + u[2] * v[2][2] + v[3][2]));
}
private:
using base_type::v;
};
using matrix2f = matrix2<float>;
using matrix2d = matrix2<double>;
using matrix3f = matrix3<float>;
using matrix3d = matrix3<double>;
using matrix4f = matrix4<float>;
using matrix4d = matrix4<double>;
}
}
}
namespace usdrt
{
using omni::math::linalg::GfIsClose;
using GfMatrix3d = omni::math::linalg::matrix3<double>;
using GfMatrix3f = omni::math::linalg::matrix3<float>;
using GfMatrix4d = omni::math::linalg::matrix4<double>;
using GfMatrix4f = omni::math::linalg::matrix4<float>;
}
| 41,278 | C | 28.400997 | 121 | 0.510902 |
omniverse-code/kit/include/usdrt/gf/README.md | usdrt::Gf
=========
The usdrt::Gf library is a strategic re-namespacing and type aliasing
of omni\:\:math\:\:linalg in support of the ongoing Omniverse
runtime initiative. This allows us to maintain parity between C++ class names
(ex: `usdrt::GfVec3d`) and Python class names (ex: `usdrt.Gf.Vec3d`)
for code that integrates the forthcoming USDRT libraries. These are intended
to be pin-compatible replacements for their USD equivalents, without the
associated overhead (no USD library or other dependencies, no boost).
C++ functionality
-----------------
These types are aliased in the usdrt namespace:
- GfHalf
- GfMatrix(3/4)(d/f/h)
- GfQuat(d/f/h)
- GfVec(2/3/4)(d/f/h/i)
- GfRange(1/2/3)(d/f)
- GfRect2i
These functions are aliased in the usdrt namespace:
- GfCompDiv
- GfCompMult
- GfCross
- GfDegreesToRadians
- GfDot
- GfGetComplement
- GfGetLength
- GfGetNormalized
- GfGetProjection
- GfIsClose
- GfLerp
- GfMax
- GfMin
- GfNormalize
- GfRadiansToDegrees
- GfSlerp
Note that pointers to usdrt Gf types can be safely reinterpret_cast to
pointers of equivalent pxr Gf types and other types with matching memory layouts:
```
pxr::GfVec3d pxrVec(1.0, 2.0, 3.0);
usdrt::GfVec3d rtVec(*reinterpret_cast<usdrt::GfVec3d*>(&pxrVec));
assert(rtVec[0] == 1.0);
assert(rtVec[1] == 2.0);
assert(rtVec[2] == 3.0);
```
pybind11 Python bindings
------------------------
Python bindings using pybind11 for these classes can be found in
`source/bindings/python/usdrt.Gf`. The python bindings deliver
these classes in the usdrt package:
- Gf.Matrix(3/4)(d/f/h)
- Gf.Quat(d/f/h)
- Gf.Vec(2/3/4)(d/f/h/i)
- Gf.Range(1/2/3)(d/f)
- Gf.Rect2i
Like in USD, usdrt::GfHalf is transparently converted to and from double, which
is Python's preferred floating point representation.
usdrt.Gf classes implement the python buffer protocol, so they can
be initialized from other types that also implement the buffer protocol,
including Pixar's Gf types and numpy.
```
import pxr, usdrt
pxr_vec = pxr.Gf.Vec3d(1.0, 2.0, 3.0)
rt_vec = usdrt.Gf.Vec3d(pxr_vec)
assert rt_vec[0] == 1.0
assert rt_vec[1] == 2.0
assert rt_vec[2] == 3.0
```
| 2,127 | Markdown | 23.45977 | 81 | 0.719323 |
omniverse-code/kit/include/omni/StringView.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Implementation of \ref omni::span
#pragma once
#include "../carb/cpp/StringView.h"
namespace omni
{
//! @copydoc carb::cpp::string_view
using string_view = ::carb::cpp::string_view;
//! @copydoc carb::cpp::wstring_view
using wstring_view = ::carb::cpp::wstring_view;
#if CARB_HAS_CPP20
//! basic_string_view<char8_t>
//! @see basic_string_view
using u8string_view = ::carb::cpp::u8string_view;
#endif
//! @copydoc carb::cpp::u16string_view
using u16string_view = ::carb::cpp::u16string_view;
//! @copydoc carb::cpp::u32string_view
using u32string_view = ::carb::cpp::u32string_view;
} // namespace omni
| 1,067 | C | 27.105262 | 77 | 0.732896 |
omniverse-code/kit/include/omni/Function.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Implementation of \c omni::function.
#pragma once
#include <functional>
#include "detail/FunctionImpl.h"
#include "../carb/detail/NoexceptType.h"
namespace omni
{
//! Thrown when \c function::operator() is called but the function is unbound.
using std::bad_function_call;
//! \cond DEV
template <typename Signature>
class function;
//! \endcond
//! A polymorphic function wrapper which is compatible with \c std::function.
//!
//! For most usage, it is equivalent to the \c std::function API, but there are a few minor changes for ABI stability
//! and C interoperation.
//!
//! * The \c target and \c target_type functions are not available. These rely on RTTI, which is not required for
//! Omniverse builds and is not ABI safe.
//! * No support for allocators, as these were removed in C++17. The \c carbReallocate function is used for all memory
//! management needs.
//! * A local buffer for storing functors. While the C++ Standard encourages this, this implementation keeps the size
//! and alignment fixed.
//! * An \c omni::function is trivially-relocatable.
template <typename TReturn, typename... TArgs>
class function<TReturn(TArgs...)> : private ::omni::detail::FunctionData
{
using base_type = ::omni::detail::FunctionData;
using traits = ::omni::detail::FunctionTraits<TReturn(TArgs...)>;
public:
//! The return type of this function.
using result_type = typename traits::result_type;
public:
//! Create an unbound instance.
function(std::nullptr_t) noexcept : base_type(nullptr)
{
}
//! Create an unbound instance.
function() noexcept : function(nullptr)
{
}
//! Create an instance as a copy of \a other.
//!
//! If \a other was bound before the call, then the created instance will be bound to the same target.
function(function const& other) = default;
//! Create an instance by moving from \a other.
//!
//! If \a other was bound before the call, then the created instance will be bound to the same target. After this
//! call, \a other will be unbound.
function(function&& other) noexcept = default;
//! Reset this function wrapper to unbound.
function& operator=(std::nullptr_t) noexcept
{
reset();
return *this;
}
//! Copy the \a other instance into this one.
//!
//! If copying the function fails, both instances will remain unchanged.
function& operator=(function const& other) = default;
//! Move the \a other instance into this one.
function& operator=(function&& other) noexcept = default;
CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE()
//! The binding constructor for function, which wraps \a f for invocation.
//!
//! The created instance will have a "target type" (referred to as \c Target here) of \c std::decay_t<Target> which
//! is responsible for invoking the function. The following descriptions use a common set of symbols to describe
//! types:
//!
//! * \c UReturn -- A return type which is the same as or implicitly convertible from \c TReturn. If \c UReturn
//! is \c void, then \c TReturn must be implicitly discardable.
//! * \c UArgs... -- An argument pack where all arguments are implicitly convertible to \c TArgs... .
//! * \c UArg0Obj -- The object type of the possibly-dereferenced first type in the \c TArgs... pack. In other
//! words, if \c TArgs... was `{Object*, int}`, then \c UArg0Obj would be \c Object. Any cv-qualifiers follow the
//! dereference (e.g.: if \c TArg0 is `Object const*`, then \c UArg0Obj is `Object const`).
//! * \c UArg1N... -- Same as \c UArgs... but do not include the first type in the pack.
//!
//! The \c Target can be one of the following:
//!
//! 1. A function pointer -- \c UReturn(*)(UArgs...)
//! 2. A pointer to a member function -- `UReturn UArg0Obj::*(UArg1N...)`
//! 3. A pointer to member data -- `UReturn UArg0Obj::*` when `sizeof(TArgs...) == 1`
//! 4. Another `omni::function` -- `omni::function<UReturn(UArgs...)>` where \c UReturn and \c UArgs... are
//! different from \c TReturn and \c TArgs... (the exact same type uses a copy or move operation)
//! 5. An `std::function` -- `std::function<UReturn(UArgs...)>`, but \c UReturn and \c UArgs... can all match
//! \c TReturn and \c TArgs...
//! 6. A functor with \c operator() accepting \c UArgs... and returning \c UReturn
//!
//! If the \c Target does not match any of preceding possibilities, this function does not participate in overload
//! resolution in a SFINAE-safe manner. If \c Target is non-copyable, then the program is ill-formed.
//!
//! For cases 1-5, if `f == nullptr`, then the function is initialized as unbound. Note the quirky case on #6, where
//! the composite `omni::function<void()>{std::function<void()>{}}` will create an unbound function. But this is not
//! commutative, as `std::function<void()>{omni::function<void()>{}}` will create a bound function which throws when
//! called.
template <typename F, typename Assigner = ::omni::detail::FunctionAssigner<traits, F>>
function(F&& f) : base_type(Assigner{}, std::forward<F>(f))
{
}
//! Bind this instance to \a f according to the rules in the binding constructor.
//!
//! If the process of binding a \c function to \a f fails, this instance will remain unchanged.
template <typename F, typename Assigner = ::omni::detail::FunctionAssigner<traits, F>>
function& operator=(F&& f)
{
return operator=(function{ std::forward<F>(f) });
}
CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE()
//! If this function has context it needs to destroy, then perform that cleanup.
~function() noexcept = default;
//! Invoke this function with the provided \a args.
//!
//! If this function is not bound (see `operator bool() const`), the program will throw \c bad_function_call if
//! exceptions are enabled or panic if they are not.
TReturn operator()(TArgs... args) const
{
if (m_trampoline == nullptr)
::omni::detail::null_function_call();
auto f = reinterpret_cast<TReturn (*)(::omni::detail::FunctionBuffer const*, TArgs...)>(m_trampoline);
return f(&m_buffer, std::forward<TArgs>(args)...);
}
//! Check that this function is bound.
explicit operator bool() const noexcept
{
return bool(m_trampoline);
}
//! Swap the contents of \a other with this one.
void swap(function& other) noexcept
{
base_type::swap(other);
}
};
//! Check if \a func is not activated.
template <typename TReturn, typename... TArgs>
bool operator==(function<TReturn(TArgs...)> const& func, std::nullptr_t) noexcept
{
return !func;
}
//! Check if \a func is not activated.
template <typename TReturn, typename... TArgs>
bool operator==(std::nullptr_t, function<TReturn(TArgs...)> const& func) noexcept
{
return !func;
}
//! Check if \a func is activated.
template <typename TReturn, typename... TArgs>
bool operator!=(function<TReturn(TArgs...)> const& func, std::nullptr_t) noexcept
{
return static_cast<bool>(func);
}
//! Check if \a func is activated.
template <typename TReturn, typename... TArgs>
bool operator!=(std::nullptr_t, function<TReturn(TArgs...)> const& func) noexcept
{
return static_cast<bool>(func);
}
//! Swap \a a and \a b by \c function::swap.
template <typename TReturn, typename... TArgs>
void swap(function<TReturn(TArgs...)>& a, function<TReturn(TArgs...)>& b) noexcept
{
a.swap(b);
}
} // namespace omni
| 8,072 | C | 38.768473 | 120 | 0.666254 |
omniverse-code/kit/include/omni/Expected.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! \file
//! \brief Implementation of \c omni::expected and related functions and structures.
#pragma once
#include "detail/ExpectedImpl.h"
namespace omni
{
template <typename TValue, typename TError>
class expected;
//! The unexpected value of an \ref expected monad. This is used as a convenient mechanism to report the error case when
//! constructing an \c expected return.
//!
//! \code
//! expected<string, Result> foo(bool x)
//! {
//! // C++17: TError is deduced as `Result`
//! return unexpected(kResultNotImplemented);
//! }
//! \endcode
template <typename TError>
class unexpected : public omni::detail::UnexpectedImpl<TError>
{
using base_impl = omni::detail::UnexpectedImpl<TError>;
template <typename UError>
friend class unexpected;
public:
using base_impl::base_impl;
//! Swap the contents of this instance with \a other.
//!
//! If \c TError is \c noexcept swappable or if it is \c void, this operation is also \c noexcept.
//!
//! \note
//! This function only participates in overload resolution if \c TError is swappable or is \c void.
template <
typename UError,
typename IsNoexcept = std::enable_if_t<
carb::cpp::conjunction<
std::is_same<TError, UError>,
typename omni::detail::ExpectedTransformIfNonVoid<carb::cpp::is_swappable, UError, std::true_type>::type>::value,
typename omni::detail::ExpectedTransformIfNonVoid<carb::cpp::is_nothrow_swappable, UError, std::true_type>::type>>
constexpr void swap(unexpected& other) noexcept(IsNoexcept::value)
{
base_impl::swap(static_cast<base_impl&>(other));
}
//! Swap the contents of \a lhs with \a rhs.
//!
//! If \c UError is \c noexcept swappable or if it is \c void, this operation is also \c noexcept.
template <typename UError,
typename IsNoexcept = std::enable_if_t<
omni::detail::ExpectedTransformIfNonVoid<carb::cpp::is_swappable, UError, std::true_type>::type::value,
typename omni::detail::ExpectedTransformIfNonVoid<carb::cpp::is_nothrow_swappable, UError, std::true_type>::type>>
friend constexpr void swap(unexpected& lhs, unexpected<UError>& rhs) noexcept(IsNoexcept::value)
{
lhs.swap(rhs);
}
//! If \c TError and \c UError are not \c void, then return `this->error() == other.error()` if they are equality
//! comparable (it is a compilation failure if they are not). If both \c TError and \c UError are \c void, then
//! return \c true. If one is \c void and the other is not, this is a compilation failure.
template <typename UError>
constexpr bool operator==(unexpected<UError> const& other) const
{
static_assert(std::is_void<TError>::value == std::is_void<UError>::value, "Can not compare void and non-void");
return base_impl::operator==(other);
}
//! If \c TError and \c UError are not \c void, then return `lhs.error() == rhs.error()` if they are equality
//! comparable (it is a compilation failure if they are not). If both \c TError and \c UError are \c void, then
//! return \c true. If one is \c void and the other is not, this is a compilation failure.
template <typename UError>
friend constexpr bool operator==(unexpected const& lhs, unexpected<UError> const& rhs)
{
return lhs.operator==(rhs);
}
};
#if CARB_HAS_CPP17
//! Allow deduction of \c TError from the `unexpected(t)` expression.
template <typename T>
unexpected(T) -> unexpected<T>;
//! An empty `unexpected()` constructor call implies `TError = void`.
unexpected()->unexpected<void>;
#endif
//! Used in \ref expected constructors to designate that the error type should be constructed.
struct unexpect_t;
//! A monad which holds either an expected value (the success case) or an unexpected value (the error case).
//!
//! \tparam TValue The type of expected value, returned in the success case.
//! \tparam TError The type of unexpected value, returned in the error case.
//!
//! Simple use of \c expected instances involve checking if an instance \c has_value() before accessing either the
//! \c value() or \c error() member.
//!
//! \code
//! expected<int, string> foo();
//!
//! int main()
//! {
//! auto ex = foo();
//! if (ex)
//! std::cout << "Successfully got " << ex.value() << std::endl;
//! else
//! std::cout << "Error: " << ex.error() << std::endl;
//! }
//! \endcode
//!
//! Advanced usage of \c expected involves using the monadic operations, which act on the stored value. This example is
//! equivalent to the above:
//!
//! \code
//! expected<int, string> foo();
//!
//! int main()
//! {
//! foo()
//! .transform([](int value) { std::cout << "Successfully got " << value << std::endl; })
//! .transform_error([](string const& err) { std::cout << "Error: " << err << std::endl; });
//! }
//! \endcode
template <typename TValue, typename TError>
class CARB_NODISCARD_TYPE expected : public omni::detail::ExpectedImpl<TValue, TError>
{
private:
using base_impl = omni::detail::ExpectedImpl<TValue, TError>;
public:
//! The type used in success case.
using value_type = TValue;
//! The type used in error cases. Unlike the C++23 definition of \c std::expected, this is allowed to be \c void to
//! match parity with other languages with result monads.
using error_type = TError;
//! The \c unexpected type which contains this monad's \ref error_type.
using unexpected_type = unexpected<error_type>;
//! Get an \c expected type with \c UValue as the \ref value_type and the same \ref error_type as this.
template <typename UValue>
using rebind = expected<UValue, error_type>;
public:
using base_impl::base_impl;
//! Create a valued instance through default construction.
//!
//! This constructor is only enabled if \ref value_type is default-constructable or \c void.
//!
//! This function is \c noexcept if \ref value_type has a \c noexcept default constructor or if it is \c void.
expected() = default;
//! Copy an expected instance from another. After this call, `this->has_value() == src.has_value()` and either the
//! \c value or \c error will have been constructed from the \a src instance.
//!
//! This operation is only enabled if both \ref value_type and \ref error_type are copy-constructible or \c void.
//! This operation is trivial if both \ref value_type and \ref error_type have trivial copy constructors or are
//! \c void.
//!
//! This function is \c noexcept if both \ref value_type and \ref error_type have \c noexcept copy constructors or
//! are \c void.
//!
//! \param src The source to copy from. It will remain unchanged by this operation.
expected(expected const& src) = default;
//! Move an expected instance from another. After this call, `this->has_value() == src.has_value()` and either the
//! \c value or \c error will have been constructed from `std::move(src).value()` or `std::move(src).error()`. Note
//! that the \c has_value state is unchanged, but the \a src instance will be moved-from.
//!
//! This operation is only enabled if both \ref value_type and \ref error_type are move-constructible or \c void.
//! This operation is trivial if both \ref value_type and \ref error_type have trivial move constructors or are
//! \c void.
//!
//! This function is \c noexcept if both \ref value_type and \ref error_type have \c noexcept move constructors or
//! are \c void.
//!
//! \param src The source to move from. While the \ref has_value state will remain unchanged, the active \a src
//! instance will have been moved-from.
expected(expected&& src) = default;
//! Copy-assign this instance from another. After this call, `this->has_value() == src.has_value()`.
//!
//! Assignment can happen in one of two ways. In the simple case, `this->has_value() == src.has_value()` before the
//! call, so the copy assignment operator of the underlying type is used. If `this->has_value() != src.has_value()`
//! before the call, then the active instance of \c this gets the destructor called, then the other type is copy
//! constructed (generally -- see the "exceptions" section for more info). Note that this destruct-then-construct
//! process happens even when \ref value_type and \ref error_type are the same.
//!
//! This operation is only enabled if both \ref value_type and \ref error_type are copy-assignable or \c void. This
//! operation is trivial if both \ref value_type and \ref error_type have trivial copy assignment operators and
//! trivial destructors or are \c void.
//!
//! This function is \c noexcept if both \ref value_type and \ref error_type have \c noexcept copy constructors,
//! copy assignment operators, and \c noexcept destructors or are \c void.
//!
//! \note
//! On type-changing assignment with exceptions enabled, care is taken to ensure the contents of the monad are valid
//! for use when exceptions are thrown. The "simple" destruct-then-construct process is only followed when copy
//! construction of the type of the created instance is non-throwing. The exact algorithm used depends on the
//! available \c noexcept operations (if any), but they involve a stack-based temporary and rollback. Note that a
//! new instance \e might be constructed before the destruction of the old, so the ordering of these operations
//! should not be relied on.
//!
//! \param src The source to copy from. It will remain unchanged by this operation.
expected& operator=(expected const& src) = default;
//! Move-assign this instance from another. After this call, `this->has_value() == src.has_value()`.
//!
//! Assignment can happen in one of two ways. In the simple case, `this->has_value() == src.has_value()` before the
//! call, so the move assignment operator of the underlying type is used. If `this->has_value() != src.has_value()`
//! before the call, then the active instance of \c this gets the destructor called, then the other type is move
//! constructed (generally -- see the "exceptions" section for more info). Note that this destruct-then-construct
//! process happens even when \ref value_type and \ref error_type are the same.
//!
//! This operation is only enabled if both \ref value_type and \ref error_type are move-assignable or \c void. This
//! operation is trivial if both \ref value_type and \ref error_type have trivial move assignment operators and
//! trivial destructors or are \c void.
//!
//! This function is \c noexcept if both \ref value_type and \ref error_type have \c noexcept move constructors,
//! move assignment operators, and \c noexcept destructors or are \c void.
//!
//! \note
//! On type-changing assignment with exceptions enabled, care is taken to ensure the contents of the monad are valid
//! for use when exceptions are thrown. The "simple" destruct-then-construct process is only followed when move
//! construction of the type of the created instance is non-throwing. The exact algorithm used depends on the
//! available \c noexcept operations (if any), but they involve a stack-based temporary and rollback. Note that a
//! new instance \e might be constructed before the destruction of the old, so the ordering of these operations
//! should not be relied on.
//!
//! \param src The source to move from. While the \ref has_value will remain unchanged, the active \a src instance
//! will have been moved-from.
expected& operator=(expected&& src) = default;
//! Destroy this instance by calling the destructor of the active value.
//!
//! This operation is trivial if both \ref value_type and \ref error_type are trivially destructible. This function
//! is \c noexcept if both \ref value_type and \ref error_type have \c noexcept destructors.
~expected() = default;
//! Construct an instance by forwarding \a src to construct the \ref value_type by direct initialization. After this
//! call, `this->has_value()` will be true.
//!
//! This constructor is only enabled when all of the following criteria is met:
//!
//! 1. \ref value_type is constructible from \c UValue
//! 2. \ref value_type is not \c void
//! 3. `remove_cvref_t<UValue>` is not \c in_place_t
//! 4. `remove_cvref_t<UValue>` is not `expected<TValue, TError>` (the copy or move constructor is used instead)
//! 5. `remove_cvref_t<UValue>` is not a specialization of \c unexpected
//! 6. if \ref value_type is \c bool, then \c UValue can not be a specialization of \c expected
//!
//! This constructor is \c explicit if conversion from \c UValue to \ref value_type is \c explicit.
template <typename UValue = TValue,
std::enable_if_t<omni::detail::IsExpectedDirectConstructibleFrom<UValue, expected>::is_explicit, bool> = true>
constexpr explicit expected(UValue&& src) : base_impl(carb::cpp::in_place, std::forward<UValue>(src))
{
}
#ifndef DOXYGEN_BUILD
template <typename UValue = TValue,
std::enable_if_t<!omni::detail::IsExpectedDirectConstructibleFrom<UValue, expected>::is_explicit, bool> = false>
constexpr expected(UValue&& src) : base_impl(carb::cpp::in_place, std::forward<UValue>(src))
{
}
#endif
//! Convert from \a src by direct initialization from the active element. If `src.has_value()`, then this instance
//! will have a value constructed from `src.value()`; otherwise, this instance will have an error constructed from
//! `src.error()`. After this call, `this->has_value() == src.has_value()`.
//!
//! This converting constructor is not \c explicit if conversion from \c UValue to \c TValue and \c UError to
//! \c TError are not \c explicit. Conversion from \c void to \c void is also considered a non \c explicit
//! conversion. Stated differently, a \c UExpected is implicitly convertible to a \c TExpected if both of its
//! components are implicitly convertible.
//!
//! \note
//! The rules for this are almost identical to \c std::expected, but they are expanded to support \c void as the
//! \ref error_type. Any case where the C++ Standard makes an exception when \ref value_type is \c void, that same
//! exception has been extended to \ref error_type of \c void.
template <typename UValue,
typename UError,
std::enable_if_t<omni::detail::IsExpectedCopyConstructibleFrom<expected<UValue, UError>, expected>::is_explicit,
bool> = true>
constexpr explicit expected(expected<UValue, UError> const& src)
: base_impl(::omni::detail::ExpectedCtorBypass{}, src)
{
}
#ifndef DOXYGEN_BUILD
template <typename UValue,
typename UError,
std::enable_if_t<!omni::detail::IsExpectedCopyConstructibleFrom<expected<UValue, UError>, expected>::is_explicit,
bool> = false>
constexpr expected(expected<UValue, UError> const& src) : base_impl(::omni::detail::ExpectedCtorBypass{}, src)
{
}
#endif
//! Convert from \a src by direct initialization from the active element. If `src.has_value()`, then this instance
//! will have a value constructed from `move(src).value()`; otherwise, this instance will have an error constructed
//! from `move(src).error()`. After this call, `this->has_value() == src.has_value()`. Note that the contents of
//! \a src are moved-from, but not destructed, so the instances is still accessable.
//!
//! This converting constructor is not \c explicit if conversion from \c UValue to \c TValue and \c UError to
//! \c TError are not \c explicit. Conversion from \c void to \c void is also considered a non \c explicit
//! conversion. Stated differently, a \c UExpected is implicitly convertible to a \c TExpected if both of its
//! components are implicitly convertible.
//!
//! \note
//! The rules for this are almost identical to \c std::expected, but they are expanded to support \c void as the
//! \ref error_type. Any case where the C++ Standard makes an exception when \ref value_type is \c void, that same
//! exception has been extended to \ref error_type of \c void.
template <typename UValue,
typename UError,
std::enable_if_t<omni::detail::IsExpectedMoveConstructibleFrom<expected<UValue, UError>, expected>::is_explicit,
bool> = true>
constexpr explicit expected(expected<UValue, UError>&& src)
: base_impl(::omni::detail::ExpectedCtorBypass{}, std::move(src))
{
}
#ifndef DOXYGEN_BUILD
template <typename UValue,
typename UError,
std::enable_if_t<!omni::detail::IsExpectedMoveConstructibleFrom<expected<UValue, UError>, expected>::is_explicit,
bool> = false>
constexpr expected(expected<UValue, UError>&& src) : base_impl(::omni::detail::ExpectedCtorBypass{}, std::move(src))
{
}
#endif
//! Construct an instance using \a src as the error value. The constructed instance `!this->has_value()` and the
//! `this->error()` will have been constructed by `src.error()`.
//!
//! This constructor is not \c explicit if the conversion from the source \c UError to \c TError is not explicit.
//! Stated differently, an `unexpected<UError>` is implicitly convertible to a `expected<TValue, TError>` (of
//! arbitrary `TValue`) if `UError` is implicitly convertible to a `TError`.
//!
//! If \c TError is \c void, then \c UError must also be \c void to construct an instance.
template <typename UError,
std::enable_if_t<carb::cpp::conjunction<std::is_constructible<TError, UError const&>,
carb::cpp::negation<std::is_convertible<UError const&, TError>>>::value,
bool> = true>
constexpr explicit expected(unexpected<UError> const& src) : base_impl(unexpect, src.error())
{
}
#ifndef DOXYGEN_BUILD
template <typename UError,
std::enable_if_t<carb::cpp::conjunction<std::is_constructible<TError, UError const&>,
std::is_convertible<UError const&, TError>>::value,
bool> = false>
constexpr expected(unexpected<UError> const& src) : base_impl(unexpect, src.error())
{
}
#endif
//! Construct an instance using \a src as the error value. The constructed instance `!this->has_value()` and the
//! `this->error()` will have been constructed by `std::move(src).error()`.
//!
//! This constructor is not \c explicit if the conversion from the source \c UError to \c TError is not explicit.
//! Stated differently, an `unexpected<UError>` is implicitly convertible to a `expected<TValue, TError>` (of
//! arbitrary `TValue`) if `UError` is implicitly convertible to a `TError`.
//!
//! If \c TError is \c void, then \c UError must also be \c void to construct an instance.
template <typename UError,
std::enable_if_t<carb::cpp::conjunction<std::is_constructible<TError, UError&&>,
carb::cpp::negation<std::is_convertible<UError&&, TError>>>::value,
bool> = true>
constexpr explicit expected(unexpected<UError>&& src) : base_impl(unexpect, std::move(src).error())
{
}
#ifndef DOXYGEN_BUILD
template <typename UError,
std::enable_if_t<carb::cpp::conjunction<std::is_constructible<TError, UError&&>,
std::is_convertible<UError&&, TError>>::value,
bool> = false>
constexpr expected(unexpected<UError>&& src) : base_impl(unexpect, std::move(src).error())
{
}
#endif
//! Test if this instance has a \c value. If this returns \c true, then a call to \c value() will succeed, while a
//! call to \c error() would not. If this returns \c false, a call to \c error() will succeed, while a call to
//! \c value() would not.
constexpr bool has_value() const noexcept
{
return this->m_state == ::omni::detail::ExpectedState::eSUCCESS;
}
//! \copydoc expected::has_value() const
//!
//! \see has_value
constexpr explicit operator bool() const noexcept
{
return this->has_value();
}
#ifdef DOXYGEN_BUILD
//! If this instance \c has_value(), the value is returned by `&`.
//!
//! If this instance does not have a value, this call will not succeed. If exceptions are enabled, then a
//! \c bad_expected_access exception is thrown containing the copied contents of \c error(). If exceptions are
//! disabled, then the program will terminate.
//!
//! \note
//! If \ref value_type is \c void, the return type is exactly \c void instead of `void&` (which is illegal).
constexpr value_type& value() &;
//! If this instance \c has_value(), the value is returned by `const&`.
//!
//! If this instance does not have a value, this call will not succeed. If exceptions are enabled, then a
//! \c bad_expected_access exception is thrown containing the copied contents of \c error(). If exceptions are
//! disabled, then the program will terminate.
//!
//! \note
//! If \ref value_type is \c void, the return type is exactly \c void instead of `void const&` (which is illegal).
constexpr value_type const& value() const&;
//! If this instance \c has_value(), the value is returned by `&&`.
//!
//! If this instance does not have a value, this call will not succeed. If exceptions are enabled, then a
//! \c bad_expected_access exception is thrown containing the moved contents of \c error(). If exceptions are
//! disabled, then the program will terminate.
//!
//! \note
//! If \ref value_type is \c void, the return type is exactly \c void instead of `void&&` (which is illegal).
constexpr value_type&& value() &&;
//! If this instance \c has_value(), the value is returned by `const&&`.
//!
//! If this instance does not have a value, this call will not succeed. If exceptions are enabled, then a
//! \c bad_expected_access exception is thrown containing the copied contents of \c error(). If exceptions are
//! disabled, then the program will terminate.
//!
//! \note
//! If \ref value_type is \c void, the return type is exactly \c void instead of `void const&&` (which is illegal).
constexpr value_type const&& value() const&&;
//! If this instance \c has_value(), the value is copied and returned; otherwise, a \ref value_type instance is
//! constructed from \a default_value.
//!
//! \note
//! If \ref value_type is \c void, this member function does not exist. If \ref value_type is not copy
//! constructible, this will fail to compile in the immediate context (not SFINAE-safe).
//!
//! \tparam UValue Must be convertible to \ref value_type.
template <typename UValue>
constexpr value_type value_or(UValue&& default_value) const&;
//! If this instance \c has_value(), the value is moved and returned; otherwise, a \ref value_type instance is
//! constructed from \a default_value.
//!
//! \note
//! If \ref value_type is \c void, this member function does not exist. If \ref value_type is not move
//! constructible, this will fail to compile in the immediate context (not SFINAE-safe).
//!
//! \tparam UValue Must be convertible to \ref value_type.
template <typename UValue>
constexpr value_type value_or(UValue&& default_value) &&;
//! If this instance \c !has_value(), the error is returned by `&`.
//!
//! \pre
//! `!this->has_value()`: if this instance is not in the unexpected state, the program will terminate.
//!
//! \note
//! If \ref error_type is \c void, the return type is exactly \c void instead of `void&` (which is illegal).
constexpr error_type& error() & noexcept;
//! If this instance \c !has_value(), the error is returned by `const&`.
//!
//! \pre
//! `!this->has_value()`: if this instance is not in the unexpected state, the program will terminate.
//!
//! \note
//! If \ref error_type is \c void, the return type is exactly \c void instead of `void const&` (which is illegal).
constexpr error_type const& error() const& noexcept;
//! If this instance \c !has_value(), the error is returned by `&&`.
//!
//! \pre
//! `!this->has_value()`: if this instance is not in the unexpected state, the program will terminate.
//!
//! \note
//! If \ref error_type is \c void, the return type is exactly \c void instead of `void&&` (which is illegal).
constexpr error_type&& error() && noexcept;
//! If this instance \c !has_value(), the error is returned by `const&&`.
//!
//! \pre
//! `!this->has_value()`: if this instance is not in the unexpected state, the program will terminate.
//!
//! \note
//! If \ref error_type is \c void, the return type is exactly \c void instead of `void const&&` (which is illegal).
constexpr error_type const&& error() const&& noexcept;
//! Access the underlying value instance. If \c has_value() is \c false, the program will terminate.
//!
//! This function is only available if \ref value_type is not \c void.
constexpr value_type* operator->() noexcept;
//! \copydoc expected::operator->()
constexpr value_type const* operator->() const noexcept;
//! If this instance \c has_value(), the value is returned by `&`.
//!
//! If this instance does not have a value, the program will terminate.
//!
//! \note
//! If \ref value_type is \c void, this overload is not enabled (only the `const&` is accessible).
constexpr value_type& operator*() & noexcept;
//! If this instance \c has_value(), the value is returned by `const&`.
//!
//! If this instance does not have a value, the program will terminate.
//!
//! \note
//! If \ref value_type is \c void, the return type is exactly \c void instead of `void const&` (which is illegal).
constexpr value_type const& operator*() const& noexcept;
//! If this instance \c has_value(), the value is returned by `&&`.
//!
//! If this instance does not have a value, the program will terminate.
//!
//! \note
//! If \ref value_type is \c void, this overload is not enabled (only the `const&` is accessible).
constexpr value_type&& operator*() && noexcept;
//! If this instance \c has_value(), the value is returned by `const&&`.
//!
//! If this instance does not have a value, the program will terminate.
//!
//! \note
//! If \ref value_type is \c void, this overload is not enabled (only the `const&` is accessible).
constexpr value_type const&& operator*() const&& noexcept;
//! Destroy the current contents of this instance and construct the \ref value_type of this instance through
//! direct-initialization.
//!
//! If \ref value_type is not \c void, this function accepts two overloads:
//!
//! 1. `template <typename... TArgs> value_type& emplace(TArgs&&... args) noexcept` (only enabled if
//! `std::is_nothrow_constructible<value_type, TArgs...>::value` is \c true)
//! 2. `template <typename U, typename... TArgs> value_type& emplace(std::initializer_list<U>& il, TArgs&&... args)
//! noexcept` (only enabled if `std::is_nothrow_constructible<value_type, std::initializer_list<U>&,
//! TArgs...>::value` is \c true)
//!
//! After calling this function, \c has_value() will return \c true.
template <typename... TArgs>
value_type& emplace(TArgs&&... args) noexcept;
//! If \ref value_type is \c void, then \c emplace is a no argument function that returns \c void.
//!
//! After calling this function, \c has_value() will return \c true.
void emplace() noexcept;
#endif
//! Transform the value by \a f if this \c has_value() or return the error if it does not.
//!
//! \tparam F If \ref value_type is not \c void, \c F has the signature `UValue (value_type const&)`; if
//! \ref value_type is \c void, \c F has the signature `UValue ()`.
//!
//! \returns
//! An `expected<UValue, error_type>`, where the returned value has been transformed by \a f. The \ref value_type of
//! the returned instance is the result type of \c F.
template <typename F>
constexpr auto transform(F&& f) const&
{
return ::omni::detail::ExpectedOpTransform<F, expected, expected const&>::transform(std::forward<F>(f), *this);
}
//! Transform the value by \a f if this \c has_value() or return the error if it does not.
//!
//! \tparam F If \ref value_type is not \c void, \c F has the signature `UValue (value_type&)`; if \ref value_type
//! is \c void, \c F has the signature `UValue ()`.
//!
//! \returns
//! An `expected<UValue, error_type>`, where the returned value has been transformed by \a f. The \ref value_type of
//! the returned instance is the result type of \c F.
template <typename F>
constexpr auto transform(F&& f) &
{
return ::omni::detail::ExpectedOpTransform<F, expected, expected&>::transform(std::forward<F>(f), *this);
}
//! Transform the value by \a f if this \c has_value() or return the error if it does not.
//!
//! \tparam F If \ref value_type is not \c void, \c F has the signature `UValue (value_type&&)`; if \ref value_type
//! is \c void, \c F has the signature `UValue ()`.
//!
//! \returns
//! An `expected<UValue, error_type>`, where the returned value has been transformed by \a f. The \ref value_type of
//! the returned instance is the result type of \c F.
template <typename F>
constexpr auto transform(F&& f) &&
{
return ::omni::detail::ExpectedOpTransform<F, expected, expected&&>::transform(
std::forward<F>(f), std::move(*this));
}
//! Transform the value by \a f if this \c has_value() or return the error if it does not.
//!
//! \tparam F If \ref value_type is not \c void, \c F has the signature `UValue (value_type const&&)`; if
//! \ref value_type is \c void, \c F has the signature `UValue ()`.
//!
//! \returns
//! An `expected<UValue, error_type>`, where the returned value has been transformed by \a f. The \ref value_type of
//! the returned instance is the result type of \c F.
template <typename F>
constexpr auto transform(F&& f) const&&
{
return ::omni::detail::ExpectedOpTransform<F, expected, expected const&&>::transform(
std::forward<F>(f), std::move(*this));
}
//! Transform the value by \a f if this \c has_value() or return the error if it does not.
//!
//! \tparam F If \ref value_type is not \c void, \c F has the signature
//! `expected<UValue, UError> (value_type const&)`; if \ref value_type is \c void, \c F has the signature
//! `expected<UValue, UError> ()`. In both cases, \c UError must be constructible from \ref error_type or
//! \c void.
template <typename F>
constexpr auto and_then(F&& f) const&
{
return ::omni::detail::ExpectedOpAndThen<F, expected, expected const&>::and_then(std::forward<F>(f), *this);
}
//! Transform the value by \a f if this \c has_value() or return the error if it does not.
//!
//! \tparam F If \ref value_type is not \c void, \c F has the signature `expected<UValue, UError> (value_type&)`; if
//! \ref value_type is \c void, \c F has the signature `expected<UValue, UError> ()`. In both cases,
//! \c UError must be constructible from \ref error_type or \c void.
template <typename F>
constexpr auto and_then(F&& f) &
{
return ::omni::detail::ExpectedOpAndThen<F, expected, expected&>::and_then(std::forward<F>(f), *this);
}
//! Transform the value by \a f if this \c has_value() or return the error if it does not.
//!
//! \tparam F If \ref value_type is not \c void, \c F has the signature `expected<UValue, UError> (value_type&&)`;
//! if \ref value_type is \c void, \c F has the signature `expected<UValue, UError> ()`. In both cases,
//! \c UError must be constructible from \ref error_type or \c void.
template <typename F>
constexpr auto and_then(F&& f) &&
{
return ::omni::detail::ExpectedOpAndThen<F, expected, expected&&>::and_then(std::forward<F>(f), std::move(*this));
}
//! Transform the value by \a f if this \c has_value() or return the error if it does not.
//!
//! \tparam F If \ref value_type is not \c void, \c F has the signature
//! `expected<UValue, UError> (value_type const&&)`; if \ref value_type is \c void, \c F has the signature
//! `expected<UValue, UError> ()`. In both cases, \c UError must be constructible from \ref error_type or
//! \c void.
template <typename F>
constexpr auto and_then(F&& f) const&&
{
return ::omni::detail::ExpectedOpAndThen<F, expected, expected const&&>::and_then(
std::forward<F>(f), std::move(*this));
}
//! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not.
//!
//! \tparam F If \ref error_type is not \c void, \c F has the signature `UError (error_type const&)`; if
//! \ref error_type is \c void, \c F has the signature `UError ()`.
//!
//! \returns
//! An `expected<value_type, UError>`, where the returned error has been transformed by \a f. The \ref error_type of
//! the returned instance is the result type of \c F.
template <typename F>
constexpr auto transform_error(F&& f) const&
{
return ::omni::detail::ExpectedOpTransformError<F, expected, expected const&>::transform_error(
std::forward<F>(f), *this);
}
//! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not.
//!
//! \tparam F If \ref error_type is not \c void, \c F has the signature `UError (error_type&)`; if \ref error_type
//! is \c void, \c F has the signature `UError ()`.
//!
//! \returns
//! An `expected<value_type, UError>`, where the returned error has been transformed by \a f. The \ref error_type of
//! the returned instance is the result type of \c F.
template <typename F>
constexpr auto transform_error(F&& f) &
{
return ::omni::detail::ExpectedOpTransformError<F, expected, expected&>::transform_error(
std::forward<F>(f), *this);
}
//! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not.
//!
//! \tparam F If \ref error_type is not \c void, \c F has the signature `UError (error_type&&)`; if \ref error_type
//! is \c void, \c F has the signature `UError ()`.
//!
//! \returns
//! An `expected<value_type, UError>`, where the returned error has been transformed by \a f. The \ref error_type of
//! the returned instance is the result type of \c F.
template <typename F>
constexpr auto transform_error(F&& f) &&
{
return ::omni::detail::ExpectedOpTransformError<F, expected, expected&&>::transform_error(
std::forward<F>(f), std::move(*this));
}
//! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not.
//!
//! \tparam F If \ref error_type is not \c void, \c F has the signature `UError (error_type const&&)`; if
//! \ref error_type is \c void, \c F has the signature `UError ()`.
//!
//! \returns
//! An `expected<value_type, UError>`, where the returned error has been transformed by \a f. The \ref error_type of
//! the returned instance is the result type of \c F.
template <typename F>
constexpr auto transform_error(F&& f) const&&
{
return ::omni::detail::ExpectedOpTransformError<F, expected, expected const&&>::transform_error(
std::forward<F>(f), std::move(*this));
}
//! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not.
//!
//! \tparam F If \ref error_type is not \c void, \c F has the signature
//! `expected<UValue, UError> (error_type const&)`; if \ref error_type is \c void, \c F has the signature
//! `expected<UValue, UError> ()`. In both cases, \c UValue must be constructible from \ref value_type or
//! \c void.
template <typename F>
constexpr auto or_else(F&& f) const&
{
return ::omni::detail::ExpectedOpOrElse<F, expected, expected const&>::or_else(std::forward<F>(f), *this);
}
//! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not.
//!
//! \tparam F If \ref error_type is not \c void, \c F has the signature `expected<UValue, UError> (error_type&)`; if
//! \ref error_type is \c void, \c F has the signature `expected<UValue, UError> ()`. In both cases,
//! \c UValue must be constructible from \ref value_type or \c void.
template <typename F>
constexpr auto or_else(F&& f) &
{
return ::omni::detail::ExpectedOpOrElse<F, expected, expected&>::or_else(std::forward<F>(f), *this);
}
//! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not.
//!
//! \tparam F If \ref error_type is not \c void, \c F has the signature `expected<UValue, UError> (error_type&&)`;
//! if \ref error_type is \c void, \c F has the signature `expected<UValue, UError> ()`. In both cases,
//! \c UValue must be constructible from \ref value_type or \c void.
template <typename F>
constexpr auto or_else(F&& f) &&
{
return ::omni::detail::ExpectedOpOrElse<F, expected, expected&&>::or_else(std::forward<F>(f), std::move(*this));
}
//! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not.
//!
//! \tparam F If \ref error_type is not \c void, \c F has the signature
//! `expected<UValue, UError> (error_type const&&)`; if \ref error_type is \c void, \c F has the signature
//! `expected<UValue, UError> ()`. In both cases, \c UValue must be constructible from \ref value_type or
//! \c void.
template <typename F>
constexpr auto or_else(F&& f) const&&
{
return ::omni::detail::ExpectedOpOrElse<F, expected, expected const&&>::or_else(
std::forward<F>(f), std::move(*this));
}
};
//! Compare the contents of \c lhs and \c rhs for equality.
//!
//! 1. If `lhs.has_value() != rhs.has_value()`, then \c false is returned.
//! 2. If `lhs.has_value() && rhs.has_value()`, then their `.value()`s are compared; if both are \c void, the
//! comparison is always equal.
//! 3. If `!lhs.has_value() && !rhs.has_value()`, then their `.error()`s are compared; if they are both \c void, the
//! comparison is always equal.
//!
//! \par Comparability of Template Parameters
//! When provided with \p lhs and \p rhs, their \ref expected::value_type and \ref expected::error_type parameters must
//! either be equality comparable or \c void. If this is not the case, an error will occur in the immediate context
//! (testing for equality comparison of \c expected types is not SFINAE-safe). It is not legal to compare a non-`void`
//! type to a \c void type.
template <typename TValueLhs, typename TErrorLhs, typename TValueRhs, typename TErrorRhs>
constexpr bool operator==(expected<TValueLhs, TErrorLhs> const& lhs, expected<TValueRhs, TErrorRhs> const& rhs)
{
static_assert(std::is_void<TValueLhs>::value == std::is_void<TValueRhs>::value,
"Can not compare expected of non-void `value_type` with one of void `value_type`");
static_assert(std::is_void<TErrorLhs>::value == std::is_void<TErrorRhs>::value,
"Can not compare expected of non-void `error_type` with one of void `error_type`");
return ::omni::detail::ExpectedComparer<expected<TValueLhs, TErrorLhs>, expected<TValueRhs, TErrorRhs>>::eq(lhs, rhs);
}
//! Compare the contents of \a lhs with the non \c expected type \a rhs.
//!
//! \tparam TValueLhs A value which is comparable to \c TValueRhs. If it is either \c void or a non-comparable type, it
//! is an error in the immediate context (not SFINAE-safe).
template <typename TValueLhs, typename TErrorLhs, typename TValueRhs>
constexpr bool operator==(expected<TValueLhs, TErrorLhs> const& lhs, TValueRhs const& rhs)
{
static_assert(!std::is_void<TValueLhs>::value, "Can not compare void-valued expected with value");
return lhs.has_value() && static_cast<bool>(lhs.value() == rhs);
}
//! Compare the error contents of \a lhs with \a rhs.
//!
//! \returns \c true if `lhs.has_value() && (lhs.error() == rhs.error())`; the second clause is omitted if the error
//! type is \c void.
template <typename TValueLhs, typename TErrorLhs, typename TErrorRhs>
constexpr bool operator==(expected<TValueLhs, TErrorLhs> const& lhs, unexpected<TErrorRhs> const& rhs)
{
static_assert(!std::is_void<TErrorLhs>::value && std::is_void<TErrorRhs>::value,
"Can not compare expected of non-void `error_type` with unexpected<void>");
static_assert(std::is_void<TErrorLhs>::value && !std::is_void<TErrorRhs>::value,
"Can not compare expected of void `error_type` with unexpected of non-void `error_type`");
return ::omni::detail::ExpectedUnexpectedComparer<TErrorLhs, TErrorRhs>::eq(lhs, rhs);
}
} // namespace omni
| 42,846 | C | 49.826809 | 132 | 0.644027 |
omniverse-code/kit/include/omni/String.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief ABI safe string implementation
#pragma once
#include "../carb/Defines.h"
#include "detail/PointerIterator.h"
#include "../carb/cpp/StringView.h"
#include <cstddef>
#include <cstdint>
#include <initializer_list>
#include <istream>
#include <iterator>
#include <limits>
#include <memory>
#include <ostream>
#include <string>
#include <type_traits>
#if CARB_HAS_CPP17
# include <string_view>
#endif
CARB_IGNOREWARNING_MSC_WITH_PUSH(4201) // nonstandard extension used: nameless struct/union.
namespace omni
{
//! A flag type to select the omni::string constructor that allows \c printf style formatting.
struct formatted_t
{
};
//! A flag value to select the omni::string constructor that allows \c printf style formatting.
constexpr formatted_t formatted{};
//! A flag type to select the omni::string constructor that allows \c vprintf style formatting.
struct vformatted_t
{
};
//! A flag value to select the omni::string constructor that allows \c vprintf style formatting.
constexpr vformatted_t vformatted{};
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
/**
* This struct provides implementations of a subset of the functions found in std::char_traits. It is used to provide
* constexpr implementations of the functions because std::char_traits did not become constexpr until C++20. Currently
* only the methods used by omni::string are provided.
*/
struct char_traits
{
/**
* Assigns \p c to \p dest.
*/
static constexpr void assign(char& dest, const char& c) noexcept;
/**
* Assigns \p count copies of \p c to \p dest.
*
* @returns \p dest.
*/
static constexpr char* assign(char* dest, std::size_t count, char c) noexcept;
/**
* Copies \p count characters from \p source to \p dest.
*
* This function performs correctly even if \p dest and \p source overlap.
*/
static constexpr void move(char* dest, const char* source, std::size_t count) noexcept;
/**
* Copies \p count characters from \p source to \p dest.
*
* Behavior of this function is undefined if \p dest and \p source overlap.
*/
static constexpr void copy(char* dest, const char* source, std::size_t count) noexcept;
/**
* Lexicographically compares the first \p count characters of \p s1 and \p s2.
*
* @return Negative value if \p s1 is less than \p s2.
* 0 if \p s1 is equal to \p s2.
* Positive value if \p s1 is greater than \p s2.
*/
static constexpr int compare(const char* s1, const char* s2, std::size_t count) noexcept;
/**
* Computes the length of \p s.
*
* @return The length of \p s.
*/
static constexpr std::size_t length(const char* s) noexcept;
/**
* Searches the first \p count characters of \p s for the character \p ch.
*
* @return A pointer to the first character equal to \p ch, or \c nullptr if no such character exists.
*/
static constexpr const char* find(const char* s, std::size_t count, char ch) noexcept;
};
# if CARB_HAS_CPP17
template <typename T, typename Res = void>
using is_sv_convertible =
std::enable_if_t<std::conjunction<std::is_convertible<const T&, std::string_view>,
std::negation<std::is_convertible<const T&, const char*>>>::value,
Res>;
# endif
} // namespace detail
#endif
// Handle case where Windows.h may have defined 'max'
#pragma push_macro("max")
#undef max
/**
* This class is an ABI safe string implementation. It is meant to be a drop-in replacement for std::string.
*
* This class is not templated for simplicity and @rstref{ABI safety <abi-compatibility>}.
*
* Note: If exceptions are not enabled, any function that would throw will terminate the program instead.
*
* Note: All functions provide a strong exception guarantee. If they throw an exception for any reason, the function
* has no effect.
*/
class CARB_VIZ string
{
public:
/** Char traits type alias. */
#if CARB_HAS_CPP20
using traits_type = std::char_traits<char>;
#else
using traits_type = detail::char_traits;
#endif
/** Char type alias. */
using value_type = char;
/** Size type alias. */
using size_type = std::size_t;
/** Reference type alias. */
using reference = value_type&;
/** Const Reference type alias. */
using const_reference = const value_type&;
/** Pointer type alias. */
using pointer = value_type*;
/** Const Pointer type alias. */
using const_pointer = const value_type*;
/** Difference type alias. */
using difference_type = std::pointer_traits<pointer>::difference_type;
/** Iterator type alias. */
using iterator = detail::PointerIterator<pointer, string>;
/** Const Iterator type alias. */
using const_iterator = detail::PointerIterator<const_pointer, string>;
/** Const Reverse Iterator type alias. */
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
/** Reverse Iterator type alias. */
using reverse_iterator = std::reverse_iterator<iterator>;
/**
* Special value normally used to indicate that an operation failed.
*/
static constexpr size_type npos = std::numeric_limits<size_type>::max();
/**
* Default constructor. Constructs empty string.
*/
string() noexcept;
/**
* Constructs the string with \p n copies of character \p c.
* @param n Number of characters to initialize with.
* @param c The character to initialize with.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*
*/
string(size_type n, value_type c);
/**
* Constructs the string with a substring `[pos, str.size())` of \p str.
*
* @param str Another string to use as source to initialize the string with.
* @param pos Position of the first character to include.
*
* @throws std::out_of_range if \p pos is greater than `str.size()`.
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string(const string& str, size_type pos);
/**
* Constructs the string with a substring `[pos, pos + n)` of \p str. If `n == npos`, or if the
* requested substring lasts past the end of the string, the resulting substring is `[pos, str.size())`.
*
* @param str Another string to use as source to initialize the string with.
* @param pos Position of the first character to include.
* @param n Number of characters to include.
*
* @throws std::out_of_range if \p pos is greater than `str.size()`.
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string(const string& str, size_type pos, size_type n);
/**
* Constructs the string with the first \p n characters of character string pointed to by \p s. \p s can contain
* null characters. The length of the string is \p n. The behavior is undefined if `[s, s + n)` is not
* a valid range.
*
* @param s Pointer to an array of characters to use as source to initialize the string with.
* @param n Number of characters to include.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string(const value_type* s, size_type n);
/**
* Constructs the string with the contents initialized with a copy of the null-terminated character string pointed
* to by \p s . The length of the string is determined by the first null character. The behavior is undefined if
* `[s, s + Traits::length(s))` is not a valid range (for example, if \p s is a null pointer).
*
* @param s Pointer to an array of characters to use as source to initialize the string with.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string(const value_type* s);
/**
* Constructs the string with the contents of the range `[first, last)`.
*
* @param begin Start of the range to copy characters from.
* @param end End of the range to copy characters from.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename InputIterator>
string(InputIterator begin, InputIterator end);
/**
* Copy constructor. Constructs the string with a copy of the contents of \p str.
*
* @param str Another string to use as source to initialize the string with.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string(const string& str);
/**
* Move constructor. Constructs the string with the contents of \p str using move semantics. \p str is left in
* valid, but unspecified state.
*
* @param str Another string to use as source to initialize the string with.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string(string&& str) noexcept;
/**
* Constructs the string with the contents of the initializer list \p ilist.
*
* @param ilist initializer_list to initialize the string with.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string(std::initializer_list<value_type> ilist);
/**
* Constructs the string with the \c printf style format string and additional parameters.
*
* @param fmt A \c printf style format string.
* @param args Additional arguments to the format string.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <class... Args>
string(formatted_t, const char* fmt, Args&&... args);
/**
* Constructs the string with the \c vprintf style format string and additional parameters.
*
* @param fmt A \c printf style format string.
* @param ap A \c va_list as initialized by \c va_start.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string(vformatted_t, const char* fmt, va_list ap);
/**
* Copy constructor. Constructs the string with a copy of the contents of \p str.
*
* @param str Another string to use as source to initialize the string with.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
explicit string(const std::string& str);
/**
* Constructs the string with a substring `[pos, pos + n)` of \p str. If `n == npos`, or if the
* requested substring lasts past the end of the string, the resulting substring is `[pos, str.size())`.
*
* @param str Another string to use as source to initialize the string with.
* @param pos Position of the first character to include.
* @param n Number of characters to include.
*
* @throws std::out_of_range if \p pos is greater than `str.size()`.
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string(const std::string& str, size_type pos, size_type n);
/**
* Copy constructor. Constructs the string with a copy of the contents of \p sv.
*
* @param sv String view to use as source to initialize the string with.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
explicit string(const carb::cpp::string_view& sv);
/**
* Constructs the string with a substring `[pos, pos + n)` of \p sv. If `n == npos`, or if the
* requested substring lasts past the end of the string, the resulting substring is `[pos, sv.size())`.
*
* @param sv String view to use as source to initialize the string with.
* @param pos Position of the first character to include.
* @param n Number of characters to include.
*
* @throws std::out_of_range if \p pos is greater than `sv.size()`.
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string(const carb::cpp::string_view& sv, size_type pos, size_type n);
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and initializes this string with the contents of that
* `std::string_view`. This overload participates in overload resolution only if `std::is_convertible_v<const T&,
* std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` to initialize with.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
explicit string(const T& t);
/**
* Implicitly converts @p t to type `std::string_view` and initializes this string with a substring `[pos, pos + n)`
* of that `string_view`. If `n == npos`, or if the requested substring lasts past the end of the `string_view`,
* the resulting substring is `[pos, sv.size())`. This overload participates in overload resolution only if
* `std::is_convertible_v<const T&, std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` to initialize with.
* @param pos Position of the first character to include.
* @param n Number of characters to include.
*
* @throws std::out_of_range if \p pos is greater than `sv.size()`.
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string(const T& t, size_type pos, size_type n);
#endif
/**
* Cannot be constructed from `nullptr`.
*/
string(std::nullptr_t) = delete;
/**
* Destroys the string, deallocating internal storage if used.
*/
~string() noexcept;
/**
* Replaces the contents with a copy of \p str. If \c *this and str are the same object, this function has no
* effect.
*
* @param str String to be used as the source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator=(const string& str);
/**
* Replaces the contents with those of str using move semantics. str is in a valid but unspecified state afterwards.
*
* @param str String to be used as the source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator=(string&& str) noexcept;
/**
* Replaces the contents with those of null-terminated character string pointed to by \p s.
*
* @param s Pointer to a null-terminated character string to use as source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator=(const value_type* s);
/**
* Replaces the contents with character \p c.
*
* @param c Character to use as source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator=(value_type c);
/**
* Replaces the contents with those of the initializer list \p ilist.
*
* @param ilist initializer list to use as source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator=(std::initializer_list<value_type> ilist);
/**
* Replaces the contents with a copy of \p str.
*
* @param str String to be used as the source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator=(const std::string& str);
/**
* Replaces the contents with a copy of \p sv.
*
* @param sv String view to be used as the source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator=(const carb::cpp::string_view& sv);
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and replaces the contents of this string with the contents of
* that `std::string_view`. This overload participates in overload resolution only if `std::is_convertible_v<const
* T&, std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` to initialize with.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& operator=(const T& t);
#endif
/**
* Cannot be assigned from `nullptr`.
*/
string& operator=(std::nullptr_t) = delete;
/**
* Replaces the contents with \p n copies of character \p c.
*
* @param n Number of characters to initialize with.
* @param c Character to use as source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(size_type n, value_type c);
/**
* Replaces the contents with a copy of \p str.
*
* @param str String to be used as the source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(const string& str);
/**
* Replaces the string with a substring `[pos, pos + n)` of \p str. If `n == npos`, or if the
* requested substring lasts past the end of the string, the resulting substring is `[pos, str.size())`.
*
* @param str Another string to use as source to initialize the string with.
* @param pos Position of the first character to include.
* @param n Number of characters to include.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(const string& str, size_type pos, size_type n = npos);
/**
* Replaces the contents with those of str using move semantics. \p str is in a valid but unspecified state
* afterwards.
*
* @param str String to be used as the source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(string&& str);
/**
* Replace the string with the first \p n characters of character string pointed to by \p s. \p s can contain
* null characters. The length of the string is \p n. The behavior is undefined if `[s, s + n)` is not
* a valid range.
*
* @param s Pointer to an array of characters to use as source to initialize the string with.
* @param n Number of characters to include.
* @return \c *this.
*
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(const value_type* s, size_type n);
/**
* Replaces the contents with those of null-terminated character string pointed to by \p s.
*
* @param s Pointer to a null-terminated character string to use as source to initialize the string with.
* @return \c *this.
*
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(const value_type* s);
/**
* Replace the string with the contents of the range `[first, last)`.
*
* @param first Start of the range to copy characters from.
* @param last End of the range to copy characters from.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <class InputIterator>
string& assign(InputIterator first, InputIterator last);
/**
* Replaces the contents with those of the initializer list \p ilist.
*
* @param ilist initializer list to use as source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(std::initializer_list<value_type> ilist);
/**
* Replaces the contents with a copy of \p str.
*
* @param str String to be used as the source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(const std::string& str);
/**
* Replaces the string with a substring `[pos, pos + n)` of \p str. If `n == npos`, or if the
* requested substring lasts past the end of the string, the resulting substring is `[pos, str.size())`.
*
* @param str Another string to use as source to initialize the string with.
* @param pos Position of the first character to include.
* @param n Number of characters to include.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(const std::string& str, size_type pos, size_type n = npos);
/**
* Replaces the contents with a copy of \p sv.
*
* @param sv String view to be used as the source to initialize the string with.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(const carb::cpp::string_view& sv);
/**
* Replaces the string with a substring `[pos, pos + n)` of \p sv. If `n == npos`, or if the
* requested substring lasts past the end of the string, the resulting substring is `[pos, sv.size())`.
*
* @param sv String view to use as source to initialize the string with.
* @param pos Position of the first character to include.
* @param n Number of characters to include.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign(const carb::cpp::string_view& sv, size_type pos, size_type n = npos);
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and replaces the contents of this string with a substring
* `[pos, pos + n)` of that `string_view`. This overload participates in overload resolution only if
* `std::is_convertible_v<const T&, std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` to initialize with.
*
* @throws std::out_of_range if \p pos is greater than `sv.size()`.
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& assign(const T& t);
/**
* Implicitly converts @p t to type `std::string_view` and replaces the contents of this string with a substring
* `[pos, pos + n)` of that `string_view`. If `n == npos`, or if the requested substring lasts past the end of
* the `string_view`, the resulting substring is `[pos, sv.size())`. This overload participates in overload
* resolution only if `std::is_convertible_v<const T&, std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` to initialize with.
* @param pos Position of the first character to include.
* @param n Number of characters to include.
*
* @throws std::out_of_range if \p pos is greater than `sv.size()`.
* @throws std::length_error if the string would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& assign(const T& t, size_type pos, size_type n = npos);
#endif
/**
* Replaces the contents with those of the \c printf style format string and arguments.
*
* @param fmt \c printf style format string to initialize the string with. Must not overlap with \c *this.
* @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign_printf(const char* fmt, ...) CARB_PRINTF_FUNCTION(2, 3);
/**
* Replaces the contents with those of the \c vprintf style format string and arguments.
*
* @param fmt \c vprintf style format string to initialize the string with. Must not overlap with \c *this.
* @param ap \c va_list as initialized with \c va_start. Arguments must not overlap with \c *this.
* @return \c *this.
*
* @throws std::length_error if the string would be larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& assign_vprintf(const char* fmt, va_list ap);
/**
* Returns a reference to the character at specified location \p pos. Bounds checking is performed.
*
* @param pos Position of the character to return.
* @return Reference to the character at pos.
*
* @throws std::out_of_range if \p pos is greater than size().
*/
constexpr reference at(size_type pos);
/**
* Returns a reference to the character at specified location \p pos. Bounds checking is performed.
*
* @param pos Position of the character to return.
* @return Reference to the character at pos.
*
* @throws std::out_of_range if \p pos is greater than size().
*/
constexpr const_reference at(size_type pos) const;
/**
* Returns a reference to the character at specified location \p pos. No bounds checking is performed.
*
* @param pos Position of the character to return.
* @return Reference to the character at pos.
*/
constexpr reference operator[](size_type pos);
/**
* Returns a reference to the character at specified location \p pos. No bounds checking is performed.
*
* @param pos Position of the character to return.
* @return Reference to the character at pos.
*/
constexpr const_reference operator[](size_type pos) const;
/**
* Returns a reference to the first character. Behavior is undefined if this string is empty.
*
* @return Reference to the first character.
*/
constexpr reference front();
/**
* Returns a reference to the first character. Behavior is undefined if this string is empty.
*
* @return Reference to the first character.
*/
constexpr const_reference front() const;
/**
* Returns a reference to the last character. Behavior is undefined if this string is empty.
*
* @return Reference to the last character.
*/
constexpr reference back();
/**
* Returns a reference to the last character. Behavior is undefined if this string is empty.
*
* @return Reference to the last character.
*/
constexpr const_reference back() const;
/**
* Returns a pointer to the character array of the string. The returned array is null-terminated.
*
* @return Pointer to the character array of the string.
*/
constexpr const value_type* data() const noexcept;
/**
* Returns a pointer to the character array of the string. The returned array is null-terminated.
*
* @return Pointer to the character array of the string.
*/
constexpr value_type* data() noexcept;
/**
* Returns a pointer to the character array of the string. The returned array is null-terminated.
*
* @return Pointer to the character array of the string.
*/
constexpr const value_type* c_str() const noexcept;
/**
* Returns a `carb::cpp::string_view` constructed as if by `carb::cpp::string_view(data(), size())`.
*
* @return A `carb::cpp::string_view` representing the string.
*/
constexpr operator carb::cpp::string_view() const noexcept;
#if CARB_HAS_CPP17
/**
* Returns a `std::string_view` constructed as if by `std::string_view(data(), size())`.
*
* @return A `std::string_view` representing the string.
*/
constexpr operator std::string_view() const noexcept;
#endif
/**
* Returns an iterator to the first character in the string.
*
* @return iterator to the first character in the string.
*/
constexpr iterator begin() noexcept;
/**
* Returns a constant iterator to the first character in the string.
*
* @return iterator to the first character in the string.
*/
constexpr const_iterator begin() const noexcept;
/**
* Returns a constant iterator to the first character in the string.
*
* @return iterator to the first character in the string.
*/
constexpr const_iterator cbegin() const noexcept;
/**
* Returns an iterator to the character following the last character of the string.
*
* @return iterator to the character following the last character of the string.
*/
constexpr iterator end() noexcept;
/**
* Returns a constant iterator to the character following the last character of the string.
*
* @return iterator to the character following the last character of the string.
*/
constexpr const_iterator end() const noexcept;
/**
* Returns a constant iterator to the character following the last character of the string.
*
* @return iterator to the character following the last character of the string.
*/
constexpr const_iterator cend() const noexcept;
/**
* Returns a reverse iterator to the first character in the reversed string. This character is the last character in
* the non-reversed string.
*
* @return reverse iterator to the first character in the reversed string.
*/
reverse_iterator rbegin() noexcept;
/**
* Returns a constant reverse iterator to the first character in the reversed string. This character is the last
* character in the non-reversed string.
*
* @return reverse iterator to the first character in the reversed string.
*/
const_reverse_iterator rbegin() const noexcept;
/**
* Returns a constant reverse iterator to the first character in the reversed string. This character is the last
* character in the non-reversed string.
*
* @return reverse iterator to the first character in the reversed string.
*/
const_reverse_iterator crbegin() const noexcept;
/**
* Returns a reverse iterator to the character following the last character in the reversed string. This character
* corresponds to character before the first character in the non-reversed string.
*
* @return reverse iterator to the character following the last character in the reversed string.
*/
reverse_iterator rend() noexcept;
/**
* Returns a constant reverse iterator to the character following the last character in the reversed string. This
* character corresponds to character before the first character in the non-reversed string.
*
* @return reverse iterator to the character following the last character in the reversed string.
*/
const_reverse_iterator rend() const noexcept;
/**
* Returns a constant reverse iterator to the character following the last character in the reversed string. This
* character corresponds to character before the first character in the non-reversed string.
*
* @return reverse iterator to the character following the last character in the reversed string.
*/
const_reverse_iterator crend() const noexcept;
/**
* Checks if the string is empty.
*
* @return true if the string is empty, false otherwise.
*/
constexpr bool empty() const noexcept;
/**
* Returns the number of characters in the string.
*
* @return the number of characters in the string.
*/
constexpr size_type size() const noexcept;
/**
* Returns the number of characters in the string.
*
* @return the number of characters in the string.
*/
constexpr size_type length() const noexcept;
/**
* Returns the maximum number of characters that can be in the string.
*
* @return the maximum number of characters that can be in the string.
*/
constexpr size_type max_size() const noexcept;
/**
* Attempt to change the capacity of the string.
*
* If \p new_cap is greater than the current capacity(), the string will allocate a new buffer equal to or
* larger than \p new_cap.
*
* If \p new_cap is less than the current capacity(), the string may shrink the buffer.
*
* If \p new_cap is less that the current size(), the string will shrink the buffer to fit the current
* size() as if by calling shrink_to_fit().
*
* If reallocation takes place, all pointers, references, and iterators are invalidated.
*
* @return none.
*
* @throws std::length_error if \p new_cap is larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
void reserve(size_type new_cap);
/**
* Reduce the capacity of the string as if by calling shrink_to_fit().
*
* If reallocation takes place, all pointers, references, and iterators are invalidated.
*
* @return none.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
void reserve(); // deprecated in C++20
/**
* Returns the number of characters that can fit in the current storage array.
*
* @return the number of characters that can fit in the current storage array.
*/
constexpr size_type capacity() const noexcept;
/**
* Reduce capacity() to size().
*
* If reallocation takes place, all pointers, references, and iterators are invalidated.
*
* @return none.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
void shrink_to_fit();
/**
* Clears the contents of the string. capacity() is not changed by this function.
*
* All pointers, references, and iterators are invalidated.
*
* @return none.
*/
constexpr void clear() noexcept;
/**
* Inserts \p n copies of character \p c at position \p pos.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos Position to insert characters.
* @param n Number of characters to insert.
* @param c Character to insert.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::length_error if `n + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert(size_type pos, size_type n, value_type c);
/**
* Inserts the string pointed to by \p s at position \p pos.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos Position to insert characters.
* @param s String to insert.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if `Traits::length(s) + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert(size_type pos, const value_type* s);
/**
* Inserts the first \p n characters of the string pointed to by \p s at position \p pos. The range can contain null
* characters.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos Position to insert characters.
* @param s String to insert.
* @param n Number of characters to insert.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if `n + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert(size_type pos, const value_type* s, size_type n);
/**
* Inserts the string \p str at position \p pos.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos Position to insert characters.
* @param str String to insert.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::length_error if `str.size() + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert(size_type pos, const string& str);
/**
* Inserts the substring `str.substr(pos2, n)` at position \p pos1.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos1 Position to insert characters.
* @param str String to insert.
* @param pos2 Position in \p str to copy characters from.
* @param n Number of characters to insert.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`.
* @throws std::length_error if `n + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert(size_type pos1, const string& str, size_type pos2, size_type n = npos);
/**
* Inserts the character \p c before the character pointed to by \p p.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param p Iterator to the position the character should be inserted before.
* @param c Character to insert.
*
* @return Iterator to the inserted character, or \p p if no character was inserted.
*
* @throws std::out_of_range if \p p is not in the range [begin(), end()].
* @throws std::length_error if `1 + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
iterator insert(const_iterator p, value_type c);
/**
* Inserts \p n copies of the character \p c before the character pointed to by \p p.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param p Iterator to the position the character should be inserted before.
* @param n Number of characters to inserts.
* @param c Character to insert.
*
* @return Iterator to the first inserted character, or \p p if no character was inserted.
*
* @throws std::out_of_range if \p p is not in the range [begin(), end()].
* @throws std::length_error if `n + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
iterator insert(const_iterator p, size_type n, value_type c);
/**
* Inserts characters from the range `[first, last)` before the character pointed to by \p p.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param p Iterator to the position the character should be inserted before.
* @param first Iterator to the first character to insert.
* @param last Iterator to the first character not to be inserted.
*
* @return Iterator to the first inserted character, or \p p if no character was inserted.
*
* @throws std::out_of_range if \p p is not in the range [begin(), end()].
* @throws std::length_error if `std::distance(first, last) + size()` would be larger than
* max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <class InputIterator>
iterator insert(const_iterator p, InputIterator first, InputIterator last);
/**
* Inserts the characters in \p ilist before the character pointed to by \p p.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param p Iterator to the position the character should be inserted before.
* @param ilist Initializer list of characters to insert.
*
* @return Iterator to the first inserted character, or \p p if no character was inserted.
*
* @throws std::out_of_range if \p p is not in the range [begin(), end()].
* @throws std::length_error if `ilist.size() + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
iterator insert(const_iterator p, std::initializer_list<value_type> ilist);
/**
* Inserts the string \p str at position \p pos.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos Position to insert characters.
* @param str String to insert.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::length_error if `str.size() + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert(size_type pos, const std::string& str);
/**
* Inserts the substring `str.substr(pos2, n)` at position \p pos1.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos1 Position to insert characters.
* @param str String to insert.
* @param pos2 Position in \p str to copy characters from.
* @param n Number of characters to insert.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`.
* @throws std::length_error if `n + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert(size_type pos1, const std::string& str, size_type pos2, size_type n = npos);
/**
* Inserts the string_view \p sv at position \p pos.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos Position to insert characters.
* @param sv String view to insert.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::length_error if `str.size() + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert(size_type pos, const carb::cpp::string_view& sv);
/**
* Inserts the substring `sv.substr(pos2, n)` at position \p pos1.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos1 Position to insert characters.
* @param sv String view to insert.
* @param pos2 Position in \p str to copy characters from.
* @param n Number of characters to insert.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`.
* @throws std::length_error if `n + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert(size_type pos1, const carb::cpp::string_view& sv, size_type pos2, size_type n = npos);
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and inserts that `string_view` at position \p pos. This
* overload participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos Position to insert characters.
* @param t Object that can be converted to `std::string_view` to initialize with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::length_error if `str.size() + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& insert(size_type pos, const T& t);
/**
* Implicitly converts @p t to type `std::string_view` and inserts inserts the substring `sv.substr(pos2, n)` at
* position \p pos1. This overload participates in overload resolution only if `std::is_convertible_v<const T&,
* std::string_view>` is true.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param pos1 Position to insert characters.
* @param t Object that can be converted to `std::string_view` to initialize with.
* @param pos2 Position in \p str to copy characters from.
* @param n Number of characters to insert.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`.
* @throws std::length_error if `n + size()` would be larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& insert(size_type pos1, const T& t, size_type pos2, size_type n = npos);
#endif
/**
* Inserts the \c printf style format string and arguments before the \p pos position.
*
* @param pos Position to insert characters.
* @param fmt \c printf style format string to initialize the string with. Must not overlap with \c *this.
* @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this.
* @return \c *this.
*
* @throws std::out_of_range if \p pos is not in the range [0, size()].
* @throws std::length_error if the resulting string would be larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert_printf(size_type pos, const char* fmt, ...) CARB_PRINTF_FUNCTION(3, 4);
/**
* Inserts the \c vprintf style format string and arguments before the \p pos position.
*
* @param pos Position to insert characters.
* @param fmt \c vprintf style format string to initialize the string with. Must not overlap with \c *this.
* @param ap \c va_list as initialized by \c va_start. Arguments must not overlap with \c *this.
* @return \c *this.
*
* @throws std::out_of_range if \p pos is not in the range [0, size()].
* @throws std::length_error if the resulting string would be larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& insert_vprintf(size_type pos, const char* fmt, va_list ap);
/**
* Inserts the \c printf style format string and arguments before the character pointed to by \p p.
*
* @param p Iterator to the position the string should be inserted before.
* @param fmt \c printf style format string to initialize the string with. Must not overlap with \c *this.
* @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this.
* @return Iterator to the first inserted character, or \p p if nothing was inserted.
*
* @throws std::out_of_range if \p p is not in the range [begin(), end()].
* @throws std::length_error if the resulting string would be larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
iterator insert_printf(const_iterator p, const char* fmt, ...) CARB_PRINTF_FUNCTION(3, 4);
/**
* Inserts the \c vprintf style format string and arguments before the character pointed to by \p p.
*
* @param p Iterator to the position the string should be inserted before.
* @param fmt \c vprintf style format string to initialize the string with. Must not overlap with \c *this.
* @param ap \c va_list as initialized by \c va_start. Arguments must not overlap with \c *this.
* @return Iterator to the first inserted character, or \p p if nothing was inserted.
*
* @throws std::out_of_range if \p p is not in the range [begin(), end()].
* @throws std::length_error if the resulting string would be larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
iterator insert_vprintf(const_iterator p, const char* fmt, va_list ap);
/**
* Erases \p n characters from the string starting at \p pos. If \p n is \p npos or `pos + n > size()`,
* characters are erased to the end of the string.
*
* Pointers, references, and iterators may be invalidated.
*
* @param pos Position to begin erasing.
* @param n Number of characters to erase.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
*/
constexpr string& erase(size_type pos = 0, size_type n = npos);
/**
* Erases the character pointed to by \p pos.
*
* Pointers, references, and iterators may be invalidated.
*
* @param pos Position to erase character at.
*
* @return iterator pointing to the character immediately following the character erased, or end() if no such
* character exists.
*/
constexpr iterator erase(const_iterator pos);
/**
* Erases characters in the range `[first, last)`.
*
* Pointers, references, and iterators may be invalidated.
*
* @param first Position to begin erasing at.
* @param last Position to stop erasing at.
*
* @return iterator pointing to the character last pointed to before the erase, or end() if no such character
* exists.
*
* @throws std::out_of_range if the range `[first, last)` is invalid (not in the range [begin(), end()],
* or `first > last`.
*/
constexpr iterator erase(const_iterator first, const_iterator last);
/**
* Appends the character \p c to the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @return none.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
void push_back(value_type c);
/**
* Removes the last character from the string.
*
* Pointers, references, and iterators may be invalidated.
*
* @return none.
*
* @throws std::runtime_error if the string is empty().
*/
constexpr void pop_back();
/**
* Appends \p n copies of character \p c to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param n Number of characters to append.
* @param c Character to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append(size_type n, value_type c);
/**
* Appends \p str to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param str The string to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append(const string& str);
/**
* Appends the substring `str.substr(pos2, n)` to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param str The string to append.
* @param pos Position of the first character to append.
* @param n Number of characters to append.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than `str.size()`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append(const string& str, size_type pos, size_type n = npos);
/**
* Appends \p n character of the string \p s to the end of the string. The range can contain nulls.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param s String to append characters from.
* @param n Number of characters to append.
*
* @return \c *this.
*
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append(const value_type* s, size_type n);
/**
* Appends the null-terminated string \p s to the end of the string. Behavior is undefined if \p s is not a valid
* string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param s String to append characters from.
*
* @return \c *this.
*
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append(const value_type* s);
/**
* Appends characters in the range `[first, last)` to the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param first First character in the range to append.
* @param last End of the range to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <class InputIterator>
string& append(InputIterator first, InputIterator last);
/**
* Appends characters in \p ilist to the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param ilist Initializer list of characters to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append(std::initializer_list<value_type> ilist);
/**
* Appends \p str to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param str The string to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append(const std::string& str);
/**
* Appends the substring `str.substr(pos2, n)` to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param str The string to append.
* @param pos Position of the first character to append.
* @param n Number of characters to append.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than `str.size()`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append(const std::string& str, size_type pos, size_type n = npos);
/**
* Appends \p sv to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param sv The string view to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append(const carb::cpp::string_view& sv);
/**
* Appends the substring `sv.substr(pos2, n)` to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param sv The string view to append.
* @param pos Position of the first character to append.
* @param n Number of characters to append.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than `str.size()`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append(const carb::cpp::string_view& sv, size_type pos, size_type n = npos);
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and appends it to the end of the string. This overload
* participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param t Object that can be converted to `std::string_view` to initialize with.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& append(const T& t);
/**
* Implicitly converts @p t to type `std::string_view` and appends the substring `sv.substr(pos2, n)` to the end of
* the string. This overload participates in overload resolution only if `std::is_convertible_v<const T&,
* std::string_view>` is true.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param t Object that can be converted to `std::string_view` to initialize with.
* @param pos Position of the first character to append.
* @param n Number of characters to append.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than `str.size()`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& append(const T& t, size_type pos, size_type n = npos);
#endif
/**
* Appends the \c printf style format string and arguments to the string.
*
* @param fmt \c printf style format string to initialize the string with. Must not overlap with \c *this.
* @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this.
* @return \c *this.
*
* @throws std::length_error if the resulting string would be larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append_printf(const char* fmt, ...) CARB_PRINTF_FUNCTION(2, 3);
/**
* Appends the \c printf style format string and arguments to the string.
*
* @param fmt \c printf style format string to initialize the string with. Must not overlap with \c *this.
* @param ap \c va_list as initialized by \c va_start. Arguments must not overlap with \c *this.
* @return \c *this.
*
* @throws std::length_error if the resulting string would be larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& append_vprintf(const char* fmt, va_list ap);
/**
* Appends \p str to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param str The string to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator+=(const string& str);
/**
* Appends the character \p c to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param c Character to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator+=(value_type c);
/**
* Appends the null-terminated string \p s to the end of the string. Behavior is undefined if \p s is not a valid
* string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param s String to append characters from.
*
* @return \c *this.
*
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator+=(const value_type* s);
/**
* Appends characters in \p ilist to the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param ilist Initializer list of characters to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator+=(std::initializer_list<value_type> ilist);
/**
* Appends \p str to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param str The string to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator+=(const std::string& str);
/**
* Appends \p sv to the end of the string.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param sv The string view to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& operator+=(const carb::cpp::string_view& sv);
#if CARB_HAS_CPP17
/**
* Implicitly converts @c t to type `std::string_view` and appends it to the end of the string. This overload
* participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param t Object that can be converted to `std::string_view` to append.
*
* @return \c *this.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& operator+=(const T& t);
#endif
/**
* Compares \p str to this string.
*
* \code
* Comparison is performed as follows:
* If Traits::compare(this, str, min(size(), str.size())) < 0, a negative value is returned
* If Traits::compare(this, str, min(size(), str.size())) == 0, then:
* If size() < str.size(), a negative value is returned
* If size() = str.size(), zero is returned
* If size() > str.size(), a positive value is returned
* If Traits::compare(this, str, min(size(), str.size())) > 0, a positive value is returned
* \endcode
*
* @param str String to compare to.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*/
constexpr int compare(const string& str) const noexcept;
/**
* Compares \p str to the substring `substr(pos1, n1)`.
*
* @see compare() for details on how the comparison is performed.
*
* @param pos1 Position to start this substring.
* @param n1 Number of characters in this substring.
* @param str String to compare to.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::out_of_range if \p pos1 is greater than size().
*/
constexpr int compare(size_type pos1, size_type n1, const string& str) const;
/**
* Compares `str.substr(pos2, n2)` to the substring `substr(pos1, n1)`.
*
* @see compare() for details on how the comparison is performed.
*
* @param pos1 Position to start this substring.
* @param n1 Number of characters in this substring.
* @param str String to compare to.
* @param pos2 Position to start other substring.
* @param n2 Number of characters in other substring.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`.
*/
constexpr int compare(size_type pos1, size_type n1, const string& str, size_type pos2, size_type n2 = npos) const;
/**
* Compares the null-terminated string \p s to this string.
*
* @see compare() for details on how the comparison is performed.
*
* @param s String to compare to.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr int compare(const value_type* s) const;
/**
* Compares the null-terminated string \p s to the substring `substr(pos1, n1)`.
*
* @see compare() for details on how the comparison is performed.
*
* @param pos1 Position to start this substring.
* @param n1 Number of characters in this substring.
* @param s String to compare to.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::out_of_range if \p pos1 is greater than size().
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr int compare(size_type pos1, size_type n1, const value_type* s) const;
/**
* Compares the first \p n2 characters of string string \p s to the substring `substr(pos1, n1)`.
*
* @see compare() for details on how the comparison is performed.
*
* @param pos1 Position to start this substring.
* @param n1 Number of characters in this substring.
* @param s String to compare to.
* @param n2 Number of characters of \p s to compare.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::out_of_range if \p pos1 is greater than size().
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr int compare(size_type pos1, size_type n1, const value_type* s, size_type n2) const;
/**
* Compares \p str to this string.
*
* @see compare() for details on how the comparison is performed.
*
* @param str String to compare to.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*/
CARB_CPP20_CONSTEXPR int compare(const std::string& str) const noexcept;
/**
* Compares \p str to the substring `substr(pos1, n1)`.
*
* @see compare() for details on how the comparison is performed.
*
* @param pos1 Position to start this substring.
* @param n1 Number of characters in this substring.
* @param str String to compare to.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::out_of_range if \p pos1 is greater than size().
*/
CARB_CPP20_CONSTEXPR int compare(size_type pos1, size_type n1, const std::string& str) const;
/**
* Compares `str.substr(pos2, n2)` to the substring `substr(pos1, n1)`.
*
* @see compare() for details on how the comparison is performed.
*
* @param pos1 Position to start this substring.
* @param n1 Number of characters in this substring.
* @param str String to compare to.
* @param pos2 Position to start other substring.
* @param n2 Number of characters in other substring.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`.
*/
CARB_CPP20_CONSTEXPR int compare(
size_type pos1, size_type n1, const std::string& str, size_type pos2, size_type n2 = npos) const;
/**
* Compares \p sv to this string.
*
* @see compare() for details on how the comparison is performed.
*
* @param sv String view to compare to.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*/
constexpr int compare(const carb::cpp::string_view& sv) const noexcept;
/**
* Compares \p sv to the substring `substr(pos1, n1)`.
*
* @see compare() for details on how the comparison is performed.
*
* @param pos1 Position to start this substring.
* @param n1 Number of characters in this substring.
* @param sv String view to compare to.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::out_of_range if \p pos1 is greater than size().
*/
constexpr int compare(size_type pos1, size_type n1, const carb::cpp::string_view& sv) const;
/**
* Compares `sv.substr(pos2, n2)` to the substring `substr(pos1, n1)`.
*
* @see compare() for details on how the comparison is performed.
*
* @param pos1 Position to start this substring.
* @param n1 Number of characters in this substring.
* @param sv String view to compare to.
* @param pos2 Position to start other substring.
* @param n2 Number of characters in other substring.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`.
*/
constexpr int compare(
size_type pos1, size_type n1, const carb::cpp::string_view& sv, size_type pos2, size_type n2 = npos) const;
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and compares it to the string. This overload
* participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true.
*
* @see compare() for details on how the comparison is performed.
*
* @param t Object that can be converted to `std::string_view` to compare to.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
constexpr int compare(const T& t) const noexcept;
/**
* Implicitly converts @p t to type `std::string_view` and compares it to the substring `substr(pos1, n1)`. This
* overload participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true.
*
* @see compare() for details on how the comparison is performed.
*
* @param pos1 Position to start this substring.
* @param n1 Number of characters in this substring.
* @param t Object that can be converted to `std::string_view` to compare to.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::out_of_range if \p pos1 is greater than size().
*/
template <typename T, typename = detail::is_sv_convertible<T>>
constexpr int compare(size_type pos1, size_type n1, const T& t) const;
/**
* Implicitly converts @p t to type `std::string_view` and compares `sv.substr(pos2, n2)` to the substring
* `substr(pos1, n1)`. This overload participates in overload resolution only if `std::is_convertible_v<const T&,
* std::string_view>` is true.
*
* @see compare() for details on how the comparison is performed.
*
* @param pos1 Position to start this substring.
* @param n1 Number of characters in this substring.
* @param t Object that can be converted to `std::string_view` to compare to.
* @param pos2 Position to start other substring.
* @param n2 Number of characters in other substring.
*
* @return A negative value if \c *this appears before the other string in lexicographical order,
* zero if \c *this and the other string compare equivalent,
* or a positive value if \c *this appears after the other string in lexicographical order.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
constexpr int compare(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2 = npos) const;
#endif
/**
* Checks if the string begins with the character \p c.
*
* @param c Character to check.
*
* @return true if the string starts with \p c, false otherwise.
*/
constexpr bool starts_with(value_type c) const noexcept;
/**
* Checks if the string begins with the string \p s.
*
* @param s String to check.
*
* @return true if the string starts with \p s, false otherwise.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr bool starts_with(const_pointer s) const;
/**
* Checks if the string begins with the string view \p sv.
*
* @param sv String view to check.
*
* @return true if the string starts with \p sv, false otherwise.
*/
constexpr bool starts_with(carb::cpp::string_view sv) const noexcept;
#if CARB_HAS_CPP17
/**
* Checks if the string begins with the string view \p sv.
*
* @param sv String view to check.
*
* @return true if the string starts with \p sv, false otherwise.
*/
constexpr bool starts_with(std::string_view sv) const noexcept;
#endif
/**
* Checks if the string ends with the character \p c.
*
* @param c Character to check.
*
* @return true if the string ends with \p c, false otherwise.
*/
constexpr bool ends_with(value_type c) const noexcept;
/**
* Checks if the string ends with the string \p s.
*
* @param s String to check.
*
* @return true if the string ends with \p s, false otherwise.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr bool ends_with(const_pointer s) const;
/**
* Checks if the string ends with the string view \p sv.
*
* @param sv String view to check.
*
* @return true if the string ends with \p sv, false otherwise.
*/
constexpr bool ends_with(carb::cpp::string_view sv) const noexcept;
#if CARB_HAS_CPP17
/**
* Checks if the string ends with the string view \p sv.
*
* @param sv String view to check.
*
* @return true if the string ends with \p sv, false otherwise.
*/
constexpr bool ends_with(std::string_view sv) const noexcept;
#endif
/**
* Checks if the string contains the character \p c.
*
* @param c Character to check.
*
* @return true if the string contains \p c, false otherwise.
*/
constexpr bool contains(value_type c) const noexcept;
/**
* Checks if the string contains the string \p s.
*
* @param s String to check.
*
* @return true if the string contains \p s, false otherwise.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr bool contains(const_pointer s) const;
/**
* Checks if the string contains the string view \p sv.
*
* @param sv String view to check.
*
* @return true if the string contains \p sv, false otherwise.
*/
constexpr bool contains(carb::cpp::string_view sv) const noexcept;
#if CARB_HAS_CPP17
/**
* Checks if the string contains the string view \p sv.
*
* @param sv String view to check.
*
* @return true if the string contains \p sv, false otherwise.
*/
constexpr bool contains(std::string_view sv) const noexcept;
#endif
/**
* Replaces the portion of this string `[pos, pos + n1)` with \p str. If `n == npos`, or `pos + n` is greater than
* size(), the substring to the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos1 Position to start replacement.
* @param n1 Number of characters to replace.
* @param str String to replace characters with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size().
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(size_type pos1, size_type n1, const string& str);
/**
* Replaces the portion of this string `[pos, pos + n1)` with the substring `str.substr(pos2, n2)`. If
* `n == npos`, or `pos + n` is greater than size(), the substring to the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos1 Position to start replacement.
* @param n1 Number of characters to replace.
* @param str String to replace characters with.
* @param pos2 Position of substring to replace characters with.
* @param n2 Number of characters in the substring to replace with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(size_type pos1, size_type n1, const string& str, size_type pos2, size_type n2 = npos);
/**
* Replaces the portion of this string `[i1, i2)` with `[j1, j2)`.
*
* All pointers, references, and iterators may be invalidated.
*
* @param i1 Position to start replacement.
* @param i2 Position to stop replacement.
* @param j1 Start position of replacement characters.
* @param j2 End position of replacement characters.
*
* @return \c *this.
*
* @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or
* `i1 > i2`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <class InputIterator>
string& replace(const_iterator i1, const_iterator i2, InputIterator j1, InputIterator j2);
/**
* Replaces the portion of this string `[pos, pos + n1)` with \p n2 characters from string \p s. The character
* sequence can contain null characters. If `n == npos`, or `pos + n` is greater than size(), the substring to
* the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos Position to start replacement.
* @param n1 Number of characters to replace.
* @param s String to replace characters with.
* @param n2 The number of replacement characters.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(size_type pos, size_type n1, const value_type* s, size_type n2);
/**
* Replaces the portion of this string `[pos, pos + n1)` with the null-terminated string \p s. If `n == npos`, or
* `pos + n` is greater than size(), the substring to the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos Position to start replacement.
* @param n1 Number of characters to replace.
* @param s String to replace characters with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(size_type pos, size_type n1, const value_type* s);
/**
* Replaces the portion of this string `[pos, pos + n1)` with \p n2 copies of character \p c. If `n == npos`, or
* `pos + n` is greater than size(), the substring to the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos Position to start replacement.
* @param n1 Number of characters to replace.
* @param n2 Number of characters to replace with.
* @param c Character to replace with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(size_type pos, size_type n1, size_type n2, value_type c);
/**
* Replaces the portion of this string `[pos, pos + n1)` with \p str. If `n == npos`, or `pos + n` is greater than
* size(), the substring to the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos1 Position to start replacement.
* @param n1 Number of characters to replace.
* @param str String to replace characters with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size().
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(size_type pos1, size_type n1, const std::string& str);
/**
* Replaces the portion of this string `[pos, pos + n1)` with the substring `str.substr(pos2, n2)`. If
* `n == npos`, or `pos + n` is greater than size(), the substring to the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos1 Position to start replacement.
* @param n1 Number of characters to replace.
* @param str String to replace characters with.
* @param pos2 Position of substring to replace characters with.
* @param n2 Number of characters in the substring to replace with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(size_type pos1, size_type n1, const std::string& str, size_type pos2, size_type n2 = npos);
/**
* Replaces the portion of this string `[pos, pos + n1)` with \c sv. If `n == npos`, or `pos + n` is greater than
* size(), the substring to the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos1 Position to start replacement.
* @param n1 Number of characters to replace.
* @param sv String view to replace characters with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size().
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(size_type pos1, size_type n1, const carb::cpp::string_view& sv);
/**
* Replaces the portion of this string `[pos, pos + n1)` with the substring `sv.substr(pos2, n2)`. If
* `n == npos`, or `pos + n` is greater than size(), the substring to the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos1 Position to start replacement.
* @param n1 Number of characters to replace.
* @param sv String view to replace characters with.
* @param pos2 Position of substring to replace characters with.
* @param n2 Number of characters in the substring to replace with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(size_type pos1, size_type n1, const carb::cpp::string_view& sv, size_type pos2, size_type n2 = npos);
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and replaces the portion of this string `[pos, pos + n1)`
* with \p sv. If `n == npos`, or `pos + n` is greater than size(), the substring to the end of the string is
* replaced. This overload participates in overload resolution only if `std::is_convertible_v<const T&,
* std::string_view>` is true.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos1 Position to start replacement.
* @param n1 Number of characters to replace.
* @param t Object that can be converted to `std::string_view` to replace characters with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size().
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& replace(size_type pos1, size_type n1, const T& t);
/**
* Implicitly converts @p t to type `std::string_view` and replaces the portion of this string `[pos, pos + n1)`
* with the substring `sv.substr(pos2, n2)`. If `n == npos`, or `pos + n is greater than size(), the substring to
* the end of the string is replaced. This overload participates in overload resolution only if
* `std::is_convertible_v<const T&, std::string_view>` is true.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos1 Position to start replacement.
* @param n1 Number of characters to replace.
* @param t Object that can be converted to `std::string_view` to replace characters with.
* @param pos2 Position of substring to replace characters with.
* @param n2 Number of characters in the substring to replace with.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& replace(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2);
#endif
/**
* Replaces the portion of this string `[i1, i2)` with \p str.
*
* All pointers, references, and iterators may be invalidated.
*
* @param i1 Position to start replacement.
* @param i2 Position to stop replacement.
* @param str String to replace characters with.
*
* @return \c *this.
*
* @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or
* `i1 > i2`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(const_iterator i1, const_iterator i2, const string& str);
/**
* Replaces the portion of this string `[i1, i2)` with \p n characters from string \p s. The character
* sequence can contain null characters.
*
* All pointers, references, and iterators may be invalidated.
*
* @param i1 Position to start replacement.
* @param i2 Position to stop replacement.
* @param s String to replace characters with.
* @param n The number of replacement characters.
*
* @return \c *this.
*
* @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or
* `i1 > i2`.
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(const_iterator i1, const_iterator i2, const value_type* s, size_type n);
/**
* Replaces the portion of this string `[i1, i2)` with the null-terminated string \p s.
*
* All pointers, references, and iterators may be invalidated.
*
* @param i1 Position to start replacement.
* @param i2 Position to stop replacement.
* @param s String to replace characters with.
*
* @return \c *this.
*
* @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or
* `i1 > i2`.
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(const_iterator i1, const_iterator i2, const value_type* s);
/**
* Replaces the portion of this string `[i1, i2)` with \p n copies of character \p c.
*
* All pointers, references, and iterators may be invalidated.
*
* @param i1 Position to start replacement.
* @param i2 Position to stop replacement.
* @param n Number of characters to replace with.
* @param c Character to replace with.
*
* @return \c *this.
*
* @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or
* `i1 > i2`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(const_iterator i1, const_iterator i2, size_type n, value_type c);
/**
* Replaces the portion of this string `[i1, i2)` with the characters in \p ilist.
*
* All pointers, references, and iterators may be invalidated.
*
* @param i1 Position to start replacement.
* @param i2 Position to stop replacement.
* @param ilist Initializer list of character to replace with.
*
* @return \c *this.
*
* @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or
* `i1 > i2`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(const_iterator i1, const_iterator i2, std::initializer_list<value_type> ilist);
/**
* Replaces the portion of this string `[i1, i2)` with \p str.
*
* All pointers, references, and iterators may be invalidated.
*
* @param i1 Position to start replacement.
* @param i2 Position to stop replacement.
* @param str String to replace characters with.
*
* @return \c *this.
*
* @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or
* `i1 > i2`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(const_iterator i1, const_iterator i2, const std::string& str);
/**
* Replaces the portion of this string `[i1, i2)` with \p sv.
*
* All pointers, references, and iterators may be invalidated.
* @param sv String view to replace characters with.
*
* @return \c *this.
*
* @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or
* `i1 > i2`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace(const_iterator i1, const_iterator i2, const carb::cpp::string_view& sv);
#if CARB_HAS_CPP17
/**
* Implicitly converts @c t to type `std::string_view` and replaces the portion of this string `[i1, i2)` with
* \p sv. This overload participates in overload resolution only if `std::is_convertible_v<const T&,
* std::string_view>` is true.
*
* All pointers, references, and iterators may be invalidated.
* @param t Object that can be converted to `std::string_view` to replace characters with.
*
* @return \c *this.
*
* @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or
* `i1 > i2`.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
string& replace(const_iterator i1, const_iterator i2, const T& t);
#endif
/**
* Replaces the portion of this string `[pos, pos + n1)` with a \c printf style formatted string. If `n == npos`, or
* `pos + n` is greater than size(), the substring to the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos Position to start replacement.
* @param n1 Number of characters to replace.
* @param fmt \c printf style format string to replace characters with. Must not overlap with \c *this.
* @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace_format(size_type pos, size_type n1, const value_type* fmt, ...) CARB_PRINTF_FUNCTION(4, 5);
/**
* Replaces the portion of this string `[pos, pos + n1)` with a \c vprintf style formatted string. If `n == npos`,
* or `pos + n` is greater than size(), the substring to the end of the string is replaced.
*
* All pointers, references, and iterators may be invalidated.
*
* @param pos Position to start replacement.
* @param n1 Number of characters to replace.
* @param fmt \c printf style format string to replace characters with. Must not overlap with \c *this.
* @param ap \c va_list as initialized with \c va_start. Arguments must not overlap with \c *this.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace_vformat(size_type pos, size_type n1, const value_type* fmt, va_list ap);
/**
* Replaces the portion of this string `[i1, i2)` with a \c printf style formatted string.
*
* All pointers, references, and iterators may be invalidated.
*
* @param i1 Position to start replacement.
* @param i2 Position to stop replacement.
* @param fmt \c printf style format string to replace characters with. Must not overlap with \c *this.
* @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace_format(const_iterator i1, const_iterator i2, const value_type* fmt, ...) CARB_PRINTF_FUNCTION(4, 5);
/**
* Replaces the portion of this string `[i1, i2)` with a \c printf style formatted string.
*
* All pointers, references, and iterators may be invalidated.
*
* @param i1 Position to start replacement.
* @param i2 Position to stop replacement.
* @param fmt \c printf style format string to replace characters with. Must not overlap with \c *this.
* @param ap \c va_list as initialized with \c va_start. Arguments must not overlap with \c *this.
*
* @return \c *this.
*
* @throws std::out_of_range if \p pos is greater than \c size().
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error.
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string& replace_vformat(const_iterator i1, const_iterator i2, const value_type* fmt, va_list ap);
/**
* Returns a substring from `[pos, pos + n)` of this string. If `n == npos`, or `pos + n` is greater than \ref
* size(), the substring is to the end of the string.
*
* @param pos Position to start the substring.
* @param n Number of characters to include in the substring.
*
* @return A new string containing the substring.
*
* @throws std::out_of_range if \p pos is greater than size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string substr(size_type pos = 0, size_type n = npos) const;
/**
* Copies a substring from `[pos, pos + n)` to the provided destination \p s. If `n == npos`, or `pos + n` is
* greater than size(), the substring is to the end of the string. The resulting character sequence is not null
* terminated.
*
* @param s Destination to copy characters to.
* @param n Number of characters to include in the substring.
* @param pos Position to start the substring.
*
* @return number of characters copied.
*
* @throws std::invalid_argument if \p s is \c nullptr.
* @throws std::out_of_range if \p pos is greater than size().
*/
constexpr size_type copy(value_type* s, size_type n, size_type pos = 0) const;
/**
* Resizes the string to contain \p n characters. If \p n is greater than size(), copies of the character \p c
* are appended. If \p n is smaller than size(), the string is shrunk to size \p n.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param n New size of the string.
* @param c Character to append when growing the string.
*
* @return none.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
void resize(size_type n, value_type c);
/**
* Resizes the string to contain \p n characters. If \p n is greater than size(), copies of \c NUL are
* appended. If \p n is smaller than size(), the string is shrunk to size \p n.
*
* If reallocation occurs, all pointers, references, and iterators are invalidated.
*
* @param n New size of the string.
*
* @return none.
*
* @throws std::length_error if the function would result in size() being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
void resize(size_type n);
/**
* Swaps the contents of this string with \p str.
*
* All pointers, references, and iterators may be invalidated.
*
* @param str The string to swap with.
*
* @return none.
*/
void swap(string& str) noexcept;
/**
* Finds the first substring of this string that matches \p str. The search begins at \p pos.
*
* @param str String to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
constexpr size_type find(const string& str, size_type pos = 0) const noexcept;
/**
* Finds the first substring of this string that matches the first \p n characters of \p s. The string may contain
* nulls.The search begins at \p pos.
*
* @param s String to find.
* @param pos Position to begin the search.
* @param n Number of characters to search for.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type find(const value_type* s, size_type pos, size_type n) const;
/**
* Finds the first substring of this string that matches the null-terminated string \p s. The search begins at
* \p pos.
*
* @param s String to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type find(const value_type* s, size_type pos = 0) const;
/**
* Finds the first substring of this string that matches \p str. The search begins at \p pos.
*
* @param str String to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
CARB_CPP20_CONSTEXPR size_type find(const std::string& str, size_type pos = 0) const noexcept;
/**
* Finds the first substring of this string that matches \p sv. The search begins at \p pos.
*
* @param sv String view to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
constexpr size_type find(const carb::cpp::string_view& sv, size_type pos = 0) const noexcept;
#if CARB_HAS_CPP17
/**
* Implicitly converts @c t to type `std::string_view` and finds the first substring of this string that matches it.
* The search begins at \p pos. This overload participates in overload resolution only if
* `std::is_convertible_v<const T&, std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
constexpr size_type find(const T& t, size_type pos = 0) const noexcept;
#endif
/**
* Finds the first substring of this string that matches \p c. The search begins at \p pos.
*
* @param c Character to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
constexpr size_type find(value_type c, size_type pos = 0) const noexcept;
/**
* Finds the last substring of this string that matches \p str. The search begins at \p pos. If `pos == npos` or
* `pos >= size()`, the whole string is searched.
*
* @param str String to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
constexpr size_type rfind(const string& str, size_type pos = npos) const noexcept;
/**
* Finds the last substring of this string that matches the first \p n characters of \p s. The string may contain
* nulls.The search begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param s String to find.
* @param pos Position to begin the search.
* @param n Number of characters to search for.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type rfind(const value_type* s, size_type pos, size_type n) const;
/**
* Finds the last substring of this string that matches the null-terminated string \p s. The search begins at
* \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param s String to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type rfind(const value_type* s, size_type pos = npos) const;
/**
* Finds the last substring of this string that matches \p c. The search begins at \p pos. If `pos == npos` or
* `pos >= size()`, the whole string is searched.
*
* @param c Character to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
constexpr size_type rfind(value_type c, size_type pos = npos) const noexcept;
/**
* Finds the last substring of this string that matches \p str. The search begins at \p pos. If `pos == npos` or
* `pos >= size()`, the whole string is searched.
*
* @param str String to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
CARB_CPP20_CONSTEXPR size_type rfind(const std::string& str, size_type pos = npos) const noexcept;
/**
* Finds the last substring of this string that matches \p sv. The search begins at \p pos. If `pos == npos` or
* `pos >= size()`, the whole string is searched.
*
* @param sv String view to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
constexpr size_type rfind(const carb::cpp::string_view& sv, size_type pos = npos) const noexcept;
#if CARB_HAS_CPP17
/**
* Implicitly converts @c t to type `std::string_view` and finds the last substring of this string that matches it.
* The search begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched. This
* overload participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` to find.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
constexpr size_type rfind(const T& t, size_type pos = npos) const noexcept;
#endif
/**
* Finds the first character equal to one of the characters in string \p str. The search begins at \p pos.
*
* @param str String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first found character, or \c npos if no character is found.
*/
constexpr size_type find_first_of(const string& str, size_type pos = 0) const noexcept;
/**
* Finds the first character equal to one of the characters in the first \p n characters of string \p s. The search
* begins at \p pos.
*
* @param s String containing the characters to search for.
* @param pos Position to begin the search.
* @param n Number of characters in \p s to search for.
*
* @return Position of the first found character, or \c npos if no character is found.
*
* @throws std::invalid_argument if \p s is \c nullptr
*/
constexpr size_type find_first_of(const value_type* s, size_type pos, size_type n) const;
/**
* Finds the first character equal to one of the characters in null-terminated string \p s. The search begins at
* \p pos.
*
* @param s String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first found character, or \c npos if no character is found.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type find_first_of(const value_type* s, size_type pos = 0) const;
/**
* Finds the first character equal to \p c. The search begins at \p pos.
*
* @param c Character to search for.
* @param pos Position to begin the search.
*
* @return Position of the first found character, or \c npos if no character is found.
*/
constexpr size_type find_first_of(value_type c, size_type pos = 0) const noexcept;
/**
* Finds the first character equal to one of the characters in string \p str. The search begins at \p pos.
*
* @param str String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first found character, or \c npos if no character is found.
*/
CARB_CPP20_CONSTEXPR size_type find_first_of(const std::string& str, size_type pos = 0) const noexcept;
/**
* Finds the first character equal to one of the characters in string \p sv. The search begins at \p pos.
*
* @param sv String view containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first found character, or \c npos if no character is found.
*/
constexpr size_type find_first_of(const carb::cpp::string_view& sv, size_type pos = 0) const noexcept;
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and finds the first character equal to one of the characters
* in that string view. The search begins at \p pos. This overload participates in overload resolution only if
* `std::is_convertible_v<const T&, std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
constexpr size_type find_first_of(const T& t, size_type pos = 0) const noexcept;
#endif
/**
* Finds the last character equal to one of the characters in string \p str. The search begins at \p pos. If
* `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param str String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the last found character, or \c npos if no character is found.
*/
constexpr size_type find_last_of(const string& str, size_type pos = npos) const noexcept;
/**
* Finds the last character equal to one of the characters in the first \p n characters of string \p s. The search
* begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param s String containing the characters to search for.
* @param pos Position to begin the search.
* @param n Number of characters in \p s to search for.
*
* @return Position of the last found character, or \c npos if no character is found.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type find_last_of(const value_type* s, size_type pos, size_type n) const;
/**
* Finds the last character equal to one of the characters in the null-terminated string \p s. The search
* begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param s String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the last found character, or \c npos if no character is found.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type find_last_of(const value_type* s, size_type pos = npos) const;
/**
* Finds the last character equal to \p c. The search begins at \p pos. If `pos == npos` or `pos >= size()`,
* the whole string is searched.
*
* @param c Character to search for.
* @param pos Position to begin the search.
*
* @return Position of the last found character, or \c npos if no character is found.
*/
constexpr size_type find_last_of(value_type c, size_type pos = npos) const noexcept;
/**
* Finds the last character equal to one of the characters in string \p str. The search begins at \p pos. If
* `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param str String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the last found character, or \c npos if no character is found.
*/
CARB_CPP20_CONSTEXPR size_type find_last_of(const std::string& str, size_type pos = npos) const noexcept;
/**
* Finds the last character equal to one of the characters in string view \p sv. The search begins at \p pos. If
* `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param sv String view containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the last found character, or \c npos if no character is found.
*/
constexpr size_type find_last_of(const carb::cpp::string_view& sv, size_type pos = npos) const noexcept;
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and finds the last character equal to one of the characters
* in that string view. The search begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is
* searched. The search begins at \p pos. This overload participates in overload resolution only if
* `std::is_convertible_v<const T&, std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
constexpr size_type find_last_of(const T& t, size_type pos = npos) const noexcept;
#endif
/**
* Finds the first character not equal to one of the characters in string \p str. The search begins at \p pos.
*
* @param str String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first found character, or \c npos if no character is found.
*/
constexpr size_type find_first_not_of(const string& str, size_type pos = 0) const noexcept;
/**
* Finds the first character not equal to one of the characters in the first \p n characters of string \p s. The
* search begins at \p pos.
*
* @param s String containing the characters to search for.
* @param pos Position to begin the search.
* @param n Number of characters in \p s to search for.
*
* @return Position of the first found character, or \c npos if no character is found.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type find_first_not_of(const value_type* s, size_type pos, size_type n) const;
/**
* Finds the first character not equal to one of the characters in null-terminated string \p s. The search begins at
* \p pos.
*
* @param s String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first found character, or \c npos if no character is found.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type find_first_not_of(const value_type* s, size_type pos = 0) const;
/**
* Finds the first character equal to \p c. The search begins at \p pos.
*
* @param c Character to search for.
* @param pos Position to begin the search.
*
* @return Position of the first found character, or \c npos if no character is found.
*/
constexpr size_type find_first_not_of(value_type c, size_type pos = 0) const noexcept;
/**
* Finds the first character not equal to one of the characters in string \p str. The search begins at \p pos.
*
* @param str String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first found character, or \c npos if no character is found.
*/
CARB_CPP20_CONSTEXPR size_type find_first_not_of(const std::string& str, size_type pos = 0) const noexcept;
/**
* Finds the first character not equal to one of the characters in string view \p sv. The search begins at \p pos.
*
* @param sv String view containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first found character, or \c npos if no character is found.
*/
constexpr size_type find_first_not_of(const carb::cpp::string_view& sv, size_type pos = 0) const noexcept;
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and finds the first character not equal to one of the
* characters in that string view. The search begins at \p pos. This overload participates in overload resolution
* only if `std::is_convertible_v<const T&, std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
constexpr size_type find_first_not_of(const T& t, size_type pos = 0) const noexcept;
#endif
/**
* Finds the last character not equal to one of the characters in string \p str. The search begins at \p pos. If
* `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param str String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the last found character, or \c npos if no character is found.
*/
constexpr size_type find_last_not_of(const string& str, size_type pos = npos) const noexcept;
/**
* Finds the last character not equal to one of the characters in the first \p n characters of string \p s. The
* search begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param s String containing the characters to search for.
* @param pos Position to begin the search.
* @param n Number of characters in \p s to search for.
*
* @return Position of the last found character, or \c npos if no character is found.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type find_last_not_of(const value_type* s, size_type pos, size_type n) const;
/**
* Finds the last character not equal to one of the characters in the null-terminated string \p s. The
* search begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param s String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the last found character, or \c npos if no character is found.
*
* @throws std::invalid_argument if \p s is \c nullptr.
*/
constexpr size_type find_last_not_of(const value_type* s, size_type pos = npos) const;
/**
* Finds the last character not equal to \p c. The search begins at \p pos. If `pos == npos` or
* `pos >= size()`, the whole string is searched.
*
* @param c Character to search for.
* @param pos Position to begin the search.
*
* @return Position of the last found character, or \c npos if no character is found.
*/
constexpr size_type find_last_not_of(value_type c, size_type pos = npos) const noexcept;
/**
* Finds the last character not equal to one of the characters in string \p str. The search begins at \p pos. If
* `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param str String containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the last found character, or \c npos if no character is found.
*/
CARB_CPP20_CONSTEXPR size_type find_last_not_of(const std::string& str, size_type pos = npos) const noexcept;
/**
* Finds the last character not equal to one of the characters in string view \p sv. The search begins at \p pos. If
* `pos == npos` or `pos >= size()`, the whole string is searched.
*
* @param sv String view containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the last found character, or \c npos if no character is found.
*/
constexpr size_type find_last_not_of(const carb::cpp::string_view& sv, size_type pos = npos) const noexcept;
#if CARB_HAS_CPP17
/**
* Implicitly converts @p t to type `std::string_view` and finds the last character not equal to one of the
* characters in that string view. The search begins at \p pos. If `pos == npos` or `pos >= size()`, the
* whole string is searched. This overload participates in overload resolution only if `std::is_convertible_v<const
* T&, std::string_view>` is true.
*
* @param t Object that can be converted to `std::string_view` containing the characters to search for.
* @param pos Position to begin the search.
*
* @return Position of the first character of the matching substring, or \c npos if no such substring exists.
*/
template <typename T, typename = detail::is_sv_convertible<T>>
constexpr size_type find_last_not_of(const T& t, size_type pos = npos) const noexcept;
#endif
private:
// Size of the character buffer for small string optimization
constexpr static size_type kSMALL_STRING_SIZE = 32;
// The last byte of the SSO buffer contains the remaining size in the buffer
constexpr static size_type kSMALL_SIZE_OFFSET = kSMALL_STRING_SIZE - 1;
// Sentinel value indicating that the string is using heap allocated storage
constexpr static value_type kSTRING_IS_ALLOCATED = std::numeric_limits<char>::max();
// Struct that holds the data for an allocated string. This could be an anonymous struct inside the union,
// however naming it outside the union allows for the static_asserts below for ABI safety.
struct allocated_data
{
CARB_VIZ pointer m_ptr;
CARB_VIZ size_type m_size;
CARB_VIZ size_type m_capacity;
};
union
{
CARB_VIZ allocated_data m_allocated_data;
/**
* Local buffer for small string optimization. When the string is small enough to fit in the local buffer, the
* last byte is the size remaining in the buffer. This has the advantage of when the local buffer is full, the
* size remaining will be 0, which acts as the NUL terminator for the local string. When the string is larger
* than the buffer, the last byte will be m_sentinel_value, indicated the string is allocated.
*/
CARB_VIZ value_type m_local_data[kSMALL_STRING_SIZE];
};
static_assert(kSMALL_STRING_SIZE == 32, "ABI-safety: Cannot change the small string optimization size");
static_assert(size_type(kSTRING_IS_ALLOCATED) >= kSMALL_STRING_SIZE,
"Invalid assumption: Sentinel Value must be greater than max small string size.");
static_assert(sizeof(allocated_data) == 24, "ABI-safety: Cannot change allocated data size");
static_assert(offsetof(allocated_data, m_ptr) == 0, "ABI-safety: Member offset cannot change");
static_assert(offsetof(allocated_data, m_size) == 8, "ABI-safety: Member offset cannot change");
static_assert(offsetof(allocated_data, m_capacity) == 16, "ABI-safety: Member offset cannot change");
static_assert(sizeof(allocated_data) < kSMALL_STRING_SIZE,
"Invalid assumption: sizeof(allocated_data) must be less than the small string size.");
// Helper functions
constexpr bool is_local() const;
constexpr void set_local(size_type new_size) noexcept;
constexpr void set_allocated() noexcept;
constexpr reference get_reference(size_type pos) noexcept;
constexpr const_reference get_reference(size_type pos) const noexcept;
constexpr pointer get_pointer(size_type pos) noexcept;
constexpr const_pointer get_pointer(size_type pos) const noexcept;
constexpr void set_empty() noexcept;
constexpr void range_check(size_type pos, size_type size, const char* function) const;
// Checks that pos is within the range [begin(), end()]
constexpr void range_check(const_iterator pos, const char* function) const;
// Checks that first is within the range [begin(), end()], that last is within the range [begin(), end()], and that
// first <= last.
constexpr void range_check(const_iterator first, const_iterator last, const char* function) const;
// Checks if current+n > max_size(). If it is not, returns current+n.
constexpr size_type length_check(size_type current, size_type n, const char* function) const;
constexpr void set_size(size_type new_size) noexcept;
constexpr bool should_allocate(size_type n) const noexcept;
constexpr bool overlaps_this_string(const_pointer s) const noexcept;
void overlap_check(const_pointer s) const;
// Calls std::vsnprintf, but throws if it fails
size_type vsnprintf_check(char* buffer, size_type buffer_size, const char* format, va_list args);
template <class... Args>
size_type snprintf_check(char* buffer, size_type buffer_size, const char* format, Args&&... args);
void allocate_if_necessary(size_type size);
void initialize(const_pointer src, size_type size);
template <typename InputIterator>
void initialize(InputIterator begin, InputIterator end, size_type size);
void dispose();
pointer allocate_buffer(size_type old_capacity, size_type& new_capacity);
void grow_buffer_to(size_type new_capacity);
// Grows a buffer to new_size, fills it with the data from the three provided pointers, and swaps the new buffer
// for the old one. This is used in functions like insert and replace, which may need to fill the new buffer with
// characters from multiple locations.
void grow_buffer_and_fill(
size_type new_size, const_pointer p1, size_type s1, const_pointer p2, size_type s2, const_pointer p3, size_type s3);
template <class InputIterator>
void grow_buffer_and_append(size_type new_size, InputIterator first, InputIterator last);
// Internal implementations
string& assign_internal(const_pointer src, size_type new_size);
template <typename InputIterator>
string& assign_internal(InputIterator begin, InputIterator end, size_type new_size);
string& insert_internal(size_type pos, value_type c, size_type n);
string& insert_internal(size_type pos, const_pointer src, size_type n);
string& append_internal(const_pointer src, size_type n);
constexpr int compare_internal(const_pointer this_str,
const_pointer other_str,
size_type this_size,
size_type other_size) const noexcept;
void replace_setup(size_type pos, size_type replaced_size, size_type replacement_size);
};
static_assert(std::is_standard_layout<string>::value, "string must be standard layout"); // Not interop-safe because not
// trivially copyable
static_assert(sizeof(string) == 32, "ABI Safety: String must be 32 bytes");
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(const string& lhs, const string& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(const string& lhs, const char* rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::invalid_argument if \p rhs is \c nullptr.
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(const string& lhs, char rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(const string& lhs, const std::string& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::invalid_argument if \p lhs is \c nullptr.
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(const char* lhs, const string& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs Character the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(char lhs, const string& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(const std::string& lhs, const string& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(string&& lhs, string&& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(string&& lhs, const string& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::invalid_argument if \p rhs is \c nullptr.
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(string&& lhs, const char* rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs Character that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(string&& lhs, char rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(string&& lhs, const string& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(const string& lhs, string&& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::invalid_argument if \p lhs is \c nullptr.
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(const char* lhs, string&& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs Character the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(char lhs, string&& rhs);
/**
* Creates a new string by concatenating \p lhs and \p rhs.
*
* @param lhs String the comes first in the new string.
* @param rhs String that comes second in the new string.
*
* @return A new string containing the characters from \p lhs followed by the characters from \p rhs.
*
* @throws std::length_error if the resulting string would be being larger than max_size().
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string operator+(const std::string& lhs, string&& rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs and \p rhs are equal, false otherwise.
*/
constexpr bool operator==(const string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs and \p rhs are equal, false otherwise.
*
* @throws std::invalid_argument if \p rhs is \c nullptr.
*/
constexpr bool operator==(const string& lhs, const char* rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs and \p rhs are equal, false otherwise.
*
* @throws std::invalid_argument if \p lhs is \c nullptr.
*/
constexpr bool operator==(const char* lhs, const string& rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs and \p rhs are equal, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator==(const string& lhs, const std::string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs and \p rhs are equal, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator==(const std::string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs and \p rhs are not equal, false otherwise.
*/
constexpr bool operator!=(const string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs and \p rhs are not equal, false otherwise.
*
* @throws std::invalid_argument if \p rhs is \c nullptr.
*/
constexpr bool operator!=(const string& lhs, const char* rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs and \p rhs are not equal, false otherwise.
*
* @throws std::invalid_argument if \p lhs is \c nullptr.
*/
constexpr bool operator!=(const char* lhs, const string& rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs and \p rhs are not equal, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator!=(const string& lhs, const std::string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs and \p rhs are not equal, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator!=(const std::string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is less than \p rhs, false otherwise.
*/
constexpr bool operator<(const string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is less than \p rhs, false otherwise.
*
* @throws std::invalid_argument if \p rhs is \c nullptr.
*/
constexpr bool operator<(const string& lhs, const char* rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is less than \p rhs, false otherwise.
*
* @throws std::invalid_argument if \p lhs is \c nullptr.
*/
constexpr bool operator<(const char* lhs, const string& rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is less than \p rhs, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator<(const string& lhs, const std::string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is less than \p rhs, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator<(const std::string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is less than or equal to \p rhs, false otherwise.
*/
constexpr bool operator<=(const string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is less than or equal to \p rhs, false otherwise.
*
* @throws std::invalid_argument if \p rhs is \c nullptr.
*/
constexpr bool operator<=(const string& lhs, const char* rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is less than or equal to \p rhs, false otherwise.
*
* @throws std::invalid_argument if \p lhs is \c nullptr.
*/
constexpr bool operator<=(const char* lhs, const string& rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is less than or equal to \p rhs, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator<=(const string& lhs, const std::string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is less than or equal to \p rhs, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator<=(const std::string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is greater than \p rhs, false otherwise.
*/
constexpr bool operator>(const string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is greater than \p rhs, false otherwise.
*
* @throws std::invalid_argument if \p rhs is \c nullptr.
*/
constexpr bool operator>(const string& lhs, const char* rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is greater than \p rhs, false otherwise.
*
* @throws std::invalid_argument if \p lhs is \c nullptr.
*/
constexpr bool operator>(const char* lhs, const string& rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is greater than \p rhs, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator>(const string& lhs, const std::string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is greater than \p rhs, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator>(const std::string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is greater than or equal to \p rhs, false otherwise.
*/
constexpr bool operator>=(const string& lhs, const string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is greater than or equal to \p rhs, false otherwise.
*
* @throws std::invalid_argument if \p rhs is \c nullptr.
*/
constexpr bool operator>=(const string& lhs, const char* rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is greater than or equal to \p rhs, false otherwise.
*
* @throws std::invalid_argument if \p lhs is \c nullptr.
*/
constexpr bool operator>=(const char* lhs, const string& rhs);
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is greater than or equal to \p rhs, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator>=(const string& lhs, const std::string& rhs) noexcept;
/**
* Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare().
*
* @param lhs Left hand side of the comparison.
* @param rhs Right hand side of the comparison.
*
* @return true if \p lhs is greater than or equal to \p rhs, false otherwise.
*/
CARB_CPP20_CONSTEXPR bool operator>=(const std::string& lhs, const string& rhs) noexcept;
/**
* Swaps \p lhs and \p rhs via `lhs.swap(rhs)`.
*
* @param lhs String to swap.
* @param rhs String to swap.
*
* @return none.
*/
void swap(string& lhs, string& rhs) noexcept;
/**
* Erases all instances of \p val from \p str.
*
* @param str String to erase from.
* @param val Character to erase.
*
* @return The number of characters erased.
*/
template <typename U>
CARB_CPP20_CONSTEXPR string::size_type erase(string& str, const U& val);
/**
* Erases all elements of \p str the satisfy \p pred.
*
* @param str String to erase from.
* @param pred Predicate to check characters with.
*
* @return The number of characters erased.
*/
template <typename Pred>
CARB_CPP20_CONSTEXPR string::size_type erase_if(string& str, Pred pred);
/**
* Output stream operator overload. Outputs the contents of \p str to the stream \p os.
*
* @param os Stream to output the string to.
* @param str The string to output.
*
* @return \p os.
*
* @throws std::ios_base::failure if an exception is thrown during output.
*/
std::basic_ostream<char, std::char_traits<char>>& operator<<(std::basic_ostream<char, std::char_traits<char>>& os,
const string& str);
/**
* Input stream operator overload. Extracts a string from \p is into \p str.
*
* @param is Stream to get input from.
* @param str The string to put input into.
*
* @return \p is.
*
* @throws std::ios_base::failure if no characters are extracted or an exception is thrown during input.
*/
std::basic_istream<char, std::char_traits<char>>& operator>>(std::basic_istream<char, std::char_traits<char>>& is,
string& str);
/**
* Reads characters from the input stream \p input and places them in the string \p str. Characters are read until
* end-of-file is reached on \p input, the next character in the input is \p delim, or max_size() characters have
* been extracted.
*
* @param input Stream to get input from.
* @param str The string to put input into.
* @param delim Character that indicates that extraction should end.
*
* @return \p input.
*/
std::basic_istream<char, std::char_traits<char>>& getline(std::basic_istream<char, std::char_traits<char>>&& input,
string& str,
char delim);
/**
* Reads characters from the input stream \p input and places them in the string \p str. Characters are read until
* end-of-file is reached on \p input, the next character in the input it \c '\\n', or max_size() characters have
* been extracted.
*
* @param input Stream to get input from.
* @param str The string to put input into.
*
* @return \p input.
*/
std::basic_istream<char, std::char_traits<char>>& getline(std::basic_istream<char, std::char_traits<char>>&& input,
string& str);
/**
* Interprets the string \p str as a signed integer value.
*
* @param str The string to convert.
* @param pos Address of an integer to store the number of characters processed.
* @param base The number base.
*
* @return Integer value corresponding to the contents of \p str.
*
* @throws std::invalid_argument If no conversion could be performed.
* @throws std::out_of_range If the converted value would fall out of the range of the result type or if the
* underlying function (\c std::strtol) sets \c errno to \c ERANGE.
*/
int stoi(const string& str, std::size_t* pos = nullptr, int base = 10);
/**
* Interprets the string \p str as a signed integer value.
*
* @param str The string to convert.
* @param pos Address of an integer to store the number of characters processed.
* @param base The number base.
*
* @return Integer value corresponding to the contents of \p str.
*
* @throws std::invalid_argument If no conversion could be performed.
* @throws std::out_of_range If the converted value would fall out of the range of the result type or if the
* underlying function (\c std::strtol) sets \c errno to \c ERANGE.
*/
long stol(const string& str, std::size_t* pos = nullptr, int base = 10);
/**
* Interprets the string \p str as a signed integer value.
*
* @param str The string to convert.
* @param pos Address of an integer to store the number of characters processed.
* @param base The number base.
*
* @return Integer value corresponding to the contents of \p str.
*
* @throws std::invalid_argument If no conversion could be performed.
* @throws std::out_of_range If the converted value would fall out of the range of the result type or if the
* underlying function (\c std::strtoll) sets \c errno to \c ERANGE.
*/
long long stoll(const string& str, std::size_t* pos = nullptr, int base = 10);
/**
* Interprets the string \p str as a unsigned integer value.
*
* @param str The string to convert.
* @param pos Address of an integer to store the number of characters processed.
* @param base The number base.
*
* @return Unsigned Integer value corresponding to the contents of \p str.
*
* @throws std::invalid_argument If no conversion could be performed.
* @throws std::out_of_range If the converted value would fall out of the range of the result type or if the
* underlying function (\c std::strtoul) sets \c errno to \c ERANGE.
*/
unsigned long stoul(const string& str, std::size_t* pos = nullptr, int base = 10);
/**
* Interprets the string \p str as a unsigned integer value.
*
* @param str The string to convert.
* @param pos Address of an integer to store the number of characters processed.
* @param base The number base.
*
* @return Unsigned Integer value corresponding to the contents of \p str.
*
* @throws std::invalid_argument If no conversion could be performed.
* @throws std::out_of_range If the converted value would fall out of the range of the result type or if the
* underlying function (\c std::strtoull) sets \c errno to \c ERANGE.
*/
unsigned long long stoull(const string& str, std::size_t* pos = nullptr, int base = 10);
/**
* Interprets the string \p str as a floating point value.
*
* @param str The string to convert.
* @param pos Address of an integer to store the number of characters processed.
*
* @return Floating point value corresponding to the contents of \p str.
*
* @throws std::invalid_argument If no conversion could be performed.
* @throws std::out_of_range If the converted value would fall out of the range of the result type or if the
* underlying function (\c std::strtof) sets \c errno to \c ERANGE.
*/
float stof(const string& str, std::size_t* pos = nullptr);
/**
* Interprets the string \p str as a floating point value.
*
* @param str The string to convert.
* @param pos Address of an integer to store the number of characters processed.
*
* @return Floating point value corresponding to the contents of \p str.
*
* @throws std::invalid_argument If no conversion could be performed.
* @throws std::out_of_range If the converted value would fall out of the range of the result type or if the
* underlying function (\c std::strtod) sets \c errno to \c ERANGE.
*/
double stod(const string& str, std::size_t* pos = nullptr);
/**
* Interprets the string \p str as a floating point value.
*
* @param str The string to convert.
* @param pos Address of an integer to store the number of characters processed.
*
* @return Floating point value corresponding to the contents of \p str.
*
* @throws std::invalid_argument If no conversion could be performed.
* @throws std::out_of_range If the converted value would fall out of the range of the result type or if the
* underlying function (\c std::strtold) sets \c errno to \c ERANGE.
*/
long double stold(const string& str, std::size_t* pos = nullptr);
/**
* Converts the numerical value \p value to a string.
*
* @param value Value to convert.
*
* @return A string representing the value.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string to_string(int value);
/**
* Converts the numerical value \p value to a string.
*
* @param value Value to convert.
*
* @return A string representing the value.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string to_string(long value);
/**
* Converts the numerical value \p value to a string.
*
* @param value Value to convert.
*
* @return A string representing the value.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string to_string(long long value);
/**
* Converts the numerical value \p value to a string.
*
* @param value Value to convert.
*
* @return A string representing the value.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string to_string(unsigned value);
/**
* Converts the numerical value \p value to a string.
*
* @param value Value to convert.
*
* @return A string representing the value.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string to_string(unsigned long value);
/**
* Converts the numerical value \p value to a string.
*
* @param value Value to convert.
*
* @return A string representing the value.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string to_string(unsigned long long value);
/**
* Converts the numerical value \p value to a string.
*
* @param value Value to convert.
*
* @return A string representing the value.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string to_string(float value);
/**
* Converts the numerical value \p value to a string.
*
* @param value Value to convert.
*
* @return A string representing the value.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string to_string(double value);
/**
* Converts the numerical value \p value to a string.
*
* @param value Value to convert.
*
* @return A string representing the value.
*
* @throws Allocation This function may throw any exception thrown during allocation.
*/
string to_string(long double value);
} // namespace omni
namespace std
{
/**
* Hash specialization for std::string
*/
template <>
struct hash<omni::string>
{
/** Argument type alias. */
using argument_type = omni::string;
/** Result type alias. */
using result_type = std::size_t;
/** Hash operator */
size_t operator()(const argument_type& x) const noexcept
{
return carb::hashBuffer(x.data(), x.size());
}
};
} // namespace std
#include "String.inl"
#pragma pop_macro("max")
CARB_IGNOREWARNING_MSC_POP
| 172,197 | C | 40.503495 | 124 | 0.66331 |
omniverse-code/kit/include/omni/Span.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Implementation of \ref omni::span
#pragma once
#include "../carb/cpp/Span.h"
namespace omni
{
//! @copydoc carb::cpp::dynamic_extent
constexpr auto dynamic_extent = carb::cpp::dynamic_extent;
//! @copydoc carb::cpp::span
template <class T, size_t Extent = dynamic_extent>
using span = carb::cpp::span<T, Extent>;
} // namespace omni
| 794 | C | 28.444443 | 77 | 0.746851 |
omniverse-code/kit/include/omni/hydra/ISceneDelegate.h | // Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Defines.h>
#include <carb/Types.h>
#include <cstddef>
namespace omni
{
namespace usd
{
namespace hydra // carbonite style interface to allow other plugins to access scene delegates
{
// defined in rtx/hydra/IHydraEngine.h
struct IHydraSceneDelegate;
struct ISceneDelegateFactory
{
CARB_PLUGIN_INTERFACE("omni::hydra::ISceneDelegateFactory", 0, 1)
void(CARB_ABI* getInterface)(IHydraSceneDelegate& delegateInterface);
};
} // namespace hydra
} // namespace usd
} // namespace omni
| 964 | C | 25.805555 | 93 | 0.771784 |
omniverse-code/kit/include/omni/hydra/IOmniHydra.h | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "OmniHydraTypes.h"
// Avoid including USD Headers as they come from UsdPCH.h included in .cpp files
PXR_NAMESPACE_OPEN_SCOPE
class SdfPath;
class GfMatrix4d;
class GfMatrix4f;
class GfVec3f;
template<typename> class VtArray;
typedef VtArray<GfVec3f> VtVec3fArray;
PXR_NAMESPACE_CLOSE_SCOPE
namespace omni
{
namespace usd
{
namespace hydra
{
struct IOmniHydra
{
CARB_PLUGIN_INTERFACE("omni::hydra::IOmniHydra", 2, 0)
/*
* Transform Get/Set
*/
// get world space transform in s,q,t format
bool(CARB_ABI* GetWorldTransform)(pxr::SdfPath const& id, Transform& transform);
// Set standard s,q,t transform to hydra.
bool(CARB_ABI* SetWorldTransform)(pxr::SdfPath const& id, Transform const& transform);
// get local space transform in 4x4 matrix
bool(CARB_ABI* GetLocalMatrix)(pxr::SdfPath const& id, pxr::GfMatrix4d& matrix);
// set local space transform in 4x4 matrix
bool(CARB_ABI* SetLocalMatrix)(pxr::SdfPath const& id, pxr::GfMatrix4d const& matrix);
// get world space transform in 4x4 matrix
bool(CARB_ABI* GetWorldMatrix)(pxr::SdfPath const& id, pxr::GfMatrix4d& matrix);
// set world space transform in 4x4 matrix
bool(CARB_ABI* SetWorldMatrix)(pxr::SdfPath const& id, pxr::GfMatrix4d const& matrix);
/*
* Per vertex primvar buffers (points, normals, etc.)
*/
// set points directly without triggering usd notice using generic buffer descriptor
bool(CARB_ABI* SetPointsBuffer)(pxr::SdfPath const& id, BufferDesc const& bufferDesc);
// set points directly without triggering usd notice using usd point array
bool(CARB_ABI* SetPointsArray)(pxr::SdfPath const& id, pxr::VtVec3fArray const& pointsArray);
/*
* Instancer
*/
// set transform of once instance by instance path + instance index
bool(CARB_ABI* SetInstanceTransform)(const pxr::SdfPath& instancerPath,
uint32_t instanceIndex,
const Transform& transform);
// Scatter the position data to corresponding instance position slots routed by the indexMap
bool(CARB_ABI* SetInstancePosition)(const pxr::SdfPath& instancerPath,
const carb::Double3* position,
const uint32_t* indexMap,
const uint32_t& instanceCount);
// Legacy float support
bool(CARB_ABI* SetInstancePositionF)(const pxr::SdfPath& instancerPath,
const carb::Float3* position,
const uint32_t* indexMap,
const uint32_t& instanceCount);
/*
* Cached Paths
*/
// get size of prim range at specified prim.
size_t(CARB_ABI* GetPrimRangePathCount)(const pxr::SdfPath& primPath);
// This includes paths for prim + all its descendents.
void(CARB_ABI* GetPrimRangePaths)(const pxr::SdfPath& primPath, pxr::SdfPath* primRangePaths, size_t pathRangeSize);
void(CARB_ABI* BlockUSDUpdate)(bool val);
/*
* Bypass RTX render's skel deformation (in favor of external deformer processing)
*/
bool(CARB_ABI* GetBypassRenderSkelMeshProcessing)(pxr::SdfPath const& primPath, bool& bypass);
bool(CARB_ABI* SetBypassRenderSkelMeshProcessing)(pxr::SdfPath const& primPath, bool const& bypass);
bool(CARB_ABI* SetSkelMeshGraphCallbacks)(SkelMeshGraphCallback setupFunc);
};
} // namespace hydra
} // namespace usd
} // namespace omni
| 4,031 | C | 35.654545 | 120 | 0.673282 |
omniverse-code/kit/include/omni/hydra/IDebug.h | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/InterfaceUtils.h>
#include <omni/hydra/OmniHydraTypes.h>
namespace omni
{
namespace usd
{
namespace hydra
{
struct IDebug
{
CARB_PLUGIN_INTERFACE("omni::hydra::IDebug", 0, 1)
size_t(CARB_ABI* getTimestampedTransformCount)();
void(CARB_ABI* getTimestampedTransforms)(TimestampedTransform* out, size_t outCount);
};
}
}
}
| 799 | C | 24.806451 | 89 | 0.764706 |
omniverse-code/kit/include/omni/hydra/OmniHydraTypes.h | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Defines.h>
#include <carb/Types.h>
// Avoid including USD Headers as they come from UsdPCH.h included in .cpp files
PXR_NAMESPACE_OPEN_SCOPE
class UsdPrim;
PXR_NAMESPACE_CLOSE_SCOPE
namespace omni
{
namespace usd
{
namespace hydra
{
struct Transform
{
carb::Double3 position;
carb::Float4 orientation;
carb::Float3 scale;
};
struct TimestampedTransform
{
int64_t wakeupTimeNumerator;
uint64_t wakeupTimeDenominator;
int64_t sampleTimeNumerator;
uint64_t sampleTimeDenominator;
bool transformPresent;
omni::usd::hydra::Transform transform;
};
struct BufferDesc
{
BufferDesc() = default;
BufferDesc(const void* _data, uint32_t _elementStride, uint32_t _elementSize)
: data(_data), elementStride(_elementStride), elementSize(_elementSize)
{
}
const void* data = nullptr; // float elements, vec2, vec3 or vec4
uint32_t elementStride = 0; // in bytes
uint32_t elementSize = 0; // in bytes
size_t count = 0; // vertex count, ...
bool isGPUBuffer = false; // TODO - add GPU interop later
bool isSafeToRender = false; // true if the data is safe to use from the render thread
bool isDataRpResource = false;
};
using SkelMeshGraphCallback = void(*)(const pxr::UsdPrim&);
} // namespace hydra
} // namespace usd
} // namespace omni
| 1,788 | C | 26.10606 | 90 | 0.724273 |
omniverse-code/kit/include/omni/extras/DictHelpers.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Helpers for \ref carb::dictionary::Item and \ref carb::dictionary::IDictionary
#pragma once
#include "../../carb/dictionary/DictionaryUtils.h"
#include <string>
#include <vector>
namespace carb
{
namespace dictionary
{
/**
* Gets a child value from a given Item if present, otherwise returns the given default value.
* @tparam T the type of the return value and default value
* @param baseItem The \ref carb::dictionary::Item to use as a base (required)
* @param path The path of children from \p baseItem using `/` as a separator
* @param defaultValue The default value to return if no item is present at the given location
* @returns The \ref carb::dictionary::Item converted to `T` with \ref carb::dictionary::IDictionary::get(), or
* \p defaultValue if the given \p baseItem and \p path did not resolve to an Item
*/
template <typename T>
T getValueOrDefault(const Item* baseItem, const char* path, T defaultValue)
{
IDictionary* d = getCachedDictionaryInterface();
auto item = d->getItem(baseItem, path);
if (!item)
return defaultValue;
return d->get<T>(item);
}
/**
* Set a string array at the given path with the given array (creating it if it doesn't yet exist).
* @param baseItem The \ref carb::dictionary::Item to use as a base (required)
* @param path The path of children from \p baseItem using `/` as a separator
* @param arr The array of string data to set at the given path
* @returns The \ref carb::dictionary::Item that was either created or found at the given \p path
*/
inline Item* makeStringArrayAtPath(Item* baseItem, const char* path, const std::vector<std::string>& arr)
{
IDictionary* dict = getCachedDictionaryInterface();
ScopedWrite g(*dict, baseItem);
Item* item = dict->getItemMutable(baseItem, path);
if (!item)
{
item = dict->createItem(baseItem, path, ItemType::eDictionary);
}
for (size_t i = 0, count = arr.size(); i < count; ++i)
{
dict->setStringAt(item, i, arr[i].c_str());
}
return item;
}
} // namespace dictionary
} // namespace carb
| 2,540 | C | 35.299999 | 111 | 0.711417 |
omniverse-code/kit/include/omni/extras/FileSystemHelpers.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Helpers for \ref carb::filesystem::IFileSystem
#pragma once
#include "../../carb/InterfaceUtils.h"
#include "../../carb/extras/Path.h"
#include "../../carb/filesystem/IFileSystem.h"
#include "../../carb/tokens/TokensUtils.h"
#include <string>
#include <vector>
namespace omni
{
namespace extras
{
/**
* Helper function for acquiring and caching the filesystem.
* @returns \ref carb::filesystem::IFileSystem acquired as by \ref carb::getCachedInterface()
*/
inline carb::filesystem::IFileSystem* getFileSystem()
{
return carb::getCachedInterface<carb::filesystem::IFileSystem>();
}
/**
* Returns a list of all files and sub-folders in the given folder.
* @param folder The folder path to list
* @returns a `std::vector` of all files and sub-folders in \p folder (non-recursive), or an empty `std::vector` if the
* path could not be accessed or was otherwise empty. Each item in the vector will be prefixed with \p folder.
* @see carb::filesystem::IFileSystem::forEachDirectoryItem(), getDirectoryItemsOfType(), getSubfolders()
*/
inline std::vector<std::string> getDirectoryItems(const std::string& folder)
{
std::vector<std::string> items;
getFileSystem()->forEachDirectoryItem(folder.c_str(),
[](const carb::filesystem::DirectoryItemInfo* const info, void* userData) {
decltype(items)* _items = static_cast<decltype(items)*>(userData);
_items->push_back(info->path);
return carb::filesystem::WalkAction::eContinue;
},
&items);
return items;
}
/**
* Returns a list of either files or sub-folders in the given folder.
* @param folder The folder path to list
* @param type The \ref carb::filesystem::DirectoryItemType to find
* @returns a `std::vector` of items of \p type in \p folder (non-recursive), or an empty `std::vector` if the path
* could not be accessed or was otherwise empty. Each item in the vector will be prefixed with \p folder.
* @see carb::filesystem::IFileSystem::forEachDirectoryItem(), getDirectoryItems(), getSubfolders()
*/
inline std::vector<std::string> getDirectoryItemsOfType(const std::string& folder,
carb::filesystem::DirectoryItemType type)
{
struct UserData
{
carb::filesystem::DirectoryItemType type;
std::vector<std::string> items;
};
UserData data{ type, {} };
getFileSystem()->forEachDirectoryItem(folder.c_str(),
[](const carb::filesystem::DirectoryItemInfo* const info, void* userData) {
decltype(data)* _data = static_cast<decltype(data)*>(userData);
if (info->type == _data->type)
_data->items.push_back(info->path);
return carb::filesystem::WalkAction::eContinue;
},
&data);
return data.items;
}
/**
* Helper function to gather all sub-folders within a given folder.
*
* Effectively the same as `getDirectoryItemsOfType(folder, carb::filesystem::DirectoryItemType::eDirectory)`
* @param folder The folder path to list
* @returns a `std::vector` of sub-folders in \p folder (non-recursive), or an empty `std::vector` if the path could not
* be accessed or was otherwise empty. Each item in the vector will be prefixed with \p folder.
* @see carb::filesystem::IFileSystem::forEachDirectoryItem(), getDirectoryItems(), getDirectoryItemsOfType()
*/
inline std::vector<std::string> getSubfolders(const std::string& folder)
{
return getDirectoryItemsOfType(folder, carb::filesystem::DirectoryItemType::eDirectory);
}
/**
* Helper function to gather all sub-folders within an array of sub-folders.
*
* @note This is not recursive; it only goes one level deeper beyond the given collection of \p folders.
* @param folders a `std::vector` of folders. This vector is walked and \ref getSubfolders() is called on each entry.
* Each entry in the vector will be prefixed with the entry from \p folders that contained it.
* @returns a `std::vector` of sub-folders comprised of all of the sub-folders of the folders given in \p folders
*/
inline std::vector<std::string> getSubfolders(const std::vector<std::string>& folders)
{
std::vector<std::string> allSubFolders;
for (const std::string& folder : folders)
{
const std::vector<std::string> subFolders = getSubfolders(folder);
allSubFolders.insert(allSubFolders.end(), subFolders.begin(), subFolders.end());
}
return allSubFolders;
}
/**
* Resolves a given path by resolving all Tokens and optionally prepending the given root path.
* @param path A path that may contain tokens (see \ref carb::tokens::ITokens)
* @param root If \p path (after token resolution) is a relative path and this is provided, the returned path is
* prepended with this value.
* @returns \p path with tokens resolved, prepended by \p root (if \p root is provided and the token-resolved path is
* relative)
*/
inline std::string resolvePath(const std::string& path, const std::string& root = {})
{
auto tokens = carb::getCachedInterface<carb::tokens::ITokens>();
carb::extras::Path resultPath = carb::tokens::resolveString(tokens, path.c_str());
// If relative - relative to the root
if (!root.empty() && resultPath.isRelative())
{
resultPath = carb::extras::Path(root).join(resultPath);
}
return resultPath;
}
/**
* Reads file content into a string.
* @warning This function reads data in a binary fashion and stores it in a `std::string`. As such, the string may
* contain non-printable characters or even `NUL` characters. No conversion of Windows line endings is performed.
* @param path The path to read
* @returns a `std::pair`, where the `first` member indicates success if `true` and the `second` member is the contents;
* if `first` is `false` then `second` will always be empty. If the file is valid but empty, `first` will be `true`
* but `second` will be empty.
*/
inline std::pair<bool, std::string> readFile(const char* path)
{
auto fs = getFileSystem();
if (fs->exists(path))
{
carb::filesystem::File* file = fs->openFileToRead(path);
if (file)
{
size_t size = fs->getFileSize(file);
if (size)
{
std::string buffer(size, ' ');
fs->readFileChunk(file, &buffer[0], size);
fs->closeFile(file);
return std::make_pair(true, buffer);
}
else
{
fs->closeFile(file);
return std::make_pair(true, std::string{});
}
}
}
return std::make_pair(false, std::string{});
}
} // namespace extras
} // namespace omni
| 7,601 | C | 41.949152 | 120 | 0.636364 |
omniverse-code/kit/include/omni/extras/StringHelpers.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief String manipulation helper utilities
#pragma once
#include "../../carb/Types.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include <cctype>
namespace omni
{
namespace extras
{
#pragma push_macro("max")
#undef max
/**
* Splits a string based on a delimiter.
* @param s The string to split
* @param d The delimiter character
* @param count The maximum number of sections to split \p s into
* @returns a `std::vector` of strings that have been split from \p s at delimiter \p d. The delimiter is not included
* in the strings. Adjacent delimiters do not produce empty strings in the returned vector. Up to \p count entries
* will be in the returned vector. e.g. `"a.b..c.dee."` would produce `{ "a", "b", "c", "dee" }` assuming that \p d is
* `.` and \p count is >= 4.
*/
inline std::vector<std::string> split(const std::string& s, char d, size_t count = std::numeric_limits<size_t>::max())
{
std::vector<std::string> res;
std::stringstream ss(s);
size_t i = 0;
while (ss.good() && i < count)
{
std::string tmp;
if (i == count - 1)
{
std::getline(ss, tmp, (char)0);
}
else
{
std::getline(ss, tmp, d);
}
if (!tmp.empty())
{
res.push_back(tmp);
}
i++;
}
return res;
}
#pragma pop_macro("max")
/**
* Checks a string to see if it ends with a given suffix.
* @param str The string to check
* @param ending The possible ending to check for
* @returns `true` if \p str ends with \p ending; `false` otherwise
*/
inline bool endsWith(const std::string& str, const std::string& ending)
{
if (ending.size() > str.size())
{
return false;
}
return std::equal(ending.rbegin(), ending.rend(), str.rbegin());
}
/**
* Checks a string to see if it begins with a given prefix.
* @param str The string to check
* @param prefix The possible prefix to check for
* @returns `true` if \p str starts with \p prefix; `false` otherwise
*/
inline bool startsWith(const std::string& str, const std::string& prefix)
{
return (str.length() >= prefix.length() && str.compare(0, prefix.size(), prefix) == 0);
}
/**
* Transforms a string to lowercase in-place.
* @warning This performs an ASCII lowercase only; current locale and UTF-8 encoding is ignored.
* @param str The string to transform in-place. When the function returns the string has been changed to ASCII
* lowercase.
*/
inline void toLower(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), [](char c) { return (char)std::tolower(c); });
}
/**
* Converts a given string to a 32-bit signed integer value.
* @warning This function will truncate values and may lose information even though `true` is returned. It's use is not
* recommended.
* @param str The string to convert. May be a decimal, hexadecimal (`0x` prefix) or octal (`0` prefix) number. A
* floating point value may also be given including with exponential notation, though floating point values will be
* casted to an integer and may lose precision.
* @param[out] outResult The reference that receives the integer result
* @returns `true` if `strtoll` or `strtod` parse \p str in its entirety; `false` otherwise. **NOTE** a return value of
* `true` does not mean that information or precision is not lost!
*/
inline bool stringToInteger(const std::string& str, int32_t& outResult)
{
char* numericEnd;
uint32_t val = (int32_t)strtoll(str.c_str(), &numericEnd, 0);
if (*numericEnd == '\0')
{
outResult = val;
return true;
}
double fVal = strtod(str.c_str(), &numericEnd);
if (*numericEnd == '\0')
{
outResult = static_cast<int32_t>(fVal);
return true;
}
return false;
}
//! Default delimiters for \ref stringToInt2.
constexpr char kInt2Delimiters[] = ",x";
/**
* Converts a string value to an Int2 representation, that is, a two-component vector.
* \details This function attempts to convert values such as `0,-1` or `99x84` into a \ref carb::Int2. The delimiters
* given by \p delims are tried in order, passed along with \p str to \ref split(). If two components are found,
* both components must successfully parse with \ref stringToInteger() in order to consider the result valid.
* @warning See the warnings at \ref stringToInteger() about potential data loss.
* @param str The string to convert
* @param[out] outResult Reference that receives the \ref carb::Int2 result from parsing. Only valid if `true` is
* returned.
* @param delims Delimiters to separate the vector components
* @returns `true` if parsing was successful; `false` otherwise
*/
inline bool stringToInt2(const std::string& str, carb::Int2& outResult, const char* delims = kInt2Delimiters)
{
// try splitting by different delimiters
for (int delimIndex = 0; delims[delimIndex] != 0; delimIndex++)
{
auto delim = delims[delimIndex];
auto pathAndOther = split(str, delim);
if (pathAndOther.size() == 2)
{
int32_t x, y;
if (extras::stringToInteger(pathAndOther[0], x) && extras::stringToInteger(pathAndOther[1], y))
{
outResult = { x, y };
return true;
}
}
}
return false;
}
//! \defgroup stringtrim String Trimming Utilities
//! @{
//! Default whitespace characters for string trimming functions
constexpr char kTrimCharsDefault[] = " \t\n\r\f\v";
/**
* Performs an in-place right-trim on a given string.
* \details This will trim the characters in \p t from the right side of \p s. e.g. given \p s = `" asdf "` with the
* default \p t value, \p s would be modified to contain `" asdf"`. This is effectively
* `s.erase(s.find_last_not_of(t) + 1)`.
* @param s The string to trim in-place
* @param t A string containing the list of characters to trim (such as \ref kTrimCharsDefault)
* @returns \p s for convenience
* @see ltrim(), trim(), trimCopy()
*/
inline std::string& rtrim(std::string& s, const char* t = kTrimCharsDefault)
{
s.erase(s.find_last_not_of(t) + 1);
return s;
}
/**
* Performs an in-place left-trim on a given string.
* \details This will trim the characters in \p t from the left side of \p s. e.g. given \p s = `" asdf "` with the
* default \p t value, \p s would be modified to contain `"asdf "`. This is effectively
* `s.erase(0, s.find_first_not_of(t))`.
* @param s The string to trim in-place
* @param t A string containing the list of characters to trim (such as \ref kTrimCharsDefault)
* @returns \p s for convenience
* @see rtrim(), trim(), trimCopy()
*/
inline std::string& ltrim(std::string& s, const char* t = kTrimCharsDefault)
{
s.erase(0, s.find_first_not_of(t));
return s;
}
/**
* Performs an in-place trim (from both sides) on a given string.
* \details This will trim the characters in \p t from both sides of \p s. e.g. given \p s = `" asdf "` with the
* default \p t value, \p s would be modified to contain `"asdf"`. This is effectively
* `ltrim(rtrim(s, t), t)`.
* @param s The string to trim in-place
* @param t A string containing the list of characters to trim (such as \ref kTrimCharsDefault)
* @returns \p s for convenience
* @see ltrim(), rtrim(), trimCopy()
*/
inline std::string& trim(std::string& s, const char* t = kTrimCharsDefault)
{
return ltrim(rtrim(s, t), t);
}
/**
* Performs a trim (from both sides) on a given string, returning a copy.
* \details This will trim the characters in \p t from both sides of \p s. e.g. given \p s = `" asdf "` with the
* default \p t value, `"asdf"` would be returned. This is effectively `std::string copy(s); return trim(copy);`.
* @param s The string to trim
* @param t A string containing the list of characters to trim (such as \ref kTrimCharsDefault)
* @returns The trimmed string
* @see ltrim(), rtrim(), trim()
*/
inline std::string trimCopy(std::string s, const char* t = kTrimCharsDefault)
{
trim(s, t);
return s;
}
//! @}
/**
* Replaces all instances of a substring within a given string with a replacement value.
* \details This function calls `std::string::replace()` in a loop so that all instances are replaced.
* \note The replacement is not recursive, so \p replaceWith may contain the substring \p subStr without causing endless
* recursion. Whenever a replacement occurs, the search for \p subStr resumes after the inserted \p replaceWith.
* @param str The string to modify in-place
* @param subStr The substring to find within \p str
* @param replaceWith The substring that all instances of \p subStr are replaced with
*/
inline void replaceAll(std::string& str, const std::string& subStr, const std::string& replaceWith)
{
size_t pos = str.find(subStr);
while (pos != std::string::npos)
{
str.replace(pos, subStr.size(), replaceWith);
pos = str.find(subStr, pos + replaceWith.size());
}
}
/**
* Checks two strings for equality in an ASCII case-insensitive manner.
* \warning This function checks for ASCII case-insensitivity only. UTF-8 encoding and locale are ignored.
* @param str1 The first string to compare
* @param str2 The second string to compare
* @returns `true` if the strings are equal when ASCII case is ignored; `false` otherwise
*/
inline bool stringCompareCaseInsensitive(const std::string& str1, const std::string& str2)
{
return ((str1.size() == str2.size()) && std::equal(str1.begin(), str1.end(), str2.begin(), [](char a, char b) {
return std::tolower(a) == std::tolower(b);
}));
}
/**
* Checks if two given file paths are equal with case sensitivity based on the platform.
* \warning For Windows, this function checks for ASCII case-insensitivity only. UTF-8 encoding and locale are ignored.
* Therefore, this function does not work properly with Windows paths that may contain non-ASCII characters and its
* use should be avoided.
* \note This is intended for file paths only. URLs are case sensitive.
* @param strLeft The first path to compare
* @param strRight The second path to compare
* @returns `true` if \p strLeft and \p strRight are equal paths with the caveats presented above; `false` otherwise
*/
inline bool isPathEqual(const std::string& strLeft, const std::string& strRight)
{
#if CARB_PLATFORM_WINDOWS
if (strLeft.size() != strRight.size())
{
return false;
}
return stringCompareCaseInsensitive(strLeft, strRight);
#else
return (strLeft == strRight);
#endif
}
} // namespace extras
} // namespace omni
| 11,124 | C | 35.47541 | 120 | 0.670982 |
omniverse-code/kit/include/omni/extras/PathMap.h | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief A set of helper templates to provide platform specific behavior around path handling.
*/
#pragma once
#include "../core/Platform.h"
#include "../../carb/extras/Utf8Parser.h"
#include "../../carb/CarbWindows.h"
#include <map>
#include <unordered_map>
#if !OMNI_PLATFORM_WINDOWS
# include <algorithm>
#endif
namespace omni
{
/** common namespace for extra helper functions and classes. */
namespace extras
{
#if OMNI_PLATFORM_WINDOWS
/** Custom hash functor for a case sensitive or insensitive hash based on the OS. On Windows
* this allows the keys with any casing to hash to the same bucket for lookup. This reimplements
* the std::hash<std::string> FNV1 functor except that it first lower-cases each character. This
* intentionally avoids allocating a new string that is lower-cased for performance reasons.
* On Linux, this just uses std::hash<> directly which implements a case sensitive hash.
*
* On Windows, note that this uses the Win32 function LCMapStringW() to do the lower case
* conversion. This is done because functions such as towlower() do not properly lower case
* codepoints outside of the ASCII range unless the current codepage for the calling thread
* is set to one that specifically uses those extended characters. Since changing the codepage
* for the thread is potentially destructive, we need to use another way to lower case
* the string's codepoints for hashing.
*/
struct PathHash
{
/** Accumulates a buffer of bytes into an FNV1 hash.
*
* @param[in] value The initial hash value to accumulate onto. For the first call
* in a sequence, this should be std::_FNV_offset_basis.
* @param[in] data The buffer of data to accumulate into the hash. This may not
* be `nullptr`.
* @param[in] bytes The total number of bytes to accumulate into the hash.
* @returns The accumulated hash value. This value is suitable to pass back into this
* function in the @p value parameter for the next buffer being accumulated.
*/
size_t accumulateHash(size_t value, const void* data, size_t bytes) const noexcept
{
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
for (size_t i = 0; i < bytes; i++)
{
value ^= ptr[i];
value *= std::_FNV_prime;
}
return value;
}
/** Case insensitive string hashing operator.
*
* @param[in] key The key string to be hashed. This may be any length and contain any
* UTF-8 codepoints. This may be empty.
* @returns The calculated FNV1 hash of the given string as though it had been converted to
* all lower case first. This will ensure that hashes match for the same string
* content excluding case.
*/
size_t operator()(const std::string& key) const noexcept
{
carb::extras::Utf8Iterator it(key.c_str());
carb::extras::Utf8Iterator::CodePoint cp;
size_t hash = std::_FNV_offset_basis;
size_t count;
int result;
while (it)
{
cp = *it;
it++;
count = carb::extras::Utf8Parser::encodeUtf16CodePoint(cp, &cp);
result = LCMapStringW(CARBWIN_LOCALE_INVARIANT, CARBWIN_LCMAP_LOWERCASE, reinterpret_cast<WCHAR*>(&cp),
(int)count, reinterpret_cast<WCHAR*>(&cp), 2);
if (result != 0)
hash = accumulateHash(hash, &cp, count * sizeof(WCHAR));
}
return hash;
}
};
/** Custom comparison functor for a case insensitive comparison. This does a simple case
* insensitive string comparison on the contents of each string's buffer. The return
* value indicates the ordering of the two string inputs.
*
* Note that this uses the Win32 function LCMapStringW() to do the lower case conversion.
* This is done because functions such as towlower() do not properly lower case codepoints
* outside of the ASCII range unless the current codepage for the calling thread is set
* to one that specifically uses those extended characters. Since changing the codepage
* for the thread is potentially destructive, we need to use another way to lower case
* the strings' codepoints for comparison.
*/
struct PathCompare
{
/** Case insensitive string comparison operator.
*
* @param[in] left The first string to compare. This may be of any length and contain
* any UTF-8 codepoint.
* @param[in] right The second string to compare. This may be of any length and contain
* any UTF-8 codepoint.
* @returns `0` if the two strings are equal disregarding case.
* @returns A negative value if the first string should be lexicographical ordered before
* the second string disregarding case.
* @returns A positive value if the first string should be lexicographical ordered after
* the second string disregarding case.
*/
int32_t operator()(const std::string& left, const std::string& right) const noexcept
{
carb::extras::Utf8Iterator itLeft(left.c_str());
carb::extras::Utf8Iterator itRight(right.c_str());
carb::extras::Utf8Iterator::CodePoint l;
carb::extras::Utf8Iterator::CodePoint r;
size_t countLeft;
size_t countRight;
int resultLeft;
int resultRight;
// walk the strings and compare the lower case versions of each codepoint.
while (itLeft && itRight)
{
l = *itLeft;
r = *itRight;
itLeft++;
itRight++;
countLeft = carb::extras::Utf8Parser::encodeUtf16CodePoint(l, &l);
countRight = carb::extras::Utf8Parser::encodeUtf16CodePoint(r, &r);
resultLeft = LCMapStringW(CARBWIN_LOCALE_INVARIANT, CARBWIN_LCMAP_LOWERCASE, reinterpret_cast<WCHAR*>(&l),
(int)countLeft, reinterpret_cast<WCHAR*>(&l), 2);
resultRight = LCMapStringW(CARBWIN_LOCALE_INVARIANT, CARBWIN_LCMAP_LOWERCASE, reinterpret_cast<WCHAR*>(&r),
(int)countRight, reinterpret_cast<WCHAR*>(&r), 2);
if (l != r)
return l - r;
}
// the strings only match if both ended at the same point and all codepoints matched.
if (!itLeft && !itRight)
return 0;
if (!itLeft)
return -1;
return 1;
}
};
/** Custom greater-than functor for a case insensitive map lookup. This does a simple case
* insensitive string comparison on the contents of each string's buffer.
*/
struct PathGreater
{
bool operator()(const std::string& left, const std::string& right) const noexcept
{
PathCompare compare;
return compare(left, right) > 0;
}
};
/** Custom less-than functor for a case insensitive map lookup. This does a simple case
* insensitive string comparison on the contents of each string's buffer.
*/
struct PathLess
{
bool operator()(const std::string& left, const std::string& right) const noexcept
{
PathCompare compare;
return compare(left, right) < 0;
}
};
/** Custom equality functor for a case insensitive map lookup. This does a simple case
* insensitive string comparison on the contents of each string's buffer.
*/
struct PathEqual
{
bool operator()(const std::string& left, const std::string& right) const noexcept
{
// the two strings are different lengths -> they cannot possibly match => fail.
if (left.length() != right.length())
return false;
PathCompare compare;
return compare(left, right) == 0;
}
};
#else
/** Custom hash functor for a case sensitive or insensitive hash based on the OS. On Windows
* this allows the keys with any casing to hash to the same bucket for lookup. This reimplements
* the std::hash<std::string> FNV1 functor except that it first lower-cases each character. This
* intentionally avoids allocating a new string that is lower-cased for performance reasons.
* On Linux, this just uses std::hash<> directly which implements a case sensitive hash.
*
* On Windows, note that this uses the Win32 function LCMapStringW() to do the lower case
* conversion. This is done because functions such as towlower() do not properly lower case
* codepoints outside of the ASCII range unless the current codepage for the calling thread
* is set to one that specifically uses those extended characters. Since changing the codepage
* for the thread is potentially destructive, we need to use another way to lower case
* the string's codepoints for hashing.
*/
using PathHash = std::hash<std::string>;
/** Custom greater-than functor for a case sensitive or insensitive map lookup. On Windows,
* this does a simple case insensitive string comparison on the contents of each string's buffer.
* On Linux, this performs a case sensitive string comparison.
*/
using PathGreater = std::greater<std::string>;
/** Custom less-than functor for a case sensitive or insensitive map lookup. On Windows, this does
* a simple case insensitive string comparison on the contents of each string's buffer. On
* Linux, this performs a case sensitive string comparison.
*/
using PathLess = std::less<std::string>;
/** Custom equality functor for a case sensitive or insensitive map lookup. On Windows, this does
* a simple case insensitive string comparison on the contents of each string's buffer. On
* Linux, this performs a case sensitive string comparison.
*/
using PathEqual = std::equal_to<std::string>;
#endif
/** @brief A map to store file paths and associated data according to local OS rules.
*
* Templated type to use to create a map from a file name or file path to another object.
* The map implementation is based on the std::map<> implementation. This will treat the
* key as though it is a file path on the local system - on Windows the comparisons will
* be case insensitive while on Linux they will be case sensitive. This is also suitable
* for storing environment variables since they are also treated in a case insensitive manner
* on Windows and case insensitive on Linux.
*
* @tparam T The type for the map to contain as the value for each path name key.
* @tparam Compare The string comparison functor to use when matching path name keys.
*
* @note A std::map<> object is usually implemented as a red-black tree and will take on
* that algorithm's performance and storage characteristics. Please consider this
* when choosing a container type.
*/
template <typename T, class Compare = PathLess>
using PathMap = std::map<std::string, T, Compare>;
/** @brief An unordered map to store file paths and associated data according to local OS rules.
*
* Templated type to use to create an unordered map from a file name or file path to another
* object. The map implementation is based on the std::unordered_map<> implementation. This
* will treat the key as though it is a file path on the local system - on Windows the
* comparisons will be case insensitive while on Linux they will be case sensitive. This
* is also suitable for storing environment variables since they are also treated in a case
* insensitive manner on Windows and case insensitive on Linux.
*
* @tparam T The type for the map to contain as the value for each path name key.
* @tparam Hash The string hashing functor to use to generate hash values for each path
* name key.
* @tparam KeyEqual The string comparison functor to use to test if two path name keys are
* equal
*
* @note A std::unordered_map<> object is usually implemented as a hash table of lists or trees
* and will take on that algorithm's performance and storage characteristics. Please
* consider this when choosing a container type.
*/
template <typename T, class Hash = PathHash, class KeyEqual = PathEqual>
using UnorderedPathMap = std::unordered_map<std::string, T, Hash, KeyEqual>;
} // namespace extras
} // namespace omni
| 12,779 | C | 42.917526 | 119 | 0.679005 |
omniverse-code/kit/include/omni/extras/RtxSettings.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief RTX Settings utilities
//! \todo This should probably not be in Carbonite.
#pragma once
#include "../../carb/dictionary/IDictionary.h"
#include "../../carb/logging/Log.h"
#include "../../carb/settings/ISettings.h"
#include "../../carb/settings/SettingsUtils.h"
#include "../../carb/tasking/TaskingUtils.h"
#include "StringHelpers.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <unordered_map>
#include "md5.h"
namespace rtx
{
/*
Usage:
// init
globalOverrides = Settings::createContext();
vp0Context = Settings::createContext();
// update loop
{
// Frame begin
// clone global settings
Settings::cloneToContext(vp0Context, nullptr);
Settings::getIDictionary()->makeIntAtPath(vp0Context, "path/to/int", 10);
// ...
Settings::applyOverridesToContext(vp0Context, globalOverrides);
// ...
// will have all the overrides
Settings::getIDictionary()->getAsInt(vp0Context, "path/to/int");
}
*/
//! Settings path for RTX default settings.
constexpr char kDefaultSettingsPath[] = "/rtx-defaults";
//! Settings path for RTX settings.
constexpr char kSettingsPath[] = "/rtx";
//! Settings path for persistent default settings.
constexpr char kDefaultPersistentSettingsPath[] = "/persistent-defaults";
//! Settings path for persistent settings.
constexpr char kPersistentSettingsPath[] = "/persistent";
//! Settings path for transient RTX settings.
constexpr char kTransientSettingsPath[] = "/rtx-transient";
//! Settings path for RTX flag settings.
constexpr char kFlagsSettingsPath[] = "/rtx-flags";
// A note on internal setting handling.
// Settings in /rtx-transient/internal and /rtx/internal are automatically mapped to entries in /rtx-transient/hashed
// and /rtx/hashed, respectively. We use the MD5 hash of the full internal setting string as the key inside the "hashed"
// scope. See the comments in InternalSettings.h for more details.
//! Internal setting key.
constexpr char kInternalSettingKey[] = "internal";
//! Hashed setting key
constexpr char kHashedSettingKey[] = "hashed";
//! Settings root keys
constexpr const char* kInternalSettingRoots[] = {
kSettingsPath,
kTransientSettingsPath,
};
//! \defgroup rtxsettingflags RTX Settings Flags
//! @{
//! Setting Flags type definition
typedef uint32_t SettingFlags;
//! Value indicating no settings flags.
constexpr SettingFlags kSettingFlagNone = 0;
//! Indicates that a setting flag is transient.
//! \details Do not read or store in USD. Transient settings automatically disables reset feature. Note that settings
//! under /rtx-transient are transient irrespective of this setting.
constexpr SettingFlags kSettingFlagTransient = 1 << 0;
//! Flag to indicate that resetting of the setting under /rtx-defaults is not allowed.
constexpr SettingFlags kSettingFlagResetDisabled = 1 << 1;
//! Default Setting Flag
constexpr SettingFlags kSettingFlagDefault = kSettingFlagNone;
//! @}
//! Worst case hashed setting root path length.
constexpr size_t kHashedSettingPrefixMaxSize =
carb_max(carb::countOf(kSettingsPath), carb::countOf(kTransientSettingsPath)) + 1 + carb::countOf(kHashedSettingKey);
//! Worst case hashed setting string length.
constexpr size_t kHashedSettingCStringMaxLength = kHashedSettingPrefixMaxSize + MD5::kDigestStringSize + 1;
/**
* A class encapsulating render settings.
*/
class RenderSettings
{
public:
/**
* Statically-sized container for hashed setting strings.
* \details We use MD5 hashes which have constant size, so we can compute the worst case hashed setting string size
* and pass them around on the stack instead of on the heap. In the future this may also help with hashing at build
* time.
*/
struct HashedSettingCString
{
//! String data
char data[kHashedSettingCStringMaxLength];
};
/**
* Checks a path to see if it matches the RTX setting root.
* @param path The path to check
* @returns `true` if \p path compares equal (case sensitive) to \ref kSettingsPath; `false` otherwise
*/
static bool isPathRenderSettingsRoot(const char* path)
{
size_t rtxSettingsPathLen = CARB_COUNTOF(kSettingsPath) - 1;
size_t pathLen = strlen(path);
if (pathLen == rtxSettingsPathLen && strcmp(path, kSettingsPath) == 0)
{
return true;
}
return false;
}
/**
* Translates the given path to the defaults path.
* \details For instance if \p cPath is `"/rtx/foo"`, `"/rtx-defaults/foo"` would be returned.
* @param cPath The path to translate
* @returns The path key in the defaults tree. See details above.
*/
static std::string getAssociatedDefaultsPath(const char* cPath)
{
std::string path(cPath);
size_t pos = path.find_first_of("/", 1);
std::string parentPath;
std::string childPath;
if (pos == std::string::npos)
{
parentPath = path;
}
else
{
parentPath = path.substr(0, pos);
childPath = path.substr(pos);
}
return parentPath + "-defaults" + childPath;
}
/**
* Translates a string into a key-value mapping.
* \details Only two types of `<KeyType, ValueType>` are allowed: `<uint32_t, std::vector<uint32_t>>`, or
* `<std::string, uint32_t>`. A colon (`:`) is the key/value separator and a semicolon (`;`) is the map separator.
* This function first splits \p keyToValueDictStr by (`;`) and then each substring is split by (`:`). If exactly
* two values are found by this second split, the value is added to \p outputDict. When `ValueType` is a
* `std::vector`, the values are found by splitting the value substring by a comma (`,`).
* @tparam KeyType The type of the key. See above for details.
* @tparam ValueType The type of the value. See above for details.
* @param keyToValueDictStr A string that is processed according to the details above
* @param[out] outputDict The `std::unordered_map` that receives processed key/value pairs. This map is not cleared;
* any values that exist in it before this function is called remain, but existing keys that are encountered in
* \p keyToValueDictStr will overwrite existing values (however, if `ValueType` is `std::vector` the values are
* appended to existing values).
* @param debugStr (required) a string that will be used in logging if parse errors occur
*/
template <typename KeyType, typename ValueType>
static void stringToKeyTypeToValueTypeDictionary(const std::string& keyToValueDictStr,
std::unordered_map<KeyType, ValueType>& outputDict,
const char* debugStr)
{
// Convert from string to a dictionary mapping KeyType values to ValueType values
//
// Example syntax: 0:0; 1:1,2; 2:3,4; 3:5; 4:6; 5:6; 6:6; 7;6"
// Example syntax: "AsphaltStandard:0; AsphaltWeathered:1; ConcreteRough:2"
// I.e.: use semicolon (';') to separate dictionary entries from each other,
// use colon (':') to separate key from value and
// use comma (',') to separate entries in a list of values
std::stringstream ss(keyToValueDictStr);
static constexpr char kMappingSep = ';';
static constexpr char kKeyValueSep = ':';
// Split by ';' into key:value mappings
std::vector<std::string> keyToValueStrVec = omni::extras::split(keyToValueDictStr, kMappingSep);
for (auto& keyToValue : keyToValueStrVec)
{
// Split a mapping into its key and value
std::vector<std::string> keyToValueStrVec = omni::extras::split(keyToValue, kKeyValueSep);
if (keyToValueStrVec.size() == 2) // this is a key,value pair
{
// find an appropriate overloaded function to add a key:value pair to the dictionary
addValueAtKey(keyToValueStrVec[0], keyToValueStrVec[1], outputDict, debugStr);
}
}
}
/**
* A helper function to determine if a setting flag path exists.
* @param settings \ref carb::settings::ISettings as if by \ref carb::getCachedInterface()
* @param settingPath The path to check for. \ref kFlagsSettingsPath will be prepended to this value
* @returns `true` if the settings flag exists; `false` otherwise
*/
static inline bool hasSettingFlags(carb::settings::ISettings& settings, const char* settingPath)
{
std::string settingPathStr(kFlagsSettingsPath);
settingPathStr += settingPath;
return settings.getItemType(settingPathStr.c_str()) != carb::dictionary::ItemType::eCount;
}
/**
* A helper function for reading settings flags.
* @param settings \ref carb::settings::ISettings as if by \ref carb::getCachedInterface()
* @param settingPath The path to read. \ref kFlagsSettingsPath will be prepended to this value
* @returns the \ref rtxsettingflags read as an integer from the given \p settingsPath
*/
static inline SettingFlags getSettingFlags(carb::settings::ISettings& settings, const char* settingPath)
{
std::string settingPathStr(kFlagsSettingsPath);
settingPathStr += settingPath;
return SettingFlags(settings.getAsInt(settingPathStr.c_str()));
}
/**
* A helper function for writing settings flags.
* @param settings \ref carb::settings::ISettings as if by \ref carb::getCachedInterface()
* @param settingPath The path to write. \ref kFlagsSettingsPath will be prepended to this value
* @param flags The flags to write. These values will overwrite any existing flags
*/
static inline void setSettingFlags(carb::settings::ISettings& settings, const char* settingPath, SettingFlags flags)
{
std::string settingPathStr(kFlagsSettingsPath);
settingPathStr += settingPath;
settings.setInt64(settingPathStr.c_str(), flags);
}
/**
* A helper function for deleting a settings flags key.
* \post The settings path at \ref kFlagsSettingsPath + \p settingPath is destroyed.
* @param settings \ref carb::settings::ISettings as if by \ref carb::getCachedInterface()
* @param settingPath The path to delete. \ref kFlagsSettingsPath will be prepended to this value
*/
static inline void removeSettingFlags(carb::settings::ISettings& settings, const char* settingPath)
{
std::string settingPathStr(kFlagsSettingsPath);
settingPathStr += settingPath;
settings.destroyItem(settingPathStr.c_str());
}
/**
* Sets the default value for a RTX setting value and backs up the value.
* \details The \ref carb::settings::ISettings API is used to set the default value at \p settingPath if the setting
* key does not exist. If \p flags has neither \ref kSettingFlagTransient and \ref kSettingFlagResetDisabled set,
* then the default path is constructed by \ref getAssociatedDefaultsPath(). If the default path is under the
* `/persistent` root, the default path setting is updated with \p value, otherwise the default path setting is
* updated with the current value read from \p settingPath. Finally, \ref setSettingFlags() is called with
* \p settingPath and \p flags.
* @param settingPath the setting path to set default for and to back up
* @param value the default value to set at \p settingPath
* @param flags \ref rtxsettingflags to apply to \p settingPath
*/
template <typename SettingType>
static void setAndBackupDefaultSetting(const char* settingPath,
SettingType value,
SettingFlags flags = kSettingFlagDefault)
{
carb::settings::ISettings* settings = getISettings();
settings->setDefault<SettingType>(settingPath, value);
bool allowReset = (flags & (kSettingFlagTransient | kSettingFlagResetDisabled)) == 0;
if (allowReset)
{
std::string defaultSettingPath = getAssociatedDefaultsPath(settingPath);
if (!defaultSettingPath.empty())
{
std::string path(defaultSettingPath);
if (path.substr(0, std::strlen(kPersistentSettingsPath)) == kPersistentSettingsPath)
{
settings->set<SettingType>(defaultSettingPath.c_str(), value);
}
else
{
settings->setDefault<SettingType>(
defaultSettingPath.c_str(), settings->get<SettingType>(settingPath));
}
}
}
// Set per setting flag (persistent, etc.)
setSettingFlags(*settings, settingPath, flags);
}
/**
* Returns a hashed setting string based on the given setting path.
* @param s The setting path
* @returns A hashed setting string based on \p s
*/
static inline std::string getInternalSettingString(const char* s)
{
return std::string(getHashedSettingString(s).data);
}
// TODO: Make private? It looks like this function is just subscribed for change events in
// setAndBackupPersistentDefaultSetting.
//! @private
static void updateSetting(const carb::dictionary::Item* changedItem,
carb::dictionary::ChangeEventType eventType,
void* userData)
{
CARB_UNUSED(eventType);
if (!changedItem)
{
CARB_LOG_ERROR("Unexpected setting deletion");
}
const char* path = reinterpret_cast<const char*>(userData);
carb::dictionary::IDictionary* dictionary = getIDictionary();
carb::settings::ISettings* settings = getISettings();
carb::dictionary::ItemType itemType = dictionary->getItemType(changedItem);
if (itemType == carb::dictionary::ItemType::eString)
{
settings->setString(path, dictionary->getStringBuffer(changedItem));
}
else if (itemType == carb::dictionary::ItemType::eFloat)
{
settings->setFloat(path, dictionary->getAsFloat(changedItem));
}
else if (itemType == carb::dictionary::ItemType::eInt)
{
settings->setInt(path, dictionary->getAsInt(changedItem));
}
else if (itemType == carb::dictionary::ItemType::eBool)
{
settings->setBool(path, dictionary->getAsBool(changedItem));
}
}
/**
* Sets a setting value to a given default value and back up the previous value.
* \warning The \p settingPath pointer value is captured by this function. Its lifetime must be for the rest of the
* application, or undefined behavior will occur.
* @tparam SettingType the type of the value
* @param settingPath the setting path to set default for and to back up. **NOTE** see warning above
* @param value The default value to assign
*/
template <typename SettingType>
static void setAndBackupPersistentDefaultSetting(const char* settingPath, SettingType value)
{
carb::settings::ISettings* settings = getISettings();
std::string persistentPath = std::string("/persistent") + settingPath;
settings->setDefault<SettingType>(persistentPath.c_str(), value);
std::string defaultSettingPath = getAssociatedDefaultsPath(persistentPath.c_str());
if (!defaultSettingPath.empty())
{
std::string path(defaultSettingPath);
if (path.substr(0, std::strlen(kPersistentSettingsPath)) == kPersistentSettingsPath)
{
settings->set<SettingType>(defaultSettingPath.c_str(), value);
}
else
{
settings->set<SettingType>(
defaultSettingPath.c_str(), settings->get<SettingType>(persistentPath.c_str()));
}
}
settings->subscribeToNodeChangeEvents(
persistentPath.c_str(), RenderSettings::updateSetting, (void*)(settingPath));
settings->set<SettingType>(settingPath, settings->get<SettingType>(persistentPath.c_str()));
}
/**
* Sets a setting value to a given array value and backs up the previous value.
* @tparam SettingArrayType the type of the elements of the array
* @param settingPath the setting path to set default for and to back up
* @param array The array of values to assign as the default for \p settingPath
* @param arrayLength The number of items in \p array
* @param flags \ref rtxsettingflags to apply to \p settingPath
*/
template <typename SettingArrayType>
static void setAndBackupDefaultSettingArray(const char* settingPath,
const SettingArrayType* array,
size_t arrayLength,
SettingFlags flags = kSettingFlagDefault)
{
carb::settings::ISettings* settings = getISettings();
settings->setDefaultArray<SettingArrayType>(settingPath, array, arrayLength);
bool allowReset = (flags & (kSettingFlagTransient | kSettingFlagResetDisabled)) == 0;
if (allowReset)
{
std::string defaultSettingPath = getAssociatedDefaultsPath(settingPath);
if (!defaultSettingPath.empty())
{
settings->destroyItem(defaultSettingPath.c_str());
size_t arrayLength = settings->getArrayLength(settingPath);
for (size_t idx = 0; idx < arrayLength; ++idx)
{
std::string elementPath = std::string(settingPath) + "/" + std::to_string(idx);
std::string defaultElementPath = std::string(defaultSettingPath) + "/" + std::to_string(idx);
settings->setDefault<SettingArrayType>(
defaultElementPath.c_str(), settings->get<SettingArrayType>(elementPath.c_str()));
}
}
}
// Set per setting flag (persistent, etc.)
setSettingFlags(*settings, settingPath, flags);
}
/**
* Reads the default value for the given path and restores it.
* @param path The setting path to restore
*/
static void resetSettingToDefault(const char* path)
{
carb::dictionary::IDictionary* dictionary = getIDictionary();
carb::settings::ISettings* settings = getISettings();
std::string defaultsPathStorage;
defaultsPathStorage = getAssociatedDefaultsPath(path);
const carb::dictionary::Item* srcItem = settings->getSettingsDictionary(defaultsPathStorage.c_str());
carb::dictionary::ItemType srcItemType = dictionary->getItemType(srcItem);
size_t srcItemArrayLength = dictionary->getArrayLength(srcItem);
if ((srcItemType == carb::dictionary::ItemType::eDictionary) && (srcItemArrayLength == 0))
{
resetSectionToDefault(path);
return;
}
switch (srcItemType)
{
case carb::dictionary::ItemType::eBool:
{
settings->set<bool>(path, dictionary->getAsBool(srcItem));
break;
}
case carb::dictionary::ItemType::eInt:
{
settings->set<int32_t>(path, dictionary->getAsInt(srcItem));
break;
}
case carb::dictionary::ItemType::eFloat:
{
settings->set<float>(path, dictionary->getAsFloat(srcItem));
break;
}
case carb::dictionary::ItemType::eString:
{
settings->set<const char*>(path, dictionary->getStringBuffer(srcItem));
break;
}
case carb::dictionary::ItemType::eDictionary:
{
if (srcItemArrayLength > 0)
{
settings->update(path, srcItem, nullptr, carb::dictionary::kUpdateItemOverwriteOriginal, nullptr);
}
break;
}
default:
break;
}
}
/**
* Restores the subtree at the given path from the backed up values.
* @param path The subtree setting path
*/
static void resetSectionToDefault(const char* path)
{
carb::settings::ISettings* settings = getISettings();
std::string defaultsPathStorage;
const char* defaultsPath = nullptr;
defaultsPathStorage = getAssociatedDefaultsPath(path);
if (!defaultsPathStorage.empty())
{
defaultsPath = defaultsPathStorage.c_str();
}
if (defaultsPath)
{
// Do not delete existing original settings.
// If the source item exists (rtx-default value), overwrite the destination (original rtx value).
// Otherwise, leave them as-is. We want to keep original values until we find some default values in the
// future. Plugins may load at a later time and we should not remove original values until we have some
// default values.
settings->update(path, settings->getSettingsDictionary(defaultsPath), nullptr,
carb::dictionary::kUpdateItemOverwriteOriginal, nullptr);
}
else
{
CARB_LOG_ERROR("%s: failed to resolve default paths", __func__);
}
}
/**
* Creates a root level dictionary item.
* \details This item is created as via \ref carb::dictionary::IDictionary::createItem() with `<rtx context>` as the
* name.
* @returns a \ref carb::dictionary::Item that is of type \ref carb::dictionary::ItemType::eDictionary
*/
static carb::dictionary::Item* createContext()
{
return getIDictionary()->createItem(nullptr, "<rtx context>", carb::dictionary::ItemType::eDictionary);
}
/**
* Helper function to destroy a dictionary item.
* \details This function is a helper function to call \ref carb::dictionary::IDictionary::destroyItem().
* @param ctx the \ref carb::dictionary::Item to destroy
*/
static void destroyContext(carb::dictionary::Item* ctx)
{
getIDictionary()->destroyItem(ctx);
}
/**
* Copies a source context to a destination context.
* \warning This function appears to have a bug where \p dstContext is used after destroyed if \p srcContext is not
* `nullptr`.
* @param dstContext The destination context to overwrite
* @param srcContext The source context to copy to \p dstContext. Maybe `nullptr` to re-initialize \p dstContext.
*/
static void cloneToContext(carb::dictionary::Item* dstContext, carb::dictionary::Item* srcContext)
{
carb::dictionary::IDictionary* dict = getIDictionary();
carb::settings::ISettings* settings = getISettings();
dict->destroyItem(dstContext);
if (srcContext)
{
// TODO: It is undefined behavior to use dstContext after destroyItem above
dict->update(dstContext, "", srcContext, "", carb::dictionary::kUpdateItemOverwriteOriginal, nullptr);
}
else
{
dstContext = settings->createDictionaryFromSettings(kSettingsPath);
}
}
/**
* Copies a subtree over the destination subtree.
* @param dstContext The destination to overwrite
* @param overridesContext The subtree to write over \p dstContext
*/
static void applyOverridesToContext(carb::dictionary::Item* dstContext, carb::dictionary::Item* overridesContext)
{
if (!overridesContext)
{
CARB_LOG_ERROR("%s needs context to override from", __FUNCTION__);
}
carb::dictionary::IDictionary* dict = getIDictionary();
dict->update(dstContext, "", overridesContext, "", carb::dictionary::kUpdateItemOverwriteOriginal, nullptr);
}
/**
* Dictionary access helper function.
* @returns \ref carb::dictionary::IDictionary as by \ref carb::getCachedInterface()
*/
static carb::dictionary::IDictionary* getIDictionary()
{
return carb::getCachedInterface<carb::dictionary::IDictionary>();
}
/**
* Settings access helper function.
* @returns \ref carb::settings::ISettings as by \ref carb::getCachedInterface()
*/
static carb::settings::ISettings* getISettings()
{
return carb::getCachedInterface<carb::settings::ISettings>();
}
/**
* Translates plaintext internal settings to hashed settings and removes the plaintext settings.
* \details This is to ensure that the plaintext internal settings are not inadvertently saved to USD.
*/
static void hashInternalRenderSettings()
{
auto settings = getISettings();
auto hashRtxSetting = [&settings](const char* itemPath, uint32_t, void*) -> uint32_t {
const carb::dictionary::ItemType itemType = settings->getItemType(itemPath);
if (itemType == carb::dictionary::ItemType::eDictionary)
{
return 0;
}
const auto newHashedPath = getHashedSettingString(itemPath);
switch (settings->getItemType(itemPath))
{
case carb::dictionary::ItemType::eBool:
settings->setBool(newHashedPath.data, settings->getAsBool(itemPath));
break;
case carb::dictionary::ItemType::eFloat:
settings->setFloat(newHashedPath.data, settings->getAsFloat(itemPath));
break;
case carb::dictionary::ItemType::eInt:
settings->setInt(newHashedPath.data, settings->getAsInt(itemPath));
break;
case carb::dictionary::ItemType::eString:
settings->setString(newHashedPath.data, settings->getStringBuffer(itemPath));
break;
case carb::dictionary::ItemType::eDictionary:
CARB_FALLTHROUGH;
default:
CARB_ASSERT(0);
}
if (hasSettingFlags(*settings, itemPath))
{
setSettingFlags(*settings, newHashedPath.data, getSettingFlags(*settings, itemPath));
removeSettingFlags(*settings, itemPath);
}
return 0;
};
carb::dictionary::IDictionary* dictionary = getIDictionary();
for (const char* root : kInternalSettingRoots)
{
std::stringstream ss;
ss << root << '/' << kInternalSettingKey;
const std::string internalRoot = ss.str();
carb::settings::walkSettings(dictionary, settings, carb::dictionary::WalkerMode::eSkipRoot,
internalRoot.c_str(), 0, hashRtxSetting, nullptr);
settings->destroyItem(internalRoot.c_str());
}
}
private:
// Key : Value = uint32_t : std::vector<uint32_t>
static void addValueAtKey(std::string key,
std::string value,
std::unordered_map<uint32_t, std::vector<uint32_t>>& outputDict,
const char* debugStr)
{
static const char kListElemSep = ',';
int intKey = 0;
if (!omni::extras::stringToInteger(key, intKey))
{
CARB_LOG_WARN("Non-integer value %s set in \"%s\"", key.c_str(), debugStr);
}
// Split the value into a list of values
std::vector<std::string> intVecStrVec = omni::extras::split(value, kListElemSep);
int32_t intVecValueEntry = 0;
outputDict[intKey].clear();
for (auto& intVecValueEntryStr : intVecStrVec)
{
if (omni::extras::stringToInteger(intVecValueEntryStr, intVecValueEntry))
{
outputDict[intKey].push_back(intVecValueEntry);
}
else
{
CARB_LOG_WARN("Non-integer value %s set in \"%s\"", intVecValueEntryStr.c_str(), debugStr);
}
}
}
// Key : Value = std::string : uint32_t
static void addValueAtKey(std::string key,
std::string value,
std::unordered_map<std::string, uint32_t>& outputDict,
const char* debugStr)
{
int32_t outInt = 0;
if (omni::extras::stringToInteger(value, outInt))
{
outputDict[key] = outInt;
}
else
{
CARB_LOG_WARN("Non-integer value %s set in \"%s\"", key.c_str(), debugStr);
}
}
static HashedSettingCString getHashedSettingString(const char* settingStr)
{
constexpr size_t sizeOfRtxSettingsRoot = carb::countOf(kSettingsPath) - 1;
const bool isRtxSettingsPath =
strncmp(settingStr, kSettingsPath, sizeOfRtxSettingsRoot) == 0 && settingStr[sizeOfRtxSettingsRoot] == '/';
// Default to kTransientSettingsPath for anything outside /rtx/.
// We don't promise that anything works for paths not rooted in /rtx[-transient]/internal, but implement
// reasonable behavior rather than crash or map all invalid settings to a null string. Improperly rooted strings
// will work fine except that hashInternalRenderSettings() won't know to translate them.
const char* hashedRoot = isRtxSettingsPath ? kSettingsPath : kTransientSettingsPath;
return getHashedSettingString(
MD5::getDigestString(MD5::run((const uint8_t*)settingStr, strlen(settingStr))), hashedRoot);
}
static HashedSettingCString getHashedSettingString(const MD5::DigestString& digestStr, const char* root)
{
HashedSettingCString result = {};
char* s = std::copy_n(root, strlen(root), result.data);
*s++ = '/';
s = std::copy_n(kHashedSettingKey, carb::countOf(kHashedSettingKey) - 1, s);
*s++ = '/';
s = std::copy_n(digestStr.s, MD5::kDigestStringSize, s);
*s = '\0';
return result;
}
};
/**
* Dummy function.
* \todo remove this?
* @returns `false`
*/
inline bool enableAperture()
{
// Enabling Aperture mode adds 2 ray types.
return false;
}
/**
* Caches and returns the value of "/rtx/mdltranslator/distillMaterial".
* \details The value is read from \ref carb::settings::ISettings once and cached; future calls to this function are
* very fast.
* @thread_safety This function is thread safe.
* @returns The value read from `/rtx/mdltranslator/distillMaterial`
*/
inline bool enableMDLDistilledMtls()
{
auto&& init = [] {
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
return settings->getAsBool("/rtx/mdltranslator/distillMaterial");
};
static bool result = init();
return result;
}
/**
* Caches and returns whether the value of "/rtx/rendermode" is "abisko".
* \details The value is read from \ref carb::settings::ISettings once and cached; future calls to this function are
* very fast.
* @thread_safety This function is thread safe.
* @returns `true` if the value read from `/rtx/rendermode` is equal to `abisko`
*/
inline bool enableAbiskoMode()
{
auto&& init = [] {
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
const char* renderMode = settings->getStringBuffer("/rtx/rendermode");
return strcmp(renderMode, "abisko") == 0;
};
static bool result = init();
return result;
}
// Returns how many ray types we are going to use during the whole Kit rendering. This CAN'T be changed once the
// renderer is initialized
/**
* Returns how many ray types the renderer will use based on settings.
* \details This value cannot be changed once the renderer is initialized. This value is read from
* \ref carb::settings::ISettings the first time this function is called and cached so that future calls are very
* fast.
* @thread_safety This function is thread safe.
* @returns The number of ray types the renderer will use
*/
inline uint32_t getRayTypeCount()
{
auto&& init = [] {
uint32_t rayCount = 2; // MATERIAL_RAY and VISIBILITY_RAY for RTX are always available
if (!rtx::enableAbiskoMode()) // Abisko only has two ray types
{
if (rtx::enableAperture())
{
rayCount += 2; // APERTURE_MATERIAL_RAY and APERTURE_VISIBILTY_RAY
}
if (rtx::enableMDLDistilledMtls())
{
rayCount += 1; // DISTILLED_MATERIAL_RAY
}
}
return rayCount;
};
static uint32_t result = init();
return result;
}
/**
* A helper function that atomically sets the setting value at path if and only if it doesn't exist.
* @param settings \ref carb::settings::ISettings as if by \ref carb::getCachedInterface()
* @param path The settings path to check
* @param value The value to write to \p path if it doesn't exist
* @retval true The value did not exist and was atomically set to \p value
* @retval false The value already existed and was not set
*/
inline bool setDefaultBoolEx(carb::settings::ISettings* settings, const char* path, bool value)
{
// Unfortunately need a write lock since we might be writing
carb::dictionary::ScopedWrite writeLock(*carb::getCachedInterface<carb::dictionary::IDictionary>(),
const_cast<carb::dictionary::Item*>(settings->getSettingsDictionary(path)));
if (settings->getItemType(path) != carb::dictionary::ItemType::eCount)
return false;
settings->setBool(path, value);
return true;
}
} // namespace rtx
| 34,487 | C | 39.95962 | 121 | 0.635051 |
omniverse-code/kit/include/omni/extras/DataStreamer.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../log/ILog.h"
#include "../../carb/events/IEvents.h"
#include "../../carb/events/EventsUtils.h"
#include "../../carb/tasking/ITasking.h"
#include "../../carb/tasking/TaskingUtils.h"
#include "../../carb/RString.h"
namespace omni
{
namespace extras
{
/** An ID that identifies a data type. */
using DataStreamType = int64_t;
/** The event type when an event contains data.
* If you need to send other events through the stream, you can use another ID.
*/
constexpr carb::events::EventType kEventTypeData = 0;
/** Generate a unique ID for a specific data type.
* @tparam T The type to generate an ID for.
* @returns A unique ID for T.
*/
template <typename T>
DataStreamType getDataStreamType() noexcept
{
#if CARB_COMPILER_MSC
return carb::fnv1aHash(__FUNCSIG__);
#elif CARB_COMPILER_GNUC
return carb::fnv1aHash(__PRETTY_FUNCTION__);
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/** This allows a series of ordered packets of raw binary data to be sent
* through @ref carb::events::IEvents.
*
* To use this class, the data producer will call pushData() whenever it has
* a packet of data, then it will either call pump() or pumpAsync() to send
* the data to the listeners.
*
* It's also possible to grab the underlying event stream and send other events
* through for the listener to consume.
*
* Each listener should call getEventStream() and use it to construct a
* @ref DataListener implementation.
*/
class DataStreamer
{
public:
DataStreamer() noexcept
{
m_events = carb::getFramework()->tryAcquireInterface<carb::events::IEvents>();
if (m_events == nullptr)
{
OMNI_LOG_ERROR("unable to acquire IEvents");
return;
}
m_tasking = carb::getFramework()->tryAcquireInterface<carb::tasking::ITasking>();
if (m_tasking == nullptr)
{
OMNI_LOG_ERROR("unable to acquire ITasking");
return;
}
m_eventStream = m_events->createEventStream();
if (!m_eventStream)
{
OMNI_LOG_ERROR("unable to create an event stream");
return;
}
m_initialized = true;
}
~DataStreamer() noexcept
{
flush();
}
/** Synchronously submit a packet of data to all listeners.
*
* @remarks This will call the onDataReceived() function for all listeners
* on the current thread.
* The onDataReceived() calls are serialized, so this can be
* called concurrently with pumpAsync() or other calls to pump().
*/
void pump() noexcept
{
if (!m_initialized)
{
return;
}
m_throttler.acquire();
m_eventStream->pump();
m_throttler.release();
}
/** Asynchronously submit a packet of data to all listeners.
*
* @remarks This will spawn a task which calls the onDataReceived()
* function for all listeners.
*
* @note To verify that all tasks have finished, you must call flush().
* This is automatically done when deleting the class instance.
*/
void pumpAsync(carb::tasking::Priority priority = carb::tasking::Priority::eLow) noexcept
{
if (!m_initialized)
{
return;
}
m_tasking->addThrottledTask(m_throttler, priority, m_tasks, [this] { m_eventStream->pump(); });
}
/** Push a new packet of data into the stream.
*
* @tparam T The type pointed to by @p data.
* This type will be copied around, so it must be trivially copyable.
* @param[in] data The data packet to submit to the stream.
* The data in this pointer is copied, so the pointer is
* is safe to be invalidated after this call returns.
* @param[in] size The length of @p data in elements.
*
* @remarks After a packet of data is placed in the stream, it will just be
* queued up.
* For each call to pushData(), there should be a corresponding
* call to pump() or pumpAsync() to dequeue that packet and send
* it to the listeners.
*/
template <typename T>
void pushData(const T* data, size_t size) noexcept
{
static_assert(std::is_trivially_copyable<T>::value, "non-trivially-copyable types will not work here");
if (!m_initialized)
{
return;
}
m_eventStream->push(
kEventTypeData,
std::make_pair("data", carb::cpp::string_view(reinterpret_cast<const char*>(data), size * sizeof(T))),
std::make_pair("type", getDataStreamType<T>()));
}
/** Retrieve the event stream used by the data streamer.
* @returns The event stream used by the data streamer.
*
* @remarks This event stream can be subscribed to, but you can also send
* further events on this stream as long as their type is not
* @ref kEventTypeData.
*/
carb::events::IEventStreamPtr getEventStream() noexcept
{
return m_eventStream;
}
/** Check if the class actually initialized successfully.
* @returns whether the class actually initialized successfully.
*/
bool isWorking() noexcept
{
return m_initialized;
}
/** Wait for all asynchronous tasks created by pumpAsync() to finish. */
void flush() noexcept
{
CARB_LOG_INFO("waiting for all tasks to finish");
m_tasks.wait();
CARB_LOG_INFO("all tasks have finished");
}
private:
/** The events interface. */
carb::events::IEvents* m_events;
/** The tasking interface, which we need for pumpAsync(). */
carb::tasking::ITasking* m_tasking;
/** The event stream we're using to queue and send data. */
carb::events::IEventStreamPtr m_eventStream;
/** A group to hold all of our tasks so we can shut down safely. */
carb::tasking::TaskGroup m_tasks;
/** This is used to serialize calls to @ref m_eventStream->pump(). */
carb::tasking::SemaphoreWrapper m_throttler{ 1 };
/** Flag to specify whether the class initialized properly. */
bool m_initialized = false;
};
/** This is an abstract class that allows data from a @ref DataStreamer to be
* received in an easy way.
*
* The listener implementation just needs to add an onDataReceived() call to
* receive the raw binary data and an onEventReceived() call to handle any
* other events that may be sent on the stream.
*/
class DataListener
{
public:
/** Constructor.
* @param[in] stream The event stream from a @ref DataStreamer to listen to.
*/
DataListener(carb::events::IEventStreamPtr stream) noexcept
{
m_dict = carb::getFramework()->tryAcquireInterface<carb::dictionary::IDictionary>();
if (m_dict == nullptr)
{
OMNI_LOG_ERROR("failed to acquire IDictionary");
return;
}
m_sub = carb::events::createSubscriptionToPop(stream.get(),
[this](const carb::events::IEvent* e) {
if (e->type != kEventTypeData)
{
onEventReceived(e);
return;
}
const carb::dictionary::Item* child;
child = m_dict->getItem(e->payload, "type");
if (child == nullptr)
{
OMNI_LOG_ERROR("the event had no /type field?");
return;
}
DataStreamType type = m_dict->getAsInt64(child);
child = m_dict->getItem(e->payload, "data");
if (child == nullptr)
{
OMNI_LOG_ERROR("the event had no /data field?");
return;
}
size_t len;
const char* bytes = m_dict->getStringBuffer(child, &len);
onDataReceived(bytes, len, type);
},
0, "DataListener");
}
virtual ~DataListener() noexcept
{
// in case disconnect() has additional functionality in the future
disconnect();
}
protected:
/** The function that will receive data packets.
* @param[in] payload The packet of data that was received.
* This pointer will be invalid after this call returns,
* so it must not be held.
* Due to the nature of @ref carb::events::IEvents, there
* is no guarantee that the alignment of this data will
* be correct, so you should memcpy it into a separate
* buffer first to be safe.
* @param[in] bytes The length of @p payload in bytes.
* @param[in] type The data type ID of the data contained in @p payload.
*/
virtual void onDataReceived(const void* payload, size_t bytes, DataStreamType type) noexcept = 0;
/** The function that will receive non-data events from the stream.
* @param[in] e The event that was received.
*/
virtual void onEventReceived(const carb::events::IEvent* e) noexcept = 0;
/** Disconnect this listener from the event stream.
* @remarks This might be useful if your information wants to do something
* during shutdown that would crash if an event was received
* concurrently.
*/
void disconnect() noexcept
{
m_sub = nullptr;
}
/** The dictionary interface used to read the event payloads. */
carb::dictionary::IDictionary* m_dict = nullptr;
private:
/** The event subscription used for this stream. */
carb::events::ISubscriptionPtr m_sub;
};
} // namespace extras
} // namespace omni
| 11,347 | C | 36.206557 | 115 | 0.547986 |
omniverse-code/kit/include/omni/extras/SettingsHelpers.h | // Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Helpers for carb.settings
#pragma once
#include "../../carb/settings/SettingsUtils.h"
#include <string>
#include <vector>
namespace carb
{
namespace settings
{
/**
* Access a setting key if present, otherwise returning a default value.
* \details This function does not use the \ref carb::settings::ISettings API to set the value as a default if \p path
* does not exist. In order to do that, use \ref setDefaultAndGetSetting().
* @tparam T the type of the return value and default value
* @param path The setting key path to check
* @param defaultValue The default value to return if the setting key does not exist
* @returns The value read from \p path, or \p defaultValue if the setting key does not exist
*/
template <typename T>
T getSettingOrDefault(const char* path, T defaultValue = {})
{
ISettings* s = getCachedInterface<ISettings>();
if (s->getItemType(path) == dictionary::ItemType::eCount)
return defaultValue;
return s->get<T>(path);
}
/**
* Sets a default value for a setting key and returns the current value.
* \details Setting a default value will only have an effect if the setting key is not already present. The distinction
* between this function and \ref getSettingOrDefault() is that this function will set the default value with the
* \ref carb::settings::ISettings API. Any attempts to query the key directly will return the default value if it has
* not been modified.
* @tparam T the type of the return value and default value
* @param path The setting key path
* @param defaultValue The default value to set for the setting key if it does not exist
* @return The current value read from \p path, which will be \p defaultValue if the setting key did not exist before
* this function was called.
*/
template <typename T>
T setDefaultAndGetSetting(const char* path, T defaultValue = {})
{
ISettings* s = getCachedInterface<ISettings>();
s->setDefault<T>(path, defaultValue);
return s->get<T>(path);
}
/**
* Appends a set of string values to the end of a setting key.
* @see carb::settings::ISettings
* @param path The setting key path containing a string array. If the key does not exist it will be created. If the key
* is already present as a different type it will be changed to a string array.
* @param values A `std::vector` of string values to add to the end of the string array at the setting key
*/
inline void appendToStringArray(const char* path, const std::vector<std::string>& values)
{
if (values.empty())
return;
ISettings* s = getCachedInterface<ISettings>();
// Hold a write lock while the modification takes place
carb::dictionary::ScopedWrite writeLock(
*getCachedInterface<dictionary::IDictionary>(), const_cast<dictionary::Item*>(s->getSettingsDictionary("/")));
// TODO: This could be implemented a lot more efficiently than fully copying everything twice
std::vector<std::string> v = settings::getStringArray(s, path);
v.insert(v.end(), values.begin(), values.end());
settings::setStringArray(s, path, v);
}
} // namespace settings
} // namespace carb
| 3,585 | C | 41.188235 | 119 | 0.730544 |
omniverse-code/kit/include/omni/extras/UniqueApp.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Helper class to manage a unique process.
*/
#pragma once
#include "../core/Omni.h"
#include <string>
#if OMNI_PLATFORM_WINDOWS
# include "../../carb/CarbWindows.h"
# include "../../carb/extras/WindowsPath.h"
#else
# include <unistd.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
#endif
namespace omni
{
/** common namespace for extra helper functions and classes. */
namespace extras
{
/** Helper class to manage a unique app. A unique app is one that is intended to only
* run a single instance of it at any given time. This contains helper functions to handle
* common tasks that are intended to be used on both the unique app's side and on the host
* app side. This contains two major sets of helper functions.
* * One set is to manage the uniqueness of the app itself. These can either be called
* entirely from within the unique app process after launch to determine if another
* instance of the app is already running and that the new one should exit immediately.
* Alternatively, the launching host app could also first check if the unique app process
* is already running before deciding to launch it in the first place.
* * The other set is to manage notifying the unique app process when it should exit
* naturally. These functions setup a signal that a host app is still running that
* the unique app can then poll on. The host app is responsible for setting its
* 'running' signal early on its launch. The unique app process will then periodically
* poll to see if any host apps are still running.
*
* Note that a 'connection' to the unique app is not actually a connection in a communication
* sense. This is more akin to a reference count on an object that the operating system will
* manage regardless of how the host app exits or stops running. The 'connection' can exist
* for the host app before the unique app is even launched (in fact, this behavior is preferred
* since it simplifies polling and avoids the possibility of an unintentional early exit).
* The host app's 'connection' to the unique app does not require any actual communication, just
* that the connection object remain open until it is either explicitly closed or the host app
* process exits.
*/
class UniqueApp
{
public:
/** Constructor: creates a new unique app object with default settings.
*
* This creates a new object with all default settings. Note that this will use the default
* guard name. If the caller doesn't set a different guard name with @ref setGuardName(),
* the uniqueness of the app represented by this object may conflict with other apps that
* also use that name.
*/
UniqueApp() = default;
/** Constructor: creates a new unique app object with explicit settings.
*
* @param[in] guardPath The directory to store the various guard files in. This may not
* be `nullptr`. This may be a relative or absolute path. If this
* is an empty string, the current directory will be used instead.
* @param[in] guardName The prefix to use for the guard objects. This may not be
* `nullptr`. If this is an empty string, the default prefix will
* be used. This should be a name that is unique to the app being
* launched. However, all instances trying to launch that single
* unique app must use the same guard name.
*
* This creates a new object with explicit settings for the guard path and guard names.
* This is a convenience shortcut for creating an object with default settings, then
* changing the guard path and guard name manually using @ref setGuardPath() and
* @ref setGuardName().
*/
UniqueApp(const char* guardPath, const char* guardName)
{
setGuardPath(guardPath);
setGuardName(guardName);
}
~UniqueApp()
{
// Note: We are *intentionally* leaking any created guard objects here. If either of
// them were to be closed on destruction of the object, undesirable effects would
// result:
// * If the launch guard was created, closing it would allow other instances
// of the unique app to successfully launch.
// * If this process 'connected' to the unique app process, closing the exit
// guard object would remove its reference and could allow the unique app to
// exit prematurely thinking all of its 'clients' had exited already.
//
// An alternative to this would require forcing all callers to store the created
// object at a global level where it would live for the duration of the process.
// While this is certainly possible, enforcing that would be difficult at best.
}
/** Sets the path to put the guard file(s) in.
*
* @param[in] path The directory to store the various guard files in. This may not
* be `nullptr`. This may be a relative or absolute path. If this is
* an empty string, the current directory will be used instead.
* @returns no return value.
*
* @note If the given path or any components on it do not exist at the time a guard
* file is being created, any missing directories will be created. This only
* occurs when a guard file is being used however, not directly during this call.
*
* @thread_safety This call is not thread safe. It is the caller's responsibility to
* ensure this call is protected.
*/
void setGuardPath(const char* path)
{
if (path[0] == 0 || path == nullptr)
path = ".";
m_guardPath = path;
}
/** Sets the name for the guard file(s).
*
* @param[in] name The prefix to use for the guard objects. This may not be `nullptr`.
* If this is an empty string, the default prefix will be used. This
* should be a name that is unique to the app being launched. However,
* all instances trying to launch that single unique app must use the
* same guard name.
* @returns no return value.
*
* @thread_safety This call is not thread safe. It is the caller's responsibility to
* ensure this call is protected.
*/
void setGuardName(const char* name)
{
if (name[0] == 0 || name == nullptr)
name = kDefaultNamePrefix;
m_guardName = name;
}
/** Creates the run guard object for the unique app.
*
* @returns `true` if the unique app launch guard was newly created successfully. Returns
* `false` if the launch guard could not be created or it was already created by
* another process.
*
* This creates the run guard object that is used to determine if the unique app is
* already running. This is intended to be called exactly once from the unique app's
* process early during its startup. The guard object that is created will exist for the
* remaining lifetime of the unique app's process. Once the process that calls this exits,
* the object will be cleaned up by the operating system.
*
* The @ref checkLaunchGuard() function is intended to be used to determine if this
* object still exists. It may be called either from within the unique app itself
* to determine if new launches of it should just exit, or it may called from a host app
* to determine whether to launch the unique app in the first place. This function
* however is intended to be called from the unique app itself and acts as both the
* guard object creation and a check for its existence.
*
* @thread_safety This call is not thread safe. It is the caller's responsibility to
* ensure calls to it are protected. However, since this is intended
* to work between multiple processes, thread safety is not necessarily the
* main concern and a race condition may still be possible. This is intended
* to only be called once from the creating process.
*/
bool createLaunchGuard()
{
FileHandle handle;
// this process has already created the launch guard object -> nothing to do => succeed.
if (m_launchGuard != kBadFileHandle)
return true;
#if OMNI_PLATFORM_WINDOWS
std::string name = m_guardName + kLaunchLockExtension;
handle = CreateEventA(nullptr, false, false, name.c_str());
if (handle == nullptr)
return false;
if (GetLastError() == CARBWIN_ERROR_ALREADY_EXISTS)
{
CloseHandle(handle);
return false;
}
#else
std::string path = _getGuardName(kLaunchLockExtension).c_str();
handle = _openFile(path.c_str());
if (handle == kBadFileHandle)
return false;
if (!_lockFile(handle, LockType::eExclusive))
{
close(handle);
return false;
}
#endif
// save the exit guard event so we can destroy it later.
m_launchGuard = handle;
// intentionally 'leak' the guard handle here. This will keep the handle open for the
// entire remaining duration of the process. This is important because the existence
// of the guard object is what is used by other host apps to determine if the unique
// app is already running. Once the unique app process exits (or it makes a call to
// @ref destroyLaunchGuard()), the OS will automatically close the guard object.
return true;
}
/** Destroys the locally created launch guard object.
*
* @returns No return value.
*
* This destroys the launch guard object that was most recently created with
* @ref createLaunchGuard(). The launch guard object can be recreated with another
* call to @ref createLaunchGuard() later.
*
* @thread_safety This call is not thread safe. It is the caller's responsibility to
* ensure any calls are protected. However, note that since this is a
* global object potentially used for interprocess operations, there may
* still be a possible race condition with its use.
*/
void destroyLaunchGuard()
{
FileHandle fp = m_launchGuard;
m_launchGuard = kBadFileHandle;
_closeFile(fp);
}
/** Tests whether the unique app is already running.
*
* @returns `true` if the unique app is currently running. Returns `false` if the
* unique app is not running or if the guard object could not be accessed.
*
* This tests whether the unique app is currently running. This is done by trying
* to detect whether the guard object exists in the system. When the unique app process
* exits (naturally or otherwise), the operating system will remove the guard object
* automatically.
*
* This call differs from @ref createLaunchGuard() in that this will not create the guard
* object if it does not already exist. This is intended to be used from host apps before
* launching the unique app instead of checking for uniqueness from the unique app itself.
*
* @thread_safety This call is technically thread safe on Windows. On Linux it is thread
* safe as long as @ref setGuardPath() is not called concurrently. However,
* since it is meant to test for an object that is potentially owned by
* another process there may still be race conditions that could arise.
*/
bool checkLaunchGuard()
{
#if OMNI_PLATFORM_WINDOWS
HANDLE event;
DWORD error;
std::string name = m_guardName + kLaunchLockExtension;
event = CreateEventA(nullptr, false, false, name.c_str());
// failed to create the event handle (?!?) => fail.
if (event == nullptr)
return false;
error = GetLastError();
CloseHandle(event);
return error == CARBWIN_ERROR_ALREADY_EXISTS;
#else
FileHandle fp;
bool success;
fp = _openFile(_getGuardName(kLaunchLockExtension).c_str());
if (fp == kBadFileHandle)
return false;
success = _lockFile(fp, LockType::eExclusive, LockAction::eTest);
_closeFile(fp);
return !success;
#endif
}
/** Notifies the unique app that a host app is running.
*
* @returns `true` if the unique app was successfully notified of the new running
* host app. Returns `false` if the notification either couldn't be sent or
* could not be completed.
*
* This lets the unique app know that the calling host app is still running. This
* is done by adding a shared lock reference to a marker file that the unique app
* can poll on periodically. The operating system will automatically remove the lock
* reference(s) for this call once the calling process exits (naturally or otherwise).
*
* This is intended to be called only once by any given host app. However, it may be
* called multiple times without much issue. The only downside to calling it multiple
* times would be that extra handles (Windows) or file descriptors (Linux) will be
* consumed for each call.
*
* @thread_safety This call is not thread safe. It is the caller's responsibility to
* ensure calls to it are protected. However, since it is meant to
* operate between processes, there may still be unavoidable race conditions
* that could arise.
*/
bool connectClientProcess()
{
bool success;
FileHandle fp;
// this object has already 'connected' to the unique app -> nothing to do => succeed.
if (m_exitGuard != kBadFileHandle)
return true;
fp = _openFile(_getGuardName(kExitLockExtension).c_str());
// failed to open the guard file (?!?) => fail.
if (fp == kBadFileHandle)
return false;
// grab a shared lock to the file. This will allow all clients to still also grab a
// shared lock but will prevent the unique app from grabbing its exclusive lock
// that it uses to determine whether any client apps are still 'connected'.
success = _lockFile(fp, LockType::eShared);
if (!success)
_closeFile(fp);
// save the exit guard handle in case we need to explicitly disconnect this app later.
else
m_exitGuard = fp;
// intentionally 'leak' the file handle here. Since the file lock is associated with
// the file handle, we can't close it until the process exits otherwise the unique app
// will think this client has 'disconnected'. If we leak the handle, the OS will take
// care of closing the handle when the process exits and that will automatically remove
// this process's file lock.
return success;
}
/** 'Disconnect' the calling process from the exit guard.
*
* @returns No return value.
*
* This closes the calling process's reference to the exit guard file. This will allow
* the exit guard for a host app process to be explicitly cleaned up before exit if
* needed.
*
* @thread_safety This call is not thread safe. It is the caller's responsibility to
* ensure calls to it are protected.
*/
void disconnectClientProcess()
{
FileHandle fp = m_exitGuard;
m_exitGuard = kBadFileHandle;
_closeFile(fp);
}
/** Tests whether all 'connected' host apps have exited.
*
* @returns `true` if all connected host apps have exited (naturally or otherwise). Returns
* `false` if at least one host app is still running.
*
* This tests whether all 'connected' host apps have exited. A host app is considered to
* be 'connected' if it had called @ref connectClientProcess() that had succeeded.
* Once a host app exits, all of its 'connections' to the unique app are automatically
* cleaned up by the operating system.
*
* This is intended to be called from the unique app periodically to determine if it
* should exit itself. The expectation is that this would be called once per minute or
* so to check whether it should be shut down. When this does succeed, the unique app
* should perform any final cleanup tasks then exit itself.
*
* @thread_safety This call is not thread safe. It is the caller's responsibility to ensure
* calls to it are protected. However, since it is meant to operate between
* processes, there may still be unavoidable race conditions that could arise.
*/
bool haveAllClientsExited()
{
bool success;
FileHandle fp;
std::string path;
path = _getGuardName(kExitLockExtension);
fp = _openFile(path.c_str());
// failed to open the guard file (?!?) => fail.
if (fp == kBadFileHandle)
return false;
success = _lockFile(fp, LockType::eExclusive, LockAction::eTest);
_closeFile(fp);
// the file lock was successfully acquired -> no more clients are 'connected' => delete
// the lock file as a final cleanup step.
if (success)
_deleteFile(path.c_str());
// all the clients have 'disconnected' when we're able to successfully grab an exclusive
// lock on the file. This means that all of the clients have exited and the OS has
// released their shared locks on the file thus allowing us to grab an exclusive lock.
return success;
}
private:
/** Extension of the name for the launch guard locks. */
static constexpr const char* kLaunchLockExtension = ".lock";
/** Extension of the name for the exit guard locks. */
static constexpr const char* kExitLockExtension = ".exit";
/** Default prefix for the lock guards. */
static constexpr const char* kDefaultNamePrefix = "nvidia-unique-app";
#if OMNI_PLATFORM_WINDOWS
using FileHandle = HANDLE;
static constexpr FileHandle kBadFileHandle = CARBWIN_INVALID_HANDLE_VALUE;
#else
/** Platform specific type for a file handle. */
using FileHandle = int;
/** Platform specific value for a failed file open operation. */
static constexpr FileHandle kBadFileHandle = -1;
#endif
/** Names for the type of lock to apply or test. */
enum class LockType
{
/** A shared (read) lock. Multiple shared locks may succeed simultaneously on the same
* file. If at least one shared lock exists on a file, it will prevent anything else
* from acquiring an exclusive lock on the same file.
*/
eShared,
/** An exclusive (write) lock. Only a single exclusive lock may exist on a file at any
* given time. The file must be completely unlocked in order for an exclusive lock to
* succeed (unless a process's existing shared lock is being upgraded to an exclusive
* lock). If the file has any shared locks on it from another process, an exclusive
* lock cannot be acquired.
*/
eExclusive,
};
/** Names for the action to take when locking a file. */
enum class LockAction
{
eSet, ///< attempt to acquire a lock on the file.
eTest, ///< test whether a lock is immediately possible on a file.
};
/** Creates the full name of the guard object for a given extension.
*
* @param[in] extension The extension to use on the guard name. This should either be
* @a kLaunchLockExtension or @a kExitLockExtension.
* @returns A string representing the full name and path of the guard object to create or
* test.
*/
std::string _getGuardName(const char* extension) const
{
return m_guardPath + "/" + m_guardName + extension;
}
/** Opens a guard file for read and write.
*
* @param[in] filename The name and path of the file to open. This may not be `nullptr`
* or an empty string. The file may already exist. If the file
* does not exist, it will be created.
* @returns A handle to the opened file. This may be passed to _closeFile() or _lockFile()
* as needed. When the handle is no longer necessary, it should be closed using
* _closeFile(). Returns @a kBadFileHandle if the file could not be opened.
*/
static FileHandle _openFile(const char* filename)
{
// make sure the path up to the file exists. Note that this will likely just fail to
// open the file below if creating the directories fail.
_makeDirectories(filename);
#if OMNI_PLATFORM_WINDOWS
std::wstring pathW = carb::extras::convertCarboniteToWindowsPath(filename);
return CreateFileW(pathW.c_str(), CARBWIN_GENERIC_READ | CARBWIN_GENERIC_WRITE,
CARBWIN_FILE_SHARE_READ | CARBWIN_FILE_SHARE_WRITE, nullptr, CARBWIN_OPEN_ALWAYS, 0, nullptr);
#else
return open(filename, O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP);
#endif
}
/** Closes a guard file opened with _openFile().
*
* @param[in] fp The file handle to close. This may be kBadFileHandle.
* @returns No return value.
*/
static void _closeFile(FileHandle fp)
{
#if OMNI_PLATFORM_WINDOWS
CloseHandle(fp);
#else
close(fp);
#endif
}
/** Deletes a file on the file system.
*
* @param[in] filename The name and path of the file to delete. This may not be
* `nullptr` or an empty string. The file will only be deleted
* if all open handles to it have been closed. Depending on the
* platform, the file may still exist and be able to be opened
* again if an open file handle to it still exists.
* @returns No return value.
*/
static void _deleteFile(const char* filename)
{
#if OMNI_PLATFORM_WINDOWS
std::wstring pathW = carb::extras::convertCarboniteToWindowsPath(filename);
DeleteFileW(pathW.c_str());
#else
unlink(filename);
#endif
}
/** Attempts to lock a file.
*
* @param[in] fp The handle to the file to attempt to lock. This must be a valid
* file handle returned by a call to _openFile(). This may not be
* @a kBadFileHandle.
* @param[in] type The type of lock to grab.
* @param[in] action Whether to set the lock or test it. Setting the lock will grab
* a new lock reference to the file. Testing it will just check if
* the requested type of lock can be immediately grabbed without
* changing the file's lock state.
* @returns `true` if the lock is successfully acquired in 'set' mode or if the lock is
* immediately available to be acquired in 'test' mode. Returns `false` if the
* lock could not be acquired in 'set' mode or if the lock was not immediately
* available to be acquired in 'test' mode. Also returns `false` if an error
* occurred.
*/
static bool _lockFile(FileHandle fp, LockType type, LockAction action = LockAction::eSet)
{
#if OMNI_PLATFORM_WINDOWS
BOOL success;
CARBWIN_OVERLAPPED ov = {};
DWORD flags = CARBWIN_LOCKFILE_FAIL_IMMEDIATELY;
if (type == LockType::eExclusive)
flags |= CARBWIN_LOCKFILE_EXCLUSIVE_LOCK;
success = LockFileEx(fp, flags, 0, 1, 0, reinterpret_cast<LPOVERLAPPED>(&ov));
if (action == LockAction::eTest)
UnlockFileEx(fp, 0, 1, 0, reinterpret_cast<LPOVERLAPPED>(&ov));
return success;
#else
int result;
struct flock fl;
fl.l_type = (type == LockType::eExclusive ? F_WRLCK : F_RDLCK);
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 1;
fl.l_pid = 0;
result = fcntl(fp, (action == LockAction::eTest ? F_GETLK : F_SETLK), &fl);
if (result != 0)
return false;
if (action == LockAction::eTest)
return fl.l_type == F_UNLCK;
return true;
#endif
}
/** Creates all the directories leading up to a path.
*
* @param[in] path The full path to create all the directories for. This may be an absolute
* or relative path. If the path ends in a path separator all paths up to
* and including the last component will be created. Otherwise the last
* component will be assumed to be a filename and be ignored. This may not
* be `nullptr`.
* @returns `true` if all the directories on the given path either already existed or were
* successfully created. Returns `false` otherwise.
*/
static bool _makeDirectories(const std::string& path)
{
size_t start = 0;
#if CARB_PLATFORM_WINDOWS
constexpr const char* separators = "\\/";
if (path.size() > 3 && (path[1] == ':' || path[0] == '/' || path[0] == '\\'))
start = 3;
#elif CARB_POSIX
constexpr const char* separators = "/";
if (path.size() > 1 && path[0] == '/')
start = 1;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
for (;;)
{
size_t pos = path.find_first_of(separators, start);
std::string next;
if (pos == std::string::npos)
break;
next = path.substr(0, pos);
start = pos + 1;
#if CARB_PLATFORM_WINDOWS
std::wstring pathW = carb::extras::convertCarboniteToWindowsPath(next);
DWORD attr = GetFileAttributesW(pathW.c_str());
if (attr != CARBWIN_INVALID_FILE_ATTRIBUTES)
{
// already a directory -> nothing to do => skip it.
if ((attr & CARBWIN_FILE_ATTRIBUTE_DIRECTORY) != 0)
continue;
// exists but not a directory -> cannot continue => fail.
else
return false;
}
// failed to create the directory -> cannot continue => fail.
if (!CreateDirectoryW(pathW.c_str(), nullptr))
return false;
#elif CARB_POSIX
struct stat st;
if (stat(next.c_str(), &st) == 0)
{
// already a directory -> nothing to do => skip it.
if (S_ISDIR(st.st_mode))
continue;
// exists but not a directory -> cannot continue => fail.
else
return false;
}
// failed to create the directory -> cannot continue => fail.
if (mkdir(next.c_str(), S_IRWXU | S_IRGRP | S_IROTH) != 0)
return false;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
return true;
}
/** The path to use to store the guard files. This may either be a relative or absolute
* path and will most often be specified by the caller. This defaults to the current
* directory.
*/
std::string m_guardPath = ".";
/** The name to use for the guard files. This should be unique to the app being launched.
* There is no formatting or syntax requirement for this aside from being valid on the
* file system for the calling platform. This defaults to @a kDefaultNamePrefix.
*/
std::string m_guardName = kDefaultNamePrefix;
/** The last created launch guard object. This is used to prevent multiple launch guard
* objects from being created from this object for a single unique app process.
*/
FileHandle m_launchGuard = kBadFileHandle;
/** The last created exit guard object. This is used to prevent multiple 'connections'
* to the unique app from being created from this object for a single host app process.
*/
FileHandle m_exitGuard = kBadFileHandle;
};
} // namespace extras
} // namespace omni
| 29,501 | C | 41.571429 | 121 | 0.621572 |
omniverse-code/kit/include/omni/extras/Version.h | // Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Version utilities
#pragma once
#include "StringHelpers.h"
#include "../../carb/RString.h"
#include <string>
namespace omni
{
namespace extras
{
/**
* Version struct, follows Semantic Versioning 2.0. https://semver.org/
* @warning This struct is not @rstref{ABI safe <abi-compatibility>} and must not be passed through ABI boundaries. For
* an ABI-safe version, see \ref omni::ext::Version.
*/
struct SemanticVersion
{
//! The major version, as defined by <a href="https://semver.org">Semantic Versioning</a>. May be negative to match
//! any major version.
int32_t major{ -1 };
//! The minor version, as defined by <a href="https://semver.org">Semantic Versioning</a>. May be negative to match
//! any minor version.
int32_t minor{ -1 };
//! The patch version, as defined by <a href="https://semver.org">Semantic Versioning</a>. May be negative to match
//! any patch version.
int32_t patch{ -1 };
std::string prerelease; //!< A string indicating a pre-release value. May be empty
std::string build; //!< A string indicating a build value. May be empty
//! Constructor.
//! \details Initializes a SemanticVersion with `-1` for all version values and empty pre-release and build values.
SemanticVersion() = default;
/**
* Converts this version to a string.
* \details If \ref major, \ref minor and \ref patch are negative, an empty string is returned. Otherwise the string
* returned is `<major>.<minor>.<patch>[-<prerelease>][+<build>]`. The `+<build>` section is only included if
* \p includeBuildMetadata is `true`. The `-<prerelease>` and `+<build>` sections are only included if the
* \ref prerelease and \ref build members (respectively) are not empty.
* @param includeBuildMetadata If `true`, the `+<build>` section is included in the returned string
* @returns the version string. See above for detailed explanation
*/
std::string toString(bool includeBuildMetadata = true) const
{
if (this->major < 0 && this->minor < 0 && this->patch < 0)
return "";
else
{
std::ostringstream ss;
if (this->major >= 0 || this->minor >= 0 || this->patch >= 0)
ss << this->major << "." << this->minor << "." << this->patch;
if (!std::string(this->prerelease).empty())
ss << "-" << this->prerelease;
if (includeBuildMetadata && !std::string(this->build).empty())
ss << "+" << this->build;
return ss.str();
}
}
//! Replaces major, minor or patch values with zeros if they are negative.
void replaceNegativesWithZeros() noexcept
{
if (this->major < 0)
this->major = 0;
if (this->minor < 0)
this->minor = 0;
if (this->patch < 0)
this->patch = 0;
}
//! Checks if the major, minor and patch values are all zeros.
//! @returns `true` if the \ref major, \ref minor and \ref patch values are all zero; `false` otherwise
bool isAllZeroes() const noexcept
{
return this->major == 0 && this->minor == 0 && this->patch == 0;
}
//! Returns a default-constructed SemanticVersion.
//! @returns a default-constructed SemanticVersion
static SemanticVersion getDefault() noexcept
{
return {};
}
};
/**
* Checks if the given SemanticVersion has negative major, minor and patch values.
* @param v A \ref SemanticVersion to test
* @returns `true` if @p v has negative major, minor and patch values; `false` otherwise
*/
inline bool isAnyVersion(const SemanticVersion& v)
{
return v.major < 0 && v.minor < 0 && v.patch < 0;
}
/**
* Semantic Version pre-release less-than comparator.
* @param x A pre-release value from a \ref SemanticVersion
* @param y A pre-release value from a \ref SemanticVersion
* @returns `true` if \p x should be ordered-before \p y according to rules at https://semver.org/#spec-item-11
*/
inline bool prereleaseCmpLess(const char* x, const char* y)
{
// SemVer prerelease part comparison according to: https://semver.org/#spec-item-11
const size_t xLen = strlen(x);
const size_t yLen = strlen(y);
// ("" < "") => false
if (xLen == 0 && yLen == 0)
return false;
// ("abc" < "") => true
if (yLen == 0)
return true;
// ("" < "abc") => false
if (xLen == 0)
return false;
const char* xPartFrom = x;
const char* yPartFrom = y;
while (1)
{
// Find next '.'. Chunks are: [xPartFrom, xPartTo] and [yPartFrom, yPartTo]
const char* xPartTo = strchr(xPartFrom, '.');
xPartTo = xPartTo ? xPartTo : x + xLen;
const char* yPartTo = strchr(yPartFrom, '.');
yPartTo = yPartTo ? yPartTo : y + yLen;
const size_t xPartLen = xPartTo - xPartFrom;
const size_t yPartLen = yPartTo - yPartFrom;
// Try to convert to integer until next '.'.
char* end;
const long xNum = strtol(xPartFrom, &end, 10);
const bool xIsNum = (end == xPartTo);
const long yNum = strtol(yPartFrom, &end, 10);
const bool yIsNum = (end == yPartTo);
// "123" < "abc"
if (xIsNum && !yIsNum)
return true;
if (!xIsNum && yIsNum)
return false;
if (xIsNum && yIsNum)
{
// numerical comparison
if (xNum != yNum)
return xNum < yNum;
}
else
{
// string comparison until next nearest '.'
const int res = strncmp(xPartFrom, yPartFrom, carb_min(xPartLen, yPartLen));
// if different "zzz" < "abc", return:
if (res != 0)
return res < 0;
// they are the same, but one longer? "abc" < "abcdef"
if (xPartLen != yPartLen)
return xPartLen < yPartLen;
}
// Go to the next `.` part
xPartFrom = xPartTo + 1;
yPartFrom = yPartTo + 1;
// Reached the end of both? => they are equal
if (xPartFrom == x + xLen + 1 && yPartFrom == y + yLen + 1)
break;
// x ended first? "abc.def" < "abc.def.xyz"
if (xPartFrom == x + xLen + 1)
return true;
// y ended first?
if (yPartFrom == y + yLen + 1)
return false;
}
return false;
}
//! @copydoc prereleaseCmpLess(const char*,const char*)
inline bool prereleaseCmpLess(const std::string& x, const std::string& y)
{
return prereleaseCmpLess(x.c_str(), y.c_str());
}
/**
* Less-than comparator for two versions.
* @tparam VersionT The type of the version struct, typically \ref omni::ext::Version or \ref SemanticVersion.
* @param lhs The first version to compare
* @param rhs The second version to compare
* @returns `true` if \p lhs should be ordered-before \p rhs; `false` otherwise
* @see prereleaseCmpLess(const char*,const char*)
*/
template <class VersionT>
inline bool versionsCmpLess(const VersionT& lhs, const VersionT& rhs)
{
if (lhs.major != rhs.major)
return lhs.major < rhs.major;
if (lhs.minor != rhs.minor)
return lhs.minor < rhs.minor;
if (lhs.patch != rhs.patch)
return lhs.patch < rhs.patch;
return prereleaseCmpLess(lhs.prerelease, rhs.prerelease);
}
/**
* Less-than operator for two semantic versions.
* @param lhs The first \ref SemanticVersion to compare
* @param rhs The second \ref SemanticVersion to compare
* @returns `true` if \p lhs should be ordered-before \p rhs; `false` otherwise
* @see prereleaseCmpLess(const char*,const char*), versionsCmpLess()
*/
inline bool operator<(const SemanticVersion& lhs, const SemanticVersion& rhs)
{
return versionsCmpLess(lhs, rhs);
}
/**
* Equality operator for two semantic versions.
* @param lhs The first \ref SemanticVersion to compare
* @param rhs The second \ref SemanticVersion to compare
* @returns `true` if \p lhs and \p rhs are equal; `false` otherwise
*/
inline bool operator==(const SemanticVersion& lhs, const SemanticVersion& rhs)
{
// Notice that "build metadata" is ignored in version comparison
return lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch == rhs.patch && lhs.prerelease == rhs.prerelease;
}
/**
* Parses a given string into a semantic version.
* @param str The string to parse into a semantic version, as described by \ref SemanticVersion::toString()
* @param outVersion A reference that will receive the semantic version. If `false` is returned, this reference will be
* in an indeterminate state.
* @returns `true` if parsing succeeded and \p outVersion has received the parsed semantic version; `false` if parsing
* failed and \p outVersion is in an indeterminate state and should not be used
*/
inline bool stringToVersion(const std::string& str, SemanticVersion& outVersion)
{
outVersion = SemanticVersion::getDefault();
// [major].[minor].[patch]-[prerelease]+[build]
auto versionAndBuild = extras::split(str, '+');
// Only one `+` allowed in semver
if (versionAndBuild.size() > 2)
return false;
auto versionParts = extras::split(versionAndBuild[0], '-', 2);
// parse first part: [major].[minor].[patch]
{
auto parts = extras::split(versionParts[0], '.');
if (parts.empty())
return false;
// 1.2.3.4 is not semver
if (parts.size() > 3)
return false;
if (!extras::stringToInteger(parts[0], outVersion.major))
return false;
if (parts.size() > 1)
{
if (!extras::stringToInteger(parts[1], outVersion.minor))
return false;
}
if (parts.size() > 2)
{
if (!extras::stringToInteger(parts[2], outVersion.patch))
return false;
}
}
// parse second part: [prerelease]+[build]
if (versionParts.size() > 1)
outVersion.prerelease = versionParts[1];
if (versionAndBuild.size() > 1)
outVersion.build = versionAndBuild[1];
return true;
}
/**
* Parses a string to a semantic version, or a default value if parsing fails.
* @param str The string to parse
* @returns a \ref SemanticVersion parsed from \p str, or \ref SemanticVersion::getDefault() if parsing fails
*/
inline SemanticVersion stringToVersionOrDefault(const std::string& str)
{
SemanticVersion v;
if (!stringToVersion(str, v))
v = SemanticVersion::getDefault();
return v;
}
/**
* Attempts to parse the Git hash from an Omniverse-specific semantic version.
* \details An Omniverse Flow version format is `<version>+<gitbranch>.<number>.<githash>.<build_location>`. This
* function parses out the `<githash>` from this format.
* @param version The \ref SemanticVersion to process
* @param outHash A reference that receives the Git hash if `true` is returned; if `false` is returned this will be
* `00000000`.
* @returns `true` if parsing succeeded; `false` otherwise
*/
inline bool gitHashFromOmniverseVersion(const extras::SemanticVersion& version, std::string& outHash)
{
// Omniverse Flow format: "{version}+{gitbranch}.{number}.{githash}.{build_location}"
auto parts = extras::split(version.build, '.');
outHash = "00000000";
if (parts.size() > 2)
{
outHash = parts[2];
return true;
}
return false;
}
} // namespace extras
} // namespace omni
| 11,937 | C | 33.304598 | 122 | 0.626539 |
omniverse-code/kit/include/omni/extras/md5.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief MD5 hash utils
#pragma once
// This file seems like it was copied from somewhere without attribution.
// TODO: It should be refactored or reimplemented with our coding guidelines
#ifndef DOXYGEN_BUILD
# include "../../carb/Defines.h"
// Can't undo this at the end of this file when doing static compilation, the compiler complains
CARB_IGNOREWARNING_MSC(4307) // 'operator' : integral constant overflow
namespace MD5
{
//! Integer portions of sines of integers, in radians.
constexpr uint32_t K[64] = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,
0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,
0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,
0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,
0xeb86d391 };
//! Per-round bit shift amounts.
constexpr uint32_t S[64] = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9,
14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 };
//! Struct representing an MD5 digest.
struct digest
{
//! MD5 digest bytes
uint8_t u8[16];
};
//! String size of an MD5 digest (not including NUL terminator).
constexpr size_t kDigestStringSize = sizeof(digest) * 2;
struct DigestString
{
//! String of length \ref kDigestStringSize
//! @warning this is **not** NUL terminated!
char s[kDigestStringSize];
};
struct Data
{
uint32_t A0 = 0x67452301;
uint32_t B0 = 0xefcdab89;
uint32_t C0 = 0x98badcfe;
uint32_t D0 = 0x10325476;
static constexpr uint32_t kBlocksize = 64;
uint8_t buffer[kBlocksize] = {};
};
constexpr uint32_t rotate_left(uint32_t x, int n)
{
return (x << n) | (x >> (32 - n));
}
constexpr uint32_t packUint32(const uint8_t block[Data::kBlocksize], uint32_t index)
{
uint32_t u32 = 0;
for (uint32_t i = 0; i < 4; i++)
{
u32 |= uint32_t(block[index + i]) << (8 * i);
}
return u32;
}
constexpr void processBlock(Data& data, const uint8_t block[Data::kBlocksize])
{
uint32_t A = data.A0;
uint32_t B = data.B0;
uint32_t C = data.C0;
uint32_t D = data.D0;
for (uint32_t i = 0; i < 64; i++)
{
uint32_t F = 0;
uint32_t g = 0;
switch (i / 16)
{
case 0:
F = (B & C) | ((~B) & D);
g = i;
break;
case 1:
F = (D & B) | ((~D) & C);
g = (5 * i + 1) % 16;
break;
case 2:
F = B ^ C ^ D;
g = (3 * i + 5) % 16;
break;
case 3:
F = C ^ (B | (~D));
g = (7 * i) % 16;
break;
}
// constexpr won't allow us to do pointer cast
uint32_t Mg = packUint32(block, g * 4);
F = F + A + K[i] + Mg;
A = D;
D = C;
C = B;
B = B + rotate_left(F, S[i]);
}
data.A0 += A;
data.B0 += B;
data.C0 += C;
data.D0 += D;
}
constexpr void memcopyConst(uint8_t dst[], const uint8_t src[], size_t count)
{
for (size_t i = 0; i < count; i++)
dst[i] = src[i];
}
template <typename T>
constexpr void unpackUint(uint8_t dst[], T u)
{
for (uint32_t i = 0; i < sizeof(T); i++)
dst[i] = 0xff & (u >> (i * 8));
}
constexpr void processLastBlock(Data& data, const uint8_t str[], size_t strLen, size_t blockIndex)
{
auto lastChunkSize = strLen % Data::kBlocksize;
lastChunkSize = (!lastChunkSize && strLen) ? Data::kBlocksize : lastChunkSize;
// We need at least 9 available bytes - 1 for 0x80 and 8 bytes for the length
bool needExtraBlock = (Data::kBlocksize - lastChunkSize) < (sizeof(size_t) + 1);
bool lastBitInExtraBlock = (lastChunkSize == Data::kBlocksize);
{
uint8_t msg[Data::kBlocksize]{};
memcopyConst(msg, &str[blockIndex * Data::kBlocksize], lastChunkSize);
if (!lastBitInExtraBlock)
msg[lastChunkSize] = 0x80;
if (!needExtraBlock)
unpackUint(&msg[Data::kBlocksize - 8], strLen * 8);
processBlock(data, msg);
}
if (needExtraBlock)
{
uint8_t msg[Data::kBlocksize]{};
if (lastBitInExtraBlock)
msg[0] = 0x80;
unpackUint(&msg[Data::kBlocksize - 8], strLen * 8);
processBlock(data, msg);
}
}
constexpr digest createDigest(Data& data)
{
digest u128 = {};
unpackUint(&u128.u8[0], data.A0);
unpackUint(&u128.u8[4], data.B0);
unpackUint(&u128.u8[8], data.C0);
unpackUint(&u128.u8[12], data.D0);
return u128;
}
constexpr digest run(const uint8_t src[], size_t count)
{
Data data;
// Compute the number of blocks we need to process. We may need to add a block for padding
size_t blockCount = 1;
if (count)
{
blockCount = (count + Data::kBlocksize - 1) / Data::kBlocksize;
for (size_t i = 0; i < blockCount - 1; i++)
processBlock(data, &src[i * Data::kBlocksize]);
}
processLastBlock(data, src, count, blockCount - 1);
return createDigest(data);
}
template <size_t lengthWithNull>
constexpr static inline digest run(const char (&str)[lengthWithNull])
{
// Can't do pointer cast at compile time, need to create a copy
uint8_t unsignedStr[lengthWithNull] = {};
for (size_t i = 0; i < lengthWithNull; i++)
unsignedStr[i] = (uint8_t)str[i];
constexpr size_t length = lengthWithNull - 1;
return run(unsignedStr, length);
}
// TODO: Move the rest of the MD5 implementation details into the detail namespace in a non-functional change.
namespace detail
{
constexpr static inline char nibbleToHex(uint8_t n)
{
n &= 0xf;
const char base = n < 10 ? '0' : ('a' - 10);
return base + n;
}
} // namespace detail
constexpr static inline DigestString getDigestString(const MD5::digest& d)
{
DigestString s = {};
for (uint32_t i = 0; i < carb::countOf(d.u8); i++)
{
const uint32_t offset = i * 2;
s.s[offset + 0] = detail::nibbleToHex(d.u8[i] >> 4);
s.s[offset + 1] = detail::nibbleToHex(d.u8[i]);
}
return s;
}
} // namespace MD5
#endif
| 7,527 | C | 31.034042 | 116 | 0.585625 |
omniverse-code/kit/include/omni/extras/OutArrayUtils.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Provides templated helper functions to fill an arbitrary array of values.
//!
#pragma once
#include "../core/IObject.h" // for omni::core::Result
#include <type_traits>
#include <vector>
namespace omni
{
//! common namespace for extra helper functions and classes.
namespace extras
{
//! Fills the array given by outArray by calling fillFn.
//!
//! fillFn's signature is void(T* outArray, uint32_t outArrayCount).
//!
//! If outArrayCount is `nullptr`, kResultInvalidArgument is returned.
//!
//! If outArray is `nullptr`, *outArrayCount is populated with requiredAccount.
//!
//! If *outArrayCount is less than requiredCount, kResultInsufficientBuffer is returned.
//!
//! If the checks above pass, outArray is filled by the given function. *outArrayCount is updated to requiredCount.
template <typename T, typename Callable, typename SizeType>
omni::core::Result fillOutArray(T* outArray, SizeType* outArrayCount, SizeType requiredCount, Callable&& fillFn)
{
static_assert(std::is_unsigned<SizeType>::value, "SizeType must be an unsigned integer type!");
if (!outArrayCount)
{
return omni::core::kResultInvalidArgument;
}
if (!outArray)
{
*outArrayCount = requiredCount;
return omni::core::kResultSuccess;
}
if (*outArrayCount < requiredCount)
{
*outArrayCount = requiredCount;
return omni::core::kResultInsufficientBuffer;
}
*outArrayCount = requiredCount;
fillFn(outArray, requiredCount);
return omni::core::kResultSuccess;
}
//! Retrieves an array of unknown size using @p getFn and passes it to @p fillFn.
//!
//! This utility is useful for transferring a raw array from the ABI to a modern C++ container.
//!
//! In order to avoid heap access, @p stackCount can be used to try to transfer the array from @p getFn to @p fillFn
//! using temporary stack storage. @p stackCount is the number of T's that should be temporarily allocated on the
//! stack. If
//! @p stackCount is inadequate, this function falls back to using the heap. Care should be taken to not set @p
//! stackCount to a value that would cause a stack overflow.
//!
//! The source array may be dynamically growing in another thread, in which case this method will try @p maxRetryCount
//! times to allocate an array of the proper size and retrieve the values. If this method exceeds the retry count,
//! @ref omni::core::kResultTryAgain is returned.
//!
//! @retval omni::core::kResultSuccess on success, an appropriate error code otherwise.
template <typename T, typename GetCallable, typename FillCallable>
omni::core::Result getOutArray(GetCallable&& getFn,
FillCallable&& fillFn,
uint32_t stackCount = (4096 / sizeof(T)),
uint32_t maxRetryCount = (UINT32_MAX - 1))
{
// constructors won't run when we call alloca, make sure the type doesn't need a constructor to run.
static_assert(std::is_trivially_default_constructible<T>::value, "T must be trivially default constructible");
T* stack = CARB_STACK_ALLOC(T, stackCount);
std::vector<T> heap;
T* buffer = stack;
uint32_t count = stackCount;
omni::core::Result result = getFn(buffer, &count);
uint32_t retryCount = maxRetryCount + 1;
while (--retryCount)
{
switch (result)
{
case omni::core::kResultSuccess:
if (buffer)
{
fillFn(buffer, count);
return omni::core::kResultSuccess;
}
CARB_FALLTHROUGH; // (alloca returned nullptr, count is now correct and we should alloc on heap)
case omni::core::kResultInsufficientBuffer:
heap.resize(count);
buffer = heap.data();
result = getFn(buffer, &count);
break;
default:
return result;
}
}
return omni::core::kResultTryAgain;
}
} // namespace extras
} // namespace omni
| 4,495 | C | 35.852459 | 118 | 0.670968 |
omniverse-code/kit/include/omni/extras/ForceLink.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Provides functionality to force a symbol to be linked to a module
* instead of the optimizer potentially removing it out.
*/
#pragma once
#include "../core/Platform.h"
#if OMNI_PLATFORM_WINDOWS
// see below for why we unfortunately either need this or to forward declare SetLastError()
// directly here instead of using something like strerror_s() on Windows.
# include "../../carb/CarbWindows.h"
#endif
namespace omni
{
/** common namespace for extra helper functions and classes. */
namespace extras
{
/** Helper class to force the linking of a C++ symbol. This is done by having the symbol's
* address be passed to a function in another module. Since, at link time, the linker
* doesn't know what the other module's function will do with the symbol, it can't discard
* the symbol. This is useful for ensuring that debug-only or initializer-only symbols
* do not get unintentionally eliminated from the module they are present in.
*
* Note that since this does not have any data members, it shouldn't occupy any space in the
* module's data section. It will however generate a C++ static initializer and shutdown
* destructor.
*
* This class should not be used directly, but instead through the @ref OMNI_FORCE_SYMBOL_LINK
* macro.
*/
class ForceSymbolLink
{
public:
/** Constructor: passes an argument's value to a system library.
*
* @param[in] ptr The address to pass on to a system library call. This prevents the
* linker from being able to discard the symbol as unused or unreferenced.
* This value is not accessed as a pointer in any way so any value is
* acceptable.
* @returns No return value.
*/
ForceSymbolLink(void* ptr)
{
#if OMNI_PLATFORM_WINDOWS
// On Windows, we unfortunately can't call into something like strerror_s() to
// accomplish this task because the CRT is statically linked to the module that
// will be using this. That would make the function we're passing the symbol
// to local and therefore the symbol will still be discardable. Instead, we'll
// pass the address to SetLastError() which will always be available from 'kernel32'.
SetLastError(static_cast<DWORD>(reinterpret_cast<uintptr_t>(ptr)));
#else
char* str;
CARB_UNUSED(str);
str = strerror(static_cast<int>(reinterpret_cast<uintptr_t>(ptr)));
#endif
}
};
} // namespace extras
} // namespace omni
/** Helper to force a symbol to be linked.
*
* @param[in] symbol_ The symbol that must be linked to the calling module. This must be a
* valid symbol name including any required namespaces given the calling
* location.
* @param[in] tag_ A single token name to give to the symbol that forces the linking.
* This is used purely for debugging purposes to give an identifiable name
* to the symbol that is used to force linking of @p symbol_. This must
* be a valid C++ single token name (ie: only contains [A-Za-z0-9_] and
* must not start with a number).
* @returns No return value.
*
* @remarks This is used to ensure an unused symbol is linked into a module. This is done
* by tricking the linker into thinking the symbol is not discardable because its
* address is being passed to a function in another module. This is useful for
* example to ensure symbols that are meant purely for debugger use are not discarded
* from the module. Similarly, it can be used on symbols that are only meant to
* anchor C++ object initializers but are unreferenced otherwise.
*/
#define OMNI_FORCE_SYMBOL_LINK(symbol_, tag_) \
static omni::extras::ForceSymbolLink CARB_JOIN( \
g_forceLink##tag_##_, CARB_JOIN(CARB_JOIN(__COUNTER__, _), __LINE__))(&(symbol_))
| 4,578 | C | 46.206185 | 120 | 0.659677 |
omniverse-code/kit/include/omni/extras/PrivacySettings.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Helper class to retrieve the current privacy settings state.
*/
#pragma once
#include "../../carb/InterfaceUtils.h"
#include "../../carb/settings/ISettings.h"
#include "../../carb/extras/StringSafe.h"
namespace omni
{
/** common namespace for extra helper functions and classes. */
namespace extras
{
/** Consent level names. These consent levels control which types of structured log events
* produced by an app will be sent to telemetry servers for analysis. Each consent
* level will default to `false` before the privacy settings have been loaded.
*/
enum class ConsentLevel
{
/** Privacy consent level that corresponds to the @ref PrivacySettings::kPerformanceKey
* setting name. This consent level controls whether events such as hardware information,
* app performance statistics, resource usage levels, or crash reports will be sent to
* telemetry servers for analysis.
*/
ePerformance,
/** Privacy consent level that corresponds to the @ref PrivacySettings::kPersonalizationKey
* setting name. This consent level controls whether events such as user app settings,
* window layouts, search keywords, etc will be sent to telemetry servers for analysis.
*/
ePersonalization,
/** Privacy consent level that corresponds to the @ref PrivacySettings::kUsageKey setting
* name. This consent level controls whether events such as user activity, app feature
* usage, extension usage, etc will be sent to the telemetry servers for analysis.
*/
eUsage,
/** The total number of available consent levels. This is not a valid consent level to
* query and will always return `false`.
*/
eCount,
};
/** Static helper class to provide standardized access to the telemetry privacy setting values.
* These settings provide information such as the active user ID and the consent permissions
* for the various event types. These settings are expected to already have been loaded into
* the settings registry (accessible through ISettings). This just provides simple access
* to the settings values but does not provide functionality for loading the settings in the
* first place or providing a wrapper for change subscriptions on those settings.
*
* Loading the settings is left up to the `omni.structuredlog.plugin` module. This module will
* manage loading the settings when it initializes. It will also refresh the settings any
* time the original settings file for them changes. This file is located at
* `$HOME_PATH/.nvidia-omniverse/config/privacy.toml` (where `$HOME_PATH` is the user's home
* directory on the local system).
*
* This helper class does not directly handle change subscriptions to the various privacy
* settings. This is done to avoid complication and potential issues during shutdown
* of global objects. It does however expose the paths of the various privacy settings
* so that external callers can subscribe for and manage their own change notifications.
*
* @note The methods in this helper class are just as thread safe as the ISettings interface
* itself is when retrieving a value. All methods are static so there is no state
* data that could be clobbered by multiple threads in this object itself.
*
* @note The Carbonite framework must be initialized before using this helper class. A
* crash will occur if the framework is not initialized first.
*/
class PrivacySettings
{
public:
/** @addtogroup keySettings Privacy Settings Keys
*
* Paths for the various expected privacy settings. These can be used to manually
* access the settings values or to subscribe for change notifications on either
* each individual setting or the entire privacy settings tree.
* @{
*/
/** The settings key path for the version of the privacy settings file. */
static constexpr const char* kVersionKey = "/privacy/version";
/** The settings key path for the 'performance' consent level. */
static constexpr const char* kPerformanceKey = "/privacy/performance";
/** The settings key path for the 'personalization' consent level. */
static constexpr const char* kPersonalizationKey = "/privacy/personalization";
/** The settings key path for the 'usage' consent level. */
static constexpr const char* kUsageKey = "/privacy/usage";
/** The settings key path for the current user ID name. */
static constexpr const char* kUserIdKey = "/privacy/userId";
/** The settings key path for the current user's email address. This is not
* expected to be present for all users.
*/
static constexpr const char* kEmailKey = "/privacy/email";
/** The settings key path for the 'external build' flag. */
static constexpr const char* kExternalBuildKey = "/privacy/externalBuild";
/** The settings key path for the 'send extra diagnostic data' flag. */
static constexpr const char* kExtraDiagnosticDataOptInKey = "/privacy/extraDiagnosticDataOptIn";
/** The settings key path for the identity provider's name. */
static constexpr const char* kIdpNameKey = "/privacy/idpName";
/** The settings key path for the identity provider's identifier. */
static constexpr const char* kIdpIdKey = "/privacy/idpId";
/** The settings key path for all of the privacy settings tree. */
static constexpr const char* kSettingTree = "/privacy";
/** @} */
/** Retrieves the version setting found in the privacy config.
*
* @returns A string containing the version information value for the privacy settings
* file. This version gives an indication of what other values might be
* expected in the file.
*
* @thread_safety This call is thread safe.
*/
static const char* getVersion()
{
return _getSettingStringValue(kVersionKey, "1.0");
}
/** Retrieves the user ID found in the privacy config.
*
* @returns A string containing the user ID that is currently logged into omniverse.
* This is the user ID that should be used when writing out any structured
* log events or sending crash reports. This does not necessarily reflect the
* user ID that will be used to login to a Nucleus server instance however.
* @returns An empty string if no user ID setting is currently present.
*
* @thread_safety This call is thread safe.
*/
static const char* getUserId()
{
return _getSettingStringValue(kUserIdKey, "");
}
/** Retrieves the user email address if specified in the privacy config.
*
* @returns A string containing the currently logged in user's email address. This
* is only expected to be present for some users. This email address will
* not be emitted with any structured log events.
* @returns An empty string if no user email address is currently present.
*
* @thread_safety This call is thread safe.
*/
static const char* getEmail()
{
return _getSettingStringValue(kEmailKey, "");
}
/** Retrieves the identity provider's name if specified in the privacy config.
*
* @retval A string containing the name of the identity provider that was used to
* authenticate the current user. This name is optional.
* @retval An empty string if no identity provider name is currently present.
*
* @thread_safety This call is thread safe.
*/
static const char* getIdpName()
{
return _getSettingStringValue(kIdpNameKey, "");
}
/** Retrieves the identity provider's identifier if specified in the privacy config.
*
* @retval A string containing the identifier of the identity provider that was used to
* authenticate the current user. This identifier is optional.
* @retval An empty string if no identity provider identifier is currently present.
*
* @thread_safety This call is thread safe.
*/
static const char* getIdpId()
{
return _getSettingStringValue(kIdpIdKey, "");
}
/** Retrieves the consent state for a requested consent level.
*
* @param[in] level The consent level to query.
* @returns The current state of the requested consent level if present.
* @returns `false` if the state of the requested consent level could not be successfully
* queried.
*
* @thread_safety This call is thread safe.
*/
static bool getConsentLevel(ConsentLevel level)
{
static const char* map[] = { kPerformanceKey, kPersonalizationKey, kUsageKey };
if (((size_t)level) >= ((size_t)ConsentLevel::eCount))
return false;
return _getSettingBoolValue(map[(size_t)level], false);
}
/** Checks whether the user has opted into sending diagnostic data.
*
* @returns `true` if the user has opted into sending diagnostic data.
* @returns `false` if the user has opted out of sending diagnostic data.
*/
static bool canSendExtraDiagnosticData()
{
const char* optIn = _getSettingStringValue(kExtraDiagnosticDataOptInKey, "");
return carb::extras::compareStringsNoCase(optIn, "externalBuilds") == 0;
}
private:
/** Attempts to retrieve the ISettings interface.
*
* @returns The ISettings interface object if loaded and successfully acquired.
* @returns `nullptr` if the ISettings interface object could not be acquired or has not
* already been loaded.
*
* @note This does not attempt to load the ISettings plugin itself. It is assumed that
* an external caller will have already loaded the appropriate module before calling
* into here. However, if acquiring the interface object does fail, all calls that
* use it will still gracefully fail.
*
* @thread_safety This call is thread safe.
*/
static carb::settings::ISettings* _getSettingsInterface()
{
return carb::getCachedInterface<carb::settings::ISettings>();
}
/** Attempts to retrieve a setting as a string value.
*
* @param[in] name The name of the setting to retrieve the value for. This may
* not be `nullptr`.
* @param[in] defaultValue The default value to return in case the setting cannot be
* returned for any reason. This value is not interpreted or
* accessed in any way except to return it to the caller in
* failure cases.
* @returns The value of the requested setting if it is present and accessible as a string.
* @returns The @p defaultValue parameter if the ISettings interface object could not be
* acquired or is not loaded.
* @returns The @p defaultValue parameter if the requested setting is not accessible as a
* string value.
*
* @thread_safety This call is thread safe.
*/
static const char* _getSettingStringValue(const char* name, const char* defaultValue)
{
carb::settings::ISettings* settings = _getSettingsInterface();
const char* value;
if (settings == nullptr || name == nullptr)
return defaultValue;
value = settings->getStringBuffer(name);
if (value == nullptr)
return defaultValue;
return value;
}
/** Attempts to retrieve a setting as a boolean value.
*
* @param[in] name The name of the setting to retrieve the value for. This may
* not be `nullptr`.
* @param[in] defaultValue The default value to return in case the setting cannot be
* returned for any reason. This value is not interpreted or
* accessed in any way except to return it to the caller in
* failure cases.
* @returns The value of the requested setting if it is present and accessible as a boolean.
* @returns The @p defaultValue parameter if the ISettings interface object could not be
* acquired or is not loaded.
* @returns The @p defaultValue parameter if the requested setting is not accessible as a
* string value.
*
* @thread_safety This call is thread safe.
*/
static bool _getSettingBoolValue(const char* name, bool defaultValue)
{
carb::settings::ISettings* settings = _getSettingsInterface();
if (settings == nullptr || !settings->isAccessibleAs(carb::dictionary::ItemType::eBool, name))
return defaultValue;
return settings->getAsBool(name);
}
};
} // namespace extras
} // namespace omni
| 13,366 | C | 42.399351 | 102 | 0.674921 |
omniverse-code/kit/include/omni/extras/OmniConfig.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../../carb/Defines.h"
#include "../../carb/filesystem/IFileSystem.h"
#include "../../carb/dictionary/IDictionary.h"
#include "../../carb/dictionary/ISerializer.h"
#include "../../carb/extras/Utf8Parser.h"
#include "../../carb/extras/Path.h"
#include "../../carb/extras/EnvironmentVariable.h"
#include "ScratchBuffer.h"
#if CARB_POSIX
# include <unistd.h>
# include <pwd.h>
#elif CARB_PLATFORM_WINDOWS
# include "../../carb/CarbWindows.h"
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
namespace omni
{
namespace extras
{
/** Retrieve the path to the home directory.
* @retval The path to the home directory.
* @retval Empty path on failure.
* @remarks This retrieves the path to `$HOME` on POSIX platforms and `%USEPROFILE%` on Windows.
* If those are unset, this uses system calls as a fallback.
*/
inline carb::extras::Path getHomePath()
{
#if CARB_POSIX
constexpr const char* homeVar = "HOME";
#elif CARB_PLATFORM_WINDOWS
constexpr const char* homeVar = "USERPROFILE";
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
// POSIX and Windows both have an envvar for this
std::string home;
if (carb::extras::EnvironmentVariable::getValue(homeVar, home) && !home.empty())
{
return home;
}
#if CARB_POSIX
// omni-config-cpp had code to handle cases where $HOME was unset, so that remains here.
struct passwd info;
struct passwd* out = nullptr;
omni::extras::ScratchBuffer<char, 4096> buffer;
const long len = sysconf(_SC_GETPW_R_SIZE_MAX);
if (len == -1)
{
return {}; // sysconf() failed
}
if (!buffer.resize(len))
{
return {};
}
const int result = CARB_RETRY_EINTR(getpwuid_r(getuid(), &info, buffer.data(), len, &out));
if (result != 0 || out != &info)
{
return {};
}
return info.pw_dir;
#elif CARB_PLATFORM_WINDOWS
omni::extras::ScratchBuffer<wchar_t, 2048> buffer;
void* token = nullptr;
unsigned long len = 0;
if (!OpenProcessToken(GetCurrentProcess(), CARBWIN_TOKEN_QUERY, &token))
{
return {};
}
CARB_SCOPE_EXIT
{
CloseHandle(token);
};
GetUserProfileDirectoryW(token, nullptr, &len);
if (len == 0)
{
return {};
}
if (!buffer.resize(len))
{
return {};
}
if (!GetUserProfileDirectoryW(token, buffer.data(), &len))
{
return {};
}
const size_t offset = (wcsncmp(buffer.data(), L"\\\\?\\", 4) == 0) ? 4 : 0;
return carb::extras::convertWideStringToUtf8(buffer.data() + offset);
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
}
/** This collects information about standard paths for Omniverse applications, such as the config
* directory, the logs directory, etc.
* This is designed to be a replacement of the omniverse::GlobalConfig class from omni-config-cpp.
* This class is designed for serialized access.
* This does not require the carb framework to be initialized, but omniverse.toml will not be
* loaded without the carb framework.
*/
class OmniConfig
{
public:
OmniConfig(const char* configFileName = "omniverse.toml")
{
carb::extras::Path base;
m_configFileName = configFileName;
m_homePath = omni::extras::getHomePath();
if (!m_homePath.empty())
{
base = m_homePath.join(".nvidia-omniverse");
}
// config directory
std::string omniConfigPath;
if (carb::extras::EnvironmentVariable::getValue("OMNI_CONFIG_PATH", omniConfigPath) && !omniConfigPath.empty())
{
m_baseConfigPath = omniConfigPath;
}
else if (!base.empty())
{
m_baseConfigPath = base.join("config");
}
// log directory
if (!base.empty())
{
m_baseLogsPath = base.join("logs");
}
// data, library and cache directories
// OVCC-1272: This is not a POSIX operation but omni-config-cpp just assumed all non-windows
// was Linux, leading to this split.
#if CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS
const carb::extras::Path xdgData = _getXdgDataDir(m_homePath);
if (!xdgData.empty())
{
m_baseDataPath = xdgData.join("ov").join("data");
m_baseLibraryPath = xdgData.join("ov").join("pkg");
}
const carb::extras::Path xdgCache = _getXdgCacheDir(m_homePath);
if (!xdgCache.empty())
{
m_baseCachePath = xdgCache.join("ov");
}
#elif CARB_PLATFORM_WINDOWS
// OVCC-1271: More robust to use SHGetKnownFolder here (FOLDERID_LocalAppData)
std::string localAppDataStr;
if (carb::extras::EnvironmentVariable::getValue("LOCALAPPDATA", localAppDataStr) && !localAppDataStr.empty())
{
const auto localAppDataOv = carb::extras::Path(localAppDataStr).join("ov");
m_baseDataPath = localAppDataOv.join("data");
m_baseLibraryPath = localAppDataOv.join("pkg");
m_baseCachePath = localAppDataOv.join("cache");
}
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
// Load setting overrides from the config file specified.
// This function uses Carbonite to load these.
_loadSettingOverrides();
}
~OmniConfig()
{
if (m_omniverseToml != nullptr)
{
m_dictionary->destroyItem(m_omniverseToml);
}
}
/** Retrieves the directory to the path to the $HOME directory (%USERPROFILE% on Windows).
* @retval The $HOME directory.
* @retval Empty path on failure.
*/
inline carb::extras::Path getHomePath()
{
return m_homePath;
}
/** Retrieves the directory to the path where Omniverse config files are stored.
* @retval The config directory.
* @retval Empty path on failure.
* @note This can be overridden with the `$OMNI_CONFIG_PATH` environment variable.
*/
inline carb::extras::Path getBaseConfigPath()
{
return m_baseConfigPath;
}
/** Retrieves the directory to the path where Omniverse log files are stored.
* @retval The logs directory.
* @retval Empty path on failure.
*/
inline carb::extras::Path getBaseLogsPath()
{
return m_baseLogsPath;
}
/** Retrieves the directory to the path where Omniverse data files are stored.
* @retval The data directory.
* @retval Empty path on failure.
* @note This returns a non-standard path on Mac OS.
* This is a bug that was inherited from omni-config-cpp.
* This will be fixed in a later version, so this should be considered unstable on Mac OS.
*/
inline carb::extras::Path getBaseDataPath()
{
return m_baseDataPath;
}
/** Retrieves the directory to the path where Omniverse library files are stored.
* @retval The library directory.
* @retval Empty path on failure.
* @note This returns a non-standard path on Mac OS.
* This is a bug that was inherited from omni-config-cpp.
* This will be fixed in a later version, so this should be considered unstable on Mac OS.
*/
inline carb::extras::Path getBaseLibraryPath()
{
return m_baseLibraryPath;
}
/** Retrieves the directory to the path where Omniverse cache files are stored.
* @retval The data directory.
* @retval Empty path on failure.
* @note This returns a non-standard path on Mac OS.
* This is a bug that was inherited from omni-config-cpp.
* This will be fixed in a later version, so this should be considered unstable on Mac OS.
*/
inline carb::extras::Path getBaseCachePath()
{
return m_baseCachePath;
}
/** Retrieves the omniverse.toml dictionary.
* @retval The omniverse.toml dictionary contents.
* This is valid until the class instance is destroyed.
* @retval nullptr if omniverse.toml couldn't be loaded (e.g. the file doesn't exist, the carb
* framework isn't loaded).
* @remarks This is the dictionary that provides overrides for default paths.
* You may want to retrieve this for additional information from omniverse.toml (e.g.
* kit-kernel retrieves paths.documents_root).
* @note omniverse.toml is loaded when the class is constructed.
*/
inline carb::dictionary::Item* getOmniverseToml()
{
return m_omniverseToml;
}
/** Helper to retrieve config strings from omniverse.toml.
* @param path The path to the element in the config.
* Path separators are `/`, so if you wanted `{ paths: { documents_root: "..." } }`,
* you would pass `"paths/documents_root"`.
* @retval The string from @p path in omniverse.toml, if it exists and was a string.
* @retval Empty string if the requested item was not as string, the requested path did not
* exist, omniverse.toml did not exist or the carb framework was not loaded.
*/
std::string getConfigEntry(const char* path)
{
if (m_omniverseToml == nullptr)
{
return {};
}
const carb::dictionary::Item* item = m_dictionary->getItem(m_omniverseToml, path);
if (item == nullptr)
{
return {};
}
return m_dictionary->getStringBuffer(item);
}
private:
#if CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS
/** Retrieve the XDG standard data directory.
* @param[in] home The user's home directory.
* @retval The XDG standard data directory.
* @retval Empty string if nothing could be retrieved.
*/
inline carb::extras::Path _getXdgDataDir(const carb::extras::Path& home)
{
const char* xdg = getenv("XDG_DATA_HOME");
if (xdg != nullptr && xdg[0] != '\0')
{
return xdg;
}
if (home.empty())
{
return {};
}
return home.join(".local").join("share");
}
/** Retrieve the XDG standard cache directory.
* @param[in] home The user's home directory.
* @retval The XDG standard cache directory.
* @retval Empty string if nothing could be retrieved.
*/
inline carb::extras::Path _getXdgCacheDir(const carb::extras::Path& home)
{
const char* xdg = getenv("XDG_CACHE_HOME");
if (xdg != nullptr && xdg[0] != '\0')
{
return xdg;
}
if (home.empty())
{
return {};
}
return home.join(".cache");
}
#endif
/** Load omniverse.toml into m_omniverseToml.
*/
inline void _loadOmniverseToml()
{
carb::Framework* framework = carb::getFramework();
if (framework == nullptr)
{
return;
}
m_dictionary = framework->tryAcquireInterface<carb::dictionary::IDictionary>();
carb::filesystem::IFileSystem* fs = framework->tryAcquireInterface<carb::filesystem::IFileSystem>();
carb::dictionary::ISerializer* serializer =
framework->tryAcquireInterface<carb::dictionary::ISerializer>("carb.dictionary.serializer-toml.plugin");
if (fs == nullptr || m_dictionary == nullptr || serializer == nullptr)
{
return;
}
// Load the file contents
carb::filesystem::File* f = fs->openFileToRead(m_baseConfigPath.join(m_configFileName).getStringBuffer());
if (f == nullptr)
{
return;
}
CARB_SCOPE_EXIT
{
fs->closeFile(f);
};
omni::extras::ScratchBuffer<char, 4096> buffer;
size_t size = fs->getFileSize(f);
if (!buffer.resize(size + 1))
{
return;
}
size_t read = fs->readFileChunk(f, buffer.data(), size);
if (read != size)
{
return;
}
buffer.data()[size] = '\0';
// Parse the toml
m_omniverseToml = serializer->createDictionaryFromStringBuffer(buffer.data());
}
/** Load the setting overrides from the base config path using the Carbonite framework.
*/
void _loadSettingOverrides()
{
_loadOmniverseToml(); // this loads m_omniverseToml
if (m_omniverseToml == nullptr)
{
return;
}
// Load the individual settings
const carb::dictionary::Item* libraryRoot = m_dictionary->getItem(m_omniverseToml, "paths/library_root");
if (libraryRoot != nullptr)
{
m_baseLibraryPath = m_dictionary->getStringBuffer(libraryRoot);
}
const carb::dictionary::Item* dataRoot = m_dictionary->getItem(m_omniverseToml, "paths/data_root");
if (dataRoot != nullptr)
{
m_baseDataPath = m_dictionary->getStringBuffer(dataRoot);
}
const carb::dictionary::Item* cacheRoot = m_dictionary->getItem(m_omniverseToml, "paths/cache_root");
if (cacheRoot != nullptr)
{
m_baseCachePath = m_dictionary->getStringBuffer(cacheRoot);
}
const carb::dictionary::Item* logsRoot = m_dictionary->getItem(m_omniverseToml, "paths/logs_root");
if (logsRoot != nullptr)
{
m_baseLogsPath = m_dictionary->getStringBuffer(logsRoot);
}
}
std::string m_configFileName;
carb::extras::Path m_homePath;
carb::extras::Path m_baseConfigPath;
carb::extras::Path m_baseLogsPath;
carb::extras::Path m_baseDataPath;
carb::extras::Path m_baseLibraryPath;
carb::extras::Path m_baseCachePath;
/** The contents of omniverse.toml.
* This gets set if _loadOmniverseToml() succeeds.
*/
carb::dictionary::Item* m_omniverseToml = nullptr;
/** A cached dictionary interface.
* This gets set if _loadOmniverseToml() succeeds.
*/
carb::dictionary::IDictionary* m_dictionary = nullptr;
};
} // namespace extras
} // namespace omni
| 14,506 | C | 30.674672 | 119 | 0.611885 |
omniverse-code/kit/include/omni/extras/ScratchBuffer.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief A helper class to provide a resizable scratch buffer.
#pragma once
#include "../../carb/Defines.h"
#include <algorithm>
#include <iterator>
namespace omni
{
/** common namespace for extra helper functions and classes. */
namespace extras
{
/** A templated helper class to provide a simple resizable scratch buffer. The buffer will only
* perform a dynamic allocation if the requested size requires it. If only a small size is
* needed, a stack buffer will be used instead. The intended usage pattern is to create the
* object, set its required size, then write to each item in the array as needed. The buffer
* will not be initialized unless the contained type is a class that constructs itself. It
* is left up to the caller to initialize the buffer's contents in all other cases.
*
* The buffer will always occupy enough stack space to hold the larger of 512 bytes worth of
* the contained type, or 16 items of the contained type. If the size is set beyond that
* limit, a new buffer will be allocated from the heap. There is no tracking of how many
* items have been written to the buffer - that is left as an exercise for the caller.
*
* @thread_safety There are no thread safety protections on this class. This is intended
* to be used as a local scratch buffer. If potential concurrent access is
* required, it is the caller's responsibility to protect access to this
* object.
*
* @tparam T The data type that will be contained in the scratch buffer. This
* can be any primitive, struct, or class type.
* @tparam BaseSize_ The number of items of type @p T that can be held in the scratch
* buffer's stack array without needing to allocate from the heap.
* By default, this is guaranteed to be at least 16 items.
* @tparam ShrinkThreshold_ The threshold expressed as a percentage of the buffer's
* previous size below which the buffer itself will be shrunken
* on a resize operation that makes it smaller. If the new
* size of the buffer expressed as a percentage of the old size
* is larger than this number, the previous buffer will be
* kept instead of allocating and copying a new one. This is
* done as a performance optimization for callers that need
* to grow and shrink their buffer frequently, but don't
* necessarily want to incur the overhead of an allocation
* and copy each time. For example, if the threshold is 25%
* and the buffer is resized from 20 items to 6, a reallocation
* will not occur since the new size is 30% of the previous.
* By contrast, if it is resized to 4 items from 20, a reallocation
* will occur since the new size is 20% of the previous. By default
* the buffer will only grow and never shrink regardless of the
* size and number of resize requests.
*/
#ifdef DOXYGEN_BUILD // Sphinx does not like the computation and reports errors, so special case for documentation.
template <typename T, size_t BaseSize_ = 16, size_t ShrinkThreshold_ = 100>
#else
template <typename T, size_t BaseSize_ = CARB_MAX(512ull / sizeof(T), 16ull), size_t ShrinkThreshold_ = 100>
#endif
class ScratchBuffer
{
public:
/** The data type contained in this scratch buffer. This can be any primitive, struct,
* or class type. This is present here so that external callers can inspect the contained
* type if needed.
*/
using DataType = T;
/** The guaranteed base size of this scratch buffer in items. This is present here so that
* external callers can inspect the guaranteed size of the buffer object.
*/
static constexpr size_t BaseSize = BaseSize_;
/** Constructor: initializes a new empty scratch buffer.
*
* @returns no return value.
*/
ScratchBuffer()
{
m_dynamicArray = m_localArray;
m_size = BaseSize;
m_capacity = BaseSize;
}
/** Copy constructor: copies a scratch buffer from another one.
*
* @param[in] right The other scratch buffer to copy. The contents of the buffer will
* be copied into this object and this object will be resized to match
* the size of @p right. The other object will not be modified.
* @returns no return value.
*/
ScratchBuffer(const ScratchBuffer& right)
{
*this = right;
}
/** Move constructor: moves another scratch buffer into this one
*
* @param[in] right The other scratch buffer to move from. The contents of the buffer
* will be copied into this object and this object will be resized to match
* the size of @p right. The other object will be reset back to an empty
* state after the data is moved.
* @returns no return value.
*/
ScratchBuffer(ScratchBuffer&& right)
{
*this = std::move(right);
}
~ScratchBuffer()
{
if (m_dynamicArray != nullptr && m_dynamicArray != m_localArray)
delete[] m_dynamicArray;
}
/** Assignment operator (copy).
*
* @param[in] right The other scratch buffer to copy from.
* @returns A reference to this object. All items in the @p right buffer will be copied
* into this object by the most efficient means possible.
*/
ScratchBuffer& operator=(const ScratchBuffer& right)
{
if (&right == this)
return *this;
if (!resize(right.m_size))
return *this;
std::copy_n(right.m_dynamicArray, m_size, m_dynamicArray);
return *this;
}
/** Assignment operator (move).
*
* @param[in] right The other scratch buffer to move from.
* @returns A reference to this object. All items in the @p right buffer will be moved
* into this object by the most efficient means possible. The @p right buffer
* will be cleared out upon return (this only really has a meaning if the
* contained type is a movable class).
*/
ScratchBuffer& operator=(ScratchBuffer&& right)
{
if (&right == this)
return *this;
if (!resize(right.m_size))
return *this;
std::copy_n(std::make_move_iterator(right.m_dynamicArray), m_size, m_dynamicArray);
return *this;
}
/** Array access operator.
*
* @param[in] index The index to access the array at. It is the caller's responsibility
* to ensure this index is within the bounds of the array.
* @returns A reference to the requested entry in the array as an lvalue.
*/
T& operator[](size_t index)
{
return m_dynamicArray[index];
}
/** Array accessor.
*
* @returns The base address of the buffer. This address will be valid until the next
* call to resize(). It is the caller's responsibility to protect access to
* this buffer as needed.
*/
T* data()
{
return m_dynamicArray;
}
/** @copydoc data() */
const T* data() const
{
return m_dynamicArray;
}
/** Retrieves the current size of the buffer in items.
*
* @returns The current size of this buffer in items. This value is valid until the next
* call to resize(). The size in bytes can be calculated by multiplying this
* value by `sizeof(DataType)`.
*/
size_t size() const
{
return m_size;
}
/** Attempts to resize this buffer.
*
* @param[in] count The new requested size of the buffer in items. This may not be zero.
* @returns `true` if the buffer was successfully resized. If the requested count is
* smaller than or equal to the @p BaseSize value for this object, resizing will
* always succeed.
* @returns `false` if the buffer could not be resized. On failure, the previous contents
* and size of the array will be left unchanged.
*/
bool resize(size_t count)
{
T* tmp = m_localArray;
size_t copyCount;
if (count == 0)
return true;
// the buffer is already the requested size -> nothing to do => succeed.
if (count == m_size)
return true;
// the buffer is already large enough => don't resize unless the change is drastic.
if (count <= m_capacity)
{
if ((count * 100) >= ShrinkThreshold_ * m_size)
{
m_size = count;
return true;
}
}
if (count > BaseSize)
{
tmp = new (std::nothrow) T[count];
if (tmp == nullptr)
return false;
}
// the buffer didn't change -> nothing to copy => update parameters and succeed.
if (tmp == m_dynamicArray)
{
m_size = count;
m_capacity = BaseSize;
return true;
}
copyCount = m_size;
if (m_size > count)
copyCount = count;
std::copy_n(std::make_move_iterator(m_dynamicArray), copyCount, tmp);
if (m_dynamicArray != nullptr && m_dynamicArray != m_localArray)
delete[] m_dynamicArray;
m_dynamicArray = tmp;
m_size = count;
m_capacity = count;
return true;
}
private:
/** The stack allocated space for the buffer. This is always sized to be the larger of
* 512 bytes or enough space to hold 16 items. This array should never be accessed
* directly. If this buffer is in use, the @p m_dynamicArray member will point to
* this buffer.
*/
T m_localArray[BaseSize];
/** The dynamically allocated buffer if the current size is larger than the base size
* of this buffer, or a pointer to @p m_localArray if smaller or equal. This will
* never be `nullptr`.
*/
T* m_dynamicArray;
/** The current size of the buffer in items. */
size_t m_size = BaseSize;
/** The current maximum size of the buffer in items. */
size_t m_capacity = BaseSize;
};
} // namespace extras
} // namespace omni
| 11,198 | C | 37.750865 | 115 | 0.603411 |
omniverse-code/kit/include/omni/extras/ContainerHelper.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/** @file
* @brief Helper functions for dealing with docker containers. These functions will
* fail gracefully on Windows or Mac.
*/
#pragma once
#include "../../carb/Defines.h"
#if CARB_PLATFORM_LINUX
# include <fcntl.h>
# include <unistd.h>
#endif
namespace omni
{
namespace extras
{
#if CARB_PLATFORM_LINUX || defined(DOXYGEN_BUILD)
# ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
inline int readIntFromFile(const char* file) noexcept
{
auto fd = ::open(file, O_RDONLY, 0);
if (fd == -1)
{
return -1;
}
char buffer[64];
auto size = CARB_RETRY_EINTR(::read(fd, buffer, sizeof(buffer) - 1));
::close(fd);
if (size <= 0)
{
return -1;
}
buffer[size] = '\0';
return std::atoi(buffer);
}
inline bool isRunningInContainer() noexcept
{
FILE* fp;
// first (and easiest) check is to check whether the `/.dockerenv` file exists. This file
// is not necessarily always present though.
if (access("/.dockerenv", F_OK) == 0)
{
return true;
}
// a more reliable but more expensive check is to verify the control group of `init`. If
// running under docker, all of the entries will have a path that starts with `/docker` or
// `/lxc` instead of just `/`.
fp = fopen("/proc/1/cgroup", "r");
if (fp != nullptr)
{
char line[256];
while (fgets(line, CARB_COUNTOF(line), fp) != nullptr)
{
if (feof(fp) || ferror(fp))
break;
if (strstr(line, ":/docker") != nullptr || strstr(line, ":/lxc") != nullptr)
{
return true;
}
}
fclose(fp);
}
return false;
}
} // namespace detail
# endif
/** Attempts to read the current effective CPU usage quota for processes in a container.
*
* @returns The effective number of logical cores that processes in the container will have
* access to if a limit has been imposed. If no limit has been imposed when running
* the container, -1 will be returned.
*
* @remarks This reads and calculates the effective CPU usage quota for processes in a container.
* If a limit has been imposed, the result is the number of logical cores that can be
* used. Note that this does not actually guarantee that the processes will not be
* able to run on some cores, but rather that the CPU scheduler will only give a
* certain percentage of its time to processes in the container thereby effectively
* making their performance similar to running on a system with the returned number
* of cores.
*
* @note This will still return a valid result outside of a container if a CPU usage limit has
* been imposed on the system. By default, Linux systems allow unlimited CPU usage.
*/
inline int getDockerCpuLimit() noexcept
{
// See:
// https://docs.docker.com/config/containers/resource_constraints/#cpu
// https://engineering.squarespace.com/blog/2017/understanding-linux-container-scheduling
const auto cfsQuota = detail::readIntFromFile("/sys/fs/cgroup/cpu/cpu.cfs_quota_us");
const auto cfsPeriod = detail::readIntFromFile("/sys/fs/cgroup/cpu/cpu.cfs_period_us");
if (cfsQuota > 0 && cfsPeriod > 0)
{
// Since we can have fractional CPUs, round up half a CPU to a whole CPU, but make sure we have an even number.
return ::carb_max(1, (cfsQuota + (cfsPeriod / 2)) / cfsPeriod);
}
return -1;
}
/** Attempts to detect whether this process is running inside a container.
*
* @returns `true` if this process is running inside a container. Returns `false` otherwise.
*
* @remarks This detects if the calling process is running inside a container. This is done
* by checking for certain files or their contents that are known (and documented)
* to be modified by Docker. Note that this currently only supports detecting Docker
* and LXC containers.
*/
inline bool isRunningInContainer()
{
static bool s_inContainer = detail::isRunningInContainer();
return s_inContainer;
}
#else
inline int getDockerCpuLimit() noexcept
{
return -1;
}
inline bool isRunningInContainer() noexcept
{
return false;
}
#endif
} // namespace extras
} // namespace omni
| 4,791 | C | 29.138365 | 119 | 0.658526 |
omniverse-code/kit/include/omni/math/linalg/debug.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "half.h"
#include "matrix.h"
#include "quat.h"
#include "vec.h"
#include <iomanip>
#include <iostream>
namespace omni
{
namespace math
{
namespace linalg
{
// =================================================================================
// Debug output operators for linalg types
std::ostream& operator<<(std::ostream& out, half const& v)
{
return out << (float)v;
}
template <typename T, size_t precision = 4>
struct NumericFormatter
{
explicit NumericFormatter(T d)
{
m_val = d;
}
static constexpr size_t s_precision = precision;
static constexpr size_t s_width = 14;
T m_val;
};
template <typename T>
std::ostream& operator<<(std::ostream& out, NumericFormatter<T> const& f)
{
return out << std::setprecision(NumericFormatter<T>::s_precision) << std::fixed << std::left
<< std::setw(NumericFormatter<T>::s_width) << std::setfill(' ') << f.m_val;
}
template <typename T, size_t N>
std::ostream& operator<<(std::ostream& out, base_matrix<T, N> const& m)
{
using Fmt = NumericFormatter<T>;
for (size_t i = 0; i < (N - 1); ++i)
{
out << '|';
for (size_t j = 0; j < (N - 1); ++j)
out << Fmt(m[i][j]);
out << Fmt(m[i][N - 1]) << '|';
if (i < (N - 1))
out << '\n';
}
return out;
}
template<typename T, size_t N>
std::ostream& operator<<(std::ostream& out, base_vec<T, N> const& v)
{
using Fmt = NumericFormatter<T>;
out << '(';
for (size_t i = 0; i < (N - 1); ++i)
out << Fmt(v[0]);
return out << Fmt(v[N - 1]) << ')';
}
template <typename T>
std::ostream& operator<<(std::ostream& out, quat<T> const& q)
{
auto i = q.GetImaginary();
auto real = q.GetReal();
return out << vec4<T>{ real, i[0], i[1], i[2] };
}
} // linalg
} // math
} // omni
| 2,278 | C | 24.043956 | 96 | 0.585601 |
omniverse-code/kit/include/omni/math/linalg/SafeCast.h | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <pxr/pxr.h>
#include <type_traits>
#include <stdint.h>
// Forward declarations, to avoid needing to include the world.
PXR_NAMESPACE_OPEN_SCOPE
namespace pxr_half
{
class half;
}
using GfHalf = pxr_half::half;
class GfVec2h;
class GfVec2f;
class GfVec2d;
class GfVec2i;
class GfVec3h;
class GfVec3f;
class GfVec3d;
class GfVec3i;
class GfVec4h;
class GfVec4f;
class GfVec4d;
class GfVec4i;
class GfQuath;
class GfQuatf;
class GfQuatd;
class GfMatrix2f;
class GfMatrix2d;
class GfMatrix3f;
class GfMatrix3d;
class GfMatrix4f;
class GfMatrix4d;
PXR_NAMESPACE_CLOSE_SCOPE
namespace omni
{
namespace math
{
namespace linalg
{
class half;
template <typename T, std::size_t N>
class base_vec;
template <typename T>
class vec2;
template <typename T>
class vec3;
template <typename T>
class vec4;
template <typename T>
class quat;
template <typename T, std::size_t N>
class base_matrix;
template <typename T>
class matrix2;
template <typename T>
class matrix3;
template <typename T>
class matrix4;
using vec2h = vec2<half>;
using vec2f = vec2<float>;
using vec2d = vec2<double>;
using vec2i = vec2<int>;
using vec3h = vec3<half>;
using vec3f = vec3<float>;
using vec3d = vec3<double>;
using vec3i = vec3<int>;
using vec4h = vec4<half>;
using vec4f = vec4<float>;
using vec4d = vec4<double>;
using vec4i = vec4<int>;
using quath = quat<half>;
using quatf = quat<float>;
using quatd = quat<double>;
using matrix2f = matrix2<float>;
using matrix2d = matrix2<double>;
using matrix3f = matrix3<float>;
using matrix3d = matrix3<double>;
using matrix4f = matrix4<float>;
using matrix4d = matrix4<double>;
template<typename T>
struct TypeStruct
{
using type = T;
};
template<typename USD_TYPE>
struct OmniType : TypeStruct<void> {};
template<typename OMNI_TYPE>
struct USDType : TypeStruct<void> {};
template <> struct OmniType<pxr::GfHalf> : TypeStruct<half> {};
template <> struct OmniType<float> : TypeStruct<float> {};
template <> struct OmniType<double> : TypeStruct<double> {};
template <> struct OmniType<int> : TypeStruct<int> {};
template <> struct OmniType<unsigned char> : TypeStruct<unsigned char> {};
template <> struct OmniType<unsigned int> : TypeStruct<unsigned int> {};
template <> struct OmniType<int64_t> : TypeStruct<int64_t> {};
template <> struct OmniType<uint64_t> : TypeStruct<uint64_t> {};
template <> struct OmniType<bool> : TypeStruct<bool> {};
template <> struct OmniType<pxr::GfVec2h> : TypeStruct<vec2h> {};
template <> struct OmniType<pxr::GfVec2f> : TypeStruct<vec2f> {};
template <> struct OmniType<pxr::GfVec2d> : TypeStruct<vec2d> {};
template <> struct OmniType<pxr::GfVec2i> : TypeStruct<vec2i> {};
template <> struct OmniType<pxr::GfVec3h> : TypeStruct<vec3h> {};
template <> struct OmniType<pxr::GfVec3f> : TypeStruct<vec3f> {};
template <> struct OmniType<pxr::GfVec3d> : TypeStruct<vec3d> {};
template <> struct OmniType<pxr::GfVec3i> : TypeStruct<vec3i> {};
template <> struct OmniType<pxr::GfVec4h> : TypeStruct<vec4h> {};
template <> struct OmniType<pxr::GfVec4f> : TypeStruct<vec4f> {};
template <> struct OmniType<pxr::GfVec4d> : TypeStruct<vec4d> {};
template <> struct OmniType<pxr::GfVec4i> : TypeStruct<vec4i> {};
template <> struct OmniType<pxr::GfQuath> : TypeStruct<quath> {};
template <> struct OmniType<pxr::GfQuatf> : TypeStruct<quatf> {};
template <> struct OmniType<pxr::GfQuatd> : TypeStruct<quatd> {};
template <> struct OmniType<pxr::GfMatrix2f> : TypeStruct<matrix2f> {};
template <> struct OmniType<pxr::GfMatrix2d> : TypeStruct<matrix2d> {};
template <> struct OmniType<pxr::GfMatrix3f> : TypeStruct<matrix3f> {};
template <> struct OmniType<pxr::GfMatrix3d> : TypeStruct<matrix3d> {};
template <> struct OmniType<pxr::GfMatrix4f> : TypeStruct<matrix4f> {};
template <> struct OmniType<pxr::GfMatrix4d> : TypeStruct<matrix4d> {};
template <> struct USDType<half> : TypeStruct<pxr::GfHalf> {};
template <> struct USDType<float> : TypeStruct<float> {};
template <> struct USDType<double> : TypeStruct<double> {};
template <> struct USDType<int> : TypeStruct<int> {};
template <> struct USDType<unsigned char> : TypeStruct<unsigned char> {};
template <> struct USDType<unsigned int> : TypeStruct<unsigned int> {};
template <> struct USDType<int64_t> : TypeStruct<int64_t> {};
template <> struct USDType<uint64_t> : TypeStruct<uint64_t> {};
template <> struct USDType<bool> : TypeStruct<bool> {};
template <> struct USDType<vec2h> : TypeStruct<pxr::GfVec2h> {};
template <> struct USDType<vec2f> : TypeStruct<pxr::GfVec2f> {};
template <> struct USDType<vec2d> : TypeStruct<pxr::GfVec2d> {};
template <> struct USDType<vec2i> : TypeStruct<pxr::GfVec2i> {};
template <> struct USDType<vec3h> : TypeStruct<pxr::GfVec3h> {};
template <> struct USDType<vec3f> : TypeStruct<pxr::GfVec3f> {};
template <> struct USDType<vec3d> : TypeStruct<pxr::GfVec3d> {};
template <> struct USDType<vec3i> : TypeStruct<pxr::GfVec3i> {};
template <> struct USDType<vec4h> : TypeStruct<pxr::GfVec4h> {};
template <> struct USDType<vec4f> : TypeStruct<pxr::GfVec4f> {};
template <> struct USDType<vec4d> : TypeStruct<pxr::GfVec4d> {};
template <> struct USDType<vec4i> : TypeStruct<pxr::GfVec4i> {};
template <> struct USDType<quath> : TypeStruct<pxr::GfQuath> {};
template <> struct USDType<quatf> : TypeStruct<pxr::GfQuatf> {};
template <> struct USDType<quatd> : TypeStruct<pxr::GfQuatd> {};
template <> struct USDType<matrix2f> : TypeStruct<pxr::GfMatrix2f> {};
template <> struct USDType<matrix2d> : TypeStruct<pxr::GfMatrix2d> {};
template <> struct USDType<matrix3f> : TypeStruct<pxr::GfMatrix3f> {};
template <> struct USDType<matrix3d> : TypeStruct<pxr::GfMatrix3d> {};
template <> struct USDType<matrix4f> : TypeStruct<pxr::GfMatrix4f> {};
template <> struct USDType<matrix4d> : TypeStruct<pxr::GfMatrix4d> {};
template <typename USD_TYPE>
const typename OmniType<USD_TYPE>::type* safeCastToOmni(const USD_TYPE* p)
{
return reinterpret_cast<const typename OmniType<USD_TYPE>::type*>(p);
}
template <typename USD_TYPE>
typename OmniType<USD_TYPE>::type* safeCastToOmni(USD_TYPE* p)
{
return reinterpret_cast<typename OmniType<USD_TYPE>::type*>(p);
}
template <typename USD_TYPE>
const typename OmniType<USD_TYPE>::type& safeCastToOmni(const USD_TYPE& p)
{
return reinterpret_cast<const typename OmniType<USD_TYPE>::type&>(p);
}
template <typename USD_TYPE>
typename OmniType<USD_TYPE>::type& safeCastToOmni(USD_TYPE& p)
{
return reinterpret_cast<typename OmniType<USD_TYPE>::type&>(p);
}
template <typename OMNI_TYPE>
const typename USDType<OMNI_TYPE>::type* safeCastToUSD(const OMNI_TYPE* p)
{
return reinterpret_cast<const typename USDType<OMNI_TYPE>::type*>(p);
}
template <typename OMNI_TYPE>
typename USDType<OMNI_TYPE>::type* safeCastToUSD(OMNI_TYPE* p)
{
return reinterpret_cast<typename USDType<OMNI_TYPE>::type*>(p);
}
template <typename OMNI_TYPE>
const typename USDType<OMNI_TYPE>::type& safeCastToUSD(const OMNI_TYPE& p)
{
return reinterpret_cast<const typename USDType<OMNI_TYPE>::type&>(p);
}
template <typename OMNI_TYPE>
typename USDType<OMNI_TYPE>::type& safeCastToUSD(OMNI_TYPE& p)
{
return reinterpret_cast<typename USDType<OMNI_TYPE>::type&>(p);
}
}
}
}
| 7,659 | C | 28.236641 | 77 | 0.727771 |
omniverse-code/kit/include/omni/math/linalg/README.md | Moved to include/usdrt/gf
=========================
The implementation of the omni\:\:math\:\:linalg classes has been moved
to `include/usdrt/gf`. The existing headers are left in place as stubs
that include the relocated files so that existing code will work as-is.
| 268 | Markdown | 37.428566 | 71 | 0.705224 |
omniverse-code/kit/include/omni/population/Population.h | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Types.h>
namespace carb { namespace ujitso { struct Agent; } };
namespace omni
{
namespace fabric
{
struct FabricId;
struct UsdStageId;
}
};
namespace omni
{
namespace population
{
// Temporary struct until cache merging and querying are implemented in FabricAgent
struct FabricCache
{
const omni::fabric::FabricId& fabricId;
const omni::fabric::UsdStageId& usdStageId;
};
struct IPopulation
{
CARB_PLUGIN_INTERFACE("omni::population::IPopulation", 0, 1);
// fabricCache is optional, nullptr will create a new cache. Will be removed later.
// if fabricCache contains data, that stage and cache will be populated.
// We pass both the Fabric stage and the cache because in IStageReaderWriter they are tied.
void(CARB_ABI* populateFabric)(carb::ujitso::Agent& agent, const char* usdStagePath, const FabricCache* fabricCache);
};
// TODO: this is only for tests right now, the entire code should be in tests.
// The reason it is here is because test.unit has no dependency on USD now.
// We can either add USD dependency to test.unit or move omni.population tests to e.g. test.unit.fabric
struct IValidate
{
CARB_PLUGIN_INTERFACE("omni::population::IValidate", 0, 1);
bool (CARB_ABI* validateFabric)(const char* stagePath, const omni::fabric::FabricId& fabricId);
};
} // namespace population
} // namespace omni
| 1,910 | C | 32.526315 | 125 | 0.717277 |
omniverse-code/kit/include/omni/detail/ExpectedImpl.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../../carb/cpp/Functional.h"
#include "../../carb/cpp/Memory.h"
#include "../../carb/cpp/TypeTraits.h"
#include "../../carb/cpp/Utility.h"
#include "../../carb/cpp/Memory.h"
#include "../../carb/cpp/TypeTraits.h"
#include "../core/IObject.h"
#include "ConvertsFromAnyCvRef.h"
#include "ParamPack.h"
#include <cstddef>
#include <initializer_list>
//! \cond DEV
//!
//! \file
//! Implementation details for \c omni::expected and related classes.
//!
//! \warning
//! Take \e extreme care when altering anything that can affect ABI. This is not just the obvious things like object
//! structure. ABI altering changes also include changing the trivial-ness of a destructor or copy operation based on a
//! member type.
namespace omni
{
template <typename TValue, typename TError>
class expected;
template <typename TError>
class unexpected;
struct unexpect_t
{
explicit unexpect_t() = default;
};
constexpr unexpect_t unexpect{};
template <typename TError>
class bad_expected_access;
//! \warning
//! This is not ABI safe, since it derives from \c std::exception.
template <>
class bad_expected_access<void> : public std::exception
{
public:
bad_expected_access() = default;
char const* what() const noexcept override
{
return "Invalid access of `omni::expected`";
}
};
//! \warning
//! This is not ABI safe, since it derives from \c std::exception through \c bad_expected_access<void>.
template <typename TError>
class bad_expected_access : public bad_expected_access<void>
{
public:
explicit bad_expected_access(TError e) : m_error(std::move(e))
{
}
TError const& error() const& noexcept
{
return m_error;
}
TError& error() & noexcept
{
return m_error;
}
TError const&& error() const&& noexcept
{
return std::move(m_error);
}
TError&& error() && noexcept
{
return std::move(m_error);
}
private:
TError m_error;
};
namespace detail
{
using carb::cpp::bool_constant;
using carb::cpp::conjunction;
using carb::cpp::disjunction;
using carb::cpp::in_place;
using carb::cpp::in_place_t;
using carb::cpp::is_void;
using carb::cpp::negation;
using carb::cpp::remove_cvref_t;
using carb::cpp::type_identity;
using carb::cpp::void_t;
using omni::core::Result;
using std::conditional_t;
using std::enable_if_t;
using std::false_type;
using std::integral_constant;
using std::is_constructible;
using std::is_copy_constructible;
using std::is_move_constructible;
using std::is_nothrow_constructible;
using std::is_nothrow_copy_assignable;
using std::is_nothrow_copy_constructible;
using std::is_nothrow_destructible;
using std::is_nothrow_move_assignable;
using std::is_nothrow_move_constructible;
using std::is_trivially_copy_assignable;
using std::is_trivially_copy_constructible;
using std::is_trivially_destructible;
using std::is_trivially_move_assignable;
using std::is_trivially_move_constructible;
using std::true_type;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Helpers //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename T>
struct IsExpected : false_type
{
};
template <typename TValue, typename TError>
struct IsExpected<omni::expected<TValue, TError>> : true_type
{
};
template <typename T>
struct IsUnexpected : false_type
{
};
template <typename TError>
struct IsUnexpected<omni::unexpected<TError>> : true_type
{
};
//! This empty structure is used when an \c expected is going to store a \c void element. This is needed because \c void
//! is not a valid \c union member.
struct ExpectedStorageVoid
{
};
//! Test if \c T is a valid \c value_type for \c omni::expected or \c omni::unexpected.
template <typename T>
struct IsValidExpectedValue : conjunction<disjunction<std::is_object<T>, is_void<T>>, negation<std::is_array<T>>>
{
};
//! Test if \c T is a valid \c error_type for \c omni::expected. This is similar to \c IsValidExpectedValue with the
//! additional restrictions that it can not be CV qualified.
template <typename T>
struct IsValidExpectedError : conjunction<disjunction<std::is_object<T>, is_void<T>>,
negation<std::is_array<T>>,
negation<IsUnexpected<T>>,
negation<std::is_const<T>>,
negation<std::is_volatile<T>>>
{
};
//! Apply \c TTTransform to \c T if it is possibly cv \c void or be \c TFallback if it is \c void.
template <template <typename...> class TTTransform, typename T, typename TFallback = void, typename = void_t<>>
struct ExpectedTransformIfNonVoid
{
using type = TFallback;
};
template <template <typename...> class TTTransform, typename T, typename TFallback>
struct ExpectedTransformIfNonVoid<TTTransform, T, TFallback, std::enable_if_t<!std::is_void<T>::value>>
{
using type = typename TTTransform<T>::type;
};
template <typename TFromValue,
typename TFromError,
typename TFromValueExpr,
typename TFromErrorExpr,
typename TToValue,
typename TToError,
typename = void_t<>>
struct IsExpectedConvertibleImpl : std::false_type
{
};
template <typename TFromValue, typename TFromError, typename TFromValueExpr, typename TFromErrorExpr, typename TToValue, typename TToError>
struct IsExpectedConvertibleImpl<
TFromValue,
TFromError,
TFromValueExpr,
TFromErrorExpr,
TToValue,
TToError,
std::enable_if_t<conjunction<
// (18.1): is_constructible_v<T, UF> is true; and
disjunction<conjunction<std::is_void<TToValue>, std::is_void<TFromValue>>, std::is_constructible<TToValue, TFromValue>>,
// (18.2): is_constructible_v<E, GF> is true; and
disjunction<conjunction<std::is_void<TToError>, std::is_void<TFromError>>, std::is_constructible<TToError, TFromError>>,
// (18.3): if T is not cv bool, converts-from-any-cvref<T, expected<U, G>> is false; and
disjunction<std::is_same<bool, std::remove_cv_t<TToValue>>,
negation<ConvertsFromAnyCvRef<TToValue, omni::expected<TFromValue, TFromError>>>>,
// (18.4): is_constructible_v<unexpected<E>, expected<U, G>&> is false; and
negation<std::is_constructible<omni::unexpected<TToError>, omni::expected<TFromValue, TFromError>&>>,
// (18.5): is_constructible_v<unexpected<E>, expected<U, G>> is false; and
negation<std::is_constructible<omni::unexpected<TToError>, omni::expected<TFromValue, TFromError>>>,
// (18.6): is_constructible_v<unexpected<E>, const expected<U, G>&> is false; and
negation<std::is_constructible<omni::unexpected<TToError>, omni::expected<TFromValue, TFromError> const&>>,
// (18.7): is_constructible_v<unexpected<E>, const expected<U, G>> is false.
negation<std::is_constructible<omni::unexpected<TToError>, omni::expected<TFromValue, TFromError> const>>>::value>>
: std::true_type
{
static constexpr bool is_explicit = disjunction<negation<std::is_convertible<TFromValueExpr, TToValue>>,
negation<std::is_convertible<TFromErrorExpr, TToError>>>::value;
};
//! Type test to determine if \c omni::expected \c TFrom is convertible to \c TTo by a converting constructor. The
//! elements are transformed by \c TTTypeTransformer for expressiion value category changes (copy vs move).
//!
//! The final structure will have either 1 or 2 member values:
//!
//! * `static constexpr bool value`: This is \c true if \c TFrom is convertible to \c TTo or \c false if it is not.
//! * `static constexpr bool is_explicit`: This is \c true if the conversion between types should be \c explicit or
//! \c false if it is an implicit conversion. This member is only present if \c value is \c true and is safe for use
//! in SFINAE contexts.
//!
//! This type is responsible for filtering out cases where \c TFrom is exactly equal to \c TTo. If this is the case, it
//! is not convertable, but either copyable or moveable (depending on the member types).
//!
//! \see IsExpectedCopyConstructibleFrom
//! \see IsExpectedMoveConstructibleFrom
template <typename TFrom, typename TTo, template <typename...> class TTTypeTransformer, typename = void_t<>>
struct IsExpectedConvertible : std::false_type
{
};
template <typename TFromValue, typename TFromError, typename TToValue, typename TToError, template <typename...> class TTTypeTransformer>
struct IsExpectedConvertible<
omni::expected<TFromValue, TFromError>,
omni::expected<TToValue, TToError>,
TTTypeTransformer,
std::enable_if_t<!conjunction<std::is_same<TFromValue, TToValue>, std::is_same<TFromError, TToError>>::value>>
: IsExpectedConvertibleImpl<TFromValue,
TFromError,
typename ExpectedTransformIfNonVoid<TTTypeTransformer, TFromValue>::type,
typename ExpectedTransformIfNonVoid<TTTypeTransformer, TFromError>::type,
TToValue,
TToError>
{
};
template <typename T>
struct AddConstLvalueRef
{
using type = std::add_lvalue_reference_t<std::add_const_t<T>>;
};
template <typename TFrom, typename TTo>
using IsExpectedCopyConstructibleFrom = IsExpectedConvertible<TFrom, TTo, AddConstLvalueRef>;
template <typename TFrom, typename TTo>
using IsExpectedMoveConstructibleFrom = IsExpectedConvertible<TFrom, TTo, type_identity>;
template <typename TFrom, typename TTo, typename = void_t<>>
struct IsExpectedDirectConstructibleFromImpl : std::false_type
{
};
template <typename UValue, typename TValue, typename TError>
struct IsExpectedDirectConstructibleFromImpl<
UValue,
omni::expected<TValue, TError>,
std::enable_if_t<
conjunction<negation<is_void<TValue>>,
negation<std::is_same<in_place_t, remove_cvref_t<UValue>>>,
negation<std::is_same<omni::expected<TValue, TError>, remove_cvref_t<UValue>>>,
is_constructible<TValue, UValue>,
negation<IsUnexpected<remove_cvref_t<UValue>>>,
disjunction<negation<std::is_same<bool, remove_cvref_t<TValue>>>, negation<IsExpected<UValue>>>>::value>>
: std::false_type
{
static constexpr bool is_explicit = !std::is_convertible<UValue, TValue>::value;
};
template <typename TFrom, typename TTo>
struct IsExpectedDirectConstructibleFrom : IsExpectedDirectConstructibleFromImpl<TFrom, TTo>
{
};
//! This is used by expected base classes in order to create versions of special constructors (copy and move) without
//! defining them in a way that would interfere with their trivial definition from `= default`.
struct ExpectedCtorBypass
{
};
#if CARB_EXCEPTIONS_ENABLED
//! Implementation of \c expected_reinit which optimizes the algorithm based on if the operations are potentially
//! throwing. The generic case assumes that all operations can throw.
template <typename TOld, typename TNew, typename TParamPack, typename = void_t<>>
struct ExpectedReinitImpl
{
template <typename... TArgs>
static void reinit(TOld* pold, TNew* pnew, TArgs&&... args)
{
TOld temp{ std::move(*pold) };
carb::cpp::destroy_at(pold);
try
{
carb::cpp::construct_at(pnew, std::forward<TArgs>(args)...);
}
catch (...)
{
carb::cpp::construct_at(pold, std::move(temp));
throw;
}
}
};
//! If `TNew(TArgs...)` construction is non-throwing, then we don't need to back up anything.
template <typename TOld, typename TNew, typename... TArgs>
struct ExpectedReinitImpl<TOld, TNew, ParamPack<TArgs...>, std::enable_if_t<std::is_nothrow_constructible<TNew, TArgs...>::value>>
{
static void reinit(TOld* pold, TNew* pnew, TArgs&&... args)
{
carb::cpp::destroy_at(pold);
carb::cpp::construct_at(pnew, std::forward<TArgs>(args)...);
}
};
//! If \c TNew is non-throwing move, but `TNew(TArgs...)` could throw, then create it on the stack first, then move it.
template <typename TOld, typename TNew, typename... TArgs>
struct ExpectedReinitImpl<TOld,
TNew,
ParamPack<TArgs...>,
std::enable_if_t<conjunction<std::is_nothrow_move_constructible<TNew>,
negation<std::is_nothrow_constructible<TNew, TArgs...>>>::value>>
{
static void reinit(TOld* pold, TNew* pnew, TArgs&&... args)
{
TNew temp{ std::forward<TArgs>(args)... };
carb::cpp::destroy_at(pold);
carb::cpp::construct_at(pnew, std::move(temp));
}
};
#else // !CARB_EXCEPTIONS_ENABLED
//! Without exceptions enabled, there is no mechanism for failure, so the algorithm is simple.
template <typename TOld, typename TNew, typename TParamPack>
struct ExpectedReinitImpl
{
template <typename... TArgs>
static void reinit(TOld* pold, TNew* pnew, TArgs&&... args) noexcept
{
carb::cpp::destroy_at(pold);
carb::cpp::construct_at(pnew, std::forward<TArgs>(args)...);
}
};
#endif // CARB_EXCEPTIONS_ENABLED
//! Used in type-changing assignment -- reinitializes the contents of an \c ExpectedStorage union from \c TOld to
//! \c TNew without allowing an uninitialized state to leak (a \c std::bad_variant_access equivalent is not allowed for
//! \c std::expected implementations).
//!
//! \exception
//! An exception raised will leave the \a pold in a non-destructed, but possibly moved-from state.
template <typename TOld, typename TNew, typename... TArgs>
constexpr void expected_reinit(TOld* pold, TNew* pnew, TArgs&&... args)
{
ExpectedReinitImpl<TOld, TNew, ParamPack<TArgs...>>::reinit(pold, pnew, std::forward<TArgs>(args)...);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Unexpected //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename TError>
class UnexpectedImpl
{
static_assert(IsValidExpectedError<TError>::value, "Type is not valid for an expected error type");
template <typename UError>
friend class UnexpectedImpl;
public:
constexpr UnexpectedImpl(UnexpectedImpl const&) = default;
constexpr UnexpectedImpl(UnexpectedImpl&&) = default;
template <typename UError = TError,
typename = std::enable_if_t<conjunction<negation<IsUnexpected<remove_cvref_t<UError>>>,
negation<std::is_same<remove_cvref_t<UError>, in_place_t>>,
is_constructible<TError, UError>>::value>>
constexpr explicit UnexpectedImpl(UError&& src) : m_error{ std::forward<UError>(src) }
{
}
template <typename... TArgs, typename = std::enable_if_t<is_constructible<TError, TArgs...>::value>>
constexpr explicit UnexpectedImpl(in_place_t, TArgs&&... args) : m_error{ std::forward<TArgs>(args)... }
{
}
template <typename U,
typename... TArgs,
typename = std::enable_if_t<is_constructible<TError, std::initializer_list<U>&, TArgs...>::value>>
constexpr explicit UnexpectedImpl(in_place_t, std::initializer_list<U> init_list, TArgs&&... args)
: m_error{ init_list, std::forward<TArgs>(args)... }
{
}
constexpr TError& error() & noexcept
{
return m_error;
}
constexpr TError const& error() const& noexcept
{
return m_error;
}
constexpr TError&& error() && noexcept
{
return std::move(m_error);
}
constexpr TError const&& error() const&& noexcept
{
return std::move(m_error);
}
constexpr void swap(UnexpectedImpl<TError>& other)
{
using std::swap;
swap(m_error, other.m_error);
}
template <typename UError>
constexpr bool operator==(UnexpectedImpl<UError> const& other) const
{
return m_error == other.m_error;
}
protected:
TError m_error;
};
template <>
class UnexpectedImpl<void>
{
public:
constexpr UnexpectedImpl() noexcept
{
}
constexpr explicit UnexpectedImpl(in_place_t) noexcept
{
}
constexpr void error() const noexcept
{
}
constexpr void swap(UnexpectedImpl<void>) noexcept
{
}
constexpr bool operator==(UnexpectedImpl<void>) const noexcept
{
return true;
}
};
//! Called from `expected::error()` overloads when the instance `has_value()`.
[[noreturn]] inline void invalid_expected_access_error() noexcept
{
CARB_FATAL_UNLESS(false, "Call to `omni::expected::error()` on successful instance");
}
#if CARB_EXCEPTIONS_ENABLED
template <typename T>
[[noreturn]] inline enable_if_t<conjunction<negation<std::is_same<std::decay_t<T>, ExpectedStorageVoid>>,
std::is_constructible<std::decay_t<T>, T>>::value>
invalid_expected_access(T&& x)
{
throw ::omni::bad_expected_access<std::decay_t<T>>(std::forward<T>(x));
}
template <typename T>
[[noreturn]] inline enable_if_t<conjunction<negation<std::is_same<std::decay_t<T>, ExpectedStorageVoid>>,
negation<std::is_constructible<std::decay_t<T>, T>>>::value>
invalid_expected_access(T&&)
{
throw ::omni::bad_expected_access<void>();
}
[[noreturn]] inline void invalid_expected_access(ExpectedStorageVoid)
{
throw ::omni::bad_expected_access<void>();
}
#else // !CARB_EXCEPTIONS_ENABLED
template <typename T>
[[noreturn]] inline enable_if_t<std::is_same<std::decay_t<T>, ExpectedStorageVoid>::value> invalid_expected_access(T&&)
{
CARB_FATAL_UNLESS(false, "Invalid access of `omni::expected::value()`");
}
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Storage //
// This section governs the byte layout of an `omni::excepted` and the trivialness of its special member functions //
// (namely: copy, move, and destructor -- initialization is never trivial). All information relevant to the ABI of //
// `expected` should be defined in this section. //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
enum class ExpectedState : std::uint8_t
{
//! The instance holds the success value.
eSUCCESS = 0,
//! The instance holds an error.
eUNEXPECTED = 1,
};
//! The \c ExpectedStorage type stores the value or error contents of an \c expected instance.
//!
//! This is stored as a union to make \c e.value and \c e.error show up properly in debugging.
//!
//! The member \c uninit is used for the copy and move constructors, but only exists in this state inside of an
//! \c ExpectedImplBase constructor for types with non-trivial versions of these operations. While the copy or move
//! constructor needs to initialize either \c value or \c error, there is no syntax in C++ to conditionally do this
//! based on a value.
//!
//! \tparam TrivialDtor If both the \c TValue and \c TError types are either \c void or have trivial destructors, then
//! the union itself does not need a destructor.
// clang-format off
template <typename TValue,
typename TError,
bool TrivialDtor = conjunction<disjunction<is_void<TValue>, is_trivially_destructible<TValue>>,
disjunction<is_void<TError>, is_trivially_destructible<TError>>
>::value
>
union ExpectedStorage;
// clang-format on
template <typename TValue, typename TError>
union ExpectedStorage<TValue, TError, /*TrivialDtor=*/true>
{
conditional_t<is_void<TValue>::value, ExpectedStorageVoid, TValue> value;
conditional_t<is_void<TError>::value, ExpectedStorageVoid, TError> error;
ExpectedStorageVoid uninit;
template <typename... TArgs>
constexpr explicit ExpectedStorage(in_place_t, TArgs&&... args) : value{ std::forward<TArgs>(args)... }
{
}
template <typename... TArgs>
constexpr explicit ExpectedStorage(unexpect_t, TArgs&&... args) : error{ std::forward<TArgs>(args)... }
{
}
constexpr explicit ExpectedStorage(ExpectedCtorBypass) : uninit{}
{
}
};
template <typename TValue, typename TError>
union ExpectedStorage<TValue, TError, /*TrivialDtor=*/false>
{
conditional_t<is_void<TValue>::value, ExpectedStorageVoid, TValue> value;
conditional_t<is_void<TError>::value, ExpectedStorageVoid, TError> error;
ExpectedStorageVoid uninit;
template <typename... TArgs>
constexpr explicit ExpectedStorage(in_place_t, TArgs&&... args) : value{ std::forward<TArgs>(args)... }
{
}
template <typename... TArgs>
constexpr explicit ExpectedStorage(unexpect_t, TArgs&&... args) : error{ std::forward<TArgs>(args)... }
{
}
constexpr explicit ExpectedStorage(ExpectedCtorBypass) : uninit{}
{
}
~ExpectedStorage() noexcept
{
// Intentionally empty -- it is the responsibility of the owner to call value or error destructor, since only it
// knows which alternative is active.
}
};
template <typename TValue, typename TError>
class ExpectedImplBase
{
using StoredValueType = conditional_t<is_void<TValue>::value, ExpectedStorageVoid, TValue>;
using StoredErrorType = conditional_t<is_void<TError>::value, ExpectedStorageVoid, TError>;
template <typename UValue, typename UError>
friend class ExpectedImplBase;
protected:
template <typename... TArgs, typename = enable_if_t<is_constructible<StoredValueType, TArgs...>::value>>
explicit ExpectedImplBase(in_place_t,
TArgs&&... args) noexcept(is_nothrow_constructible<StoredValueType, TArgs...>::value)
: m_state{ ExpectedState::eSUCCESS }, m_storage{ in_place, std::forward<TArgs>(args)... }
{
}
template <typename... TArgs, typename = enable_if_t<is_constructible<StoredErrorType, TArgs...>::value>>
explicit ExpectedImplBase(unexpect_t,
TArgs&&... args) noexcept(is_nothrow_constructible<StoredErrorType, TArgs...>::value)
: m_state{ ExpectedState::eUNEXPECTED }, m_storage{ unexpect, std::forward<TArgs>(args)... }
{
}
template <typename UValue, typename UError>
constexpr explicit ExpectedImplBase(ExpectedCtorBypass bypass, ExpectedImplBase<UValue, UError> const& src)
: m_state{ src.m_state }, m_storage{ bypass }
{
if (src.m_state == ExpectedState::eSUCCESS)
carb::cpp::construct_at(carb::cpp::addressof(m_storage.value), src.m_storage.value);
else
carb::cpp::construct_at(carb::cpp::addressof(m_storage.error), src.m_storage.error);
m_state = src.m_state;
}
template <typename UValue, typename UError>
constexpr explicit ExpectedImplBase(ExpectedCtorBypass bypass, ExpectedImplBase<UValue, UError>&& src)
: m_state{ src.m_state }, m_storage{ bypass }
{
if (src.m_state == ExpectedState::eSUCCESS)
carb::cpp::construct_at(carb::cpp::addressof(m_storage.value), std::move(src.m_storage.value));
else
carb::cpp::construct_at(carb::cpp::addressof(m_storage.error), std::move(src.m_storage.error));
m_state = src.m_state;
}
//! Destroy the contents of this instance. This is called from the destructor of types with non-trivial destructors.
//! It \e must only be called once. See \c ExpectedPayload with \c ExpectedPayloadTag::eCALL_DTOR for usage.
//!
//! \pre This is either a success or unexpected
//! \post The active alternative has been destroyed -- this implementation is in an uninitialized state
void unsafe_destroy()
{
if (m_state == ExpectedState::eSUCCESS)
carb::cpp::destroy_at(carb::cpp::addressof(m_storage.value));
else
carb::cpp::destroy_at(carb::cpp::addressof(m_storage.error));
}
void copy_from(ExpectedImplBase const& src)
{
if (m_state == src.m_state)
{
if (m_state == ExpectedState::eSUCCESS)
m_storage.value = src.m_storage.value;
else
m_storage.error = src.m_storage.error;
}
else if (m_state == ExpectedState::eSUCCESS) // && src.m_state == ExpectedState::eUNEXPECTED
{
expected_reinit(
carb::cpp::addressof(m_storage.value), carb::cpp::addressof(m_storage.error), src.m_storage.error);
}
else // m_state == ExpectedState::eUNEXPECTED && src.m_state == ExpectedState::eSUCCESS
{
expected_reinit(
carb::cpp::addressof(m_storage.error), carb::cpp::addressof(m_storage.value), src.m_storage.value);
}
m_state = src.m_state;
}
void move_from(ExpectedImplBase&& src)
{
if (m_state == src.m_state)
{
if (m_state == ExpectedState::eSUCCESS)
m_storage.value = std::move(src.m_storage.value);
else
m_storage.error = std::move(src.m_storage.error);
}
else if (m_state == ExpectedState::eSUCCESS) // && src.m_state == ExpectedState::eUNEXPECTED
{
expected_reinit(carb::cpp::addressof(m_storage.value), carb::cpp::addressof(m_storage.error),
std::move(src.m_storage.error));
}
else // m_state == ExpectedState::eUNEXPECTED && src.m_state == ExpectedState::eSUCCESS
{
expected_reinit(carb::cpp::addressof(m_storage.error), carb::cpp::addressof(m_storage.value),
std::move(src.m_storage.value));
}
m_state = src.m_state;
}
protected:
ExpectedState m_state;
ExpectedStorage<TValue, TError> m_storage;
};
//! Special case of base class where both alternatives are \c void and we only want to store a byte.
template <>
class ExpectedImplBase<void, void>
{
protected:
explicit ExpectedImplBase(in_place_t) noexcept : m_state{ ExpectedState::eSUCCESS }
{
}
explicit ExpectedImplBase(unexpect_t) noexcept : m_state{ ExpectedState::eUNEXPECTED }
{
}
//! This covers both copy and move constructor use cases, since there isn't data to move anyway.
explicit ExpectedImplBase(ExpectedCtorBypass, ExpectedImplBase const& src) noexcept : m_state{ src.m_state }
{
}
//! Fills the same role as the non-specialized version, but does nothing.
constexpr void unsafe_destroy()
{
}
protected:
ExpectedState m_state;
};
//! Used by \c ExpectedPayload in order to determine which special member functions need definitions vs which of them
//! can be defaulted.
//!
//! - \c eTRIVIAL -- copy, move, and destructor are all trivial, so nothing must be done for any operation
//! - \c eCALL_COPY -- copy is non-trivial, but move and destructor are trivial
//! - \c eCALL_MOVE -- move is non-trivial, but copy and destructor are trivial
//! - \c eCALL_BOTH -- both copy and move are non-trivial, but the destructor is
//! - \c eCALL_DTOR -- the destructor must be called, which makes both copy- and move-assignment non-trivial, as
//! assignment from the opposite alternative can cause the destructor to be called.
//!
//! \see ExpectedPayloadTagFor
enum class ExpectedPayloadTag : std::uint8_t
{
eTRIVIAL,
eCALL_COPY,
eCALL_MOVE,
eCALL_BOTH,
eCALL_DTOR,
};
// clang-format off
template <typename TValue,
typename TError,
bool TrivialCopy = conjunction<disjunction<is_void<TValue>, conjunction<is_trivially_copy_assignable<TValue>, is_trivially_copy_constructible<TValue>>>,
disjunction<is_void<TError>, conjunction<is_trivially_copy_assignable<TError>, is_trivially_copy_constructible<TError>>>
>::value,
bool TrivialMove = conjunction<disjunction<is_void<TValue>, conjunction<is_trivially_move_assignable<TValue>, is_trivially_move_constructible<TValue>>>,
disjunction<is_void<TError>, conjunction<is_trivially_move_assignable<TError>, is_trivially_move_constructible<TError>>>
>::value,
bool TrivialDtor = conjunction<disjunction<is_void<TValue>, is_trivially_destructible<TValue>>,
disjunction<is_void<TError>, is_trivially_destructible<TError>>
>::value
>
struct ExpectedPayloadTagFor;
// clang-format on
template <typename TValue, typename TError>
struct ExpectedPayloadTagFor<TValue, TError, /*TrivialCopy=*/true, /*TrivialMove=*/true, /*TrivialDtor=*/true>
: integral_constant<ExpectedPayloadTag, ExpectedPayloadTag::eTRIVIAL>
{
};
template <typename TValue, typename TError>
struct ExpectedPayloadTagFor<TValue, TError, /*TrivialCopy=*/false, /*TrivialMove=*/true, /*TrivialDtor=*/true>
: integral_constant<ExpectedPayloadTag, ExpectedPayloadTag::eCALL_COPY>
{
};
template <typename TValue, typename TError>
struct ExpectedPayloadTagFor<TValue, TError, /*TrivialCopy=*/true, /*TrivialMove=*/false, /*TrivialDtor=*/true>
: integral_constant<ExpectedPayloadTag, ExpectedPayloadTag::eCALL_MOVE>
{
};
template <typename TValue, typename TError>
struct ExpectedPayloadTagFor<TValue, TError, /*TrivialCopy=*/false, /*TrivialMove=*/false, /*TrivialDtor=*/true>
: integral_constant<ExpectedPayloadTag, ExpectedPayloadTag::eCALL_BOTH>
{
};
template <typename TValue, typename TError, bool TrivialCopy, bool TrivialMove>
struct ExpectedPayloadTagFor<TValue, TError, TrivialCopy, TrivialMove, /*TrivialDtor=*/false>
: integral_constant<ExpectedPayloadTag, ExpectedPayloadTag::eCALL_DTOR>
{
};
//! The payload is responsible for managing the special member functions of copy and move construction and assignment,
//! as well as the destructor.
template <typename TValue, typename TError, ExpectedPayloadTag Optimization = ExpectedPayloadTagFor<TValue, TError>::value>
class ExpectedPayload;
template <typename TValue, typename TError>
class ExpectedPayload<TValue, TError, ExpectedPayloadTag::eTRIVIAL> : public ExpectedImplBase<TValue, TError>
{
public:
using ExpectedImplBase<TValue, TError>::ExpectedImplBase;
ExpectedPayload(ExpectedPayload const&) = default;
ExpectedPayload(ExpectedPayload&&) = default;
ExpectedPayload& operator=(ExpectedPayload const&) = default;
ExpectedPayload& operator=(ExpectedPayload&&) = default;
~ExpectedPayload() = default;
};
template <typename TValue, typename TError>
class ExpectedPayload<TValue, TError, ExpectedPayloadTag::eCALL_COPY> : public ExpectedImplBase<TValue, TError>
{
public:
using ExpectedImplBase<TValue, TError>::ExpectedImplBase;
ExpectedPayload(ExpectedPayload const&) = default;
ExpectedPayload(ExpectedPayload&&) = default;
// clang-format off
ExpectedPayload& operator=(ExpectedPayload const& src)
noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_copy_constructible<TValue>, is_nothrow_copy_assignable<TValue>>>,
disjunction<is_void<TError>, conjunction<is_nothrow_copy_constructible<TError>, is_nothrow_copy_assignable<TError>>>
>::value
)
{
this->copy_from(src);
return *this;
}
// clang-format on
ExpectedPayload& operator=(ExpectedPayload&&) = default;
~ExpectedPayload() = default;
};
template <typename TValue, typename TError>
class ExpectedPayload<TValue, TError, ExpectedPayloadTag::eCALL_MOVE> : public ExpectedImplBase<TValue, TError>
{
public:
using ExpectedImplBase<TValue, TError>::ExpectedImplBase;
ExpectedPayload(ExpectedPayload const&) = default;
ExpectedPayload(ExpectedPayload&&) = default;
ExpectedPayload& operator=(ExpectedPayload const&) = default;
// clang-format off
ExpectedPayload& operator=(ExpectedPayload&& src)
noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_move_constructible<TValue>, is_nothrow_move_assignable<TValue>>>,
disjunction<is_void<TError>, conjunction<is_nothrow_move_constructible<TError>, is_nothrow_move_assignable<TError>>>
>::value
)
{
this->move_from(std::move(src));
return *this;
}
// clang-format on
~ExpectedPayload() = default;
};
template <typename TValue, typename TError>
class ExpectedPayload<TValue, TError, ExpectedPayloadTag::eCALL_BOTH> : public ExpectedImplBase<TValue, TError>
{
public:
using ExpectedImplBase<TValue, TError>::ExpectedImplBase;
ExpectedPayload(ExpectedPayload const&) = default;
ExpectedPayload(ExpectedPayload&&) = default;
// clang-format off
ExpectedPayload& operator=(ExpectedPayload const& src)
noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_copy_constructible<TValue>, is_nothrow_copy_assignable<TValue>>>,
disjunction<is_void<TError>, conjunction<is_nothrow_copy_constructible<TError>, is_nothrow_copy_assignable<TError>>>
>::value
)
{
this->copy_from(src);
return *this;
}
ExpectedPayload& operator=(ExpectedPayload&& src)
noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_move_constructible<TValue>, is_nothrow_move_assignable<TValue>>>,
disjunction<is_void<TError>, conjunction<is_nothrow_move_constructible<TError>, is_nothrow_move_assignable<TError>>>
>::value
)
{
this->move_from(std::move(src));
return *this;
}
// clang-format on
~ExpectedPayload() = default;
};
template <typename TValue, typename TError>
class ExpectedPayload<TValue, TError, ExpectedPayloadTag::eCALL_DTOR> : public ExpectedImplBase<TValue, TError>
{
public:
using ExpectedImplBase<TValue, TError>::ExpectedImplBase;
ExpectedPayload(ExpectedPayload const&) = default;
ExpectedPayload(ExpectedPayload&&) = default;
// clang-format off
ExpectedPayload& operator=(ExpectedPayload const& src)
noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_copy_constructible<TValue>, is_nothrow_copy_assignable<TValue>>>,
disjunction<is_void<TError>, conjunction<is_nothrow_copy_constructible<TError>, is_nothrow_copy_assignable<TError>>>
>::value
)
{
this->copy_from(src);
return *this;
}
ExpectedPayload& operator=(ExpectedPayload&& src)
noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_move_constructible<TValue>, is_nothrow_move_assignable<TValue>>>,
disjunction<is_void<TError>, conjunction<is_nothrow_move_constructible<TError>, is_nothrow_move_assignable<TError>>>
>::value
)
{
this->move_from(std::move(src));
return *this;
}
~ExpectedPayload()
noexcept(conjunction<disjunction<is_void<TValue>, is_nothrow_destructible<TValue>>,
disjunction<is_void<TError>, is_nothrow_destructible<TError>>
>::value
)
{
this->unsafe_destroy();
}
// clang-format on
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// API //
// These classes layer the API based on the type of TValue and TError (specifically: Are they void or an object?). //
// Definitions in this section shall not affect the ABI of an `omni::expected` type; special members are all defined //
// by `= default` or by `using BaseType::BaseType`. //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// clang-format off
//! This class controls the presence and trivialness of copy and move constructors.
//!
//! A copy or move constructor can be defaulted, defined, or deleted. The operation is defaulted when both \c TValue and
//! \c TError are either \c void or have that operation as trivial as well (this comes from the definition of when this
//! is allowed on \c union types). If either \c TValue or \c TError has the operation deleted, it is deleted on the
//! \c expected type as well. For the cases where the operation is non-trivial, it is defined explicitly using the
//! \c ExpectedCtorBypass trick. Since these 3 options can happen for both copy and move operations, this results in 9
//! partial specializations.
//!
//! The `= delete` overloads are not needed, as `= default`ing these will still end up with a deleted definition since
//! the \c ExpectedStorage union is deleted by default. However, this leads to awful error messages that lead people to
//! think the implementation is broken. By spelling them out, the `= delete` looks more intentional.
template <typename TValue,
typename TError,
bool CopyCtor = conjunction<disjunction<is_void<TValue>, is_copy_constructible<TValue>>,
disjunction<is_void<TError>, is_copy_constructible<TError>>
>::value,
bool DefaultCopyCtor = conjunction<bool_constant<CopyCtor>,
disjunction<is_void<TValue>, is_trivially_copy_constructible<TValue>>,
disjunction<is_void<TError>, is_trivially_copy_constructible<TError>>
>::value,
bool MoveCtor = conjunction<disjunction<is_void<TValue>, is_move_constructible<TValue>>,
disjunction<is_void<TError>, is_move_constructible<TError>>
>::value,
bool DefaultMoveCtor = conjunction<bool_constant<MoveCtor>,
disjunction<is_void<TValue>, is_trivially_move_constructible<TValue>>,
disjunction<is_void<TError>, is_trivially_move_constructible<TError>>
>::value
>
class ExpectedApiCtors;
// clang-format on
template <typename TValue, typename TError>
class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/true, /*MoveCtor=*/true, /*DefaultMoveCtor=*/true>
: public ExpectedPayload<TValue, TError>
{
public:
using ExpectedPayload<TValue, TError>::ExpectedPayload;
ExpectedApiCtors(ExpectedApiCtors const&) = default;
ExpectedApiCtors(ExpectedApiCtors&&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default;
~ExpectedApiCtors() = default;
};
template <typename TValue, typename TError>
class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/true, /*MoveCtor=*/false, /*DefaultMoveCtor=*/false>
: public ExpectedPayload<TValue, TError>
{
public:
using ExpectedPayload<TValue, TError>::ExpectedPayload;
ExpectedApiCtors(ExpectedApiCtors const&) = default;
ExpectedApiCtors(ExpectedApiCtors&&) = delete;
ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default;
~ExpectedApiCtors() = default;
};
template <typename TValue, typename TError>
class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/true, /*MoveCtor=*/true, /*DefaultMoveCtor=*/false>
: public ExpectedPayload<TValue, TError>
{
public:
using ExpectedPayload<TValue, TError>::ExpectedPayload;
ExpectedApiCtors(ExpectedApiCtors const&) = default;
constexpr ExpectedApiCtors(ExpectedApiCtors&& src) noexcept(
conjunction<disjunction<is_void<TValue>, is_nothrow_move_constructible<TValue>>,
disjunction<is_void<TError>, is_nothrow_move_constructible<TError>>>::value)
: ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, std::move(src) }
{
}
ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default;
~ExpectedApiCtors() = default;
};
template <typename TValue, typename TError>
class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/false, /*DefaultCopyCtor=*/false, /*MoveCtor=*/true, /*DefaultMoveCtor=*/true>
: public ExpectedPayload<TValue, TError>
{
public:
using ExpectedPayload<TValue, TError>::ExpectedPayload;
ExpectedApiCtors(ExpectedApiCtors const&) = delete;
ExpectedApiCtors(ExpectedApiCtors&&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default;
~ExpectedApiCtors() = default;
};
template <typename TValue, typename TError>
class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/false, /*DefaultCopyCtor=*/false, /*MoveCtor=*/false, /*DefaultMoveCtor=*/false>
: public ExpectedPayload<TValue, TError>
{
public:
using ExpectedPayload<TValue, TError>::ExpectedPayload;
ExpectedApiCtors(ExpectedApiCtors const&) = delete;
ExpectedApiCtors(ExpectedApiCtors&&) = delete;
ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default;
~ExpectedApiCtors() = default;
};
template <typename TValue, typename TError>
class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/false, /*DefaultCopyCtor=*/false, /*MoveCtor=*/true, /*DefaultMoveCtor=*/false>
: public ExpectedPayload<TValue, TError>
{
public:
using ExpectedPayload<TValue, TError>::ExpectedPayload;
ExpectedApiCtors(ExpectedApiCtors const&) = delete;
constexpr ExpectedApiCtors(ExpectedApiCtors&& src) noexcept(
conjunction<disjunction<is_void<TValue>, is_nothrow_move_constructible<TValue>>,
disjunction<is_void<TError>, is_nothrow_move_constructible<TError>>>::value)
: ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, std::move(src) }
{
}
ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default;
~ExpectedApiCtors() = default;
};
template <typename TValue, typename TError>
class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/false, /*MoveCtor=*/true, /*DefaultMoveCtor=*/true>
: public ExpectedPayload<TValue, TError>
{
public:
using ExpectedPayload<TValue, TError>::ExpectedPayload;
constexpr ExpectedApiCtors(ExpectedApiCtors const& src) noexcept(
conjunction<disjunction<is_void<TValue>, is_nothrow_copy_constructible<TValue>>,
disjunction<is_void<TError>, is_nothrow_copy_constructible<TError>>>::value)
: ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, src }
{
}
ExpectedApiCtors(ExpectedApiCtors&&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default;
~ExpectedApiCtors() = default;
};
template <typename TValue, typename TError>
class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/false, /*MoveCtor=*/false, /*DefaultMoveCtor=*/false>
: public ExpectedPayload<TValue, TError>
{
public:
using ExpectedPayload<TValue, TError>::ExpectedPayload;
constexpr ExpectedApiCtors(ExpectedApiCtors const& src) noexcept(
conjunction<disjunction<is_void<TValue>, is_nothrow_copy_constructible<TValue>>,
disjunction<is_void<TError>, is_nothrow_copy_constructible<TError>>>::value)
: ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, src }
{
}
ExpectedApiCtors(ExpectedApiCtors&&) = delete;
ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default;
~ExpectedApiCtors() = default;
};
template <typename TValue, typename TError>
class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/false, /*MoveCtor=*/true, /*DefaultMoveCtor=*/false>
: public ExpectedPayload<TValue, TError>
{
public:
using ExpectedPayload<TValue, TError>::ExpectedPayload;
constexpr ExpectedApiCtors(ExpectedApiCtors const& src) noexcept(
conjunction<disjunction<is_void<TValue>, is_nothrow_copy_constructible<TValue>>,
disjunction<is_void<TError>, is_nothrow_copy_constructible<TError>>>::value)
: ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, src }
{
}
constexpr ExpectedApiCtors(ExpectedApiCtors&& src) noexcept(
conjunction<disjunction<is_void<TValue>, is_nothrow_move_constructible<TValue>>,
disjunction<is_void<TError>, is_nothrow_move_constructible<TError>>>::value)
: ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, std::move(src) }
{
}
ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default;
ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default;
~ExpectedApiCtors() = default;
};
//! \tparam IsObject Is the error an object type? This is false in the case where \c TError is a possibly cv-qualified
//! \c void. The allowance of cv-qualified types is why the partial specialization operates on this extra
//! parameter instead of simply covering the case of `class ExpectedApiError<TValue, void>`.
template <typename TValue, typename TError, bool IsObject = !is_void<TError>::value>
class ExpectedApiError : public ExpectedApiCtors<TValue, TError>
{
using BaseType = ExpectedApiCtors<TValue, TError>;
public:
using BaseType::BaseType;
template <typename... TArgs, typename = enable_if_t<is_constructible<TError, TArgs...>::value>>
explicit ExpectedApiError(unexpect_t, TArgs&&... args) noexcept(is_nothrow_constructible<TError, TArgs...>::value)
: BaseType{ unexpect, std::forward<TArgs>(args)... }
{
}
constexpr TError const& error() const& noexcept
{
if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED))
invalid_expected_access_error();
return this->m_storage.error;
}
constexpr TError& error() & noexcept
{
if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED))
invalid_expected_access_error();
return this->m_storage.error;
}
constexpr TError const&& error() const&& noexcept
{
if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED))
invalid_expected_access_error();
return std::move(this->m_storage.error);
}
constexpr TError&& error() && noexcept
{
if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED))
invalid_expected_access_error();
return std::move(this->m_storage.error);
}
protected:
//! \{
//! Called from \c ExpectedApiValue when a caller attempts to access a \c value requiring function, but the monad is
//! in the error state. These functions throw their errors in the exception, but when \c TError is \c void, the
//! \c m_storage.error is invalid (if both \c TValue and \c TError are \c void, \c m_storage does not exist at all).
//! Handling this at the \c ExpectedApiError layer seems the most elegant approach.
//!
//! \pre `this->m_state == ExpectedState::eUNEXPECTED`
[[noreturn]] void invalid_value_access() const&
{
CARB_FATAL_UNLESS(
this->m_state == ExpectedState::eUNEXPECTED, "internal error: omni::expected::m_state must be eUNEXPECTED");
invalid_expected_access(this->m_storage.error);
}
[[noreturn]] void invalid_value_access() &
{
CARB_FATAL_UNLESS(
this->m_state == ExpectedState::eUNEXPECTED, "internal error: omni::expected::m_state must be eUNEXPECTED");
invalid_expected_access(this->m_storage.error);
}
[[noreturn]] void invalid_value_access() &&
{
CARB_FATAL_UNLESS(
this->m_state == ExpectedState::eUNEXPECTED, "internal error: omni::expected::m_state must be eUNEXPECTED");
invalid_expected_access(std::move(this->m_storage.error));
}
[[noreturn]] void invalid_value_access() const&&
{
CARB_FATAL_UNLESS(
this->m_state == ExpectedState::eUNEXPECTED, "internal error: omni::expected::m_state must be eUNEXPECTED");
invalid_expected_access(std::move(this->m_storage.error));
}
//! \}
};
template <typename TValue, typename TError>
class ExpectedApiError<TValue, TError, /*IsObject=*/false> : public ExpectedApiCtors<TValue, TError>
{
using BaseType = ExpectedApiCtors<TValue, TError>;
using BaseType::BaseType;
public:
constexpr ExpectedApiError(unexpect_t) noexcept : BaseType{ unexpect }
{
}
// NOTE: This from-unexpected constructor does not have a mirror in the `ExpectedApiError<..., IsObject=True>`
// implementation, as that conversion constructor comes from the `expected` class.
constexpr ExpectedApiError(unexpected<void> const&) noexcept : BaseType{ unexpect }
{
}
constexpr void error() const& noexcept
{
if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED))
invalid_expected_access_error();
}
constexpr void error() && noexcept
{
if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED))
invalid_expected_access_error();
}
protected:
[[noreturn]] void invalid_value_access() const
{
CARB_FATAL_UNLESS(
this->m_state == ExpectedState::eUNEXPECTED, "internal error: omni::expected::m_state must be eUNEXPECTED");
invalid_expected_access(ExpectedStorageVoid{});
}
};
//! \tparam IsObject Is the value an object type? This is false in the case where \c TValue is a possibly cv-qualified
//! \c void. The allowance of cv-qualified types is why the partial specialization operates on this extra
//! parameter instead of simply covering the case of `class ExpectedApiValue<void, TError>`.
template <typename TValue, typename TError, bool IsObject = !is_void<TValue>::value>
class ExpectedApiValue : public ExpectedApiError<TValue, TError>
{
using BaseType = ExpectedApiError<TValue, TError>;
using BaseType::BaseType;
public:
template <typename = std::enable_if_t<std::is_default_constructible<TValue>::value>>
constexpr ExpectedApiValue() noexcept(std::is_nothrow_default_constructible<TValue>::value) : BaseType{ in_place }
{
}
template <typename... TArgs, typename = enable_if_t<is_constructible<TValue, TArgs...>::value>>
explicit ExpectedApiValue(in_place_t, TArgs&&... args) noexcept(is_nothrow_constructible<TValue, TArgs...>::value)
: BaseType{ in_place, std::forward<TArgs>(args)... }
{
}
constexpr TValue& value() &
{
if (this->m_state != ExpectedState::eSUCCESS)
this->invalid_value_access();
else
return this->m_storage.value;
}
constexpr TValue const& value() const&
{
if (this->m_state != ExpectedState::eSUCCESS)
this->invalid_value_access();
else
return this->m_storage.value;
}
constexpr TValue&& value() &&
{
if (this->m_state != ExpectedState::eSUCCESS)
std::move(*this).invalid_value_access();
else
return std::move(this->m_storage.value);
}
constexpr TValue const&& value() const&&
{
if (this->m_state != ExpectedState::eSUCCESS)
std::move(*this).invalid_value_access();
else
return std::move(this->m_storage.value);
}
template <typename UValue>
constexpr TValue value_or(UValue&& default_value) const&
{
if (this->m_state == ExpectedState::eSUCCESS)
return this->m_storage.value;
else
return static_cast<TValue>(std::forward<UValue>(default_value));
}
template <typename UValue>
constexpr TValue value_or(UValue&& default_value) &&
{
if (this->m_state == ExpectedState::eSUCCESS)
return std::move(this->m_storage.value);
else
return static_cast<TValue>(std::forward<UValue>(default_value));
}
constexpr TValue const& operator*() const& noexcept
{
return this->value();
}
constexpr TValue& operator*() & noexcept
{
return this->value();
}
constexpr TValue const&& operator*() const&& noexcept
{
return std::move(*this).value();
}
constexpr TValue&& operator*() && noexcept
{
return std::move(*this).value();
}
constexpr TValue const* operator->() const noexcept
{
return &this->value();
}
constexpr TValue* operator->() noexcept
{
return &this->value();
}
template <typename... TArgs>
constexpr std::enable_if_t<std::is_nothrow_constructible<TValue, TArgs...>::value, TValue&> emplace(TArgs&&... args) noexcept
{
return this->emplace_impl(std::forward<TArgs>(args)...);
}
template <typename U, typename... TArgs>
constexpr std::enable_if_t<std::is_nothrow_constructible<TValue, std::initializer_list<U>&, TArgs...>::value, TValue&> emplace(
std::initializer_list<U>& arg0, TArgs&&... args) noexcept
{
return this->emplace_impl(arg0, std::forward<TArgs>(args)...);
}
private:
template <typename... TArgs>
constexpr TValue& emplace_impl(TArgs&&... args)
{
if (this->m_state == ExpectedState::eSUCCESS)
expected_reinit(carb::cpp::addressof(this->m_storage.value), carb::cpp::addressof(this->m_storage.value),
std::forward<TArgs>(args)...);
else
expected_reinit(carb::cpp::addressof(this->m_storage.error), carb::cpp::addressof(this->m_storage.value),
std::forward<TArgs>(args)...);
this->m_state = ExpectedState::eSUCCESS;
return this->m_storage.value;
}
};
template <typename TValue, typename TError>
class ExpectedApiValue<TValue, TError, /*IsObject=*/false> : public ExpectedApiError<TValue, TError>
{
using BaseType = ExpectedApiError<TValue, TError>;
public:
using BaseType::BaseType;
constexpr explicit ExpectedApiValue() noexcept : BaseType{ in_place }
{
}
constexpr explicit ExpectedApiValue(in_place_t) noexcept : BaseType{ in_place }
{
}
ExpectedApiValue(ExpectedApiValue const&) = default;
ExpectedApiValue(ExpectedApiValue&&) = default;
ExpectedApiValue& operator=(ExpectedApiValue const&) = default;
ExpectedApiValue& operator=(ExpectedApiValue&&) = default;
~ExpectedApiValue() = default;
constexpr void value() &
{
if (this->m_state != ExpectedState::eSUCCESS)
this->invalid_value_access();
}
constexpr void value() const&
{
if (this->m_state != ExpectedState::eSUCCESS)
this->invalid_value_access();
}
constexpr void value() &&
{
if (this->m_state != ExpectedState::eSUCCESS)
std::move(*this).invalid_value_access();
}
constexpr void value() const&&
{
if (this->m_state != ExpectedState::eSUCCESS)
std::move(*this).invalid_value_access();
}
constexpr void operator*() const noexcept
{
value();
}
constexpr void emplace() noexcept
{
if (this->m_state != ExpectedState::eSUCCESS)
{
// Destroy the error state if one exists (note that if TError is also void, there is no m_storage)
this->unsafe_destroy();
this->m_state = ExpectedState::eSUCCESS;
}
}
};
template <typename TValue, typename TError>
class ExpectedImpl : public ExpectedApiValue<TValue, TError>
{
using BaseType = ExpectedApiValue<TValue, TError>;
static_assert(!std::is_same<in_place_t, std::remove_cv_t<TValue>>::value, "expected value can not be in_place_t");
static_assert(!std::is_same<in_place_t, std::remove_cv_t<TError>>::value, "expected error can not be in_place_t");
static_assert(!std::is_same<unexpect_t, std::remove_cv_t<TValue>>::value, "expected value can not be unexpect_t");
static_assert(!std::is_same<unexpect_t, std::remove_cv_t<TError>>::value, "expected error can not be unexpect_t");
public:
using BaseType::BaseType;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Monadic Operations //
// Functions like `expected::transform` are complicated by `void`, which is syntactically separate from a value type. //
// The implementation is split into separate parts: `ExpectedMonadOpImpl`, which contains the implementation of all //
// valid monadic operations and is specialized per type transform; `ExpectedOp___` per function, which chooses the //
// proper type transformation. The grouping of functions this way seems slightly easier to read, but it still hairy. //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MSC thinks some of the code branches in these implementations are unreachable. Specifically, it dislikes the use of a
// return statement after a call to `carb::cpp::invoke(f)` (with no second parameter). The invoke implementation is
// not marked `[[noreturn]]` or anything like that and the unit tests exercise that code path, so it is unclear why MSC
// thinks that. This can be removed when MS fixes the bug.
CARB_IGNOREWARNING_MSC_WITH_PUSH(4702) // unreachable code
//! Each \c ExpectedMonadOpImpl contains the four monadic operations for \c expected (22.8.6.7). The template parameters
//! represent the non-ref-qualified \c value_type and \c error_type parameters of the \c expected instance and result
//! type; \c TValue and \c TError for the instance, \c RValue and \c RError for the result. The function implementation
//! takes care of the ref-qualification of the expression category (e.g. the \c expected::transform ref-qualified as
//! `&&` passes \c TExpected as `std::move(*this)` so the values are moved).
//!
//! Partial specializations of this place \c void for the type parameters, since the syntax for invoking and returning
//! \c void is different than a non \c void value. There are 16 specializations of this template, but not all
//! specializations contain implementations for all functions, as some of them are invalid. For example, it is not legal
//! to change the type of \c error_type via the \c transform operation, so the \c ExpectedMonadOpImpl where
//! `(TError == void) != (RError == void)` do not exist.
template <typename TValue, typename TError, typename RValue, typename RError>
struct ExpectedMonadOpImpl
{
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, TError> transform(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<RValue, TError>(
in_place, carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value()));
else
return omni::expected<RValue, TError>(unexpect, std::forward<TExpected>(ex).error());
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, RError> and_then(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value());
else
return omni::expected<RValue, RError>(unexpect, std::forward<TExpected>(ex).error());
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, RError> transform_error(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<RValue, RError>(in_place, std::forward<TExpected>(ex).value());
else
return omni::expected<RValue, RError>(
unexpect, carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error()));
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, RError> or_else(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<RValue, RError>(in_place, std::forward<TExpected>(ex).value());
else
return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error());
}
};
template <typename TError, typename RError>
struct ExpectedMonadOpImpl<void, TError, void, RError>
{
template <typename FTransform, typename TExpected>
static constexpr omni::expected<void, TError> transform(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
{
carb::cpp::invoke(std::forward<FTransform>(f));
return omni::expected<void, TError>(in_place);
}
else
{
return omni::expected<void, TError>(unexpect, std::forward<TExpected>(ex).error());
}
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<void, RError> and_then(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return carb::cpp::invoke(std::forward<FTransform>(f));
else
return omni::expected<void, RError>(unexpect, std::forward<TExpected>(ex).error());
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<void, RError> transform_error(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<void, RError>(in_place);
else
return omni::expected<void, RError>(
unexpect, carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error()));
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<void, RError> or_else(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<void, RError>(in_place);
else
return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error());
}
};
template <typename TValue, typename RValue>
struct ExpectedMonadOpImpl<TValue, void, RValue, void>
{
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, void> transform(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<RValue, void>(
in_place, carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value()));
else
return omni::expected<RValue, void>(unexpect);
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, void> and_then(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value());
else
return omni::expected<RValue, void>(unexpect);
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, void> transform_error(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
{
return omni::expected<RValue, void>(in_place, std::forward<TExpected>(ex).value());
}
else
{
carb::cpp::invoke(std::forward<FTransform>(f));
return omni::expected<RValue, void>(unexpect);
}
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, void> or_else(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<RValue, void>(in_place, std::forward<TExpected>(ex).value());
else
return carb::cpp::invoke(std::forward<FTransform>(f));
}
};
template <typename TValue, typename TError, typename RError>
struct ExpectedMonadOpImpl<TValue, TError, void, RError>
{
template <typename FTransform, typename TExpected>
static constexpr omni::expected<void, TError> transform(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
{
carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value());
return omni::expected<void, TError>(in_place);
}
else
{
return omni::expected<void, TError>(unexpect, std::forward<TExpected>(ex).error());
}
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<void, RError> and_then(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value());
else
return omni::expected<void, RError>(unexpect, std::forward<TExpected>(ex).error());
}
};
template <typename TError, typename RValue, typename RError>
struct ExpectedMonadOpImpl<void, TError, RValue, RError>
{
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, TError> transform(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<RValue, TError>(in_place, carb::cpp::invoke(std::forward<FTransform>(f)));
else
return omni::expected<RValue, TError>(unexpect, std::forward<TExpected>(ex).error());
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, RError> and_then(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return carb::cpp::invoke(std::forward<FTransform>(f));
else
return omni::expected<RValue, RError>(unexpect, std::forward<TExpected>(ex).error());
}
};
template <typename TValue>
struct ExpectedMonadOpImpl<TValue, void, void, void>
{
template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>>
static constexpr TReturn transform(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
{
carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value());
return TReturn(in_place);
}
else
{
return TReturn(unexpect);
}
}
template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>>
static constexpr TReturn and_then(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value());
else
return TReturn(unexpect);
}
};
template <typename RValue>
struct ExpectedMonadOpImpl<void, void, RValue, void>
{
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, void> transform(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<RValue, void>(in_place, carb::cpp::invoke(std::forward<FTransform>(f)));
else
return omni::expected<RValue, void>(unexpect);
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, void> and_then(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return carb::cpp::invoke(std::forward<FTransform>(f));
else
return omni::expected<RValue, void>(unexpect);
}
};
template <typename TValue, typename TError, typename RValue>
struct ExpectedMonadOpImpl<TValue, TError, RValue, void>
{
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, void> transform_error(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
{
return omni::expected<RValue, void>(in_place, std::forward<TExpected>(ex).value());
}
else
{
carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error());
return omni::expected<RValue, void>(unexpect);
}
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, void> or_else(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<RValue, void>(in_place, std::forward<TExpected>(ex).value());
else
return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error());
}
};
template <typename TError>
struct ExpectedMonadOpImpl<void, TError, void, void>
{
template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>>
static constexpr TReturn transform_error(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
{
return TReturn(in_place);
}
else
{
carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error());
return TReturn(unexpect);
}
}
template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>>
static constexpr TReturn or_else(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return TReturn(in_place);
else
return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error());
}
};
template <typename TValue, typename RValue, typename RError>
struct ExpectedMonadOpImpl<TValue, void, RValue, RError>
{
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, RError> transform_error(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<RValue, RError>(in_place, std::forward<TExpected>(ex).value());
else
return omni::expected<RValue, RError>(unexpect, carb::cpp::invoke(std::forward<FTransform>(f)));
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<RValue, RError> or_else(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<RValue, RError>(in_place, std::forward<TExpected>(ex).value());
else
return carb::cpp::invoke(std::forward<FTransform>(f));
}
};
template <typename RError>
struct ExpectedMonadOpImpl<void, void, void, RError>
{
template <typename FTransform, typename TExpected>
static constexpr omni::expected<void, RError> transform_error(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<void, RError>(in_place);
else
return omni::expected<void, RError>(unexpect, carb::cpp::invoke(std::forward<FTransform>(f)));
}
template <typename FTransform, typename TExpected>
static constexpr omni::expected<void, RError> or_else(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return omni::expected<void, RError>(in_place);
else
return carb::cpp::invoke(std::forward<FTransform>(f));
}
};
template <>
struct ExpectedMonadOpImpl<void, void, void, void>
{
template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>>
static constexpr TReturn transform(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
{
carb::cpp::invoke(std::forward<FTransform>(f));
return TReturn(in_place);
}
else
{
return TReturn(unexpect);
}
}
template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>>
static constexpr TReturn and_then(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return carb::cpp::invoke(std::forward<FTransform>(f));
else
return TReturn(unexpect);
}
template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>>
static constexpr TReturn transform_error(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
{
return TReturn(in_place);
}
else
{
carb::cpp::invoke(std::forward<FTransform>(f));
return TReturn(unexpect);
}
}
template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>>
static constexpr TReturn or_else(FTransform&& f, TExpected&& ex)
{
if (ex.has_value())
return TReturn(in_place);
else
return carb::cpp::invoke(std::forward<FTransform>(f));
}
};
template <typename FTransform, typename TExpected, typename RefExpected, typename = void_t<>>
struct ExpectedOpTransform
{
};
template <typename FTransform, typename TValue, typename TError, typename RefExpected>
struct ExpectedOpTransform<FTransform,
omni::expected<TValue, TError>,
RefExpected,
void_t<carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().value())>>>
: ExpectedMonadOpImpl<TValue, TError, carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().value())>, TError>
{
};
template <typename FTransform, typename TError, typename RefExpected>
struct ExpectedOpTransform<FTransform, omni::expected<void, TError>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform>>>
: ExpectedMonadOpImpl<void, TError, carb::cpp::invoke_result_t<FTransform>, TError>
{
};
template <typename FTransform, typename TExpected, typename RefExpected, typename = void_t<>>
struct ExpectedOpAndThen
{
template <typename UExpected>
static constexpr void and_then(FTransform&&, UExpected&&)
{
// HELLO! If you're seeing one of these failures, that means you called `.and_then` with a callable that can't
// be called with the `value_type` of the expected. This base template is only used through misuse of that
// member function, so one of these `static_assert`s will always hit and give a slightly better diagnostic.
static_assert(is_void<typename TExpected::value_type>::value,
"function provided to `and_then` must accept the `expected::value_type`");
static_assert(!is_void<typename TExpected::value_type>::value,
"function provided to `and_then` must accept no parameters");
}
};
template <typename TExpected, typename UExpected>
struct ExpectedOpAndThenImpl
{
template <typename FTransform, typename VExpected>
static constexpr void and_then(FTransform&&, VExpected&&)
{
// HELLO! If you're seeing this failure, it means the function provided to `.and_then` did not return an
// `expected` when called with the `value_type`.
static_assert(is_void<FTransform>::value, "function provided to `and_then` must return an `expected<T, E>`");
}
};
template <typename TValue, typename TError, typename UValue, typename UError>
struct ExpectedOpAndThenImpl<omni::expected<TValue, TError>, omni::expected<UValue, UError>>
: ExpectedMonadOpImpl<TValue, TError, UValue, UError>
{
};
template <typename FTransform, typename TValue, typename TError, typename RefExpected>
struct ExpectedOpAndThen<FTransform,
omni::expected<TValue, TError>,
RefExpected,
void_t<carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().value())>>>
: ExpectedOpAndThenImpl<omni::expected<TValue, TError>,
carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().value())>>
{
};
template <typename FTransform, typename TError, typename RefExpected>
struct ExpectedOpAndThen<FTransform, omni::expected<void, TError>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform>>>
: ExpectedOpAndThenImpl<omni::expected<void, TError>, carb::cpp::invoke_result_t<FTransform>>
{
};
template <typename FTransform, typename TExpected, typename RefExpected, typename = void_t<>>
struct ExpectedOpTransformError
{
};
template <typename FTransform, typename TValue, typename TError, typename RefExpected>
struct ExpectedOpTransformError<FTransform,
omni::expected<TValue, TError>,
RefExpected,
void_t<carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().error())>>>
: ExpectedMonadOpImpl<TValue,
TError,
TValue,
carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().error())>>
{
};
template <typename FTransform, typename TValue, typename RefExpected>
struct ExpectedOpTransformError<FTransform, omni::expected<TValue, void>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform>>>
: ExpectedMonadOpImpl<TValue, void, TValue, carb::cpp::invoke_result_t<FTransform>>
{
};
template <typename FTransform, typename TExpected, typename RefExpected, typename = void_t<>>
struct ExpectedOpOrElse
{
template <typename UExpected>
static constexpr void or_else(FTransform&&, UExpected&&)
{
// HELLO! If you're seeing one of these failures, that means you called `.or_else` with a callable that can't
// be called with the `value_type` of the expected. This base template is only used through misuse of that
// member function, so one of these `static_assert`s will always hit and give a slightly better diagnostic.
static_assert(is_void<typename TExpected::error_type>::value,
"function provided to `or_else` must accept the `expected::value_type`");
static_assert(!is_void<typename TExpected::error_type>::value,
"function provided to `or_else` must accept no parameters");
}
};
template <typename TExpected, typename UExpected>
struct ExpectedOpOrElseImpl
{
template <typename FTransform, typename VExpected>
static constexpr void or_else(FTransform&&, VExpected&&)
{
// HELLO! If you're seeing this failure, it means the function provided to `.or_else` did not return an
// `expected` when called with the `value_type`.
static_assert(is_void<FTransform>::value, "function provided to `or_else` must return an `expected<T, E>`");
}
};
template <typename TValue, typename TError, typename UValue, typename UError>
struct ExpectedOpOrElseImpl<omni::expected<TValue, TError>, omni::expected<UValue, UError>>
: ExpectedMonadOpImpl<TValue, TError, UValue, UError>
{
};
template <typename FTransform, typename TValue, typename TError, typename RefExpected>
struct ExpectedOpOrElse<FTransform,
omni::expected<TValue, TError>,
RefExpected,
void_t<carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().error())>>>
: ExpectedOpOrElseImpl<omni::expected<TValue, TError>,
carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().error())>>
{
};
template <typename FTransform, typename TValue, typename RefExpected>
struct ExpectedOpOrElse<FTransform, omni::expected<TValue, void>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform>>>
: ExpectedOpOrElseImpl<omni::expected<TValue, void>, carb::cpp::invoke_result_t<FTransform>>
{
};
CARB_IGNOREWARNING_MSC_POP
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Comparison Functions //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename TExpected1, typename TExpected2, typename = void_t<>>
struct ExpectedComparer
{
};
template <typename TValue1, typename TError1, typename TValue2, typename TError2>
struct ExpectedComparer<
expected<TValue1, TError1>,
expected<TValue2, TError2>,
std::enable_if_t<negation<disjunction<is_void<TValue1>, is_void<TError1>, is_void<TValue2>, is_void<TError2>>>::value>>
{
template <typename TExpectedLhs, typename TExpectedRhs>
static constexpr bool eq(TExpectedLhs const& lhs, TExpectedRhs const& rhs)
{
if (lhs.has_value() && rhs.has_value())
return lhs.value() == rhs.value();
else if (!lhs.has_value() && !rhs.has_value())
return lhs.error() == rhs.error();
else
return false;
}
};
template <typename TValue1, typename TValue2>
struct ExpectedComparer<expected<TValue1, void>,
expected<TValue2, void>,
enable_if_t<negation<disjunction<is_void<TValue1>, is_void<TValue2>>>::value>>
{
template <typename TExpectedLhs, typename TExpectedRhs>
static constexpr bool eq(TExpectedLhs const& lhs, TExpectedRhs const& rhs)
{
if (lhs.has_value() && rhs.has_value())
return lhs.value() == rhs.value();
else if (!lhs.has_value() && !rhs.has_value())
return true;
else
return false;
}
};
template <typename TError1, typename TError2>
struct ExpectedComparer<expected<void, TError1>,
expected<void, TError2>,
enable_if_t<negation<disjunction<is_void<TError1>, is_void<TError2>>>::value>>
{
template <typename TExpectedLhs, typename TExpectedRhs>
static constexpr bool eq(TExpectedLhs const& lhs, TExpectedRhs const& rhs)
{
if (lhs.has_value() && rhs.has_value())
return true;
else if (!lhs.has_value() && !rhs.has_value())
return lhs.error() == rhs.error();
else
return false;
}
};
template <>
struct ExpectedComparer<expected<void, void>, expected<void, void>, void>
{
template <typename TExpected>
static constexpr bool eq(TExpected const& lhs, TExpected const& rhs)
{
return lhs.has_value() == rhs.has_value();
}
};
template <typename TErrorLhs, typename TErrorRhs>
struct ExpectedUnexpectedComparer
{
template <typename TExpected, typename TUnexpected>
static constexpr bool eq(TExpected const& lhs, TUnexpected const& rhs)
{
return !lhs.has_value() && static_cast<bool>(lhs.error() == rhs.error());
}
};
template <>
struct ExpectedUnexpectedComparer<void, void>
{
template <typename TExpected>
static constexpr bool eq(TExpected const& lhs, unexpected<void> const&)
{
return !lhs.has_value();
}
};
} // namespace detail
} // namespace omni
//! \endcond
| 84,514 | C | 37.821773 | 162 | 0.642781 |
omniverse-code/kit/include/omni/detail/ParamPack.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
//! \cond DEV
//! \file
//! \brief Contains the \c ParamPack helper type.
namespace omni
{
namespace detail
{
//! Wrapper type containing a pack of template parameters. This is only useful in metaprogramming.
template <typename... Args>
struct ParamPack
{
};
} // namespace detail
} // namespace omni
//! \endcond
| 767 | C | 23.774193 | 98 | 0.756193 |
omniverse-code/kit/include/omni/detail/ConvertsFromAnyCvRef.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../../carb/cpp/TypeTraits.h"
#include <type_traits>
//! \cond DEV
namespace omni
{
namespace detail
{
//! This is defined by the exposition-only concept "converts-from-any-cvref" in 22.5.3.2/1 [optional.ctor]. Generally
//! tests if a given \c T can be constructed from a \c W by value, const value, reference, or const reference. This is
//! used for wrapper monads like \c optional and \c expected to disquality overloads in cases of ambiguity with copy or
//! move constructors. For example, constructing `optional<optional<string>> x{optional<string>{"hi"}}` should use the
//! value-constructing overload (22.5.3.2/23) instead of the converting constructor (22.5.3.2/33). Note that the end
//! result is the same.
template <typename T, typename W>
using ConvertsFromAnyCvRef = carb::cpp::disjunction<std::is_constructible<T, W&>,
std::is_convertible<W&, T>,
std::is_constructible<T, W>,
std::is_convertible<W, T>,
std::is_constructible<T, W const&>,
std::is_convertible<W const&, T>,
std::is_constructible<T, W const>,
std::is_convertible<W const, T>>;
} // namespace detail
} // namespace omni
//! \endcond
| 1,942 | C | 44.186045 | 119 | 0.600927 |
omniverse-code/kit/include/omni/detail/FunctionImpl.h | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "../../carb/Defines.h"
#include "../../carb/Memory.h"
#include "../../carb/cpp/Functional.h"
#include "../../carb/cpp/TypeTraits.h"
#include "../../carb/detail/NoexceptType.h"
#include "../core/Assert.h"
#include "../core/IObject.h"
#include "../core/ResultError.h"
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <functional>
#include <memory>
#include <new>
#include <utility>
namespace omni
{
template <typename Signature>
class function;
//! \cond DEV
namespace detail
{
CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE()
// NOTE: GCC added a warning about the use of memcpy and memset on class types with non-trivial copy-assignment. In most
// cases, this is a valid warning that should be paid attention to.
#if CARB_COMPILER_GNUC && __GNUC__ >= 8
# define OMNI_FUNCTION_PUSH_IGNORE_CLASS_MEMACCESS() CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Wclass-memaccess")
# define OMNI_FUNCTION_POP_IGNORE_CLASS_MEMACCESS() CARB_IGNOREWARNING_GNUC_POP
#else
# define OMNI_FUNCTION_PUSH_IGNORE_CLASS_MEMACCESS()
# define OMNI_FUNCTION_POP_IGNORE_CLASS_MEMACCESS()
#endif
using carb::cpp::bool_constant;
using carb::cpp::conjunction;
using carb::cpp::disjunction;
using carb::cpp::is_invocable_r;
using carb::cpp::negation;
using carb::cpp::void_t;
using omni::core::Result;
//! Called when attempting to invoke a function that is unbound. It will throw \c std::bad_function_call if exceptions
//! are enabled or terminate immediately.
[[noreturn]] inline void null_function_call()
{
#if CARB_EXCEPTIONS_ENABLED
throw std::bad_function_call();
#else
OMNI_FATAL_UNLESS(false, "Attempt to call null function");
std::terminate(); // Enforce [[noreturn]]
#endif
}
//! Called when an internal function operation returns a non-success error case. This function will throw a
//! \c ResultError if exceptions are enabled or terminate immediately.
[[noreturn]] inline void function_operation_failure(Result rc, char const* msg)
{
#if CARB_EXCEPTIONS_ENABLED
throw core::ResultError(rc, msg);
#else
OMNI_FATAL_UNLESS(false, "%s: %s", msg, core::resultToString(rc));
std::terminate(); // Enforce [[noreturn]]
#endif
}
//! Metafunction to check if \c T is a \c omni::function or not.
template <typename T>
struct IsFunction : std::false_type
{
};
template <typename Signature>
struct IsFunction<omni::function<Signature>> : std::true_type
{
};
constexpr std::size_t kFUNCTION_BUFFER_SIZE = 16U;
constexpr std::size_t kFUNCTION_BUFFER_ALIGN = alignof(std::max_align_t);
constexpr std::size_t kFUNCTION_SIZE = 32U;
//! \see FunctionBuffer
struct FunctionUnusedBase
{
};
//! \see FunctionBuffer
struct FunctionUnused : virtual FunctionUnusedBase
{
};
//! This data type stores the content of the functor or a pointer to it. Only the \c raw member is used by the
//! implementation, but the other union members are here to make sure size and alignment stay as expected even when
//! strange types are used.
union alignas(kFUNCTION_BUFFER_ALIGN) FunctionBuffer
{
std::array<char, kFUNCTION_BUFFER_SIZE> raw;
void* pointer;
void (*pfunc)();
void (FunctionUnused::*pmemfunc)();
std::max_align_t FunctionUnused::*pmemsel;
};
static_assert(sizeof(FunctionBuffer) == kFUNCTION_BUFFER_SIZE, "Actual size of FunctionBuffer does not match goal");
static_assert(alignof(FunctionBuffer) == kFUNCTION_BUFFER_ALIGN, "Actual align of FunctionBuffer does not match goal");
struct FunctionCharacteristics
{
//! The size of this instance. This is useful for ABI compatibility if needs expand.
size_t _size;
//! Called on function destructor. If the target functor is trivially-destructible, then this should be \c nullptr
//! to make nothing happen on destruction.
void (*destroy)(FunctionBuffer* self);
//! Called when a function is copied. If the target functor is trivially-relocatable, then this should be \c nullptr
//! so the buffer is copied by \c memcpy.
Result (*clone)(FunctionBuffer* target, FunctionBuffer const* source);
constexpr FunctionCharacteristics(void (*destroy_)(FunctionBuffer*),
Result (*clone_)(FunctionBuffer*, FunctionBuffer const*)) noexcept
: _size{ sizeof(FunctionCharacteristics) }, destroy{ destroy_ }, clone{ clone_ }
{
}
};
//! This holds the core data of the \c omni::function type.
struct FunctionData
{
FunctionBuffer m_buffer;
//! The entry point into the function. The real type is `TReturn(*)(FunctionBuffer const*, TArgs...)`.
void* m_trampoline;
//! The management of the erased target of this function. This will be null in cases where the copy constructor and
//! destructor are trivial, meaning \c memcpy and \c memset are acceptable substitutes.
FunctionCharacteristics const* m_characteristics;
explicit FunctionData(std::nullptr_t) noexcept
{
clear_unsafe();
}
FunctionData(FunctionData const& src)
{
// NOTE: Another approach could be to copy m_trampoline and m_characteristics, then conditionally memcpy the
// m_buffer. However, the current approach of unconditional memcpy makes the operation twice as fast.
copy_from_unsafe(src);
if (m_characteristics && m_characteristics->clone)
{
if (auto rc = m_characteristics->clone(&m_buffer, &src.m_buffer))
{
clear_unsafe();
function_operation_failure(rc, "failed to clone function");
}
}
}
FunctionData(FunctionData&& src) noexcept
{
copy_from_unsafe(src);
src.clear_unsafe();
}
//! Initialize through binding with the given \a assigner and functor \a f.
//!
//! \tparam Assigner The assigner type for this function, picked through `FunctionAssigner<F>`.
template <typename Assigner, typename F>
FunctionData(Assigner assigner, F&& f)
{
if (auto rc = bind_unsafe(assigner, std::forward<F>(f)))
{
function_operation_failure(rc, "failed to bind to functor");
}
}
FunctionData& operator=(FunctionData const& src)
{
if (this == &src)
return *this;
// The copy constructor can throw, but the move-assignment can not, so we get the proper commit or rollback
// semantics
return operator=(FunctionData{ src });
}
FunctionData& operator=(FunctionData&& src) noexcept
{
if (this == &src)
return *this;
reset();
copy_from_unsafe(src);
src.clear_unsafe();
return *this;
}
~FunctionData() noexcept
{
reset();
}
//! Clear the contents of this instance without checking.
//!
//! \pre No cleanup is performed, so the responsibility for doing this must have been taken care of (`reset`) or
//! deferred (move-assigned from).
void clear_unsafe() noexcept
{
OMNI_FUNCTION_PUSH_IGNORE_CLASS_MEMACCESS()
std::memset(this, 0, sizeof(*this));
OMNI_FUNCTION_POP_IGNORE_CLASS_MEMACCESS()
}
//! Copy the contents of \a src to this instance without clearing.
//!
//! \pre `this != &src`
//! \pre No cleanup is performed, so the responsibility for doing so must have been taken care of (`reset`) or
//! deferred (copied to another instance).
//! \post The copied-from \a src cannot be destructed in the normal manner.
void copy_from_unsafe(FunctionData const& src) noexcept
{
OMNI_FUNCTION_PUSH_IGNORE_CLASS_MEMACCESS()
std::memcpy(this, &src, sizeof(*this));
OMNI_FUNCTION_POP_IGNORE_CLASS_MEMACCESS()
}
//! Assign the function or functor \a f with the \c Assigner.
//!
//! \tparam Assigner The appropriate \c FunctionAssigner type for the \c FunctionTraits and \c F we are trying to
//! bind.
//! \pre This function must be either uninitialized or otherwise clear. This function will overwrite any state
//! without checking if it is engaged ahead of time. As such, it should only be called from a constructor or
//! after a \c reset.
template <typename Assigner, typename F>
CARB_NODISCARD Result bind_unsafe(Assigner, F&& f)
{
if (!Assigner::is_active(f))
{
clear_unsafe();
return core::kResultSuccess;
}
if (Result rc = Assigner::initialize(m_buffer, std::forward<F>(f)))
return rc;
m_trampoline = reinterpret_cast<void*>(&Assigner::trampoline);
m_characteristics = Assigner::characteristics();
return core::kResultSuccess;
}
void reset() noexcept
{
if (m_characteristics && m_characteristics->destroy)
m_characteristics->destroy(&m_buffer);
clear_unsafe();
}
void swap(FunctionData& other) noexcept
{
if (this == &other)
return;
std::array<char, sizeof(*this)> temp;
std::memcpy(temp.data(), this, sizeof(temp));
std::memcpy(this, &other, sizeof(*this));
OMNI_FUNCTION_PUSH_IGNORE_CLASS_MEMACCESS()
std::memcpy(&other, temp.data(), sizeof(other));
OMNI_FUNCTION_POP_IGNORE_CLASS_MEMACCESS()
}
};
static_assert(sizeof(FunctionData) == kFUNCTION_SIZE, "FunctionData incorrect size");
static_assert(alignof(FunctionData) == kFUNCTION_BUFFER_ALIGN, "FunctionData incorrect alignment");
struct TrivialFunctorCharacteristics
{
static FunctionCharacteristics const* characteristics() noexcept
{
return nullptr;
}
};
template <typename Signature>
struct FunctionTraits;
template <typename TReturn, typename... TArgs>
struct FunctionTraits<TReturn(TArgs...)>
{
using result_type = TReturn;
};
//! The "assigner" for a function is used in bind operations. It is responsible for managing copy and delete operations,
//! detecting if a binding target is non-null, and creating a trampoline function to bridge the gap between the function
//! signature `TReturn(TArgs...)` and the target function signature.
//!
//! When the bind \c Target is not bindable-to, this base case is matched, which has no member typedef \c type. This is
//! used in \c omni::function to disqualify types which cannot be bound to. When the \c Target is bindable (see the
//! partial specializations below), the member \c type is a structure with the following static functions:
//!
//! * `TReturn trampoline(FunctionBuffer const*, TArgs...)` -- The trampoline function performs an arbitrary action to
//! convert `TArgs...` and `TReturn` of the actual call.
//! * `FunctionCharacteristics const* characteristics() noexcept` -- Give the singleton which describes the managment
//! operations for this target.
//! * `bool is_active(Target const&) noexcept` -- Detects if the \c Target is null or not.
//! * `Result initialize(FunctionBuffer&, Target&&)` -- Initializes the buffer from the provided target.
//!
//! See \c FunctionAssigner
template <typename TTraits, typename Target, typename = void>
struct FunctionAssignerImpl
{
};
//! Binding for any pointer-like type.
template <typename TReturn, typename... TArgs, typename TPointer>
struct FunctionAssignerImpl<FunctionTraits<TReturn(TArgs...)>,
TPointer,
std::enable_if_t<conjunction<is_invocable_r<TReturn, TPointer, TArgs...>,
disjunction<std::is_pointer<TPointer>,
std::is_member_function_pointer<TPointer>,
std::is_member_object_pointer<TPointer>>>::value>>
{
struct type : TrivialFunctorCharacteristics
{
static TReturn trampoline(FunctionBuffer const* buf, TArgs... args)
{
auto realfn = const_cast<TPointer*>(reinterpret_cast<TPointer const*>(buf->raw.data()));
// NOTE: The use of invoke_r here is for cases where TReturn is void, but `(*realfn)(args...)` is not. It is
// fully qualified to prevent ADL ambiguity with std::invoke_r when any of TArgs reside in the std
// namespace.
return ::carb::cpp::invoke_r<TReturn>(*realfn, std::forward<TArgs>(args)...);
}
CARB_NODISCARD static Result initialize(FunctionBuffer& buffer, TPointer fn) noexcept
{
static_assert(sizeof(fn) <= sizeof(buffer.raw), "Function too large to fit in buffer");
std::memcpy(buffer.raw.data(), &fn, sizeof(fn));
return 0;
}
static bool is_active(TPointer func) noexcept
{
return bool(func);
}
};
};
//! Binding to a class or union type with `operator()`.
template <typename TReturn, typename... TArgs, typename Functor>
struct FunctionAssignerImpl<FunctionTraits<TReturn(TArgs...)>,
Functor,
std::enable_if_t<conjunction<
// do not match exactly this function
negation<std::is_same<Functor, omni::function<TReturn(TArgs...)>>>,
// must be a class or union type (not a pointer or reference to a function)
disjunction<std::is_class<Functor>, std::is_union<Functor>>,
// must be callable
is_invocable_r<TReturn, Functor&, TArgs...>>::value>>
{
struct InBuffer : TrivialFunctorCharacteristics
{
static TReturn trampoline(FunctionBuffer const* buf, TArgs... args)
{
auto real = const_cast<Functor*>(reinterpret_cast<Functor const*>(buf->raw.data()));
// NOTE: invoke_r is fully qualified to prevent ADL ambiguity with std::invoke_r when any of TArgs reside in
// the std namespace.
return ::carb::cpp::invoke_r<TReturn>(*real, std::forward<TArgs>(args)...);
}
template <typename F>
CARB_NODISCARD static Result initialize(FunctionBuffer& buffer, F&& func)
{
static_assert(sizeof(func) <= sizeof(buffer), "Provided functor is too large to fit in buffer");
// GCC 7.1-7.3 has a compiler bug where a diagnostic for uninitialized `func` is emitted in cases where it refers to a
// lambda expression which has been `forward`ed multiple times. This is erroneous in GCC 7.1-7.3, but other compilers
// complaining about uninitialized access might have a valid point.
#if CARB_COMPILER_GNUC && !CARB_TOOLCHAIN_CLANG && __GNUC__ == 7 && __GNUC_MINOR__ <= 3
CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Wmaybe-uninitialized")
#endif
std::memcpy(buffer.raw.data(), &func, sizeof(func));
#if CARB_COMPILER_GNUC && !CARB_TOOLCHAIN_CLANG && __GNUC__ == 7 && __GNUC_MINOR__ <= 3
CARB_IGNOREWARNING_GNUC_POP
#endif
return 0;
}
static constexpr bool is_active(Functor const&) noexcept
{
return true;
}
};
struct InBufferWithDestructor : InBuffer
{
static FunctionCharacteristics const* characteristics() noexcept
{
static FunctionCharacteristics const instance{
[](FunctionBuffer* self) { reinterpret_cast<Functor*>(self->raw.data())->~Functor(); },
nullptr,
};
return &instance;
}
};
struct HeapAllocated
{
template <typename... AllocArgs>
static Functor* make(AllocArgs&&... args)
{
std::unique_ptr<void, void (*)(void*)> tmp{ carb::allocate(sizeof(Functor), alignof(Functor)),
&carb::deallocate };
if (!tmp)
return nullptr;
new (tmp.get()) Functor{ std::forward<AllocArgs>(args)... };
return static_cast<Functor*>(tmp.release());
}
CARB_NODISCARD static Result clone(FunctionBuffer* target, FunctionBuffer const* source)
{
if (auto created = make(*static_cast<Functor const*>(source->pointer)))
{
target->pointer = static_cast<void*>(created);
return core::kResultSuccess;
}
else
{
return core::kResultFail;
}
}
static void destroy(FunctionBuffer* buffer) noexcept
{
auto real = static_cast<Functor*>(buffer->pointer);
real->~Functor();
carb::deallocate(real);
}
static TReturn trampoline(FunctionBuffer const* buf, TArgs... args)
{
auto real = static_cast<Functor*>(buf->pointer);
return ::carb::cpp::invoke_r<TReturn>(*real, std::forward<TArgs>(args)...);
}
template <typename Signature>
static bool is_active(omni::function<Signature> const& f) noexcept
{
// omni::function derives from FunctionData, so this is a correct cast, even though it is not defined yet.
// The use of reinterpret_cast is required here because omni::function derives privately.
auto underlying = reinterpret_cast<FunctionData const*>(&f);
return underlying->m_trampoline;
}
template <typename Signature>
static bool is_active(std::function<Signature> const& f) noexcept
{
return bool(f);
}
template <typename UFunctor>
static bool is_active(UFunctor const&) noexcept
{
return true;
}
template <typename UFunctor>
CARB_NODISCARD static Result initialize(FunctionBuffer& buffer, UFunctor&& func)
{
if (auto created = make(std::forward<UFunctor>(func)))
{
buffer.pointer = static_cast<void*>(created);
return core::kResultSuccess;
}
else
{
// we can't guarantee that anything in make sets the error code, so use the generic "fail"
return core::kResultFail;
}
}
static FunctionCharacteristics const* characteristics() noexcept
{
static FunctionCharacteristics const instance{
&destroy,
&clone,
};
return &instance;
}
};
// clang-format off
using type =
std::conditional_t<
conjunction<bool_constant<(sizeof(Functor) <= kFUNCTION_BUFFER_SIZE && kFUNCTION_BUFFER_ALIGN % alignof(Functor) == 0)>,
// we're really looking for relocatability, but trivial copy will do for now
std::is_trivially_copyable<Functor>
>::value,
std::conditional_t<std::is_trivially_destructible<Functor>::value,
InBuffer,
InBufferWithDestructor>,
HeapAllocated>;
// clang-format on
};
//! Choose the proper function assigner from its properties. This will fail in a SFINAE-safe manner if the \c Target is
//! not bindable to a function with the given \c TTraits.
template <typename TTraits, typename Target>
using FunctionAssigner = typename FunctionAssignerImpl<TTraits, std::decay_t<Target>>::type;
CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE()
} // namespace detail
//! \endcond
} // namespace omni
| 19,915 | C | 36.365854 | 132 | 0.63068 |
omniverse-code/kit/include/omni/detail/PointerIterator.h | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Provides @c omni::detail::PointerIterator class for constructing pointer-based iterators.
#pragma once
#include "../../carb/Defines.h"
#include <iterator>
#include <type_traits>
#if CARB_HAS_CPP20
# include <concepts>
#endif
namespace omni
{
//! Internal implementation details namespace.
namespace detail
{
//! @class PointerIterator
//!
//! This iterator adapter wraps a pointer type into a class. It does not change the semantics of any operations from the
//! fundamental logic of pointers. There are no bounds checks, there is no additional safety.
//!
//! @tparam TPointer The pointer to base this wrapper on. The underlying value type of the pointer can be
//! const-qualified.
//! @tparam TContainer The container type this iterator iterates over. This is useful to make types distinct, even in
//! cases where @c TPointer would be identical; for example, a @c string vs a @c vector<char>. This
//! is allowed to be @c void for cases where there is no underlying container.
//!
//! @code
//! // This is meant to be used on contiguous containers where returning a pointer from @c begin and @c end would be
//! // inappropriate.
//! template <typename T>
//! class MyContainer
//! {
//! public:
//! using iterator = detail::PointerIterator<T*, MyContainer>;
//! using const_iterator = detail::PointerIterator<T const*, MyContainer>;
//!
//! // ...
//!
//! iterator begin() { return iterator{data()}; }
//! };
//! @endcode
template <typename TPointer, typename TContainer>
class PointerIterator
{
static_assert(std::is_pointer<TPointer>::value, "TPointer must be a pointer type");
private:
using underlying_traits_type = std::iterator_traits<TPointer>;
public:
//! The underlying value that dereferencing this iterator returns. Note that this is not const-qualified; the
//! @c const_iterator for a container will still return @c T.
using value_type = typename underlying_traits_type::value_type;
//! The reference type dereferencing this iterator returns. This is const-qualified, so @c iterator for a container
//! will return @c T& and @c const_iterator will return `const T&`.
using reference = typename underlying_traits_type::reference;
//! The underlying pointer type @c operator->() returns. This is const-qualified, so @c iterator for a container
//! will return @c T* and @c const_iterator will return `const T*`.
using pointer = typename underlying_traits_type::pointer;
//! The type used to represent the distance between two iterators. This will always be @c std::ptrdiff_t.
using difference_type = typename underlying_traits_type::difference_type;
//! The category of this iterator. This will always be @c std::random_access_iterator_tag.
using iterator_category = typename underlying_traits_type::iterator_category;
#if CARB_HAS_CPP20
//! The concept this iterator models. This will always be @c std::contiguous_iterator_tag.
using iterator_concept = typename underlying_traits_type::iterator_concept;
#endif
public:
//! Default construction of a pointer-iterator results in an iterator pointing to @c nullptr.
constexpr PointerIterator() noexcept : m_ptr{ nullptr }
{
}
//! Create an iterator from @a src pointer.
explicit constexpr PointerIterator(pointer src) noexcept : m_ptr{ src }
{
}
//! Instances are trivially copy-constructible.
PointerIterator(const PointerIterator&) = default;
//! Instances are trivially move-constructible.
PointerIterator(PointerIterator&&) = default;
//! Instances are trivially copyable.
PointerIterator& operator=(const PointerIterator&) = default;
//! Instances are trivially movable.
PointerIterator& operator=(PointerIterator&&) = default;
//! Instances are trivially destructible.
~PointerIterator() = default;
// clang-format off
//! Converting constructor to allow conversion from a non-const iterator type to a const iterator type. Generally,
//! this allows a @c TContainer::iterator to become a @c TContainer::const_iterator.
//!
//! This constructor is only enabled if:
//!
//! 1. The @c TContainer for the two types is the same.
//! 2. The @c TPointer is different from @c UPointer (there is a conversion which needs to occur).
//! 3. A pointer to an array of the @a src const-qualified @c value_type (aka `remove_reference_t<reference>`) is
//! convertible to an array of this const-qualified @c value_type. This restricts conversion of iterators from a
//! derived to a base class pointer type.
template <typename UPointer,
typename = std::enable_if_t
< !std::is_same<TPointer, UPointer>::value
&& std::is_convertible
<
std::remove_reference_t<typename PointerIterator<UPointer, TContainer>::reference>(*)[],
std::remove_reference_t<reference>(*)[]
>::value
>
>
constexpr PointerIterator(const PointerIterator<UPointer, TContainer>& src) noexcept
: m_ptr{src.operator->()}
{
}
// clang-format on
//! Dereference this iterator to get its value.
constexpr reference operator*() const noexcept
{
return *m_ptr;
}
//! Get the value at offset @a idx from this iterator. Negative values are supported to reference behind this
//! instance.
constexpr reference operator[](difference_type idx) const noexcept
{
return m_ptr[idx];
}
//! Get a pointer to the value.
constexpr pointer operator->() const noexcept
{
return m_ptr;
}
//! Move the iterator forward by one.
constexpr PointerIterator& operator++() noexcept
{
++m_ptr;
return *this;
}
//! Move the iterator forward by one, but return the previous position.
constexpr PointerIterator operator++(int) noexcept
{
PointerIterator save{ *this };
++m_ptr;
return save;
}
//! Move the iterator backwards by one.
constexpr PointerIterator& operator--() noexcept
{
--m_ptr;
return *this;
}
//! Move the iterator backwards by one, but return the previous position.
constexpr PointerIterator operator--(int) noexcept
{
PointerIterator save{ *this };
--m_ptr;
return save;
}
//! Move the iterator forward by @a dist.
constexpr PointerIterator& operator+=(difference_type dist) noexcept
{
m_ptr += dist;
return *this;
}
//! Get a new iterator pointing @a dist elements forward from this one.
constexpr PointerIterator operator+(difference_type dist) const noexcept
{
return PointerIterator{ m_ptr + dist };
}
//! Move the iterator backwards by @a dist.
constexpr PointerIterator& operator-=(difference_type dist) noexcept
{
m_ptr -= dist;
return *this;
}
//! Get a new iterator pointing @a dist elements backwards from this one.
constexpr PointerIterator operator-(difference_type dist) const noexcept
{
return PointerIterator{ m_ptr - dist };
}
private:
pointer m_ptr;
};
//! Get an iterator @a dist elements forward from @a iter.
template <typename TPointer, typename TContainer>
inline constexpr PointerIterator<TPointer, TContainer> operator+(
typename PointerIterator<TPointer, TContainer>::difference_type dist,
const PointerIterator<TPointer, TContainer>& iter) noexcept
{
return iter + dist;
}
//! Get the distance between iterators @a lhs and @a rhs. If `lhs < rhs`, this value will be negative.
template <typename TPointer, typename UPointer, typename TContainer>
inline constexpr auto operator-(const PointerIterator<TPointer, TContainer>& lhs,
const PointerIterator<UPointer, TContainer>& rhs) noexcept
-> decltype(lhs.operator->() - rhs.operator->())
{
return lhs.operator->() - rhs.operator->();
}
//! Test for equality between @a lhs and @a rhs.
template <typename TPointer, typename UPointer, typename TContainer>
inline constexpr bool operator==(const PointerIterator<TPointer, TContainer>& lhs,
const PointerIterator<UPointer, TContainer>& rhs) noexcept
{
return lhs.operator->() == rhs.operator->();
}
//! Test for inequality between @a lhs and @a rhs.
template <typename TPointer, typename UPointer, typename TContainer>
inline constexpr bool operator!=(const PointerIterator<TPointer, TContainer>& lhs,
const PointerIterator<UPointer, TContainer>& rhs) noexcept
{
return lhs.operator->() != rhs.operator->();
}
//! Test that @a lhs points to something less than @a rhs.
template <typename TPointer, typename UPointer, typename TContainer>
inline constexpr bool operator<(const PointerIterator<TPointer, TContainer>& lhs,
const PointerIterator<UPointer, TContainer>& rhs) noexcept
{
return lhs.operator->() < rhs.operator->();
}
//! Test that @a lhs points to something less than or equal to @a rhs.
template <typename TPointer, typename UPointer, typename TContainer>
inline constexpr bool operator<=(const PointerIterator<TPointer, TContainer>& lhs,
const PointerIterator<UPointer, TContainer>& rhs) noexcept
{
return lhs.operator->() <= rhs.operator->();
}
//! Test that @a lhs points to something greater than @a rhs.
template <typename TPointer, typename UPointer, typename TContainer>
inline constexpr bool operator>(const PointerIterator<TPointer, TContainer>& lhs,
const PointerIterator<UPointer, TContainer>& rhs) noexcept
{
return lhs.operator->() > rhs.operator->();
}
//! Test that @a lhs points to something greater than or equal to @a rhs.
template <typename TPointer, typename UPointer, typename TContainer>
inline constexpr bool operator>=(const PointerIterator<TPointer, TContainer>& lhs,
const PointerIterator<UPointer, TContainer>& rhs) noexcept
{
return lhs.operator->() >= rhs.operator->();
}
} // namespace detail
} // namespace omni
| 10,824 | C | 36.71777 | 120 | 0.671286 |
omniverse-code/kit/include/omni/renderer/IDebugDraw.h | // Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Defines.h>
#include <carb/Types.h>
#include <carb/scenerenderer/SceneRendererTypes.h>
namespace omni
{
namespace renderer
{
typedef uint32_t SimplexBuffer;
typedef uint32_t RenderInstanceBuffer;
struct SimplexPoint
{
carb::Float3 position;
uint32_t color;
float width;
};
/// Invalid billboardId
const uint32_t kInvalidBillboardId = 0xFFFFffff;
struct IDebugDraw
{
CARB_PLUGIN_INTERFACE("omni::renderer::IDebugDraw", 1, 2)
/// Invalid buffer return value
enum InvalidBuffer
{
eInvalidBuffer = 0
};
/// Draw a line - actual implementation
/// \note Life time of a line is one frame
///
/// \param startPos Line start position
/// \param startColor Line start color in argb format
/// \param startWidth Line start width
/// \param endPos Line end position
/// \param endColor Line end color in argb format
/// \param endWidth Line end width
void(CARB_ABI* internalDrawLine)(const carb::Float3& startPos,
uint32_t startColor,
float startWidth,
const carb::Float3& endPos,
uint32_t endColor,
float endWidth);
/// Draw a line without width
/// \note Life time of a line is one frame
///
/// \param startPos Line start position
/// \param startColor Line start color in argb format
/// \param endPos Line end position
/// \param endColor Line end color in argb format
void drawLine(const carb::Float3& startPos, uint32_t startColor, const carb::Float3& endPos, uint32_t endColor)
{
internalDrawLine(startPos, startColor, 1.0f, endPos, endColor, 1.0f);
}
/// Draw a line
/// \note Life time of a line is one frame
///
/// \param startPos Line start position
/// \param startColor Line start color in argb format
/// \param startWidth Line start width
/// \param endPos Line end position
/// \param endColor Line end color in argb format
/// \param endWidth Line end width
void drawLine(const carb::Float3& startPos, uint32_t startColor, float startWidth, const carb::Float3& endPos, uint32_t endColor, float endWidth)
{
internalDrawLine(startPos, startColor, startWidth, endPos, endColor, endWidth);
}
/// Draw lines buffer
/// \note Life time of a line is one frame
///
/// \param pointsBuffer Buffer of points (expected size is 2xnumLines)
/// \param numLines Number of lines in the buffer
void(CARB_ABI* drawLines)(const SimplexPoint* pointsBuffer, uint32_t numLines);
/// Draw a point
/// \note Life time of a point is one frame
///
/// \param pointPos Point position
/// \param pointColor Point color in argb format
/// \param pointWidth Point width (diameter)
void(CARB_ABI* internalDrawPoint)(const carb::Float3& pointPos, uint32_t pointColor, float pointWidth);
/// Draw a point
/// \note Life time of a point is one frame
///
/// \param pointPos Point position
/// \param pointColor Point color in argb format
/// \param pointWidth Point width (diameter)
void drawPoint(const carb::Float3& pointPos, uint32_t pointColor, float pointWidth = 1.0f)
{
internalDrawPoint(pointPos, pointColor, pointWidth);
}
/// Draw points buffer
/// \note Life time of a point is one frame
///
/// \param pointsBuffer Buffer of points (expected size is numPoints)
/// \param numPoints Number of points in the buffer
void(CARB_ABI* drawPoints)(const SimplexPoint* pointsBuffer, uint32_t numPoints);
/// Draw a sphere - internal implementation
/// \note Life time of a sphere is one frame
///
/// \param spherePos Sphere positions
/// \param sphereRadius Sphere radius
/// \param sphereColor Sphere color in argb format
/// \param lineWidth Line width
/// \param tesselation Sphere tesselation
void(CARB_ABI* internalDrawSphere)(const carb::Float3& spherePos, float sphereRadius, uint32_t sphereColor, float lineWidth, uint32_t tesselation);
/// Draw a sphere
/// \note Life time of a sphere is one frame
///
/// \param spherePos Sphere positions
/// \param sphereRadius Sphere radius
/// \param sphereColor Sphere color in argb format
/// \param lineWidth Line width
/// \param tesselation Sphere tesselation
void drawSphere(const carb::Float3& spherePos, float sphereRadius, uint32_t sphereColor, float lineWidth = 1.0f, uint32_t tesselation = 32)
{
internalDrawSphere(spherePos, sphereRadius, sphereColor, lineWidth, tesselation);
}
/// Draw a box - internal implementation
/// \note Life time of a box is one frame
///
/// \param boxPos Box position
/// \param boxRotation Box rotation (quaternion)
/// \param boxSize Box size - extent
/// \param boxColor Box color in argb format
/// \param lineWidth Line width
void(CARB_ABI* internalDrawBox)(
const carb::Float3& boxPos, const carb::Float4& boxRotation, const carb::Float3& boxSize, uint32_t boxColor, float lineWidth);
/// Draw a box
/// \note Life time of a box is one frame
///
/// \param boxPos Box position
/// \param boxRotation Box rotation (quaternion)
/// \param boxSize Box size - extent
/// \param boxColor Box color in argb format
/// \param lineWidth Line width
void drawBox(const carb::Float3& boxPos, const carb::Float4& boxRotation, const carb::Float3& boxSize, uint32_t boxColor, float lineWidth = 1.0f)
{
internalDrawBox(boxPos, boxRotation, boxSize, boxColor, lineWidth);
}
/// Allocate line buffer
///
/// \param preallocatedBufferSize preallocated buffer size (number of lines expected)
/// \returns Line buffer handle
SimplexBuffer(CARB_ABI* allocateLineBuffer)(size_t preallocatedBufferSize);
/// Deallocate line buffer
///
/// \param bufferHandle Line buffer to deallocate
void(CARB_ABI* deallocateLineBuffer)(SimplexBuffer bufferHandle);
/// Set line to a buffer
///
/// \param buffer Line buffer
/// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase)
/// \param startPos Line start position
/// \param startColor Line start color in argb format
/// \param startWidth Line start width
/// \param endPos Line end position
/// \param endColor Line end color in argb format
/// \param endWidth Line end width
void(CARB_ABI* internalSetLine)(SimplexBuffer buffer,
size_t index,
const carb::Float3& startPos,
uint32_t startColor,
float startWidth,
const carb::Float3& endPos,
uint32_t endColor,
float endWidth);
/// Set line to a buffer without width
///
/// \param buffer Line buffer
/// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase)
/// \param startPos Line start position
/// \param startColor Line start color in argb format
/// \param endPos Line end position
/// \param endColor Line end color in argb format
void setLine(SimplexBuffer buffer,
size_t index,
const carb::Float3& startPos,
uint32_t startColor,
const carb::Float3& endPos,
uint32_t endColor)
{
internalSetLine(buffer, index, startPos, startColor, 1.0f, endPos, endColor, 1.0f);
}
/// Set line to a buffer
///
/// \param buffer Line buffer
/// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase)
/// \param startPos Line start position
/// \param startColor Line start color in argb format
/// \param startWidth Line start width
/// \param endPos Line end position
/// \param endColor Line end color in argb format
/// \param endWidth Line end width
void setLine(SimplexBuffer buffer,
size_t index,
const carb::Float3& startPos,
uint32_t startColor,
float startWidth,
const carb::Float3& endPos,
uint32_t endColor,
float endWidth)
{
internalSetLine(buffer, index, startPos, startColor, startWidth, endPos, endColor, endWidth);
}
/// Set point within a point buffer
///
/// \param buffer Point buffer
/// \param index Index in buffer (if index is larger than current buffer size, size will increase)
/// \param position Point position
/// \param color Point color
/// \param width Point size
void(CARB_ABI* setPoint)(SimplexBuffer handle, size_t index, const carb::Float3& position, uint32_t color, float width);
/// Allocate render instance buffer
///
/// \param handle Line buffer to instance
/// \param preallocatedBufferSize preallocated buffer size
/// \returns Render instance buffer handle
RenderInstanceBuffer(CARB_ABI* allocateRenderInstanceBuffer)(SimplexBuffer handle, size_t preallocatedSize);
/// Update render instance buffer
///
/// \param buffer Render instance buffer
/// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase)
/// \param matrix Instance transformation matrix - 4x4 matrix - 16 floats
/// \param color Instance color, final color is interpolated with PrimitiveVertex.color based on alpha (in
/// argb format)
/// \param uid unique identifier to map PrimitiveListInstance back to prim for picking.
void(CARB_ABI* internalSetRenderInstance)(RenderInstanceBuffer buffer, size_t index, const float* matrix, uint32_t color, uint32_t uid);
/// Update render instance buffer without uid
///
/// \param buffer Render instance buffer
/// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase)
/// \param matrix Instance transformation matrix - 4x4 matrix - 16 floats
/// \param color Instance color, final color is interpolated with PrimitiveVertex.color based on alpha (in
/// argb format)
void setRenderInstance(
RenderInstanceBuffer buffer, size_t index, const float* matrix, uint32_t color)
{
internalSetRenderInstance(buffer, index, matrix, color, 0);
}
/// Update render instance buffer
///
/// \param buffer Render instance buffer
/// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase)
/// \param matrix Instance transformation matrix - 4x4 matrix - 16 floats
/// \param color Instance color, final color is interpolated with PrimitiveVertex.color based on alpha (in
/// argb format)
/// \param uid unique identifier to map PrimitiveListInstance back to prim for picking.
void setRenderInstance(
RenderInstanceBuffer buffer, size_t index, const float* matrix, uint32_t color, uint32_t uid)
{
internalSetRenderInstance(buffer, index, matrix, color, uid);
}
/// Deallocate render instance buffer
///
/// \param handle Render instance buffer to deallocate
void(CARB_ABI* deallocateRenderInstanceBuffer)(RenderInstanceBuffer buffer);
/// Allocate point buffer
///
/// \param preallocateBufferSize Preallocated buffer size (number of points expected)
/// \returns Point buffer handle
SimplexBuffer(CARB_ABI* allocatePointBuffer)(size_t preallocatedBufferSize);
/// Deallocate point buffer
///
/// \param bufferHandle Point buffer to deallocate
void(CARB_ABI* deallocatePointBuffer)(SimplexBuffer bufferHandle);
/// Allocate line buffer
///
/// \param preallocatedBufferSize preallocated buffer size (number of lines expected)
/// \param flags flags to be used when create primitive list
/// \returns Line buffer handle
SimplexBuffer(CARB_ABI* allocateLineBufferEx)(size_t preallocatedBufferSize,
carb::scenerenderer::PrimitiveListFlags flags);
/// Allocate point buffer
///
/// \param preallocateBufferSize Preallocated buffer size (number of points expected)
/// \param flags flags to be used when create primitive list
/// \returns Point buffer handle
SimplexBuffer(CARB_ABI* allocatePointBufferEx)(size_t preallocatedBufferSize,
carb::scenerenderer::PrimitiveListFlags flags);
/// Add billboard asset
/// \note The asset is valid for the whole duration
///
/// \param textureAssetName Full path to the texture asset
/// \return Return assetid
uint32_t (CARB_ABI* addBillboardAsset)(const char* textureAssetName);
/// Update billboard asset
///
/// \param assetId AssetId for billboard identification
/// \param scale New scale
/// \isConstantScale Constant scale hint
void (CARB_ABI* updateBillboardAsset)(uint32_t assetId, double scale, bool isConstantScale);
/// Add billboard instance
///
/// \param assetId AssetId for billboard identification
/// \param billboardUid BillboardUid - see context get Uid for selection
/// \param tr Transformation matrix for the billboard instance, 4x4 float matrix
/// \return Return id for the current billboard instance
uint32_t (CARB_ABI* addBillboard)(uint32_t assetId, uint32_t billboardUid, const float* tr);
/// Update billboard instance
///
/// \param assetId AssetId for billboard identification
/// \param billboardId Billboard id of the instance
/// \param tr Transformation matrix for the billboard instancem 4x4 float matrix
void (CARB_ABI* updateBillboard)(uint32_t assetId, uint32_t billboardId, const float* tr);
/// Remove billboard instance
///
/// \param assetId AssetId for billboard identification
/// \param billboardId Billboard id of the instance
/// \return Returns the swapped position, last item of the array is swapped with this Id,
/// use the returned Id to update the instances in your database
uint32_t (CARB_ABI* removeBillboard)(uint32_t assetId, uint32_t billboardId);
/// Clear billboard instances for given asset
///
/// \param assetId AssetId for billboard identification
void (CARB_ABI* clearBillboardInstances)(uint32_t assetId);
/// Remove render instance on given index
///
/// \param handle Render instance buffer handle
/// \param index Index in the buffer
bool (CARB_ABI* removeRenderInstance)(omni::renderer::RenderInstanceBuffer handle, size_t index);
/// Remove debug lines on given range of indices from the vertex array
///
/// \param handle Render instance buffer handle
/// \param startIndex Starting line index in the vertex buffer
/// \param endIndex Ending line index in the vertex buffer
bool (CARB_ABI* removeLines)(omni::renderer::SimplexBuffer handle, size_t startIndex, size_t endIndex);
};
} // namespace renderer
} // namespace omni
| 16,196 | C | 41.962865 | 151 | 0.650161 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.