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/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBreakVector2.cpp | // 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.
//
#include <OgnBreakVector2Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename Type>
bool tryBreakVector(OgnBreakVector2Database& db)
{
const auto vector = db.inputs.tuple().template get<Type[2]>();
auto x = db.outputs.x().template get<Type>();
auto y = db.outputs.y().template get<Type>();
if (!vector || !x || !y){
return false;
}
*x = (*vector)[0];
*y = (*vector)[1];
return true;
}
} // namespace
// Node to break a 2-vector into it's component scalers
class OgnBreakVector2
{
public:
static bool compute(OgnBreakVector2Database& db)
{
// Compute the components, if the types are all resolved.
try
{
if (tryBreakVector<double>(db))
return true;
else if (tryBreakVector<float>(db))
return true;
else if (tryBreakVector<pxr::GfHalf>(db))
return true;
else if (tryBreakVector<int32_t>(db))
return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be broken: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto vector = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::tuple.token());
auto x = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::x.token());
auto y = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::y.token());
auto vectorType = vector.iAttribute->getResolvedType(vector);
// Require inputs to be resolved before determining outputs' type
if (vectorType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs{ vector, x, y };
std::array<uint8_t, 3> tuples{ 2, 1, 1 };
std::array<uint8_t, 3> arrays{ 0, 0, 0 };
std::array<AttributeRole, 3> roles{ vectorType.role, AttributeRole::eNone, AttributeRole::eNone };
nodeObj.iNode->resolvePartiallyCoupledAttributes(nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 2,913 | C++ | 29.041237 | 142 | 0.625815 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToFloat.cpp | // 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.
//
#include <OgnToFloatDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnToFloatDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<float>(value); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, float>(db.inputs.value(), db.outputs.converted(), functor, count);
}
template<typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnToFloatDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<float>(value); };
return ogn::compute::tryComputeWithTupleBroadcasting<tupleSize, T, float>(
db.inputs.value(), db.outputs.converted(), functor, count);
}
} // namespace
class OgnToFloat
{
public:
// Node to convert numeric inputs to floats
static bool computeVectorized(OgnToFloatDatabase& db, size_t count)
{
auto& inputType = db.inputs.value().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db, count);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (const std::exception& e)
{
db.logError("Input could not be converted to float: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto valueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token());
auto outAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::converted.token());
auto valueType = valueAttr.iAttribute->getResolvedType(valueAttr);
// The output shape must match the input shape and visa-versa, however we can't say anything
// about the input base type until it's connected
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eFloat, valueType.componentCount, valueType.arrayDepth);
outAttr.iAttribute->setResolvedType(outAttr, resultType);
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 5,427 | C++ | 38.911764 | 126 | 0.609176 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayRotate.cpp | // 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.
//
#include <OgnArrayRotateDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
// Custom implementation of std::rotate.
// Using std::rotate fails to build on Linux when the underlying type is a tuple (eg int[3])
template<class ForwardIt>
constexpr
ForwardIt
rotateArray(ForwardIt first, ForwardIt n_first, ForwardIt last)
{
if(first == n_first) return last;
if(n_first == last) return first;
ForwardIt read = n_first;
ForwardIt write = first;
ForwardIt next_read = first; // read position for when "read" hits "last"
while(read != last) {
if(write == next_read) next_read = read; // track where "first" went
std::iter_swap(write++, read++);
}
// rotate the remaining sequence into place
(rotateArray)(write, next_read, last);
return write;
}
template<typename T>
bool tryComputeAssumingType(OgnArrayRotateDatabase& db)
{
const auto& steps = db.inputs.steps();
if (auto array = db.inputs.array().template get<T[]>())
{
if (auto result = db.outputs.array().template get<T[]>())
{
*result = *array;
if (!result->empty())
{
if (steps < 0)
{
rotateArray(result->begin(), result->begin() - steps, result->end());
}
else if (steps > 0)
{
rotateArray(result->rbegin(), result->rbegin() + steps, result->rend());
}
}
return true;
}
}
return false;
}
} // namespace
class OgnArrayRotate
{
public:
static bool compute(OgnArrayRotateDatabase& db)
{
auto& inputType = db.inputs.array().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnArrayRotate: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
std::array<AttributeObj, 2> attrs {
node.iNode->getAttributeByToken(node, inputs::array.token()),
node.iNode->getAttributeByToken(node, outputs::array.token())
};
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 5,703 | C++ | 33.780488 | 92 | 0.57198 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnSelectIf.cpp | // 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.
//
#include <OgnSelectIfDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnSelectIfDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto const& condition, auto& result)
{
result = condition ? a : b;
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T, bool, T>(
db.inputs.ifTrue(), db.inputs.ifFalse(), db.inputs.condition(), db.outputs.result(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnSelectIfDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto const& condition, auto& result)
{
if (condition)
{
memcpy(result, a, sizeof(T) * N);
}
else
{
memcpy(result, b, sizeof(T) * N);
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], bool, T[N]>(
db.inputs.ifTrue(), db.inputs.ifFalse(), db.inputs.condition(), db.outputs.result(), functor, count);
}
} // namespace
class OgnSelectIf
{
public:
static bool computeVectorized(OgnSelectIfDatabase& db, size_t count)
{
NodeObj nodeObj = db.abi_node();
const AttributeObj ifTrueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::ifTrue.token());
const Type ifTrueType = ifTrueAttr.iAttribute->getResolvedType(ifTrueAttr);
const AttributeObj ifFalseAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::ifFalse.token());
const Type ifFalseType = ifFalseAttr.iAttribute->getResolvedType(ifFalseAttr);
const AttributeObj conditionAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::condition.token());
const Type conditionType = conditionAttr.iAttribute->getResolvedType(conditionAttr);
// This handles string case (arrays of strings are not supported)
if (ifTrueType.baseType == BaseDataType::eUChar && ifTrueType.arrayDepth == 1
&& ifFalseType.baseType == BaseDataType::eUChar && ifFalseType.arrayDepth == 1
&& conditionType.arrayDepth == 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
const bool condition = *db.inputs.condition(idx).template get<bool>();
auto ifTrue = db.inputs.ifTrue(idx).template get<uint8_t[]>();
auto ifFalse = db.inputs.ifFalse(idx).template get<uint8_t[]>();
auto result = db.outputs.result(idx).template get<uint8_t[]>();
if (condition)
{
result->resize(ifTrue->size());
memcpy(&((*result)[0]), &((*ifTrue)[0]), result->size());
}
else
{
result->resize(ifFalse->size());
memcpy(&((*result)[0]), &((*ifFalse)[0]), result->size());
}
}
return true;
}
try
{
switch (ifTrueType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db, count);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db, count);
case BaseDataType::eDouble:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto ifTrue = node.iNode->getAttributeByToken(node, inputs::ifTrue.token());
auto ifFalse = node.iNode->getAttributeByToken(node, inputs::ifFalse.token());
auto condition = node.iNode->getAttributeByToken(node, inputs::condition.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto ifTrueType = ifTrue.iAttribute->getResolvedType(ifTrue);
auto ifFalseType = ifFalse.iAttribute->getResolvedType(ifFalse);
auto conditionType = condition.iAttribute->getResolvedType(condition);
// Require ifTrue, ifFalse, and condition to be resolved before determining result's type
if (ifTrueType.baseType != BaseDataType::eUnknown && ifFalseType.baseType != BaseDataType::eUnknown
&& conditionType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { ifTrue, ifFalse, result };
std::array<uint8_t, 3> tupleCounts {
ifTrueType.componentCount,
ifFalseType.componentCount,
std::max(ifTrueType.componentCount, ifFalseType.componentCount)
};
std::array<uint8_t, 3> arrayDepths {
ifTrueType.arrayDepth,
ifFalseType.arrayDepth,
std::max(conditionType.arrayDepth, std::max(ifTrueType.arrayDepth, ifFalseType.arrayDepth))
};
const bool isStringInput = (ifTrueType.baseType == BaseDataType::eUChar
&& ifTrueType.arrayDepth == 1
&& ifFalseType.baseType == BaseDataType::eUChar
&& ifFalseType.arrayDepth == 1
&& conditionType.arrayDepth == 0
&& ifTrueType.role == AttributeRole::eText
&& ifFalseType.role == AttributeRole::eText);
std::array<AttributeRole, 3> rolesBuf {
ifTrueType.role,
ifFalseType.role,
isStringInput ? AttributeRole::eText : AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 9,218 | C++ | 43.110048 | 114 | 0.580386 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayGetSize.cpp |
// 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.
//
#include <OgnArrayGetSizeDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
class OgnArrayGetSize
{
public:
static bool compute(OgnArrayGetSizeDatabase& db)
{
try
{
db.outputs.size() = int(db.inputs.array().size());
return true;
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 1> attrs { inputArray };
// all should have the same tuple count
std::array<uint8_t, 1> tupleCounts {
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 1> arrayDepths {
1
};
std::array<AttributeRole, 1> rolesBuf {
inputArrayType.role
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 2,153 | C++ | 31.636363 | 107 | 0.628425 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBuildString.cpp | // 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.
//
#include <OgnBuildStringDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnBuildString
{
public:
static bool compute(OgnBuildStringDatabase& db)
{
auto const& inputValue = db.inputs.a();
auto const& suffixIn = db.inputs.b();
auto& outValue = db.outputs.value();
bool result = true;
if (inputValue.type().baseType == BaseDataType::eToken)
result = result && computeForToken(db, inputValue, suffixIn, outValue);
else
result = result && computeForString(db, inputValue, suffixIn, outValue);
auto const& dynamicInputs = db.getDynamicInputs();
if (!result || dynamicInputs.empty())
return result;
auto accumulatingValue = omni::graph::core::ogn::constructInputFromOutput(db, db.outputs.value(), outputs::value.token());
for (auto const& input : dynamicInputs)
{
if (input().type().baseType == BaseDataType::eToken)
result = result && computeForToken(db, accumulatingValue, input(), outValue);
else
result = result && computeForString(db, accumulatingValue, input(), outValue);
}
return result;
}
static bool computeForString(OgnBuildStringDatabase& db,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& inputValue,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& suffixIn,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& outValue)
{
auto const suffixData = suffixIn.get<uint8_t[]>();
// No suffix? Just copy in to out
if (suffixData->empty())
{
// the inputValue may be an alias for the outValue
if (inputValue.name() != outValue.name())
db.outputs.value().copyData(inputValue);
return true;
}
auto const inputValueData = inputValue.get<uint8_t[]>();
std::string outVal;
outVal.reserve(inputValueData.size() + suffixData.size());
outVal.append(reinterpret_cast<char const*>(inputValueData->data()), inputValueData.size());
outVal.append(reinterpret_cast<char const*>(suffixData->data()), suffixData.size());
auto outData = outValue.get<uint8_t[]>();
size_t outBufferSize = outVal.size();
outData->resize(outBufferSize);
memcpy(outData->data(), reinterpret_cast<uint8_t const*>(outVal.data()), outBufferSize);
return true;
}
static bool computeForToken(OgnBuildStringDatabase& db,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& inputValue,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& suffix,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& outValue)
{
std::vector<char const*> suffixes;
if (suffix.type().arrayDepth == 0)
{
NameToken suffixToken = *suffix.get<OgnToken>();
if (suffixToken != omni::fabric::kUninitializedToken)
suffixes.push_back(db.tokenToString(suffixToken));
}
else
{
const auto suffixTokens = *suffix.get<OgnToken[]>();
suffixes.resize(suffixTokens.size());
std::transform(suffixTokens.begin(), suffixTokens.end(), suffixes.begin(),
[&db](auto t) { return db.tokenToString(t); });
}
// No suffix? Just copy in to out
if (suffixes.empty())
{
// the input value may be an alias for the output value
if (inputValue.name() != outValue.name())
db.outputs.value().copyData(inputValue);
return true;
}
if (inputValue.type().arrayDepth > 0)
{
const auto inputValueArray = *inputValue.get<OgnToken[]>();
auto outputPathArray = *db.outputs.value().get<OgnToken[]>();
outputPathArray.resize(inputValueArray.size());
if (suffixes.size() == 1)
{
const char* suffixStr = suffixes[0];
std::transform(inputValueArray.begin(), inputValueArray.end(), outputPathArray.begin(),
[&](const auto& p)
{
std::string s = db.tokenToString(p);
s += suffixStr;
return db.stringToToken(s.c_str());
});
}
else
{
if (inputValueArray.size() != suffixes.size())
{
CARB_LOG_ERROR("inputs:value and inputs:suffix arrays are not the same size (%zu and %zu)",
inputValueArray.size(), suffixes.size());
return false;
}
for (size_t i = 0; i < inputValueArray.size(); ++i)
{
std::string s = db.tokenToString(inputValueArray[i]);
s += suffixes[i];
outputPathArray[i] = db.stringToToken(s.c_str());
}
}
return true;
}
else
{
NameToken inValue = *inputValue.get<OgnToken>();
std::string s;
if (inValue != omni::fabric::kUninitializedToken)
{
s = db.tokenToString(inValue);
}
s += suffixes[0];
*db.outputs.value().get<OgnToken>() = db.stringToToken(s.c_str());
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto inputVal = node.iNode->getAttributeByToken(node, OgnBuildStringAttributes::inputs::a.m_token);
auto outputVal = node.iNode->getAttributeByToken(node, OgnBuildStringAttributes::outputs::value.m_token);
// in and out needs to be the same
std::array<AttributeObj, 2> io{ inputVal, outputVal };
node.iNode->resolveCoupledAttributes(node, io.data(), io.size());
//retrieve all other input attributes
auto totalCount = node.iNode->getAttributeCount(node);
std::vector<AttributeObj> attrs(totalCount);
node.iNode->getAttributes(node, attrs.data(), totalCount);
size_t idx = 0;
size_t count = totalCount;
while (idx != count)
{
if (attrs[idx].iAttribute->getPortType(attrs[idx]) != AttributePortType::kAttributePortType_Input ||
attrs[idx].attributeHandle == inputVal.attributeHandle)
{
count--;
std::swap(attrs[idx], attrs[count]);
}
else
{
idx++;
}
}
auto type = inputVal.iAttribute->getResolvedType(inputVal);
// if input is an array of token, suffixes are allowed to be either a simple or an array of token(s)
if (type.baseType == BaseDataType::eToken && type.arrayDepth != 0)
{
for (auto const& attr : attrs)
{
auto suffixType = attr.iAttribute->getResolvedType(attr);
if (suffixType.baseType == BaseDataType::eUChar) // string not compatible with tokens
attr.iAttribute->setResolvedType(attr, type);
}
}
else if (type.baseType != BaseDataType::eUnknown)
{
// else, they all needs to have the same type
for (auto const& attr : attrs)
attr.iAttribute->setResolvedType(attr, type);
}
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 8,071 | C++ | 36.544186 | 130 | 0.564118 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToUint64.cpp | // 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.
//
#include <OgnToUint64Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnToUint64Database& db)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<uint64_t>(value); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, uint64_t>(db.inputs.value(), db.outputs.converted(), functor);
}
} // namespace
class OgnToUint64
{
public:
// Node to convert numeric inputs to floats
static bool compute(OgnToUint64Database& db)
{
auto& valueType = db.inputs.value().type();
switch (valueType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<uint8_t>(db);
case BaseDataType::eInt:
return tryComputeAssumingType<int32_t>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eHalf:
return tryComputeAssumingType<pxr::GfHalf>(db);
case BaseDataType::eFloat:
return tryComputeAssumingType<float>(db);
case BaseDataType::eDouble:
return tryComputeAssumingType<double>(db);
default:
db.logError("Failed to resolve input types");
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto valueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token());
auto outAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::converted.token());
auto valueType = valueAttr.iAttribute->getResolvedType(valueAttr);
// The output shape must match the input shape and visa-versa, however we can't say anything
// about the input base type until it's connected
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eUInt64, 1, valueType.arrayDepth);
outAttr.iAttribute->setResolvedType(outAttr, resultType);
}
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 2,870 | C++ | 33.178571 | 122 | 0.666899 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnStartsWith.cpp | // 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.
//
#include <OgnStartsWithDatabase.h>
#include <algorithm>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnStartsWith
{
public:
static bool compute(OgnStartsWithDatabase& db)
{
auto const& prefix = db.inputs.prefix();
auto const& value = db.inputs.value();
auto iters = std::mismatch(prefix.begin(), prefix.end(), value.begin(), value.end());
db.outputs.isPrefix() = (iters.first == prefix.end());
return true;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 972 | C++ | 24.605263 | 93 | 0.704733 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnSetGatheredAttribute.cpp | // Copyright (c) 2021-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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnSetGatheredAttributeDatabase.h>
#include <omni/graph/core/IGatherPrototype.h>
#include <carb/flatcache/FlatCache.h>
using namespace carb::flatcache;
namespace omni
{
namespace graph
{
namespace core
{
// WARNING!
// The following code uses low-level ABI functionality and should not be copied for other purposes when such
// low level access is not required. Please use the OGN-generated API whenever possible.
#define RETURN_TRUE_EXEC \
{\
db.outputs.execOut() = kExecutionAttributeStateEnabled;\
return true;\
}
class OgnSetGatheredAttribute
{
public:
static bool compute(OgnSetGatheredAttributeDatabase& db)
{
auto& nodeObj = db.abi_node();
const INode& iNode = *nodeObj.iNode;
const IGraphContext& iContext = *db.abi_context().iContext;
const omni::graph::core::IGatherPrototype* iGatherPrototype =
carb::getCachedInterface<omni::graph::core::IGatherPrototype>();
const auto& value = db.inputs.value();
const auto& mask = db.inputs.mask();
NameToken attributeName = db.inputs.name();
const char* attributeNameStr = db.tokenToString(attributeName);
if (!attributeNameStr || strlen(attributeNameStr) == 0)
RETURN_TRUE_EXEC
GatherId gatherId = static_cast<GatherId>(db.inputs.gatherId());
if (gatherId == kInvalidGatherId)
RETURN_TRUE_EXEC
if (!mask.empty() && value.size() > 1 && mask.size() != value.size())
{
db.logError("The length of the write mask (%zd) does not match the length of the value (%zd)",
mask.size(), value.size());
return false;
}
BucketId const* buckets{ nullptr };
size_t numBuckets{ 0 };
if (!iGatherPrototype->getGatheredBuckets(db.abi_context(), gatherId, buckets, numBuckets))
{
db.logError("Could not get gathered bucket list for Gather %zd", gatherId);
return false;
}
if (numBuckets == 0)
{
db.logError("Gathered bucket list is empty for Gather %zd", gatherId);
return false;
}
Type elementType;
size_t elementSize{ 0 };
if (!iGatherPrototype->getGatheredType(db.abi_context(), gatherId, attributeName, elementType, elementSize))
{
db.logError("Could not determine gathered type");
return false;
}
if (elementType.arrayDepth > 0)
{
db.logError("Gathering Array Type %s is not yet supported", elementType.getOgnTypeName().c_str());
return false;
}
if (elementSize == 0)
{
db.logError("The element type %s has zero size", elementType.getOgnTypeName().c_str());
return false;
}
Type srcDataType = db.inputs.value().type();
bool srcIsScaler = srcDataType.arrayDepth == 0;
if (!srcIsScaler)
{
// A scaler value will be broadcast
--srcDataType.arrayDepth;
}
if (!srcDataType.compatibleRawData(elementType))
{
db.logWarning("Attribute %s is not compatible with type '%s'", elementType.getTypeName().c_str(),
srcDataType.getTypeName().c_str());
RETURN_TRUE_EXEC
}
// determine the length of the content
size_t totalPrimCount{ 0 };
size_t inputArraySize = value.size();
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount = 0;
(void)db.abi_context().iContext->getBucketArray(db.abi_context(), bucketId, attributeName, primCount);
totalPrimCount += primCount;
}
PathBucketIndex const* repeatedPaths{ nullptr };
size_t numRepeatedPaths{ 0 };
if (!iGatherPrototype->getGatheredRepeatedPaths(db.abi_context(), gatherId, repeatedPaths, numRepeatedPaths))
{
db.logError("Could not get repeated paths list for Gather %zd", gatherId);
return false;
}
if (inputArraySize > 1 && totalPrimCount + numRepeatedPaths != inputArraySize)
{
db.logError(
"Given value of length %zd is not equal to the number of gathered attributes (%zd)", inputArraySize, totalPrimCount + numRepeatedPaths);
return false;
}
//printf("Setting %zd prims worth (%zd bytes) to %s\n", totalPrimCount, totalPrimCount * elementSize,
// attributeNameStr);
// Finally, we copy the data from the attribute to the buckets
const IAttributeData& iAttributeData = *db.abi_context().iAttributeData;
AttributeObj inputAttr =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnSetGatheredAttributeAttributes::inputs::value.m_token);
ConstAttributeDataHandle inputHandle = inputAttr.iAttribute->getConstAttributeDataHandle(inputAttr);
ConstRawPtr srcPtr{ nullptr };
{
const void** out = nullptr;
void** outPtr = reinterpret_cast<void**>(&out);
iAttributeData.getDataR((const void**)outPtr, db.abi_context(), &inputHandle, 1);
if (srcIsScaler)
srcPtr = reinterpret_cast<ConstRawPtr>(out);
else
srcPtr = reinterpret_cast<ConstRawPtr>(*out);
}
if (!srcPtr)
{
// No data to read
RETURN_TRUE_EXEC
}
size_t maskIndex = 0;
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount{ 0 };
uint8_t* destPtr = (uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !destPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
continue;
}
if (mask.empty())
{
size_t totalBytes = elementSize * primCount;
memcpy(destPtr, srcPtr, totalBytes);
if (!srcIsScaler)
srcPtr += totalBytes;
}
else
{
for (size_t j = 0; j < primCount; ++j)
{
if (mask[maskIndex++])
memcpy(destPtr, srcPtr, elementSize);
destPtr += elementSize;
if (!srcIsScaler)
srcPtr += elementSize;
}
}
}
// Set attribute for repeated paths
if (numRepeatedPaths > 0)
{
// If there are repeated paths, the set behaviour might be unexpected. Warn the user.
db.logWarning("Trying to set attribute when there are repeated prims in the gather. The first %zd values might be overwritten", totalPrimCount);
}
for (size_t i = 0; i < numRepeatedPaths; ++i)
{
PathBucketIndex pathBucketIndex = repeatedPaths[i];
BucketId bucketId = std::get<1>(pathBucketIndex);
ArrayIndex index = std::get<2>(pathBucketIndex);
size_t primCount{ 0 };
uint8_t* destPtr = (uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !destPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
continue;
}
if (index >= primCount)
{
db.logWarning("Bucket %zd has less entries than required", bucketId);
return false;
}
if (mask.empty() || mask[maskIndex++])
{
size_t byteCount = elementSize * index;
memcpy(destPtr + byteCount, srcPtr, elementSize);
if (!srcIsScaler)
srcPtr += elementSize;
}
}
RETURN_TRUE_EXEC
}
};
REGISTER_OGN_NODE()
}
}
}
| 8,672 | C++ | 32.616279 | 156 | 0.577721 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayFindValue.cpp | // 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.
//
#include <OgnArrayFindValueDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayFindValueDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
size_t const inputArraySize = db.inputs.array().size();
auto const value = db.inputs.value().template get<BaseType>();
if (!value || !inputArray)
return false;
for (size_t i = 0; i < inputArraySize; ++i)
{
if (memcmp(&((*inputArray)[i]), &*value, sizeof(BaseType)) == 0)
{
db.outputs.index() = int(i);
return true;
}
}
db.outputs.index() = -1;
return true;
}
} // namespace
class OgnArrayFindValue
{
public:
static bool compute(OgnArrayFindValueDatabase& db)
{
auto& inputType = db.inputs.value().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const inputValue = node.iNode->getAttributeByToken(node, inputs::value.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { inputArray, inputValue };
// all should have the same tuple count
std::array<uint8_t, 2> tupleCounts {
inputArrayType.componentCount,
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 2> arrayDepths {
1,
0,
};
std::array<AttributeRole, 2> rolesBuf {
inputArrayType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 5,811 | C++ | 37.490066 | 107 | 0.576149 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBundleInspector.cpp | // 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.
//
#include <OgnBundleInspectorDatabase.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
template <typename CppType>
std::string valueToString(const CppType& value)
{
return std::to_string(value);
}
template <>
std::string valueToString(const pxr::GfHalf& value)
{
return std::to_string((float) value);
}
template <>
std::string valueToString(const bool& value)
{
return value ? "True" : "False";
}
// TODO: This string conversion code is better suited to the BundledAttribute where it is accessible to all
// Since there are only three matrix dimensions a lookup is faster than a sqrt() call.
const int matrixDimensionMap[17]{ 1, 1, 1, 1, 2, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 4 };
// Helper template to output a convertible simple value as a string. Used when std::to_string works on the type.
template <typename CppType>
bool simpleValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto value = runtimeInput.get<CppType>() )
{
valueToSet = valueToString(*value);
return true;
}
return false;
}
// Helper template to output a convertible simple tuple value as a string.
// The output format is parenthesized "(X, Y, Z)"
template <typename CppType>
bool tupleValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto value = runtimeInput.get<CppType>() )
{
auto inputType = runtimeInput.type();
valueToSet = "(";
if (inputType.isMatrixType())
{
uint8_t dimension = inputType.dimension();
uint8_t index{ 0 };
for (uint8_t row=0; row<dimension; ++row)
{
if (row > 0)
{
valueToSet += ", ";
}
valueToSet += "(";
for (int col=0; col<dimension; ++col)
{
if (col > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[index++]);
}
valueToSet += ")";
}
}
else
{
for (uint8_t tupleIndex=0; tupleIndex<value.tupleSize(); ++tupleIndex )
{
if (tupleIndex > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[tupleIndex]);
}
}
valueToSet += ")";
return true;
}
return false;
}
// Helper template to output a convertible simple array value as a string.
// The output format has square brackets "[X, Y, Z]"
template <typename CppType>
bool arrayValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto arrayValue = runtimeInput.get<CppType>() )
{
auto role = runtimeInput.type().role;
auto baseType = runtimeInput.type().baseType;
const bool isString = (baseType == BaseDataType::eUChar) && ((role == AttributeRole::eText) || (role == AttributeRole::ePath));
if (isString)
{
std::string rawString(reinterpret_cast<const char*>(arrayValue->data()), arrayValue->size());
valueToSet = "'";
valueToSet += rawString;
valueToSet += "'";
}
else
{
valueToSet = "[";
size_t index{ 0 };
for (const auto& value : *arrayValue)
{
if (index++ > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value);
}
valueToSet += "]";
}
return true;
}
return false;
}
// Helper template to output a convertible tuple array value as a string.
// The output format has square brackets "[(X1, Y1), (X2, Y2), (X3, Y3))]"
template <typename CppType>
bool tupleArrayValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto tupleArrayValue = runtimeInput.get<CppType>() )
{
auto inputType = runtimeInput.type();
const bool isMatrix = inputType.isMatrixType();
auto tupleSize = inputType.dimension();
valueToSet = "[";
size_t index{ 0 };
for (const auto& value : *tupleArrayValue)
{
if (index++ > 0)
{
valueToSet += ", ";
}
valueToSet += "(";
if (isMatrix)
{
int tupleIndex{ 0 };
for (int row=0; row<tupleSize; ++row)
{
if (row > 0)
{
valueToSet += ", ";
}
valueToSet += "(";
for (int col=0; col<tupleSize; ++col)
{
if (col > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[tupleIndex++]);
}
valueToSet += ")";
}
}
else
{
for (int tupleIndex=0; tupleIndex<tupleSize; ++tupleIndex )
{
if (tupleIndex > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[tupleIndex]);
}
}
valueToSet += ")";
}
valueToSet += "]";
return true;
}
return false;
}
// Node whose responsibility is to analyze the contents of an input bundle attribute
// and create outputs describing them.
class OgnBundleInspector
{
private:
static void inspectRecursive
(
const int currentDepth,
const int inspectDepth,
const bool printContents,
OgnBundleInspectorDatabase& db,
const ogn::BundleContents<ogn::kOgnInput, ogn::kCpu> &inputBundle,
std::ostream &output,
ogn::array<NameToken> &names,
ogn::array<NameToken> &types,
ogn::array<NameToken> &roles,
ogn::array<int> &arrayDepths,
ogn::array<int> &tupleCounts,
ogn::array<NameToken> &values
)
{
IToken const* iToken = carb::getCachedInterface<omni::fabric::IToken>();
auto bundleName = inputBundle.abi_bundleInterface()->getName();
std::string indent{" "};
auto attributeCount = inputBundle.attributeCount();
auto childCount = inputBundle.childCount();
output << "Bundle '" << iToken->getText(bundleName) << "' from " << db.abi_node().iNode->getPrimPath(db.abi_node())
<< " (attributes = " << attributeCount << " children = " << childCount << ")" << std::endl;
// Walk the contents of the input bundle, extracting the attribute information along the way
size_t index = 0;
for (const auto& bundledAttribute : inputBundle)
{
if (bundledAttribute.isValid())
{
// The attribute names and etc apply only to top level bundle passed to the BundleInspector
if (currentDepth == 0) names[index] = bundledAttribute.name();
for (int numIndent = 0; numIndent < currentDepth; numIndent++) output << indent;
output << indent << "[" << index << "] " << db.tokenToString(bundledAttribute.name());
const Type& attributeType = bundledAttribute.type();
output << "(" << attributeType << ")";
if (currentDepth == 0)
{
{
std::ostringstream nameStream;
nameStream << attributeType.baseType;
types[index] = db.stringToToken(nameStream.str().c_str());
}
{
std::ostringstream nameStream;
nameStream << getOgnRoleName(attributeType.role);
roles[index] = db.stringToToken(nameStream.str().c_str());
}
arrayDepths[index] = attributeType.arrayDepth;
tupleCounts[index] = attributeType.componentCount;
}
// Convert the value into a string, using an empty string for unknown types
std::string valueAsString{"__unsupported__"};
bool noOutput = !simpleValueToString<bool>(bundledAttribute, valueAsString)
&& !arrayValueToString<bool[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<int64_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<int64_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<uint8_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<uint8_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<uint32_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<uint32_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<uint64_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<uint64_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<double>(bundledAttribute, valueAsString)
&& !arrayValueToString<double[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][4]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[9]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][9]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[16]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][16]>(bundledAttribute, valueAsString)
&& !simpleValueToString<float>(bundledAttribute, valueAsString)
&& !arrayValueToString<float[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<float[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<float[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<float[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<float[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<float[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<float[][4]>(bundledAttribute, valueAsString)
&& !simpleValueToString<int>(bundledAttribute, valueAsString)
&& !arrayValueToString<int[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<int[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<int[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<int[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<int[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<int[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<int[][4]>(bundledAttribute, valueAsString)
&& !simpleValueToString<pxr::GfHalf>(bundledAttribute, valueAsString)
&& !arrayValueToString<pxr::GfHalf[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<pxr::GfHalf[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<pxr::GfHalf[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<pxr::GfHalf[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<pxr::GfHalf[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<pxr::GfHalf[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<pxr::GfHalf[][4]>(bundledAttribute, valueAsString)
;
if (noOutput)
{
if (const auto tokenValue = bundledAttribute.get<OgnToken>() )
{
std::ostringstream tokenValueStream;
tokenValueStream << std::quoted(db.tokenToString(*tokenValue));
valueAsString = tokenValueStream.str();
noOutput = false;
}
}
if (noOutput)
{
if (const auto tokenArrayValue = bundledAttribute.get<OgnToken[]>() )
{
std::ostringstream tokenArrayValueStream;
tokenArrayValueStream << "[";
size_t index{ 0 };
for (const auto& value : *tokenArrayValue)
{
if (index++ > 0)
{
tokenArrayValueStream << ", ";
}
tokenArrayValueStream << std::quoted(db.tokenToString(value));
}
tokenArrayValueStream << "]";
valueAsString = tokenArrayValueStream.str();
noOutput = false;
}
}
output << " = " << valueAsString << std::endl;
if (currentDepth == 0) values[index] = db.stringToToken(valueAsString.c_str());
if (noOutput)
{
std::ostringstream nameStream;
nameStream << attributeType;
db.logWarning("No value output known for attribute %zu (%s), defaulting to '__unsupported__'", index, nameStream.str().c_str());
}
index++;
}
else
{
output << indent << "Bundle is invalid" << std::endl;
db.logWarning("Ignoring invalid bundle member '%s'", db.tokenToString(bundledAttribute.name()));
}
}
// Walk through its children, if any
if (printContents && childCount && ((currentDepth < inspectDepth) || (inspectDepth <= -1)))
{
IConstBundle2* inputBundleIFace = inputBundle.abi_bundleInterface();
// context is for building the child BundleContents
const auto context = inputBundleIFace->getContext();
std::vector<ConstBundleHandle> childBundleHandles(childCount);
inputBundleIFace->getConstChildBundles(childBundleHandles.data(), childCount);
for (const auto& childHandle : childBundleHandles)
{
if (childHandle.isValid())
{
ogn::BundleContents<ogn::kOgnInput, ogn::kCpu> childBundle(context, childHandle);
for (int numIndent = 0; numIndent < currentDepth + 1; numIndent++) output << indent;
output << "Has Child "; // No std::endl -> "Has Child Bundle from ..."
inspectRecursive(currentDepth+1, inspectDepth, printContents, db, childBundle, output, names, types, roles, arrayDepths, tupleCounts, values);
}
else
{
for (int numIndent = 0; numIndent < currentDepth; numIndent++) output << indent;
output << "One child is invalid." << std::endl;
}
}
}
}
public:
static bool compute(OgnBundleInspectorDatabase& db)
{
const auto& inputBundle = db.inputs.bundle();
auto attributeCount = inputBundle.attributeCount();
auto childCount = inputBundle.childCount();
db.outputs.bundle() = inputBundle;
const auto& printContents = db.inputs.print();
const auto& inspectDepth = db.inputs.inspectDepth();
// Rather than pollute the file with a bunch of "if (printContents)" setting up a file stream with a
// bad bit causes the output to be thrown away without parsing.
std::ofstream ofs;
ofs.setstate(std::ios_base::badbit);
auto& output = printContents ? std::cout : ofs;
db.outputs.count() = attributeCount;
db.outputs.attributeCount() = attributeCount;
db.outputs.childCount() = childCount;
// Extract the output interfaces to nicer names
auto& names = db.outputs.names();
auto& types = db.outputs.types();
auto& roles = db.outputs.roles();
auto& arrayDepths = db.outputs.arrayDepths();
auto& tupleCounts = db.outputs.tupleCounts();
auto& values = db.outputs.values();
// All outputs except the count are arrays of that size - preallocate them here
names.resize(attributeCount);
types.resize(attributeCount);
roles.resize(attributeCount);
arrayDepths.resize(attributeCount);
tupleCounts.resize(attributeCount);
values.resize(attributeCount);
inspectRecursive(0, inspectDepth, printContents, db, inputBundle, output, names, types, roles, arrayDepths, tupleCounts, values);
return true;
}
};
REGISTER_OGN_NODE();
}
}
}
| 18,952 | C++ | 42.872685 | 162 | 0.538518 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayIndex.cpp | // 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.
//
#include <OgnArrayIndexDatabase.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni {
namespace graph {
namespace nodes {
using core::ogn::array;
// unnamed namespace to avoid multiple declaration when linking
namespace {
// helper to wrap a given index from legal range [-arrayLength, arrayLength) to [0:arrayLength).
// values outside of the legal range with throw
size_t tryWrapIndex(int index, size_t arraySize)
{
int wrappedIndex = index;
if (index < 0)
wrappedIndex = (int)arraySize + index;
if ((wrappedIndex >= (int)arraySize) or (wrappedIndex < 0))
throw ogn::compute::InputError(formatString("inputs:index %d is out of range for inputs:array of size %zu", wrappedIndex, arraySize));
return size_t(wrappedIndex);
}
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayIndexDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
size_t const index = tryWrapIndex(db.inputs.index(), db.inputs.array().size());
auto outputValue = db.outputs.value().template get<BaseType>();
if (!outputValue || !inputArray)
return false;
memcpy(&*outputValue, &((*inputArray)[index]), sizeof(BaseType));
return true;
}
} // namespace
class OgnArrayIndex
{
public:
static bool compute(OgnArrayIndexDatabase& db)
{
auto& inputType = db.inputs.array().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const array = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const value = node.iNode->getAttributeByToken(node, outputs::value.token());
auto const arrayType = array.iAttribute->getResolvedType(array);
auto const valueType = value.iAttribute->getResolvedType(value);
if ((arrayType.baseType == BaseDataType::eUnknown) != (valueType.baseType == BaseDataType::eUnknown))
{
std::array<AttributeObj, 2> attrs { array, value };
// array and value should have the same tuple count
std::array<uint8_t, 2> tupleCounts {
std::max(arrayType.componentCount, valueType.componentCount),
std::max(arrayType.componentCount, valueType.componentCount)
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 2> arrayDepths {
1,
0
};
std::array<AttributeRole, 2> rolesBuf {
arrayType.role,
// Copy the attribute role from the array type to the value type
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 6,415 | C++ | 39.352201 | 142 | 0.595168 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimPath.cpp | // 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.
//
#include <OgnGetPrimPathDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimPath
{
public:
static size_t computeVectorized(OgnGetPrimPathDatabase& db, size_t count)
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!pathInterface || !tokenInterface)
{
CARB_LOG_ERROR("Failed to initialize path or token interface");
return 0;
}
auto primPaths = db.outputs.primPath.vectorized(count);
for (size_t i = 0; i < count; i++)
{
const auto& prims = db.inputs.prim(i);
if (prims.size() > 0)
{
auto text = pathInterface->getText(prims[0]);
db.outputs.path(i) = text;
primPaths[i] = tokenInterface->getHandle(text);
}
else
{
db.outputs.path(i) = "";
primPaths[i] = Token();
}
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 1,592 | C++ | 26.947368 | 79 | 0.607412 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetRelativePath.cpp | // 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.
//
#include <OgnGetRelativePathDatabase.h>
#include <omni/fabric/FabricUSD.h>
using omni::fabric::asInt;
using omni::fabric::toTfToken;
static NameToken const& getRelativePath(const NameToken& pathAsToken, const pxr::SdfPath& anchor)
{
auto pathToken = toTfToken(pathAsToken);
if (pathAsToken != omni::fabric::kUninitializedToken && pxr::SdfPath::IsValidPathString(pathToken))
{
auto relPath = pxr::SdfPath(pathToken).MakeRelativePath(anchor);
return *asInt(&relPath.GetToken());
}
return pathAsToken;
}
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetRelativePath
{
public:
static size_t computeVectorized(OgnGetRelativePathDatabase& db, size_t count)
{
auto anchor = db.inputs.anchor.vectorized(count);
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
if (anchor[idx] == omni::fabric::kUninitializedToken)
{
db.outputs.relativePath(idx).copyData(db.inputs.path(idx));
}
else
{
const auto anchorPath = pxr::SdfPath(toTfToken(anchor[idx]));
const auto inputPathArray = *db.inputs.path(idx).get<OgnToken[]>();
auto outputPathArray = *db.outputs.relativePath(idx).get<OgnToken[]>();
outputPathArray.resize(inputPathArray.size());
std::transform(inputPathArray.begin(), inputPathArray.end(), outputPathArray.begin(),
[&](const auto& p) { return getRelativePath(p, anchorPath); });
}
}
}
else
{
auto ipt = db.inputs.path().get<OgnToken>();
auto inputPath = ipt.vectorized(count);
auto oldInputs = db.state.path.vectorized(count);
auto oldAnchor = db.state.anchor.vectorized(count);
auto op = db.outputs.relativePath().get<OgnToken>();
auto outputs = op.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (oldAnchor[idx] != anchor[idx] || oldInputs[idx] != inputPath[idx])
{
if (anchor[idx] == omni::fabric::kUninitializedToken)
{
outputs[idx] = inputPath[idx];
}
else
{
const auto anchorPath = pxr::SdfPath(toTfToken(anchor[idx]));
outputs[idx] = getRelativePath(inputPath[idx], anchorPath);
}
oldAnchor[idx] = anchor[idx];
oldInputs[idx] = inputPath[idx];
}
}
}
return count;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs{ node.iNode->getAttribute(node, OgnGetRelativePathAttributes::inputs::path.m_name),
node.iNode->getAttribute(node, OgnGetRelativePathAttributes::outputs::relativePath.m_name) };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 3,813 | C++ | 35.323809 | 136 | 0.577236 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnAppendPath.cpp | // 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.
//
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/sdf/valueTypeName.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/fabric/FabricUSD.h>
#include <OgnAppendPathDatabase.h>
using omni::fabric::asInt;
using omni::fabric::toTfToken;
static NameToken const& appendPath(const NameToken& pathAsToken, const pxr::SdfPath& suffix)
{
auto pathToken = toTfToken(pathAsToken);
if (pathAsToken != omni::fabric::kUninitializedToken && pxr::SdfPath::IsValidPathString(pathToken))
{
auto newPath = pxr::SdfPath(pathToken).AppendPath(suffix);
return *asInt(&newPath.GetToken());
}
return pathAsToken;
}
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnAppendPath
{
public:
static size_t computeVectorized(OgnAppendPathDatabase& db, size_t count)
{
auto suffix = db.inputs.suffix.vectorized(count);
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
if (suffix[idx] == omni::fabric::kUninitializedToken)
{
db.outputs.path(idx).copyData(db.inputs.path(idx));
}
else
{
const auto suffixPath = pxr::SdfPath(toTfToken(suffix[idx]));
const auto inputPathArray = *db.inputs.path(idx).get<OgnToken[]>();
auto outputPathArray = *db.outputs.path(idx).get<OgnToken[]>();
outputPathArray.resize(inputPathArray.size());
std::transform(inputPathArray.begin(), inputPathArray.end(), outputPathArray.begin(),
[&](const auto& p) { return appendPath(p, suffixPath); });
}
}
}
else
{
auto ipt = db.inputs.path().get<OgnToken>();
auto inputPath = ipt.vectorized(count);
auto oldInputs = db.state.path.vectorized(count);
auto oldSuffix = db.state.suffix.vectorized(count);
auto op = db.outputs.path().get<OgnToken>();
auto outputs = op.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (oldSuffix[idx] != suffix[idx] || oldInputs[idx] != inputPath[idx])
{
if (suffix[idx] == omni::fabric::kUninitializedToken)
{
outputs[idx] = inputPath[idx];
}
else
{
const auto suffixPath = pxr::SdfPath(toTfToken(suffix[idx]));
outputs[idx] = appendPath(inputPath[idx], suffixPath);
}
oldSuffix[idx] = suffix[idx];
oldInputs[idx] = inputPath[idx];
}
}
}
return count;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs{ node.iNode->getAttribute(node, OgnAppendPathAttributes::inputs::path.m_name),
node.iNode->getAttribute(node, OgnAppendPathAttributes::outputs::path.m_name) };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 3,897 | C++ | 33.495575 | 123 | 0.576084 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnFindPrims.cpp | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnFindPrimsDatabase.h>
#include <omni/fabric/FabricUSD.h>
#include "ReadPrimCommon.h"
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnFindPrims
{
struct Listener
{
UsdStageChangeListenerRefPtr changeListener; // Lets us know when the USD stage changes
};
public:
// ----------------------------------------------------------------------------
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
auto& ls = OgnFindPrimsDatabase::sSharedState<Listener>(nodeObj);
ls.changeListener = UsdStageChangeListener::New(context, UsdStageChangeListener::ListenMode::eResync);
}
// ----------------------------------------------------------------------------
static void release(const NodeObj& nodeObj)
{
auto& ls = OgnFindPrimsDatabase::sSharedState<Listener>(nodeObj);
ls.changeListener.Reset();
}
// ----------------------------------------------------------------------------
static bool compute(OgnFindPrimsDatabase& db)
{
auto& ls = db.sharedState<Listener>();
auto inputType = db.inputs.type();
auto rootPrimPath = db.inputs.rootPrimPath();
auto rootPrim = db.inputs.rootPrim();
auto recursive = db.inputs.recursive();
auto namePrefix = db.inputs.namePrefix();
auto requiredAttributesStr = db.inputs.requiredAttributes();
auto requiredRelationship = db.inputs.requiredRelationship();
auto requiredRelationshipTargetStr = db.inputs.requiredRelationshipTarget();
auto requiredTarget = db.inputs.requiredTarget();
auto pathPattern = db.inputs.pathPattern();
auto ignoreSystemPrims = db.inputs.ignoreSystemPrims();
// We can skip compute if our state isn't dirty, and our inputs haven't changed
if (not ls.changeListener->checkDirty())
{
if (db.state.inputType() == inputType &&
db.state.rootPrim().size() == rootPrim.size() &&
(db.state.rootPrim().size() == 0 ? db.state.rootPrimPath() == rootPrimPath
: db.state.rootPrim()[0] == rootPrim[0]) &&
db.state.recursive() == recursive &&
db.state.namePrefix() == namePrefix &&
requiredAttributesStr == db.state.requiredAttributes() &&
db.state.requiredRelationship() == requiredRelationship &&
(db.state.requiredTarget.size() == 0 ? requiredRelationshipTargetStr == db.state.requiredRelationshipTarget()
: db.state.requiredTarget()[0] == requiredTarget[0]) &&
pathPattern == db.state.pathPattern() &&
ignoreSystemPrims == db.state.ignoreSystemPrims())
{
// Not dirty and inputs didn't change
return true;
}
}
db.state.inputType() = inputType;
db.state.rootPrimPath() = rootPrimPath;
db.state.rootPrim() = rootPrim;
db.state.recursive() = recursive;
db.state.namePrefix() = namePrefix;
db.state.requiredAttributes() = requiredAttributesStr;
db.state.requiredRelationship() = requiredRelationship;
db.state.requiredRelationshipTarget() = requiredRelationshipTargetStr;
db.state.requiredTarget() = requiredTarget;
db.state.pathPattern() = pathPattern;
db.state.ignoreSystemPrims() = ignoreSystemPrims;
long stageId = db.abi_context().iContext->getStageId(db.abi_context());
auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
if (!stage)
{
db.logError("Could not find USD stage %ld", stageId);
return false;
}
pxr::UsdPrim startPrim;
if(rootPrim.size() == 0)
{
if (rootPrimPath == omni::fabric::kUninitializedToken)
startPrim = stage->GetPseudoRoot();
else
{
if (const char* primPathStr = db.tokenToString(rootPrimPath))
{
startPrim = stage->GetPrimAtPath(pxr::SdfPath(primPathStr));
if (!startPrim)
{
db.logError("Could not find rootPrim \"%s\"", primPathStr);
return false;
}
}
}
}
else
{
if(rootPrim.size() > 1)
db.logWarning("Only one rootPrim target is supported, the rest will be ignored");
startPrim = stage->GetPrimAtPath(omni::fabric::toSdfPath(rootPrim[0]));
if (!startPrim)
{
db.logError("Could not find rootPrim \"%s\"", db.pathToString(rootPrim[0]));
return false;
}
}
// Figure out the required type if any
pxr::TfToken requiredTypeName;
if (inputType != omni::fabric::kUninitializedToken)
{
if (char const* typeStr = db.tokenToString(inputType))
requiredTypeName = pxr::TfToken(typeStr);
}
char const* requiredNamePrefix{ db.tokenToString(namePrefix) };
// Figure out require relationship target if any
pxr::SdfPath requiredRelationshipTarget;
pxr::TfToken requiredRelName;
if (requiredRelationship != omni::fabric::kUninitializedToken)
{
requiredRelName = pxr::TfToken(db.tokenToString(requiredRelationship));
if (!requiredRelName.IsEmpty())
{
bool validTarget = (requiredTarget.size() == 0 && !requiredRelationshipTargetStr.empty());
if(requiredTarget.size() == 0)
{
if(!requiredRelationshipTargetStr.empty())
requiredRelationshipTarget = pxr::SdfPath{ requiredRelationshipTargetStr };
}
else
{
if(requiredTarget.size() > 1)
db.logWarning("Only one requiredTarget is supported, the rest will be ignored");
requiredRelationshipTarget = omni::fabric::toSdfPath(requiredTarget[0]);
}
if (validTarget && !requiredRelationshipTarget.IsPrimPath())
{
db.logError("Required relationship target \"%s\" is not valid", requiredRelationshipTarget.GetText());
}
}
}
// now find matching prims
pxr::TfToken requiredAttribs{ std::string{ requiredAttributesStr.data(), requiredAttributesStr.size() } };
PathVector matchedPaths;
findPrims_findMatching(matchedPaths, startPrim, recursive, requiredNamePrefix, requiredTypeName,
requiredAttribs, requiredRelName, requiredRelationshipTarget,
omni::fabric::intToToken(pathPattern), ignoreSystemPrims);
// output PathC
auto outputPrims = db.outputs.prims();
outputPrims.resize(matchedPaths.size());
std::transform(matchedPaths.begin(), matchedPaths.end(), outputPrims.begin(),
[&db](auto path) {return path;});
// convert PathC to TokenC
auto outputPaths = db.outputs.primPaths();
outputPaths.resize(matchedPaths.size());
std::transform(matchedPaths.begin(), matchedPaths.end(), outputPaths.begin(),
[&db](auto path)
{
const char* pathStr = omni::fabric::intToPath(path).GetText();
return db.stringToToken(pathStr);
});
return true;
}
static bool updateNodeVersion(GraphContextObj const& context, NodeObj const& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
if (oldVersion < 2)
{
// backward compatibility: `inputs:type`
// Prior to this version `inputs:type` attribute did not support wild cards.
// The meaning of an empty string was to include all types. With the introduction of the wild cards
// we need to convert an empty string to "*" in order to include all types.
static Token const value{ "*" };
if (nodeObj.iNode->getAttributeExists(nodeObj, OgnFindPrimsAttributes::inputs::type.m_name))
{
AttributeObj attr = nodeObj.iNode->getAttribute(nodeObj, OgnFindPrimsAttributes::inputs::type.m_name);
auto roHandle = attr.iAttribute->getAttributeDataHandle(attr, kAccordingToContextIndex);
Token const* roValue = getDataR<Token const>(context, roHandle);
if (roValue && roValue->getString().empty())
{
Token* rwValue = getDataW<Token>(
context, attr.iAttribute->getAttributeDataHandle(attr, kAccordingToContextIndex));
*rwValue = value;
}
}
else
{
nodeObj.iNode->createAttribute(nodeObj, OgnFindPrimsAttributes::inputs::type.m_name, Type(BaseDataType::eToken), &value, nullptr,
kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr);
}
return true;
}
}
return false;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 10,203 | C++ | 40.819672 | 149 | 0.565814 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetGatheredAttribute.cpp | // Copyright (c) 2021-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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnGetGatheredAttributeDatabase.h>
#include <omni/graph/core/IGatherPrototype.h>
#include <carb/flatcache/FlatCache.h>
using namespace carb::flatcache;
namespace omni
{
namespace graph
{
namespace core
{
class OgnGetGatheredAttribute
{
public:
static bool compute(OgnGetGatheredAttributeDatabase& db)
{
auto& nodeObj = db.abi_node();
const INode& iNode = *nodeObj.iNode;
const IGraphContext& iContext = *db.abi_context().iContext;
const omni::graph::core::IGatherPrototype* iGatherPrototype =
carb::getCachedInterface<omni::graph::core::IGatherPrototype>();
NameToken attributeName = db.inputs.name();
const char* attributeNameStr = db.tokenToString(attributeName);
if (!attributeNameStr || strlen(attributeNameStr) == 0)
return true;
GatherId gatherId = static_cast<GatherId>(db.inputs.gatherId());
BucketId const* buckets{ nullptr };
size_t numBuckets{ 0 };
if (!iGatherPrototype->getGatheredBuckets(db.abi_context(), gatherId, buckets, numBuckets))
{
db.logError("Could not get gathered bucket list for Gather %zd", gatherId);
return false;
}
if (numBuckets == 0)
{
db.logError("Gathered bucket list is empty for Gather %zd", gatherId);
return false;
}
Type elementType;
size_t elementSize{ 0 };
if (!iGatherPrototype->getGatheredType(db.abi_context(), gatherId, attributeName, elementType, elementSize))
{
db.logError("Could not determine gathered type");
return false;
}
if (elementType.arrayDepth > 0)
{
db.logError("Gathering Array Type %s is not yet supported", elementType.getOgnTypeName().c_str());
return false;
}
Type outputType(elementType);
++outputType.arrayDepth;
// Determine if the output attribute has already been resolved to an incompatible type
if (db.outputs.value().resolved())
{
Type outType = db.outputs.value().type();
if (!outputType.compatibleRawData(outType))
{
db.logWarning("Resolved type %s of outputs:value is not compatible with type %s",
outType.getOgnTypeName().c_str(), db.outputs.value().type().getOgnTypeName().c_str());
return false;
}
}
// If it's resolved, we already know that it is compatible from the above check
if (!db.outputs.value().resolved())
{
// Not resolved, so we have to resolve it now. This node is strange in that the resolved output type
// depends on external state instead of other attributes.
AttributeObj out = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::value.m_token);
out.iAttribute->setResolvedType(out, outputType);
db.outputs.value().reset(db.abi_context(), out.iAttribute->getAttributeDataHandle(out), out);
}
AttributeObj outputAttr = nodeObj.iNode->getAttributeByToken(
nodeObj, OgnGetGatheredAttributeAttributes::outputs::value.m_token);
AttributeDataHandle outputHandle = outputAttr.iAttribute->getAttributeDataHandle(outputAttr);
// determine the length of the output
size_t totalPrimCount{ 0 };
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount = 0;
void* ptr = db.abi_context().iContext->getBucketArray(db.abi_context(), bucketId, attributeName, primCount);
if (!ptr)
{
CARB_LOG_WARN("Attribute %s not found in Gather %zd, bucket %zd", attributeNameStr, gatherId, size_t(bucketId));
return true;
}
totalPrimCount += primCount;
}
PathBucketIndex const* repeatedPaths{ nullptr };
size_t numRepeatedPaths{ 0 };
if (!iGatherPrototype->getGatheredRepeatedPaths(db.abi_context(), gatherId, repeatedPaths, numRepeatedPaths))
{
db.logError("Could not get repeated paths list for Gather %zd", gatherId);
return false;
}
//printf("Getting %zd prims worth of %s\n", totalPrimCount, attributeNameStr);
// Set the required length of output array
db.abi_context().iAttributeData->setElementCount(db.abi_context(), outputHandle, totalPrimCount + numRepeatedPaths);
// Get pointer to target data
uint8_t* destPtr = nullptr;
{
void** out = nullptr;
void** outPtr = reinterpret_cast<void**>(&out);
db.abi_context().iAttributeData->getDataW(outPtr, db.abi_context(), &outputHandle, 1);
destPtr = (uint8_t*)(*out);
}
CARB_ASSERT(destPtr);
// Finally, we copy the data into the output, bucket by bucket
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount{ 0 };
const uint8_t* srcPtr = (const uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !srcPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
return false;
}
size_t byteCount = elementSize * primCount;
{
// Copy the data
memcpy(destPtr, srcPtr, byteCount);
// Move the write pointer
destPtr += byteCount;
}
}
// Copy the data for repeated paths
for (size_t i = 0; i < numRepeatedPaths; ++i)
{
BucketId bucketId = std::get<1>(repeatedPaths[i]);
size_t primCount{ 0 };
const uint8_t* srcPtr = (const uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !srcPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
return false;
}
ArrayIndex index = std::get<2>(repeatedPaths[i]);
if (index >= primCount)
{
db.logWarning("Bucket %zd has less entries than required", bucketId);
return false;
}
size_t byteCount = elementSize * index;
{
// Copy the data
memcpy(destPtr, srcPtr + byteCount, elementSize);
// Move the write pointer
destPtr += elementSize;
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 7,383 | C++ | 34.84466 | 128 | 0.592713 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeArray.py | """
This is the implementation of the OGN node defined in OgnMakeArrayDouble3.ogn
"""
import omni.graph.core as og
class OgnMakeArray:
"""
Makes an output array attribute from input values
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
if db.inputs.a.type.base_type == og.BaseDataType.UNKNOWN:
return False
array_size = db.inputs.arraySize
out_array = []
if array_size > 0:
out_array.append(db.inputs.a.value)
if array_size > 1:
out_array.append(db.inputs.b.value)
if array_size > 2:
out_array.append(db.inputs.c.value)
if array_size > 3:
out_array.append(db.inputs.d.value)
if array_size > 4:
out_array.append(db.inputs.e.value)
out_array.extend([db.inputs.e.value] * (array_size - 5))
db.outputs.array.value = out_array
return True
@staticmethod
def on_connection_type_resolve(node) -> None:
attribs = [(node.get_attribute("inputs:" + a), None, 0, None) for a in ("a", "b", "c", "d", "e")]
attribs.append((node.get_attribute("outputs:array"), None, 1, None))
og.resolve_base_coupled(attribs)
| 1,266 | Python | 29.902438 | 105 | 0.591627 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetParentPath.cpp | // 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.
//
#include <OgnGetParentPathDatabase.h>
#include <omni/fabric/FabricUSD.h>
using omni::fabric::asInt;
using omni::fabric::toTfToken;
static NameToken const& getParentPath(const NameToken& pathAsToken)
{
auto pathToken = toTfToken(pathAsToken);
if (pathAsToken != omni::fabric::kUninitializedToken && pxr::SdfPath::IsValidPathString(pathToken))
{
auto parentPath = pxr::SdfPath(pathToken).GetParentPath();
return *asInt(&parentPath.GetToken());
}
return pathAsToken;
}
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetParentPath
{
public:
static bool computeVectorized(OgnGetParentPathDatabase& db, size_t count)
{
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
const auto inputPathArray = *db.inputs.path(idx).get<OgnToken[]>();
auto outputPathArray = *db.outputs.parentPath(idx).get<OgnToken[]>();
outputPathArray.resize(inputPathArray.size());
std::transform(inputPathArray.begin(), inputPathArray.end(), outputPathArray.begin(),
[&](const auto& p) { return getParentPath(p); });
}
}
else
{
auto ipt = db.inputs.path().get<OgnToken>();
auto inputPath = ipt.vectorized(count);
auto oldInputs = db.state.path.vectorized(count);
auto op = db.outputs.parentPath().get<OgnToken>();
auto outputs = op.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (oldInputs[idx] != inputPath[idx])
{
outputs[idx] = getParentPath(inputPath[idx]);
oldInputs[idx] = inputPath[idx];
}
}
}
return count;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs{ node.iNode->getAttribute(node, OgnGetParentPathAttributes::inputs::path.m_name),
node.iNode->getAttribute(node, OgnGetParentPathAttributes::outputs::parentPath.m_name) };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 2,841 | C++ | 32.046511 | 132 | 0.619852 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimRelationship.cpp | // 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.
//
#include "OgnGetPrimRelationshipDatabase.h"
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/relationship.h>
#include <pxr/usd/usdUtils/stageCache.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <algorithm>
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimRelationship
{
public:
// Queries relationship data on a prim
static bool compute(OgnGetPrimRelationshipDatabase& db)
{
auto& nodeObj = db.abi_node();
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
try {
auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::path.token(),
inputs::usePath.token(), db.getInstanceIndex());
const char* relName = db.tokenToString(db.inputs.name());
if (!relName)
return false;
long int stageId = iContext->getStageId(contextObj);
pxr::UsdStageRefPtr stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
pxr::UsdPrim prim = stage->GetPrimAtPath(primPath);
if (!prim)
return false;
pxr::UsdRelationship relationship = prim.GetRelationship(pxr::TfToken(relName));
pxr::SdfPathVector targets;
if (relationship.GetTargets(&targets))
{
auto& outputPaths = db.outputs.paths();
outputPaths.resize(targets.size());
std::transform(targets.begin(), targets.end(), outputPaths.begin(),
[&db](const pxr::SdfPath& path) { return db.stringToToken(path.GetText()); });
}
return true;
}
catch(const std::exception& e)
{
db.logError(e.what());
return false;
}
}
static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
if (oldVersion < 2)
{
// for older nodes, inputs:usePath must equal true so the prim path method is on by default
const bool val{ true };
nodeObj.iNode->createAttribute(nodeObj, "inputs:usePath", Type(BaseDataType::eBool), &val, nullptr,
kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr);
}
return true;
}
return false;
}
};
REGISTER_OGN_NODE()
}
}
}
| 3,133 | C++ | 31.309278 | 122 | 0.618896 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimsAtPath.cpp | // 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.
//
#include <OgnGetPrimsAtPathDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimsAtPath
{
public:
static bool computeVectorized(OgnGetPrimsAtPathDatabase& db, size_t count)
{
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
auto& outPrims = db.outputs.prims(idx);
const auto paths = *db.inputs.path(idx).template get<OgnToken[]>();
outPrims.resize(paths.size());
std::transform(paths.begin(), paths.end(), outPrims.begin(),
[&](const auto& p) {
return (p != omni::fabric::kUninitializedToken) ? db.tokenToPath(p) : omni::fabric::kUninitializedPath;
});
}
}
else
{
const auto pathPtr = db.inputs.path().template get<OgnToken>();
if (pathPtr)
{
auto path = pathPtr.vectorized(count);
auto oldPath = db.state.path.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
auto outPrims = db.outputs.prims(idx);
if (oldPath[idx] != path[idx])
{
if (path[idx] != omni::fabric::kUninitializedToken)
{
outPrims.resize(1);
outPrims[0] = db.tokenToPath(path[idx]);
}
else
{
outPrims.resize(0);
}
}
}
}
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 2,255 | C++ | 30.333333 | 127 | 0.504656 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeVector4.cpp | // 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.
//
#include <OgnMakeVector4Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename Type>
bool tryMakeVector(OgnMakeVector4Database& db)
{
const auto x = db.inputs.x().template get<Type>();
const auto y = db.inputs.y().template get<Type>();
const auto z = db.inputs.z().template get<Type>();
const auto w = db.inputs.w().template get<Type>();
auto vector = db.outputs.tuple().template get<Type[4]>();
if (vector && x && y && z && w)
{
(*vector)[0] = *x;
(*vector)[1] = *y;
(*vector)[2] = *z;
(*vector)[3] = *w;
return true;
}
const auto xArray = db.inputs.x().template get<Type[]>();
const auto yArray = db.inputs.y().template get<Type[]>();
const auto zArray = db.inputs.z().template get<Type[]>();
const auto wArray = db.inputs.w().template get<Type[]>();
auto vectorArray = db.outputs.tuple().template get<Type[][4]>();
if (!vectorArray || !xArray || !yArray || !zArray || !wArray)
{
return false;
}
if (xArray->size() != yArray->size() || xArray->size() != zArray->size() || xArray->size() != wArray->size())
{
throw ogn::compute::InputError("Input arrays of different lengths x:" +
std::to_string(xArray->size()) + ", y:" +
std::to_string(yArray->size()) + ", z:" +
std::to_string(zArray->size()) + ", w:" +
std::to_string(wArray->size()));
}
vectorArray->resize(xArray->size());
for (size_t i = 0; i < vectorArray->size(); i++)
{
(*vectorArray)[i][0] = (*xArray)[i];
(*vectorArray)[i][1] = (*yArray)[i];
(*vectorArray)[i][2] = (*zArray)[i];
(*vectorArray)[i][3] = (*wArray)[i];
}
return true;
}
} // namespace
// Node to merge 4 scalers together to make 4-vector
class OgnMakeVector4
{
public:
static bool compute(OgnMakeVector4Database& db)
{
// Compute the components, if the types are all resolved.
try
{
if (tryMakeVector<double>(db))
return true;
else if (tryMakeVector<float>(db))
return true;
else if (tryMakeVector<pxr::GfHalf>(db))
return true;
else if (tryMakeVector<int32_t>(db))
return true;
else
{
db.logError("Failed to resolve input types");
return false;
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be made: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto x = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::x.token());
auto y = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::y.token());
auto z = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::z.token());
auto w = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::w.token());
auto vector = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::tuple.token());
auto xType = vector.iAttribute->getResolvedType(x);
auto yType = vector.iAttribute->getResolvedType(y);
auto zType = vector.iAttribute->getResolvedType(z);
auto wType = vector.iAttribute->getResolvedType(w);
std::array<AttributeObj, 4> attrs{ x, y, z, w };
if (nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size()))
{
xType = vector.iAttribute->getResolvedType(x);
yType = vector.iAttribute->getResolvedType(y);
zType = vector.iAttribute->getResolvedType(z);
wType = vector.iAttribute->getResolvedType(w);
}
// Require inputs to be resolved before determining outputs' type
if (xType.baseType != BaseDataType::eUnknown && yType.baseType != BaseDataType::eUnknown &&
zType.baseType != BaseDataType::eUnknown && wType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 5> attrs{ x, y, z, w, vector };
std::array<uint8_t, 5> tuples{ 1, 1, 1, 1, 4 };
std::array<uint8_t, 5> arrays{
xType.arrayDepth,
yType.arrayDepth,
zType.arrayDepth,
wType.arrayDepth,
xType.arrayDepth
};
std::array<AttributeRole, 5> roles{ xType.role, yType.role, zType.role, wType.role, AttributeRole::eNone };
nodeObj.iNode->resolvePartiallyCoupledAttributes(
nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 5,369 | C++ | 33.645161 | 119 | 0.583349 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnCompare.cpp | // 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.
//
#include <OgnCompareDatabase.h>
#include <functional>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
std::function<bool(const T&, const T&)> getOperation(OgnCompareDatabase& db, NameToken operation)
{
// Find the desired comparison
std::function<bool(const T&, const T&)> fn;
if (operation == db.tokens.gt) fn = [](const T& a, const T& b){ return a > b; };
else if (operation == db.tokens.lt) fn =[](const T& a, const T& b){ return a < b; };
else if (operation == db.tokens.ge) fn = [](const T& a, const T& b){ return a >= b; };
else if (operation == db.tokens.le) fn = [](const T& a, const T& b){ return a <= b; };
else if (operation == db.tokens.eq) fn = [](const T& a, const T& b){ return a == b; };
else if (operation == db.tokens.ne) fn = [](const T& a, const T& b){ return a != b; };
else
{
throw ogn::compute::InputError("Failed to resolve token " + std::string(db.tokenToString(operation)) +
", expected one of (>,<,>=,<=,==,!=)");
}
return fn;
}
template<>
std::function<bool(const OgnToken&, const OgnToken&)> getOperation(OgnCompareDatabase& db, NameToken operation)
{
std::function<bool(const OgnToken&, const OgnToken&)> fn;
if (operation == db.tokens.eq)
fn = [](const OgnToken& a, const OgnToken& b) { return a == b; };
else if (operation == db.tokens.ne)
fn = [](const OgnToken& a, const OgnToken& b) { return a != b; };
else if (operation == db.tokens.gt || operation == db.tokens.lt || operation == db.tokens.ge || operation == db.tokens.le)
throw ogn::compute::InputError("Operation " + std::string(db.tokenToString(operation)) +
" not supported for Tokens, expected one of (==,!=)");
else
throw ogn::compute::InputError("Failed to resolve token " + std::string(db.tokenToString(operation)) +
", expected one of (>,<,>=,<=,==,!=)");
return fn;
}
template<typename T>
bool tryComputeAssumingType(OgnCompareDatabase& db, NameToken operation, size_t count)
{
auto op = getOperation<T>(db, operation);
auto functor = [&](auto const& a, auto const& b, auto& result)
{
result = op(a, b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T, bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnCompareDatabase& db, NameToken operation, size_t count)
{
auto op = getOperation<T>(db, operation);
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Lexicographical comparison of tuples
result = true;
for (size_t i = 0; i < N; i++)
{
if (i < (N - 1) && (a[i] == b[i]))
continue;
else if (op(a[i], b[i]))
{
result = true;
break;
}
else
{
result = false;
break;
}
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor, count);
}
bool tryComputeAssumingString(OgnCompareDatabase& db, NameToken operation, size_t count)
{
auto op = getOperation<ogn::const_string>(db, operation);
for (size_t idx = 0; idx < count; ++idx)
{
auto stringA = db.inputs.a(idx).get<const char[]>();
auto stringB = db.inputs.b(idx).get<const char[]>();
*(db.outputs.result(idx).get<bool>()) = op(stringA(), stringB());
}
return true;
}
} // namespace
class OgnCompare
{
public:
static bool computeVectorized(OgnCompareDatabase& db, size_t count)
{
try
{
auto& aType = db.inputs.a().type();
auto& bType = db.inputs.b().type();
if (aType.baseType != bType.baseType || aType.componentCount != bType.componentCount)
throw ogn::compute::InputError("Failed to resolve input types");
const auto& operation = db.inputs.operation();
if ((operation != db.tokens.gt) and (operation != db.tokens.lt) and (operation != db.tokens.ge) and
(operation != db.tokens.le) and (operation != db.tokens.eq) and (operation != db.tokens.ne))
{
std::string op{ "Unknown" };
char const* opStr = db.tokenToString(operation);
if (opStr)
op = opStr;
throw ogn::compute::InputError("Unrecognized operation '" + op + std::string("'"));
}
auto node = db.abi_node();
auto opAttrib = node.iNode->getAttributeByToken(node, inputs::operation.m_token);
bool isOpConstant = opAttrib.iAttribute->isRuntimeConstant(opAttrib);
using FUNC_SIG = bool (*)(OgnCompareDatabase& db, NameToken operation, size_t count);
auto repeatWork = [&](FUNC_SIG const& func)
{
if (isOpConstant)
{
return func(db, operation, count);
}
bool ret = true;
while (count)
{
ret = func(db, operation, 1) && ret;
db.moveToNextInstance();
--count;
}
return ret;
};
switch (aType.baseType)
{
case BaseDataType::eBool:
return repeatWork(tryComputeAssumingType<bool>);
case BaseDataType::eDouble:
switch (aType.componentCount)
{
case 1: return repeatWork(tryComputeAssumingType<double>);
case 2: return repeatWork(tryComputeAssumingType<double, 2>);
case 3: return repeatWork(tryComputeAssumingType<double, 3>);
case 4: return repeatWork(tryComputeAssumingType<double, 4>);
case 9: return repeatWork(tryComputeAssumingType<double, 9>);
case 16: return repeatWork(tryComputeAssumingType<double, 16>);
}
case BaseDataType::eFloat:
switch (aType.componentCount)
{
case 1: return repeatWork(tryComputeAssumingType<float>);
case 2: return repeatWork(tryComputeAssumingType<float, 2>);
case 3: return repeatWork(tryComputeAssumingType<float, 3>);
case 4: return repeatWork(tryComputeAssumingType<float, 4>);
}
case BaseDataType::eInt:
switch (aType.componentCount)
{
case 1: return repeatWork(tryComputeAssumingType<int32_t>);
case 2: return repeatWork(tryComputeAssumingType<int32_t, 2>);
case 3: return repeatWork(tryComputeAssumingType<int32_t, 3>);
case 4: return repeatWork(tryComputeAssumingType<int32_t, 4>);
}
case BaseDataType::eHalf:
return repeatWork(tryComputeAssumingType<pxr::GfHalf>);
case BaseDataType::eInt64:
return repeatWork(tryComputeAssumingType<int64_t>);
case BaseDataType::eUChar:
if (aType.role == AttributeRole::eText && bType.role == AttributeRole::eText &&
aType.arrayDepth == 1 && bType.arrayDepth == 1 && aType.componentCount == 1 &&
bType.componentCount == 1)
{
return repeatWork(tryComputeAssumingString);
}
return repeatWork(tryComputeAssumingType<unsigned char>);
case BaseDataType::eUInt:
return repeatWork(tryComputeAssumingType<uint32_t>);
case BaseDataType::eToken:
return repeatWork(tryComputeAssumingType<OgnToken>);
case BaseDataType::eUInt64:
return repeatWork(tryComputeAssumingType<uint64_t>);
default:
break;
}
throw ogn::compute::InputError("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto b = node.iNode->getAttributeByToken(node, inputs::b.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto aType = a.iAttribute->getResolvedType(a);
auto bType = b.iAttribute->getResolvedType(b);
// Require inputs to be resolved before determining result's type
if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown)
{
const bool isStringInput = (aType.baseType == BaseDataType::eUChar && bType.baseType == BaseDataType::eUChar
&& aType.role == AttributeRole::eText && bType.role == AttributeRole::eText
&& aType.arrayDepth == 1 && bType.arrayDepth == 1
&& aType.componentCount == 1 && bType.componentCount == 1);
const uint8_t resultArrayDepth = isStringInput ? 0 : std::max(aType.arrayDepth, bType.arrayDepth);
Type resultType(BaseDataType::eBool, 1, resultArrayDepth);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 10,275 | C++ | 40.772358 | 142 | 0.57635 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBundleConstructor.py | """
Module contains the OmniGraph node implementation of BundleConstructor
"""
import omni.graph.core as og
class OgnBundleConstructor:
"""Node to create a bundle out of dynamic attributes"""
@staticmethod
def compute(db) -> bool:
"""Compute the bundle from the dynamic input attributes"""
# Start with an empty output bundle.
output_bundle = db.outputs.bundle
output_bundle.clear()
# Walk the list of node attribute, looking for dynamic inputs
for attribute in db.abi_node.get_attributes():
if attribute.is_dynamic():
if attribute.get_port_type() != og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT:
continue
if attribute.get_extended_type() != og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR:
db.log_warn(f"Cannot add extended attribute types like '{attribute.get_name()}' to a bundle")
continue
if attribute.get_resolved_type().base_type in [og.BaseDataType.RELATIONSHIP]:
db.log_warn(f"Cannot add bundle attribute types like '{attribute.get_name()}' to a bundle")
continue
# The bundled name does not need the port namespace
new_name = attribute.get_name().replace("inputs:", "")
output_bundle.insert((attribute.get_resolved_type(), new_name))
return True
| 1,448 | Python | 37.131578 | 113 | 0.619475 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimPaths.cpp | // 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.
//
#include <OgnGetPrimPathsDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimPaths
{
public:
static size_t computeVectorized(OgnGetPrimPathsDatabase& db, size_t count)
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!pathInterface || !tokenInterface)
{
CARB_LOG_ERROR("Failed to initialize path or token interface");
return 0;
}
for (size_t p = 0; p < count; p++)
{
const auto& prims = db.inputs.prims(p);
auto& primPaths = db.outputs.primPaths(p);
primPaths.resize(prims.size());
for (size_t i = 0; i < prims.size(); i++)
{
primPaths[i] = tokenInterface->getHandle(pathInterface->getText(prims[i]));
}
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 1,448 | C++ | 27.411764 | 91 | 0.640884 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetParentPrims.cpp | // 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.
//
#include <OgnGetParentPrimsDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetParentPrims
{
public:
static size_t computeVectorized(OgnGetParentPrimsDatabase& db, size_t count)
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
if (!pathInterface)
{
CARB_LOG_ERROR("Failed to initialize path or token interface");
return 0;
}
for (size_t i = 0; i < count; i++)
{
const auto& prims = db.inputs.prims(i);
auto& parentPaths = db.outputs.parentPrims(i);
parentPaths.resize(prims.size());
std::transform(prims.begin(), prims.end(), parentPaths.begin(),
[&](const auto& p) { return pathInterface->getParent(p); });
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 1,351 | C++ | 27.166666 | 87 | 0.647668 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnEndsWith.cpp | // 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.
//
#include <OgnEndsWithDatabase.h>
#include <algorithm>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnEndsWith
{
public:
static bool compute(OgnEndsWithDatabase& db)
{
auto const& suffix = db.inputs.suffix();
auto const& value = db.inputs.value();
auto iters = std::mismatch(suffix.rbegin(), suffix.rend(), value.rbegin(), value.rend());
db.outputs.isSuffix() = (iters.first == suffix.rend());
return true;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 971 | C++ | 24.578947 | 97 | 0.704428 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantNames.cpp | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <carb/logging/Log.h>
#include <OgnGetVariantNamesDatabase.h>
namespace omni::graph::nodes
{
class OgnGetVariantNames
{
public:
static bool compute(OgnGetVariantNamesDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetName = db.tokenToString(db.inputs.variantSetName());
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
auto variantNames = variantSet.GetVariantNames();
db.outputs.variantNames().resize(variantNames.size());
for (size_t i = 0; i < variantNames.size(); i++)
{
db.outputs.variantNames()[i] = db.stringToToken(variantNames[i].c_str());
}
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
db.outputs.variantNames().resize(0);
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,721 | C++ | 28.18644 | 89 | 0.639163 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnClearVariantSelection.cpp | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include "VariantCommon.h"
#include <carb/logging/Log.h>
#include <OgnClearVariantSelectionDatabase.h>
namespace omni::graph::nodes
{
class OgnClearVariantSelection
{
public:
static bool compute(OgnClearVariantSelectionDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetName = db.tokenToString(db.inputs.variantSetName());
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
if (db.inputs.setVariant())
{
bool success = variantSet.SetVariantSelection("");
if (!success)
throw warning(std::string("Failed to clear variant selection for variant set ") + variantSetName);
}
else
{
removeLocalOpinion(prim, variantSetName);
}
db.outputs.execOut() = kExecutionAttributeStateEnabled;
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,868 | C++ | 28.203125 | 118 | 0.630621 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnHasVariantSet.cpp | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <carb/logging/Log.h>
#include <omni/usd/UsdContext.h>
#include <OgnHasVariantSetDatabase.h>
namespace omni::graph::nodes
{
class OgnHasVariantSet
{
public:
static bool compute(OgnHasVariantSetDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
db.outputs.exists() = variantSets.HasVariantSet(db.tokenToString(db.inputs.variantSetName()));
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
db.outputs.exists() = false;
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,373 | C++ | 24.444444 | 106 | 0.656956 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantSetNames.cpp | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <carb/logging/Log.h>
#include <OgnGetVariantSetNamesDatabase.h>
namespace omni::graph::nodes
{
class OgnGetVariantSetNames
{
public:
static bool compute(OgnGetVariantSetNamesDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetNames = variantSets.GetNames();
db.outputs.variantSetNames().resize(variantSetNames.size());
for (size_t i = 0; i < variantSetNames.size(); i++)
{
db.outputs.variantSetNames()[i] = db.stringToToken(variantSetNames[i].c_str());
}
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
db.outputs.variantSetNames().resize(0);
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,578 | C++ | 26.701754 | 95 | 0.636882 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnBlendVariants.cpp | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include "VariantCommon.h"
#include <carb/logging/Log.h>
#include <omni/fabric/Enums.h>
#include <omni/graph/core/ogn/Types.h>
#include <omni/math/linalg/SafeCast.h>
#include <omni/usd/UsdContext.h>
#include <pxr/usd/sdf/variantSetSpec.h>
#include <pxr/usd/sdf/variantSpec.h>
#include <OgnBlendVariantsDatabase.h>
using omni::graph::core::ogn::eAttributeType::kOgnOutput;
using omni::graph::core::ogn::eMemoryType::kCpu;
using omni::math::linalg::vec3f;
using DB = OgnBlendVariantsDatabase;
namespace omni::graph::nodes
{
namespace
{
using LerpFunction = void (*)(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
pxr::UsdAttribute attribute);
template <typename T>
void floatLerp(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
pxr::UsdAttribute attribute)
{
T a = propertyA->GetDefaultValue().Get<T>();
T b = propertyB->GetDefaultValue().Get<T>();
T c = pxr::GfLerp(alpha, a, b);
if (attribute.IsValid())
attribute.Set<T>(c);
}
template <typename T>
void discreteLerp(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
pxr::UsdAttribute attribute)
{
T a = propertyA->GetDefaultValue().Get<T>();
T b = propertyB->GetDefaultValue().Get<T>();
if (attribute.IsValid())
{
if (alpha < 0.5)
attribute.Set<T>(a);
else
attribute.Set<T>(b);
}
}
void lerpAttribute(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
const pxr::UsdAttribute& attribute)
{
if (propertyA->GetSpecType() != propertyB->GetSpecType())
throw warning("Property spec types do not match (attribute " + attribute.GetPath().GetString() + ")");
if (propertyA->GetTypeName() != attribute.GetTypeName())
throw warning("Attribute types do not match (attribute " + attribute.GetPath().GetString() + ")");
if (propertyA->GetValueType() != propertyB->GetValueType())
throw warning("Property value types do not match");
auto typeName = propertyA->GetValueType().GetTypeName();
auto handleType = [alpha, &propertyA, &propertyB, &attribute, &typeName](const char* type, LerpFunction lerpFunction) -> bool
{
if (typeName == type)
{
lerpFunction(alpha, propertyA, propertyB, attribute);
return true;
}
return false;
};
if (!handleType("bool", discreteLerp<bool>)
&& !handleType("double", floatLerp<double>)
&& !handleType("float", floatLerp<float>)
&& !handleType("pxr_half::half", floatLerp<pxr::GfHalf>)
&& !handleType("int", discreteLerp<int>)
&& !handleType("__int64", discreteLerp<int64_t>) // Windows
&& !handleType("long", discreteLerp<int64_t>) // Linux
&& !handleType("unsigned char", discreteLerp<uint8_t>)
&& !handleType("unsigned int", discreteLerp<uint32_t>)
&& !handleType("unsigned __int64", discreteLerp<uint64_t>) // Windows
&& !handleType("unsigned long", discreteLerp<uint64_t>) // Linux
&& !handleType("TfToken", discreteLerp<pxr::TfToken>)
&& !handleType("SdfTimeCode", floatLerp<pxr::SdfTimeCode>)
&& !handleType("GfVec2d", floatLerp<pxr::GfVec2d>)
&& !handleType("GfVec2f", floatLerp<pxr::GfVec2f>)
&& !handleType("GfVec2h", floatLerp<pxr::GfVec2h>)
&& !handleType("GfVec2i", discreteLerp<pxr::GfVec2i>)
&& !handleType("GfVec3d", floatLerp<pxr::GfVec3d>)
&& !handleType("GfVec3f", floatLerp<pxr::GfVec3f>)
&& !handleType("GfVec3h", floatLerp<pxr::GfVec3h>)
&& !handleType("GfVec3i", discreteLerp<pxr::GfVec3i>)
&& !handleType("GfVec4d", floatLerp<pxr::GfVec4d>)
&& !handleType("GfVec4f", floatLerp<pxr::GfVec4f>)
&& !handleType("GfVec4h", floatLerp<pxr::GfVec4h>)
&& !handleType("GfVec4i", discreteLerp<pxr::GfVec4i>)
&& !handleType("GfQuatd", floatLerp<pxr::GfQuatd>)
&& !handleType("GfQuatf", floatLerp<pxr::GfQuatf>)
&& !handleType("GfQuath", floatLerp<pxr::GfQuath>)
&& !handleType("GfMatrix2d", floatLerp<pxr::GfMatrix2d>)
&& !handleType("GfMatrix3d", floatLerp<pxr::GfMatrix3d>)
&& !handleType("GfMatrix4d", floatLerp<pxr::GfMatrix4d>))
throw warning("Unsupported property type " + typeName);
}
}
class OgnBlendVariants
{
public:
static bool compute(OgnBlendVariantsDatabase& db)
{
auto ok = [&db]()
{
db.outputs.execOut() = kExecutionAttributeStateEnabled;
return true;
};
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
std::string variantSetName = db.tokenToString(db.inputs.variantSetName());
std::string variantNameA = db.tokenToString(db.inputs.variantNameA());
std::string variantNameB = db.tokenToString(db.inputs.variantNameB());
double blend = std::max(std::min(db.inputs.blend(), 1.0), 0.0);
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
if (!variantSet.IsValid())
throw warning("Invalid variant set " + variantSetName);
bool finishing = (1.0 - blend) < 1e-6;
if (finishing && db.inputs.setVariant())
variantSet.SetVariantSelection(variantNameB);
VariantData a = getVariantData(prim, variantSetName, variantNameA);
VariantData b = getVariantData(prim, variantSetName, variantNameB);
for (const auto& [path, propertyA] : a)
{
if (b.find(path) == b.end())
continue;
auto propertyB = b[path];
auto attribute = prim.GetStage()->GetAttributeAtPath(path);
if (!attribute.IsValid())
throw warning("Invalid attribute " + path.GetString());
if (finishing && db.inputs.setVariant())
attribute.Clear();
else
lerpAttribute(blend, propertyA, propertyB, attribute);
}
return ok();
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 7,396 | C++ | 35.800995 | 129 | 0.611682 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveFrame.cpp | // 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.
//
#include <OgnCurveFrameDatabase.h>
#include "omni/math/linalg/vec.h"
#include <carb/Framework.h>
#include <carb/Types.h>
#include <math.h>
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace nodes
{
static vec3f perpendicular(vec3f v)
{
vec3f av(abs(v[0]), abs(v[1]), abs(v[2]));
// Find the smallest coordinate of v.
int axis = (av[0] < av[1] && av[0] < av[2]) ? 0 : ((av[1] < av[2]) ? 1 : 2);
// Start with that coordinate.
vec3f p(0.0f);
p[axis] = 1.0f;
// Subtract the portion parallel to v.
p -= (GfDot(p, v) / GfDot(v, v)) * v;
// Normalize
return p.GetNormalized();
}
static vec3f rotateLike(vec3f v, vec3f a, vec3f aPlusb)
{
// To apply to another vector v, the rotation that brings tangent a to tangent b:
// - reflect v through the line in direction of unit vector a
// - reflect that through the line in direction of a+b
vec3f temp = (2 * GfDot(a, v)) * a - v;
return (2 * GfDot(aPlusb, temp) / GfDot(aPlusb, aPlusb)) * aPlusb - temp;
}
class OgnCurveFrame
{
public:
static bool compute(OgnCurveFrameDatabase& db)
{
const auto& vertexStartIndices = db.inputs.curveVertexStarts();
const auto& vertexCounts = db.inputs.curveVertexCounts();
const auto& curvePoints = db.inputs.curvePoints();
auto& tangentArray = db.outputs.tangent();
auto& upArray = db.outputs.up();
auto &outArray = db.outputs.out();
size_t curveCount = vertexStartIndices.size();
if (vertexCounts.size() < curveCount)
curveCount = vertexCounts.size();
const size_t pointCount = curvePoints.size();
if (curveCount == 0)
{
tangentArray.resize(0);
upArray.resize(0);
outArray.resize(0);
return true;
}
tangentArray.resize(pointCount);
upArray.resize(pointCount);
outArray.resize(pointCount);
for (size_t curve = 0; curve < curveCount; ++curve)
{
if (vertexCounts[curve] <= 0)
continue;
const size_t vertex = vertexStartIndices[curve];
if (vertex >= pointCount)
break;
size_t vertexCount = size_t(vertexCounts[curve]);
// Limit the vertex count on this curve if it goes past the end of the points array.
if (vertexCount > pointCount - vertex)
{
vertexCount = pointCount - vertex;
}
if (vertexCount == 1)
{
// Only one vertex: predetermined frame.
tangentArray[vertex] = vec3f( 0.0f, 0.0f, 1.0f );
upArray[vertex] = vec3f( 0.0f, 1.0f, 0.0f );
outArray[vertex] = vec3f( 1.0f, 0.0f, 0.0f );
continue;
}
// First, compute all tangents.
// The first tangent is the first edge direction.
// TODO: Skip zero-length edges to get the first real edge direction.
vec3f prev = curvePoints[vertex];
vec3f current = curvePoints[vertex + 1];
vec3f prevDir = (current - prev).GetNormalized();
tangentArray[vertex] = prevDir;
for (size_t i = 1; i < vertexCount - 1; ++i)
{
vec3f next = curvePoints[vertex + i + 1];
vec3f nextDir = (next - current).GetNormalized();
// Middle tangents are averages of previous and next directions.
vec3f dir = (prevDir + nextDir).GetNormalized();
tangentArray[vertex + i] = dir;
prev = current;
current = next;
prevDir = nextDir;
}
// The last tangent is the last edge direction.
tangentArray[vertex + vertexCount - 1] = prevDir;
// Choose the first up vector as anything that's perpendicular to the first tangent.
// TODO: Use a curve "normal" for more consistency.
vec3f prevTangent = tangentArray[vertex];
vec3f prevUpVector = perpendicular(prevTangent);
// x = cross(y, z)
vec3f prevOutVector = GfCross(prevUpVector, prevTangent);
upArray[vertex] = prevUpVector;
outArray[vertex] = prevOutVector;
for (size_t i = 1; i < vertexCount; ++i)
{
vec3f nextTangent = tangentArray[vertex + i];
vec3f midTangent = prevTangent + nextTangent;
vec3f nextUpVector = rotateLike(prevUpVector, prevTangent, midTangent);
vec3f nextOutVector = rotateLike(prevOutVector, prevTangent, midTangent);
upArray[vertex + i] = nextUpVector;
outArray[vertex + i] = nextOutVector;
prevTangent = nextTangent;
prevUpVector = nextUpVector;
prevOutVector = nextOutVector;
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 5,465 | C++ | 32.533742 | 96 | 0.579323 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnLengthAlongCurve.cpp | // 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.
//
#include <OgnLengthAlongCurveDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnLengthAlongCurve
{
public:
static bool compute(OgnLengthAlongCurveDatabase& db)
{
const auto& vertexStartIndices = db.inputs.curveVertexStarts();
const auto& vertexCounts = db.inputs.curveVertexCounts();
const auto& curvePoints = db.inputs.curvePoints();
const auto& normalize = db.inputs.normalize();
auto& lengthArray = db.outputs.length();
size_t curveCount = std::min(vertexStartIndices.size(), vertexCounts.size());
const size_t pointCount = curvePoints.size();
if (curveCount == 0)
{
lengthArray.resize(0);
return true;
}
lengthArray.resize(pointCount);
for (size_t curve = 0; curve < curveCount; ++curve)
{
if (vertexCounts[curve] <= 0)
continue;
const size_t vertex = vertexStartIndices[curve];
if (vertex >= pointCount)
break;
size_t vertexCount = size_t(vertexCounts[curve]);
// Limit the vertex count on this curve if it goes past the end of the points array.
if (vertexCount > pointCount - vertex)
{
vertexCount = pointCount - vertex;
}
if (vertexCount == 1)
{
// Only one vertex: predetermined frame.
lengthArray[vertex] = 0.0f;
continue;
}
// First, compute all lengths along the curve.
auto prev = curvePoints[vertex];
lengthArray[vertex] = 0.0f;
// Sum in double precision to avoid catastrophic roundoff error.
double lengthSum = 0.0;
for (size_t i = 1; i < vertexCount; ++i)
{
auto& current = curvePoints[vertex + i];
auto edge = (current - prev);
lengthSum += edge.GetLength();
lengthArray[vertex + i] = float(lengthSum);
prev = current;
}
// Don't normalize if lengthSum is zero.
if (normalize && float(lengthSum) != 0)
{
for (size_t i = 0; i < vertexCount; ++i)
{
lengthArray[vertex + i] /= float(lengthSum);
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,908 | C++ | 28.98969 | 96 | 0.563274 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCreateTubeTopology.cpp | // 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.
//
#include <OgnCreateTubeTopologyDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnCreateTubeTopology
{
public:
static bool compute(OgnCreateTubeTopologyDatabase& db)
{
const auto& inputRows = db.inputs.rows();
const auto& inputColumns = db.inputs.cols();
auto& faceVertexCounts = db.outputs.faceVertexCounts();
auto& faceVertexIndices = db.outputs.faceVertexIndices();
const size_t rowValueCount = inputRows.size();
const size_t colValueCount = inputColumns.size();
size_t inputTubeCount;
if (colValueCount == 1 || colValueCount == rowValueCount)
{
inputTubeCount = rowValueCount;
}
else if (rowValueCount == 1)
{
inputTubeCount = colValueCount;
}
else
{
faceVertexCounts.resize(0);
faceVertexIndices.resize(0);
return true;
}
size_t validTubeCount = 0;
size_t quadCount = 0;
for (size_t inputTube = 0; inputTube < inputTubeCount; ++inputTube)
{
auto rows = inputRows[(rowValueCount == 1) ? 0 : inputTube];
auto cols = inputColumns[(colValueCount == 1) ? 0 : inputTube];
if (rows <= 0 || cols <= 1)
{
continue;
}
const size_t currentQuadCount = size_t(rows) * cols;
quadCount += currentQuadCount;
++validTubeCount;
}
// Generate a faceVertexCounts array with all 4, for all quads.
faceVertexCounts.resize(quadCount);
for (auto& faceVertex : faceVertexCounts)
{
faceVertex = 4;
}
faceVertexIndices.resize(4 * quadCount);
size_t faceVertexIndex{ 0 };
int pointIndex = 0;
for (size_t inputTube = 0; inputTube < inputTubeCount; ++inputTube)
{
auto rows = inputRows[(rowValueCount == 1) ? 0 : inputTube];
auto cols = inputColumns[(colValueCount == 1) ? 0 : inputTube];
if (rows <= 0 || cols <= 1)
{
continue;
}
for (auto row = 0; row < rows; ++row)
{
// Main quads of the row
for (auto col = 0; col < cols - 1; ++col)
{
faceVertexIndices[faceVertexIndex++] = pointIndex;
faceVertexIndices[faceVertexIndex++] = pointIndex + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + cols + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + cols;
++pointIndex;
}
// Wrap around
faceVertexIndices[faceVertexIndex++] = pointIndex;
faceVertexIndices[faceVertexIndex++] = pointIndex - cols + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + cols;
++pointIndex;
}
pointIndex += cols;
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 3,600 | C++ | 30.867256 | 81 | 0.565 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveTubeST.cpp | // 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.
//
#include <OgnCurveTubeSTDatabase.h>
#include "omni/math/linalg/vec.h"
#include <carb/Framework.h>
#include <carb/Types.h>
#include <omni/graph/core/ArrayWrapper.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <omni/graph/core/iComputeGraph.h>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
using omni::math::linalg::vec2f;
namespace omni
{
namespace graph
{
namespace nodes
{
static void computeNewSs(std::vector<float>& sValues, size_t edgeCount)
{
if (sValues.size() == edgeCount + 1)
return;
sValues.resize(edgeCount + 1);
sValues[0] = 0.0f;
if (edgeCount == 0)
return;
for (size_t i = 1; i < edgeCount; ++i)
{
sValues[i] = float(double(i) / double(edgeCount));
}
sValues[edgeCount] = 1.0f;
}
class OgnCurveTubeST
{
public:
static bool compute(OgnCurveTubeSTDatabase& db)
{
const auto& curveStartIndices = db.inputs.curveVertexStarts();
const auto& tubeVertexCounts = db.inputs.curveVertexCounts();
const auto& tubeSTStartArray = db.inputs.tubeSTStarts();
const auto& tubeQuadStartArray = db.inputs.tubeQuadStarts();
const auto& columnsArray = db.inputs.cols();
const auto& widthArray = db.inputs.width();
const auto& tArray = db.inputs.t();
auto scaleTLikeS = db.inputs.scaleTLikeS(); // Might change, so get a copy
auto& stArray = db.outputs.primvars_st();
auto& stIndicesArray = db.outputs.primvars_st_indices();
size_t curveCount = curveStartIndices.size();
if (tubeVertexCounts.size() < curveCount)
curveCount = tubeVertexCounts.size();
size_t tubeCount = tubeSTStartArray.size();
if (tubeQuadStartArray.size() < tubeCount)
{
tubeCount = tubeQuadStartArray.size();
}
const size_t colValueCount = columnsArray.size();
const int32_t tubeSTsCount = (tubeCount == 0) ? 0 : tubeSTStartArray[tubeCount - 1];
const int32_t tubeQuadsCount = (tubeCount == 0) ? 0 : tubeQuadStartArray[tubeCount - 1];
if (tubeCount != 0)
--tubeCount;
const size_t tCount = tArray.size();
size_t widthCount = 0;
if (scaleTLikeS)
{
widthCount = widthArray.size();
if (widthCount == 0 || (widthCount != 1 && widthCount != tCount && widthCount != tubeCount))
{
scaleTLikeS = false;
}
}
if (tubeSTsCount <= 0 || tubeCount == 0 || (colValueCount != 1 && colValueCount != tubeCount) ||
(colValueCount == 1 && columnsArray[0] <= 0) || (tubeCount != curveCount))
{
stArray.resize(0);
stIndicesArray.resize(0);
return true;
}
if (tCount == 0)
{
stArray.resize(0);
stIndicesArray.resize(0);
return true;
}
std::vector<float> sValues;
size_t circleN = 0;
float perimeterScale = 0.0f;
if (colValueCount == 1)
{
circleN = columnsArray[0];
computeNewSs(sValues, circleN);
perimeterScale = float(circleN * sin(M_PI / circleN));
}
stArray.resize(tubeSTsCount);
stIndicesArray.resize(4 * tubeQuadsCount);
float width = (scaleTLikeS ? widthArray[0] : 0.0f);
for (size_t tube = 0; tube < tubeCount; ++tube)
{
if (tubeSTStartArray[tube] < 0 || curveStartIndices[tube] < 0 || tubeQuadStartArray[tube] < 0 ||
tubeVertexCounts[tube] < 0)
continue;
size_t tubeSTStartIndex = tubeSTStartArray[tube];
size_t tubeSTEndIndex = tubeSTStartArray[tube + 1];
size_t tubeQuadStartIndex = 4 * tubeQuadStartArray[tube];
size_t tubeQuadEndIndex = 4 * tubeQuadStartArray[tube + 1];
size_t curveStartIndex = curveStartIndices[tube];
size_t curveEndIndex = curveStartIndex + tubeVertexCounts[tube];
if (colValueCount != 1)
{
circleN = columnsArray[tube];
if (circleN <= 0)
continue;
computeNewSs(sValues, circleN);
perimeterScale = float(circleN * sin(M_PI / circleN));
}
if ((int32_t)tubeSTEndIndex > tubeSTsCount || tubeSTEndIndex < tubeSTStartIndex)
break;
if (tubeSTEndIndex == tubeSTStartIndex)
continue;
size_t curveTCount = curveEndIndex - curveStartIndex;
size_t tubeSTCount = tubeSTEndIndex - tubeSTStartIndex;
if (curveTCount * (circleN + 1) != tubeSTCount)
{
continue;
}
if (scaleTLikeS)
{
if (widthCount == tubeCount)
{
width = widthArray[tube];
}
else if (widthCount == tCount)
{
// Use the max width along the curve for the whole curve's
// t scaling, just for stability for now.
// Some situations need varying scale, but that's more complicated,
// and not what's needed for the current use cases.
width = widthArray[curveStartIndex];
for (size_t i = curveStartIndex + 1; i < curveEndIndex; ++i)
{
if (widthArray[i] > width)
{
width = widthArray[i];
}
}
}
}
// First, compute the st values.
size_t circleIndex = 0;
float tScale = 1.0f;
if (scaleTLikeS)
{
// Scale t by 1/(2nr*sin(2pi/2n)), where 2r*sin(2pi/2n) is the side length,
// and the full denominator is the perimeter of the tube's circle.
// This is, in a sense, scaling t by the same factor that s was "scaled"
// by, to make it go from 0 to 1, instead of 0 to the perimeter.
// This way, t will change proportionally to s moving along the surface in 3D space.
tScale = 1.0f / (width * perimeterScale);
}
float tValue = tScale * tArray[curveStartIndex];
for (size_t sti = tubeSTStartIndex; sti < tubeSTEndIndex; ++sti)
{
vec2f st( sValues[circleIndex], tValue );
stArray[sti] = st;
++circleIndex;
if (circleIndex >= circleN + 1)
{
circleIndex = 0;
++curveStartIndex;
if (curveStartIndex < curveEndIndex)
{
tValue = tScale * tArray[curveStartIndex];
}
}
}
// Second, compute indices into the st values.
circleIndex = 0;
for (size_t indexi = tubeQuadStartIndex, sti = tubeSTStartIndex; indexi < tubeQuadEndIndex; indexi += 4, ++sti)
{
stIndicesArray[indexi] = int32_t(sti);
stIndicesArray[indexi + 1] = int32_t(sti + 1);
stIndicesArray[indexi + 2] = int32_t(sti + circleN + 1 + 1);
stIndicesArray[indexi + 3] = int32_t(sti + circleN + 1);
++circleIndex;
if (circleIndex >= circleN)
{
circleIndex = 0;
++sti;
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 8,158 | C++ | 32.995833 | 123 | 0.537509 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveTubePositions.cpp | // 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.
//
#include <OgnCurveTubePositionsDatabase.h>
#include <carb/Framework.h>
#include <carb/Types.h>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
using carb::Float2;
using carb::Float3;
namespace omni
{
namespace graph
{
namespace nodes
{
static void computeNewCircle(std::vector<Float2>& circle, size_t edgeCount)
{
if (circle.size() == edgeCount)
return;
circle.resize(edgeCount);
circle[0] = Float2{ 1.0f, 0.0f };
for (size_t i = 1; i < edgeCount; ++i)
{
double theta = ((2 * M_PI) / double(edgeCount)) * double(i);
float c = float(cos(theta));
float s = float(sin(theta));
circle[i] = Float2{ c, s };
}
}
class OgnCurveTubePositions
{
public:
static bool compute(OgnCurveTubePositionsDatabase& db)
{
const auto& curveStartIndices = db.inputs.curveVertexStarts();
const auto& tubeVertexCounts = db.inputs.curveVertexCounts();
const auto& curvePointsArray = db.inputs.curvePoints();
const auto& tubeStartIndices = db.inputs.tubePointStarts();
const auto& columnsArray = db.inputs.cols();
const auto& widthArray = db.inputs.width();
const auto& upArray = db.inputs.up();
const auto& outArray = db.inputs.out();
auto& pointsArray = db.outputs.points();
size_t curveCount = curveStartIndices.size();
if (tubeVertexCounts.size() < curveCount)
curveCount = tubeVertexCounts.size();
size_t tubeCount = tubeStartIndices.size();
const size_t colValueCount = columnsArray.size();
const int32_t tubePointsCount = (tubeCount == 0) ? 0 : tubeStartIndices[tubeCount - 1];
if (tubeCount != 0)
--tubeCount;
const size_t curvePointCount = curvePointsArray.size();
const size_t upCount = upArray.size();
const size_t outCount = outArray.size();
const size_t widthCount = widthArray.size();
size_t curvePointsCount = curvePointCount;
if (upCount != 1 && upCount < curvePointsCount)
curvePointsCount = upCount;
if (outCount != 1 && outCount < curvePointsCount)
curvePointsCount = outCount;
if (widthCount != 1 && widthCount < curvePointsCount)
curvePointsCount = widthCount;
if (tubePointsCount <= 0 || tubeCount == 0 || (colValueCount != 1 && colValueCount != tubeCount) ||
(colValueCount == 1 && columnsArray[0] <= 0) || (tubeCount != curveCount))
{
pointsArray.resize(0);
return true;
}
if (curvePointsCount == 0)
{
pointsArray.resize(0);
return true;
}
std::vector<Float2> circle;
size_t circleN = 0;
if (colValueCount == 1)
{
circleN = columnsArray[0];
computeNewCircle(circle, circleN);
}
pointsArray.resize(tubePointsCount);
for (size_t tube = 0; tube < tubeCount; ++tube)
{
if (tubeStartIndices[tube] < 0 || curveStartIndices[tube] < 0 || tubeVertexCounts[tube] < 0)
continue;
size_t tubeStartIndex = tubeStartIndices[tube];
size_t tubeEndIndex = tubeStartIndices[tube + 1];
size_t curveStartIndex = curveStartIndices[tube];
size_t curveEndIndex = curveStartIndex + tubeVertexCounts[tube];
if (colValueCount != 1)
{
circleN = columnsArray[tube];
if (circleN <= 0)
continue;
computeNewCircle(circle, circleN);
}
if ((int32_t)tubeEndIndex > tubePointsCount || tubeEndIndex < tubeStartIndex)
break;
if (tubeEndIndex == tubeStartIndex)
continue;
size_t curvePointCount = curveEndIndex - curveStartIndex;
size_t tubePointCount = tubeEndIndex - tubeStartIndex;
if (curvePointCount * circleN != tubePointCount)
{
continue;
}
size_t circleIndex = 0;
// Do bounds check on up and out arrays.
auto center = curvePointsArray[curveStartIndex];
auto up = upArray[(upCount == 1) ? 0 : curveStartIndex];
auto out = outArray[(outCount == 1) ? 0 : curveStartIndex];
float width = 0.5f * widthArray[(widthCount == 1) ? 0 : curveStartIndex];
for (size_t point = tubeStartIndex; point < tubeEndIndex; ++point)
{
float x = width * circle[circleIndex].x;
float y = width * circle[circleIndex].y;
auto newPoint = (center + (x * out + y * up));
pointsArray[point] = newPoint;
++circleIndex;
if (circleIndex >= circleN)
{
circleIndex = 0;
++curveStartIndex;
if (curveStartIndex < curveEndIndex)
{
center = curvePointsArray[curveStartIndex];
up = upArray[(upCount == 1) ? 0 : curveStartIndex];
out = outArray[(outCount == 1) ? 0 : curveStartIndex];
width = 0.5f * widthArray[(widthCount == 1) ? 0 : curveStartIndex];
}
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 5,884 | C++ | 33.415204 | 107 | 0.57155 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleAllocator.cpp | // 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.
//
#include "OgnRpResourceExampleAllocatorDatabase.h"
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/graph/core/BundlePrims.h>
#include <omni/math/linalg/vec.h>
using omni::math::linalg::vec3f;
using omni::graph::core::BundleAttributeInfo;
using omni::graph::core::BundlePrim;
using omni::graph::core::BundlePrims;
using omni::graph::core::ConstBundlePrim;
using omni::graph::core::ConstBundlePrims;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
class OgnRpResourceExampleAllocator
{
// NOTE: this node is meant only as an early example of gpu interop on a prerender graph.
// Storing a pointer to an RpResource is a temporary measure that will not work in a
// multi-node setting.
bool previousSuccess;
bool previousReload;
std::vector<rtx::resourcemanager::RpResource*> resourcePointerCollection;
std::vector<uint64_t> pointCountCollection;
std::vector<NameToken> primPathCollection;
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleAllocator::initialize" << std::endl;
}
static void release(const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleAllocator::release" << std::endl;
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
rtx::resourcemanager::ResourceManager* resourceManager = gpuFoundation->getResourceManager();
rtx::resourcemanager::Context* resourceManagerContext = gpuFoundation->getResourceManagerContext();
auto& internalState = OgnRpResourceExampleAllocatorDatabase::sInternalState<OgnRpResourceExampleAllocator>(nodeObj);
auto& resourcePointerCollection = internalState.resourcePointerCollection;
const size_t resourceCount = resourcePointerCollection.size();
for (size_t i = 0; i < resourceCount; i++)
{
resourceManager->releaseResource(*resourcePointerCollection[i]);
}
}
}
}
static bool compute(OgnRpResourceExampleAllocatorDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleAllocator::compute");
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
auto& internalState = db.internalState<OgnRpResourceExampleAllocator>();
const bool previousSuccess = internalState.previousSuccess;
const bool previousReload = internalState.previousReload;
internalState.previousSuccess = false;
internalState.previousReload= false;
const bool verbose = db.inputs.verbose();
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
cudaStream_t stream = (cudaStream_t)db.inputs.stream();
if (verbose)
{
std::cout<<"OgnRpResourceExampleAllocator::compute -- cudaStream: "<<stream<<std::endl;
}
if (!stream)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
auto& resourcePointerCollection = internalState.resourcePointerCollection;
auto& pointCountCollection = internalState.pointCountCollection;
auto& primPathCollection = internalState.primPathCollection;
const bool reloadAttr = db.inputs.reload();
if ((reloadAttr && !previousReload) || !previousSuccess)
{
internalState.previousReload = true;
if (resourcePointerCollection.size() != 0)
{
if (verbose)
{
std::cout << "freeing RpResource." << std::endl;
}
const size_t resourceCount = resourcePointerCollection.size();
for (size_t i = 0; i < resourceCount; i++)
{
resourceManager->releaseResource(*resourcePointerCollection[i]);
}
resourcePointerCollection.resize(0);
pointCountCollection.resize(0);
primPathCollection.resize(0);
}
}
if (resourcePointerCollection.size() == 0)
{
const auto& pointsAttr = db.inputs.points();
const size_t pointsCount = pointsAttr.size();
const vec3f* points = pointsAttr.data();
const NameToken primPath = db.inputs.primPath();
if (pointsCount == 0)
return false;
if (points == nullptr)
return false;
//const uint64_t dimension = 4;
const uint64_t dimension = 3;
const uint64_t size = pointsCount * dimension * sizeof(float);
const uint32_t deviceIndex = 0;
carb::graphics::BufferUsageFlags usageFlags = carb::graphics::kBufferUsageFlagNone;
usageFlags |= carb::graphics::kBufferUsageFlagShaderResourceStorage;
usageFlags |= carb::graphics::kBufferUsageFlagVertexBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRawOrStructuredBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRaytracingBuffer;
carb::graphics::BufferDesc bufferDesc = rtx::RtxBufferDesc(size, "Mesh Buffer", usageFlags);
rtx::resourcemanager::ResourceDesc resourceDesc;
resourceDesc.mode = rtx::resourcemanager::ResourceMode::eDefault;
resourceDesc.memoryLocation = carb::graphics::MemoryLocation::eDevice;
resourceDesc.category = rtx::resourcemanager::ResourceCategory::eVertexBuffer;
resourceDesc.usageFlags = rtx::resourcemanager::kResourceUsageFlagCudaShared;
resourceDesc.deviceMask = OMNI_ALL_DEVICES_MASK;
resourceDesc.creationDeviceIndex = deviceIndex;
for (size_t i = 0; i < 2; i++)
{
rtx::resourcemanager::RpResource* rpResource = resourceManager->getResourceFromBufferDesc(*resourceManagerContext, bufferDesc, resourceDesc);
float* cpuPtr = new float[pointsCount * dimension];
for (size_t j = 0; j < pointsCount; j++)
{
cpuPtr[dimension * j] = points[j][0];
cpuPtr[dimension * j + 1] = points[j][1];
cpuPtr[dimension * j + 2] = points[j][2];
if (dimension == 4)
cpuPtr[dimension * j + 3] = 1.f;
}
void* cudaPtr = resourceManager->getCudaDevicePointer(*rpResource, deviceIndex);
cudaError_t err = cudaMemcpy(cudaPtr, cpuPtr, pointsCount * dimension * sizeof(float), cudaMemcpyHostToDevice);
delete [] cpuPtr;
if (verbose)
{
std::cout << "prim: " << db.tokenToString(primPath) << std::endl;
std::cout << "cudaMemcpy to device error code: " << err << std::endl;
std::cout << "errorName: " << cudaGetErrorName(err) << std::endl;
std::cout << "errorDesc: " << cudaGetErrorString(err) << std::endl;
std::cout << std::endl;
}
resourcePointerCollection.push_back(rpResource);
}
pointCountCollection.push_back((uint64_t)pointsCount);
primPathCollection.push_back(primPath);
db.outputs.resourcePointerCollection.resize(resourcePointerCollection.size());
memcpy(db.outputs.resourcePointerCollection().data(),
resourcePointerCollection.data(),
resourcePointerCollection.size() * sizeof(uint64_t));
db.outputs.pointCountCollection.resize(pointCountCollection.size());
memcpy(db.outputs.pointCountCollection().data(),
pointCountCollection.data(),
pointCountCollection.size() * sizeof(uint64_t));
db.outputs.primPathCollection.resize(primPathCollection.size());
memcpy(db.outputs.primPathCollection().data(),
primPathCollection.data(),
primPathCollection.size() * sizeof(NameToken));
}
if (resourcePointerCollection.size() == 0)
{
return false;
}
db.outputs.stream() = (uint64_t)stream;
internalState.previousSuccess = true;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 10,107 | C++ | 38.027027 | 157 | 0.624617 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleHydra.cpp | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <omni/hydra/IOmniHydra.h>
#include <omni/usd/UsdContextIncludes.h>
#include <omni/usd/UsdContext.h>
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <omni/graph/core/iComputeGraph.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/math/linalg/vec.h>
#include "OgnRpResourceExampleHydraDatabase.h"
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
class OgnRpResourceExampleHydra
{
public:
static bool compute(OgnRpResourceExampleHydraDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleHydra::compute");
const bool sendToHydra = db.inputs.sendToHydra();
const bool verbose = db.inputs.verbose();
//const size_t dimension = 4;
const size_t dimension = 3;
const uint32_t deviceIndex = 0;
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
if (verbose)
{
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
return false;
}
}
auto& resourcePointerCollection = db.inputs.resourcePointerCollection();
auto& pointCountCollection = db.inputs.pointCountCollection();
auto& primPathCollection = db.inputs.primPathCollection();
const size_t primCount = primPathCollection.size();
if (primCount == 0 ||
pointCountCollection.size() != primPathCollection.size() ||
2 * pointCountCollection.size() != resourcePointerCollection.size())
{
return false;
}
rtx::resourcemanager::RpResource** rpResources = (rtx::resourcemanager::RpResource**)resourcePointerCollection.data();
const uint64_t* pointCounts = pointCountCollection.data();
const NameToken* primPaths = primPathCollection.data();
omni::usd::hydra::IOmniHydra* omniHydra = sendToHydra ?
carb::getFramework()->acquireInterface<omni::usd::hydra::IOmniHydra>() :
nullptr;
for (size_t primIndex = 0; primIndex < primCount; primIndex++)
{
rtx::resourcemanager::RpResource* rpResource = rpResources[2 * primIndex + 1]; //only want deformed positions
const uint64_t& pointsCount = pointCounts[primIndex];
const NameToken& primPath = primPaths[primIndex];
if (verbose)
{
carb::graphics::AccessFlags accessFlags = resourceManager->getResourceAccessFlags(*rpResource, deviceIndex);
std::cout << "Sending to Hydra..." << std::endl;
std::cout << "prim path: " << db.tokenToString(primPath) << std::endl;
std::cout << "\trpResource: " << rpResource << std::endl;
std::cout << "\taccessFlags: " << accessFlags << std::endl;
if (accessFlags & carb::graphics::kAccessFlagUnknown)
std::cout << "\t\tkAccessFlagUnknown" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagVertexBuffer)
std::cout << "\t\tkAccessFlagVertexBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagIndexBuffer)
std::cout << "\t\tkAccessFlagIndexBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagConstantBuffer)
std::cout << "\t\tkAccessFlagConstantBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagArgumentBuffer)
std::cout << "\t\tkAccessFlagArgumentBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagTextureRead)
std::cout << "\t\tkAccessFlagTextureRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagStorageRead)
std::cout << "\t\tkAccessFlagStorageRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagStorageWrite)
std::cout << "\t\tkAccessFlagStorageWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagColorAttachmentWrite)
std::cout << "\t\tkAccessFlagColorAttachmentWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagDepthStencilAttachmentWrite)
std::cout << "\t\tkAccessFlagDepthStencilAttachmentWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagDepthStencilAttachmentRead)
std::cout << "\t\tkAccessFlagDepthStencilAttachmentRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagCopySource)
std::cout << "\t\tkAccessFlagCopySource" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagCopyDestination)
std::cout << "\t\tkAccessFlagCopyDestination" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagAccelStructRead)
std::cout << "\t\tkAccessFlagAccelStructRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagAccelStructWrite)
std::cout << "\t\tkAccessFlagAccelStructWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagResolveSource)
std::cout << "\t\tkAccessFlagResolveSource" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagResolveDestination)
std::cout << "\t\tkAccessFlagResolveDestination" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagStorageClear)
std::cout << "\t\tkAccessFlagStorageClear" << std::endl;
const carb::graphics::BufferDesc* bufferDesc = resourceManager->getBufferDesc(rpResource);
std::cout << "\tbufferDesc: " << bufferDesc << std::endl;
if (bufferDesc != nullptr)
{
std::cout << "\tbuffer usage flags: " << bufferDesc->usageFlags << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagNone)
std::cout << "\t\tkBufferUsageFlagNone" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagShaderResource)
std::cout << "\t\tkBufferUsageFlagShaderResource" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagShaderResourceStorage)
std::cout << "\t\tkBufferUsageFlagShaderResourceStorage" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagVertexBuffer)
std::cout << "\t\tkBufferUsageFlagVertexBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagIndexBuffer)
std::cout << "\t\tkBufferUsageFlagIndexBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagConstantBuffer)
std::cout << "\t\tkBufferUsageFlagConstantBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRawOrStructuredBuffer)
std::cout << "\t\tkBufferUsageFlagRawOrStructuredBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagArgumentBuffer)
std::cout << "\t\tkBufferUsageFlagArgumentBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingAccelStruct)
std::cout << "\t\tkBufferUsageFlagRaytracingAccelStruct" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingBuffer)
std::cout << "\t\tkBufferUsageFlagRaytracingBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingScratchBuffer)
std::cout << "\t\tkBufferUsageFlagRaytracingScratchBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagExportShared)
std::cout << "\t\tkBufferUsageFlagExportShared" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagImportShared)
std::cout << "\t\tkBufferUsageFlagImportShared" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagSharedCrossAdapter)
std::cout << "\t\tkBufferUsageFlagSharedCrossAdapter" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagHostMappedForeignMemory)
std::cout << "\t\tkBufferUsageFlagHostMappedForeignMemory" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagConcurrentAccess)
std::cout << "\t\tkBufferUsageFlagConcurrentAccess" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagVisibleCrossAdapter)
std::cout << "\t\tkBufferUsageFlagVisibleCrossAdapter" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingShaderBindingTable)
std::cout << "\t\tkBufferUsageFlagRaytracingShaderBindingTable" << std::endl;
std::cout << "\tbuffer size: " << bufferDesc->size << std::endl;
std::cout << "\tbuffer debug name: " << bufferDesc->debugName << std::endl;
std::cout << "\tbuffer ext: " << bufferDesc->ext << std::endl;
}
}
if (sendToHydra)
{
omni::usd::hydra::BufferDesc desc;
desc.data = (void*)rpResource;
desc.elementSize = dimension * sizeof(float);
desc.elementStride = dimension * sizeof(float);
desc.count = pointsCount;
desc.isGPUBuffer = true;
desc.isDataRpResource = true;
pxr::SdfPath path = pxr::SdfPath(db.tokenToString(primPath));
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleHydra, sending to hydra");
omniHydra->SetPointsBuffer(pxr::SdfPath(db.tokenToString(primPath)), desc);
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 11,707 | C++ | 50.80531 | 126 | 0.606987 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleDeformer.cpp | // 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.
//
#include "OgnRpResourceExampleDeformerDatabase.h"
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/math/linalg/vec.h>
#include <stdlib.h>
#include <iostream>
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
extern "C" void modifyPositions(float3* points, size_t numPoints, unsigned sequenceCounter, int displacementAxis, bool verbose, cudaStream_t stream);
extern "C" void modifyPositionsSinusoidal(const float3* pointsRest, float3* pointsDeformed, size_t numPoints, unsigned sequenceCounter, float positionScale, float timeScale, float deformScale, bool verbose, cudaStream_t stream);
class OgnRpResourceExampleDeformer
{
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleDeformer::initialize" << std::endl;
}
static void release(const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleDeformer::release" << std::endl;
}
static bool compute(OgnRpResourceExampleDeformerDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleDeformer::compute");
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
const bool verbose = db.inputs.verbose();
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
cudaStream_t stream = (cudaStream_t)db.inputs.stream();
if (verbose)
{
std::cout<<"OgnRpResourceExampleDeformer::compute -- cudaStream: "<<stream<<std::endl;
}
if (!stream)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
auto& resourcePointerCollection = db.inputs.resourcePointerCollection();
auto& pointCountCollection = db.inputs.pointCountCollection();
auto& primPathCollection = db.inputs.primPathCollection();
const size_t primCount = primPathCollection.size();
if (primCount == 0 ||
pointCountCollection.size() != primPathCollection.size() ||
2 * pointCountCollection.size() != resourcePointerCollection.size())
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
bool& reloadAttr = db.outputs.reload();
auto& sequenceCounter = db.state.sequenceCounter();
if (reloadAttr)
{
reloadAttr = false;
sequenceCounter = 0;
}
//const uint64_t dimension = 4;
const uint64_t dimension = 3;
const uint32_t deviceIndex = 0;
rtx::resourcemanager::RpResource** rpResources = (rtx::resourcemanager::RpResource**)resourcePointerCollection.data();
const uint64_t* pointCounts = pointCountCollection.data();
const NameToken* primPaths = primPathCollection.data();
for (size_t primIndex = 0; primIndex < primCount; primIndex++)
{
rtx::resourcemanager::RpResource* rpResourceRest = rpResources[2 * primIndex];
rtx::resourcemanager::RpResource* rpResourceDeformed = rpResources[2 * primIndex + 1];
const uint64_t& pointsCount = pointCounts[primIndex];
//const NameToken& path = primPaths[primIndex];
// run some simple kernel
if (verbose)
{
std::cout
<< "OgnRpResourceExampleDeformer: Modifying " << pointsCount
<< " positions at sequence point " << sequenceCounter
<< std::endl;
}
if (db.inputs.runDeformerKernel())
{
void* cudaPtrRest = resourceManager->getCudaDevicePointer(*rpResourceRest, deviceIndex);
void* cudaPtrDeformed = resourceManager->getCudaDevicePointer(*rpResourceDeformed, deviceIndex);
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleDeformer::modifyPositions kernel");
modifyPositionsSinusoidal((float3*)cudaPtrRest, (float3*)cudaPtrDeformed, pointsCount, (unsigned)sequenceCounter, db.inputs.positionScale(), db.inputs.timeScale(), db.inputs.deformScale(), verbose, stream);
}
}
}
if (db.inputs.runDeformerKernel())
{
sequenceCounter++;
}
db.outputs.resourcePointerCollection.resize(resourcePointerCollection.size());
memcpy(db.outputs.resourcePointerCollection().data(),
resourcePointerCollection.data(),
resourcePointerCollection.size() * sizeof(uint64_t));
db.outputs.pointCountCollection.resize(pointCountCollection.size());
memcpy(db.outputs.pointCountCollection().data(),
pointCountCollection.data(),
pointCountCollection.size() * sizeof(uint64_t));
db.outputs.primPathCollection.resize(primPathCollection.size());
memcpy(db.outputs.primPathCollection().data(),
primPathCollection.data(),
primPathCollection.size() * sizeof(NameToken));
db.outputs.stream() = (uint64_t)stream;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 6,875 | C++ | 35.189473 | 228 | 0.651055 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnDeformedPointsToHydra.cpp | // 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.
//
#include "OgnDeformedPointsToHydraDatabase.h"
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/hydra/IOmniHydra.h>
#include <omni/graph/core/BundlePrims.h>
#include <omni/math/linalg/vec.h>
using omni::math::linalg::vec3f;
using omni::graph::core::BundleAttributeInfo;
using omni::graph::core::BundlePrim;
using omni::graph::core::BundlePrims;
using omni::graph::core::ConstBundlePrim;
using omni::graph::core::ConstBundlePrims;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
class OgnDeformedPointsToHydra
{
// NOTE: this node is meant only for early usage of gpu interop on a prerender graph.
// Storing a pointer to an RpResource is a temporary measure that will not work in a
// multi-node setting.
bool previousSuccess;
rtx::resourcemanager::RpResource* resourcePointer;
uint64_t pointCount;
NameToken primPath;
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
OgnDeformedPointsToHydraDatabase db(context, nodeObj);
auto& internalState = db.internalState<OgnDeformedPointsToHydra>();
internalState.resourcePointer = nullptr;
internalState.pointCount = 0;
internalState.primPath = db.stringToToken("");
internalState.previousSuccess = false;
}
static void release(const NodeObj& nodeObj)
{
}
static bool compute(OgnDeformedPointsToHydraDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnDeformedPointsToHydra::compute");
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
auto& internalState = db.internalState<OgnDeformedPointsToHydra>();
const bool previousSuccess = internalState.previousSuccess;
internalState.previousSuccess = false;
const bool verbose = db.inputs.verbose();
if (db.inputs.primPath() == db.stringToToken("") || db.inputs.points.size() == 0)
{
return false;
}
bool reload = false;
if (internalState.resourcePointer == nullptr ||
internalState.primPath != db.inputs.primPath() ||
internalState.pointCount != db.inputs.points.size() ||
!internalState.previousSuccess)
{
reload = true;
}
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
cudaStream_t stream = (cudaStream_t)db.inputs.stream();
if (verbose)
{
std::cout<<"OgnDeformedPointsToHydra::compute -- cudaStream: "<<stream<<std::endl;
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
return false;
}
const uint32_t deviceIndex = 0;
const size_t pointsCount = db.inputs.points.size();
const uint64_t dimension = 3;
const uint64_t size = pointsCount * dimension * sizeof(float);
if (reload)
{
if (internalState.resourcePointer != nullptr)
{
if (verbose)
{
std::cout << "freeing RpResource." << std::endl;
}
resourceManager->releaseResource(*internalState.resourcePointer);
internalState.resourcePointer = nullptr;
}
carb::graphics::BufferUsageFlags usageFlags = carb::graphics::kBufferUsageFlagNone;
usageFlags |= carb::graphics::kBufferUsageFlagShaderResourceStorage;
usageFlags |= carb::graphics::kBufferUsageFlagVertexBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRawOrStructuredBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRaytracingBuffer;
carb::graphics::BufferDesc bufferDesc = rtx::RtxBufferDesc(size, "Mesh Buffer", usageFlags);
rtx::resourcemanager::ResourceDesc resourceDesc;
resourceDesc.mode = rtx::resourcemanager::ResourceMode::eDefault;
resourceDesc.memoryLocation = carb::graphics::MemoryLocation::eDevice;
resourceDesc.category = rtx::resourcemanager::ResourceCategory::eVertexBuffer;
resourceDesc.usageFlags = rtx::resourcemanager::kResourceUsageFlagCudaShared;
resourceDesc.deviceMask = OMNI_ALL_DEVICES_MASK;
resourceDesc.creationDeviceIndex = deviceIndex;
internalState.resourcePointer = resourceManager->getResourceFromBufferDesc(*resourceManagerContext, bufferDesc, resourceDesc);
internalState.pointCount = pointsCount;
internalState.primPath = db.inputs.primPath();
}
const float3* cudaSrc = (const float3*)(*db.inputs.points.gpu());
void* cudaDst = resourceManager->getCudaDevicePointer(*internalState.resourcePointer, deviceIndex);
cudaMemcpy(cudaDst, (const void*)cudaSrc, size, cudaMemcpyDeviceToDevice);
if (db.inputs.sendToHydra())
{
omni::usd::hydra::IOmniHydra* omniHydra = carb::getFramework()->acquireInterface<omni::usd::hydra::IOmniHydra>();
omni::usd::hydra::BufferDesc desc;
desc.data = (void*)internalState.resourcePointer;
desc.elementSize = dimension * sizeof(float);
desc.elementStride = dimension * sizeof(float);
desc.count = pointsCount;
desc.isGPUBuffer = true;
desc.isDataRpResource = true;
pxr::SdfPath path = pxr::SdfPath(db.tokenToString(internalState.primPath));
CARB_PROFILE_ZONE(1, "OgnRpResourceToHydra_Arrays, sending to hydra");
omniHydra->SetPointsBuffer(pxr::SdfPath(db.tokenToString(internalState.primPath)), desc);
}
internalState.previousSuccess = true;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 6,928 | C++ | 34.172589 | 138 | 0.667292 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineStart.cpp | // 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.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineStartDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineStart
{
public:
static bool compute(OgnTimelineStartDatabase& db)
{
auto handler = [](timeline::TimelinePtr const& timeline)
{
timeline->play();
return true;
};
return timelineNodeExecute(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 915 | C++ | 21.341463 | 77 | 0.714754 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineGet.cpp | // 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.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineGetDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineGet
{
public:
static bool compute(OgnTimelineGetDatabase& db)
{
auto handler = [&db](timeline::TimelinePtr const& timeline)
{
db.outputs.isLooping() = timeline->isLooping();
db.outputs.isPlaying() = timeline->isPlaying();
double const currentTime = timeline->getCurrentTime();
double const startTime = timeline->getStartTime();
double const endTime = timeline->getEndTime();
db.outputs.time() = currentTime;
db.outputs.startTime() = startTime;
db.outputs.endTime() = endTime;
db.outputs.frame() = timeline->timeToTimeCode(currentTime);
db.outputs.startFrame() = timeline->timeToTimeCode(startTime);
db.outputs.endFrame() = timeline->timeToTimeCode(endTime);
db.outputs.framesPerSecond() = timeline->getTimeCodesPerSecond();
// TODO: Should we return false when the outputs didn't change?
return true;
};
return timelineNodeEvaluate(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,706 | C++ | 28.431034 | 77 | 0.672333 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimer.cpp | // 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.
//
#include "PrimCommon.h"
#include <OgnTimerDatabase.h>
using namespace pxr;
using DB = OgnTimerDatabase;
namespace omni::graph::nodes
{
namespace
{
constexpr double kUninitializedStartTime = -1.;
}
enum TimeState : uint32_t
{
kTimeStateInit,
kTimeStateStart,
kTimeStatePlay,
kTimeStateLast,
kTimeStateFinish
};
class OgnTimer
{
double m_startTime{ kUninitializedStartTime }; // The value of the context time when we started latent state
TimeState m_timeState{ kTimeStateInit };
public:
static bool compute(DB& db)
{
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
double now = iContext->getTimeSinceStart(contextObj);
auto& state = db.internalState<OgnTimer>();
auto& timeState = state.m_timeState;
auto& startTime = state.m_startTime;
const double duration = std::max(db.inputs.duration(), 1.0e-6);
const double startValue = db.inputs.startValue();
const double endValue = db.inputs.endValue();
switch (timeState)
{
case kTimeStateInit:
{
timeState = kTimeStateStart;
db.outputs.finished() = kExecutionAttributeStateLatentPush;
break;
}
case kTimeStateStart:
{
startTime = now;
timeState = kTimeStatePlay;
// Do not break here, we want to fall through to the next case
}
case kTimeStatePlay:
{
double deltaTime = now - startTime;
double value = startValue + (endValue - startValue) * deltaTime / duration;
value = std::min(value, 1.0);
db.outputs.value() = value;
if (deltaTime >= duration)
{
timeState = kTimeStateLast;
}
else
{
db.outputs.updated() = kExecutionAttributeStateEnabled;
}
break;
}
case kTimeStateLast:
{
timeState = kTimeStateFinish;
db.outputs.value() = endValue;
db.outputs.updated() = kExecutionAttributeStateEnabled;
break;
}
case kTimeStateFinish:
{
startTime = kUninitializedStartTime;
timeState = kTimeStateInit;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
break;
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
| 2,923 | C++ | 26.847619 | 112 | 0.6117 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnInterpolator.cpp | // 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.
//
#include <OgnInterpolatorDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
inline float computeInterpolation(size_t numSamples, const float* knots, const float* values, const float& param)
{
// do really simple search for now
for (size_t i = 0; i < numSamples - 1; i++)
{
float knot = knots[i];
float knotNext = knots[i + 1];
float value = values[i];
float valueNext = values[i + 1];
if (param < knot)
return value;
if (param <= knotNext)
{
float interpolant = (param - knot) / (knotNext - knot);
float interpolatedValue = interpolant * valueNext + (1.0f - interpolant) * value;
return interpolatedValue;
}
}
return values[numSamples - 1];
}
class OgnInterpolator
{
public:
static bool compute(OgnInterpolatorDatabase& db)
{
const auto& inputKnots = db.inputs.knots();
const auto& inputValues = db.inputs.values();
size_t numSamples = inputValues.size();
if (inputKnots.size() != numSamples)
{
db.logWarning("Knots size %zu does not match value size %zu, skipping evaluation", inputKnots.size(), numSamples);
return false;
}
if (numSamples > 0)
{
db.outputs.value() = computeInterpolation(numSamples, inputKnots.data(), inputValues.data(), db.inputs.param());
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,933 | C++ | 25.861111 | 126 | 0.636834 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineStop.cpp | // 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.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineStopDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineStop
{
public:
static bool compute(OgnTimelineStopDatabase& db)
{
auto handler = [](timeline::TimelinePtr const& timeline)
{
// Pause stops at the current frame, stop resets time
timeline->pause();
return true;
};
return timelineNodeExecute(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 979 | C++ | 22.333333 | 77 | 0.707865 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineSet.cpp | // 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.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineSetDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineSet
{
public:
static bool compute(OgnTimelineSetDatabase& db)
{
auto handler = [&db](timeline::TimelinePtr const& timeline)
{
auto const value = db.inputs.propValue();
bool clamped = false;
auto setTime = [&timeline](double desiredTime) -> bool
{
auto const startTime = timeline->getStartTime();
auto const endTime = timeline->getEndTime();
auto const clampedTime = std::clamp(desiredTime, startTime, endTime);
timeline->setCurrentTime(clampedTime);
return clampedTime != desiredTime; // NOLINT(clang-diagnostic-float-equal)
};
auto const propName = db.inputs.propName();
if (propName == OgnTimelineSetDatabase::tokens.Time)
clamped = setTime(value);
else if (propName == OgnTimelineSetDatabase::tokens.StartTime)
timeline->setStartTime(value);
else if (propName == OgnTimelineSetDatabase::tokens.EndTime)
timeline->setEndTime(value);
else if (propName == OgnTimelineSetDatabase::tokens.FramesPerSecond)
timeline->setTimeCodesPerSecond(value);
else
{
// The property to set is frame-based, convert to time in seconds.
auto const time = timeline->timeCodeToTime(value);
if (propName == OgnTimelineSetDatabase::tokens.Frame)
clamped = setTime(time);
else if (propName == OgnTimelineSetDatabase::tokens.StartFrame)
timeline->setStartTime(time);
else if (propName == OgnTimelineSetDatabase::tokens.EndFrame)
timeline->setEndTime(time);
}
db.outputs.clamped() = clamped;
return true;
};
return timelineNodeExecute(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,579 | C++ | 32.947368 | 90 | 0.621559 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineLoop.cpp | // 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.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineLoopDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineLoop
{
public:
static bool compute(OgnTimelineLoopDatabase& db)
{
auto handler = [&db](timeline::TimelinePtr const& timeline)
{
auto const loop = db.inputs.loop();
timeline->setLooping(loop);
return true;
};
return timelineNodeExecute(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 973 | C++ | 22.190476 | 77 | 0.707091 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnNthRoot.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:value', {'type': 'float', 'value': 36.0}, False],
],
'outputs': [
['outputs:result', {'type': 'float', 'value': 6.0}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'double', 'value': 27.0}, False],
['inputs:nthRoot', 3, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 3.0}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'float[2]', 'value': [0.25, 4.0]}, False],
],
'outputs': [
['outputs:result', {'type': 'float[2]', 'value': [0.5, 2.0]}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'float[]', 'value': [1.331, 8.0]}, False],
['inputs:nthRoot', 3, False],
],
'outputs': [
['outputs:result', {'type': 'float[]', 'value': [1.1, 2.0]}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'float[2][]', 'value': [[4.0, 16.0], [2.25, 64.0]]}, False],
],
'outputs': [
['outputs:result', {'type': 'float[2][]', 'value': [[2.0, 4.0], [1.5, 8.0]]}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'int64', 'value': 9223372036854775807}, False],
['inputs:nthRoot', 1, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 9.223372036854776e+18}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'int', 'value': 256}, False],
['inputs:nthRoot', 4, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 4.0}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'uint64', 'value': 8}, False],
['inputs:nthRoot', 3, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 2.0}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'half[2]', 'value': [0.125, 1.0]}, False],
['inputs:nthRoot', 3, False],
],
'outputs': [
['outputs:result', {'type': 'half[2]', 'value': [0.5, 1.0]}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'uchar', 'value': 25}, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 5.0}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'int64', 'value': 16}, False],
['inputs:nthRoot', -2, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 0.25}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'double', 'value': 0.125}, False],
['inputs:nthRoot', -3, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 2}, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_NthRoot", "omni.graph.nodes.NthRoot", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.NthRoot User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_NthRoot","omni.graph.nodes.NthRoot", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.NthRoot User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_NthRoot", "omni.graph.nodes.NthRoot", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.NthRoot User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnNthRootDatabase import OgnNthRootDatabase
test_file_name = "OgnNthRootTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_NthRoot")
database = OgnNthRootDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:nthRoot"))
attribute = test_node.get_attribute("inputs:nthRoot")
db_value = database.inputs.nthRoot
expected_value = 2
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
| 7,684 | Python | 40.54054 | 187 | 0.520432 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnATan2.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:a', {'type': 'float', 'value': 5.0}, False],
['inputs:b', {'type': 'float', 'value': 3.0}, False],
],
'outputs': [
['outputs:result', {'type': 'float', 'value': 59.0362434679}, False],
],
},
{
'inputs': [
['inputs:a', {'type': 'double', 'value': 70.0}, False],
['inputs:b', {'type': 'double', 'value': 10.0}, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 81.8698976458}, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_ATan2", "omni.graph.nodes.ATan2", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.ATan2 User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_ATan2","omni.graph.nodes.ATan2", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.ATan2 User test case #{i+1}", 16)
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnATan2Database import OgnATan2Database
test_file_name = "OgnATan2Template.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_ATan2")
database = OgnATan2Database(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
| 3,279 | Python | 45.857142 | 164 | 0.609332 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnBooleanExpr.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:a', True, False],
['inputs:b', True, False],
['inputs:operator', "XOR", False],
],
'outputs': [
['outputs:result', False, False],
],
},
{
'inputs': [
['inputs:a', True, False],
['inputs:b', True, False],
['inputs:operator', "XNOR", False],
],
'outputs': [
['outputs:result', True, False],
],
},
{
'inputs': [
['inputs:a', True, False],
['inputs:b', False, False],
['inputs:operator', "OR", False],
],
'outputs': [
['outputs:result', True, False],
],
},
{
'inputs': [
['inputs:a', True, False],
['inputs:b', False, False],
['inputs:operator', "AND", False],
],
'outputs': [
['outputs:result', False, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanExpr", "omni.graph.nodes.BooleanExpr", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.BooleanExpr User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanExpr","omni.graph.nodes.BooleanExpr", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.BooleanExpr User test case #{i+1}", 16)
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnBooleanExprDatabase import OgnBooleanExprDatabase
test_file_name = "OgnBooleanExprTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_BooleanExpr")
database = OgnBooleanExprDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:a"))
attribute = test_node.get_attribute("inputs:a")
db_value = database.inputs.a
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:b"))
attribute = test_node.get_attribute("inputs:b")
db_value = database.inputs.b
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:operator"))
attribute = test_node.get_attribute("inputs:operator")
db_value = database.inputs.operator
expected_value = "AND"
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:result"))
attribute = test_node.get_attribute("outputs:result")
db_value = database.outputs.result
| 5,285 | Python | 43.05 | 176 | 0.600189 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnFindPrims.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:namePrefix', "Xform", False],
],
'outputs': [
['outputs:primPaths', ["/Xform1", "/Xform2", "/XformTagged1"], False],
],
'setup': {'create_nodes': [['TestNode', 'omni.graph.nodes.FindPrims']], 'create_prims': [['Empty', {}], ['Xform1', {'_translate': ['pointd[3][]', [[1, 2, 3]]]}], ['Xform2', {'_translate': ['pointd[3][]', [[4, 5, 6]]]}], ['XformTagged1', {'foo': ['token', ''], '_translate': ['pointd[3][]', [[1, 2, 3]]]}], ['Tagged1', {'foo': ['token', '']}]]} },
{
'inputs': [
['inputs:namePrefix', "", False],
['inputs:requiredAttributes', "foo _translate", False],
],
'outputs': [
['outputs:primPaths', ["/XformTagged1"], False],
],
'setup': {} },
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_FindPrims", "omni.graph.nodes.FindPrims", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.FindPrims User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_FindPrims","omni.graph.nodes.FindPrims", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.FindPrims User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_FindPrims", "omni.graph.nodes.FindPrims", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.FindPrims User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnFindPrimsDatabase import OgnFindPrimsDatabase
test_file_name = "OgnFindPrimsTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_FindPrims")
database = OgnFindPrimsDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 2)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:ignoreSystemPrims"))
attribute = test_node.get_attribute("inputs:ignoreSystemPrims")
db_value = database.inputs.ignoreSystemPrims
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:namePrefix"))
attribute = test_node.get_attribute("inputs:namePrefix")
db_value = database.inputs.namePrefix
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pathPattern"))
attribute = test_node.get_attribute("inputs:pathPattern")
db_value = database.inputs.pathPattern
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:recursive"))
attribute = test_node.get_attribute("inputs:recursive")
db_value = database.inputs.recursive
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:requiredAttributes"))
attribute = test_node.get_attribute("inputs:requiredAttributes")
db_value = database.inputs.requiredAttributes
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:requiredRelationship"))
attribute = test_node.get_attribute("inputs:requiredRelationship")
db_value = database.inputs.requiredRelationship
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:requiredRelationshipTarget"))
attribute = test_node.get_attribute("inputs:requiredRelationshipTarget")
db_value = database.inputs.requiredRelationshipTarget
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:requiredTarget"))
attribute = test_node.get_attribute("inputs:requiredTarget")
db_value = database.inputs.requiredTarget
self.assertTrue(test_node.get_attribute_exists("inputs:rootPrim"))
attribute = test_node.get_attribute("inputs:rootPrim")
db_value = database.inputs.rootPrim
self.assertTrue(test_node.get_attribute_exists("inputs:rootPrimPath"))
attribute = test_node.get_attribute("inputs:rootPrimPath")
db_value = database.inputs.rootPrimPath
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:type"))
attribute = test_node.get_attribute("inputs:type")
db_value = database.inputs.type
expected_value = "*"
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:primPaths"))
attribute = test_node.get_attribute("outputs:primPaths")
db_value = database.outputs.primPaths
self.assertTrue(test_node.get_attribute_exists("outputs:prims"))
attribute = test_node.get_attribute("outputs:prims")
db_value = database.outputs.prims
self.assertTrue(test_node.get_attribute_exists("state:ignoreSystemPrims"))
attribute = test_node.get_attribute("state:ignoreSystemPrims")
db_value = database.state.ignoreSystemPrims
self.assertTrue(test_node.get_attribute_exists("state:inputType"))
attribute = test_node.get_attribute("state:inputType")
db_value = database.state.inputType
self.assertTrue(test_node.get_attribute_exists("state:namePrefix"))
attribute = test_node.get_attribute("state:namePrefix")
db_value = database.state.namePrefix
self.assertTrue(test_node.get_attribute_exists("state:pathPattern"))
attribute = test_node.get_attribute("state:pathPattern")
db_value = database.state.pathPattern
self.assertTrue(test_node.get_attribute_exists("state:recursive"))
attribute = test_node.get_attribute("state:recursive")
db_value = database.state.recursive
self.assertTrue(test_node.get_attribute_exists("state:requiredAttributes"))
attribute = test_node.get_attribute("state:requiredAttributes")
db_value = database.state.requiredAttributes
self.assertTrue(test_node.get_attribute_exists("state:requiredRelationship"))
attribute = test_node.get_attribute("state:requiredRelationship")
db_value = database.state.requiredRelationship
self.assertTrue(test_node.get_attribute_exists("state:requiredRelationshipTarget"))
attribute = test_node.get_attribute("state:requiredRelationshipTarget")
db_value = database.state.requiredRelationshipTarget
self.assertTrue(test_node.get_attribute_exists("state:requiredTarget"))
attribute = test_node.get_attribute("state:requiredTarget")
db_value = database.state.requiredTarget
self.assertTrue(test_node.get_attribute_exists("state:rootPrim"))
attribute = test_node.get_attribute("state:rootPrim")
db_value = database.state.rootPrim
self.assertTrue(test_node.get_attribute_exists("state:rootPrimPath"))
attribute = test_node.get_attribute("state:rootPrimPath")
db_value = database.state.rootPrimPath
| 11,264 | Python | 49.743243 | 365 | 0.694158 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnCurveTubeST.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnCurveTubeSTDatabase import OgnCurveTubeSTDatabase
test_file_name = "OgnCurveTubeSTTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_CurveTubeST")
database = OgnCurveTubeSTDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:cols"))
attribute = test_node.get_attribute("inputs:cols")
db_value = database.inputs.cols
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexCounts"))
attribute = test_node.get_attribute("inputs:curveVertexCounts")
db_value = database.inputs.curveVertexCounts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexStarts"))
attribute = test_node.get_attribute("inputs:curveVertexStarts")
db_value = database.inputs.curveVertexStarts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:scaleTLikeS"))
attribute = test_node.get_attribute("inputs:scaleTLikeS")
db_value = database.inputs.scaleTLikeS
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:t"))
attribute = test_node.get_attribute("inputs:t")
db_value = database.inputs.t
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:tubeQuadStarts"))
attribute = test_node.get_attribute("inputs:tubeQuadStarts")
db_value = database.inputs.tubeQuadStarts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:tubeSTStarts"))
attribute = test_node.get_attribute("inputs:tubeSTStarts")
db_value = database.inputs.tubeSTStarts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:width"))
attribute = test_node.get_attribute("inputs:width")
db_value = database.inputs.width
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:primvars:st"))
attribute = test_node.get_attribute("outputs:primvars:st")
db_value = database.outputs.primvars_st
self.assertTrue(test_node.get_attribute_exists("outputs:primvars:st:indices"))
attribute = test_node.get_attribute("outputs:primvars:st:indices")
db_value = database.outputs.primvars_st_indices
| 5,437 | Python | 51.796116 | 92 | 0.691926 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnTimelineGet.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnTimelineGetDatabase import OgnTimelineGetDatabase
test_file_name = "OgnTimelineGetTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_GetTimeline")
database = OgnTimelineGetDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("outputs:endFrame"))
attribute = test_node.get_attribute("outputs:endFrame")
db_value = database.outputs.endFrame
self.assertTrue(test_node.get_attribute_exists("outputs:endTime"))
attribute = test_node.get_attribute("outputs:endTime")
db_value = database.outputs.endTime
self.assertTrue(test_node.get_attribute_exists("outputs:frame"))
attribute = test_node.get_attribute("outputs:frame")
db_value = database.outputs.frame
self.assertTrue(test_node.get_attribute_exists("outputs:framesPerSecond"))
attribute = test_node.get_attribute("outputs:framesPerSecond")
db_value = database.outputs.framesPerSecond
self.assertTrue(test_node.get_attribute_exists("outputs:isLooping"))
attribute = test_node.get_attribute("outputs:isLooping")
db_value = database.outputs.isLooping
self.assertTrue(test_node.get_attribute_exists("outputs:isPlaying"))
attribute = test_node.get_attribute("outputs:isPlaying")
db_value = database.outputs.isPlaying
self.assertTrue(test_node.get_attribute_exists("outputs:startFrame"))
attribute = test_node.get_attribute("outputs:startFrame")
db_value = database.outputs.startFrame
self.assertTrue(test_node.get_attribute_exists("outputs:startTime"))
attribute = test_node.get_attribute("outputs:startTime")
db_value = database.outputs.startTime
self.assertTrue(test_node.get_attribute_exists("outputs:time"))
attribute = test_node.get_attribute("outputs:time")
db_value = database.outputs.time
| 3,183 | Python | 46.522387 | 92 | 0.699969 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnCreateTubeTopology.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:rows', [1, 2, 3], False],
['inputs:cols', [2, 3, 4], False],
],
'outputs': [
['outputs:faceVertexCounts', [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], False],
['outputs:faceVertexIndices', [0, 1, 3, 2, 1, 0, 2, 3, 4, 5, 8, 7, 5, 6, 9, 8, 6, 4, 7, 9, 7, 8, 11, 10, 8, 9, 12, 11, 9, 7, 10, 12, 13, 14, 18, 17, 14, 15, 19, 18, 15, 16, 20, 19, 16, 13, 17, 20, 17, 18, 22, 21, 18, 19, 23, 22, 19, 20, 24, 23, 20, 17, 21, 24, 21, 22, 26, 25, 22, 23, 27, 26, 23, 24, 28, 27, 24, 21, 25, 28], False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_CreateTubeTopology", "omni.graph.nodes.CreateTubeTopology", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.CreateTubeTopology User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_CreateTubeTopology","omni.graph.nodes.CreateTubeTopology", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.CreateTubeTopology User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_CreateTubeTopology", "omni.graph.nodes.CreateTubeTopology", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.CreateTubeTopology User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnCreateTubeTopologyDatabase import OgnCreateTubeTopologyDatabase
test_file_name = "OgnCreateTubeTopologyTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_CreateTubeTopology")
database = OgnCreateTubeTopologyDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:cols"))
attribute = test_node.get_attribute("inputs:cols")
db_value = database.inputs.cols
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:rows"))
attribute = test_node.get_attribute("inputs:rows")
db_value = database.inputs.rows
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts"))
attribute = test_node.get_attribute("outputs:faceVertexCounts")
db_value = database.outputs.faceVertexCounts
self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices"))
attribute = test_node.get_attribute("outputs:faceVertexIndices")
db_value = database.outputs.faceVertexIndices
| 5,763 | Python | 52.869158 | 349 | 0.661635 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnRandomNumeric.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 6649909271, False],
['inputs:min', {'type': 'uint', 'value': 0}, False],
['inputs:max', {'type': 'uint', 'value': 4294967295}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint', 'value': 0}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 6159018942, False],
['inputs:min', {'type': 'uint[]', 'value': [0, 100]}, False],
['inputs:max', {'type': 'uint', 'value': 4294967295}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint[]', 'value': [2147483648, 2160101208]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 3280530163, False],
['inputs:min', {'type': 'uint', 'value': 0}, False],
['inputs:max', {'type': 'uint[]', 'value': [4294967295, 199]}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint[]', 'value': [4294967295, 19]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 6159018942, False],
['inputs:min', {'type': 'int', 'value': -2147483648}, False],
['inputs:max', {'type': 'int', 'value': 2147483647}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'int', 'value': 0}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 6649909271, False],
['inputs:min', {'type': 'int[2]', 'value': [-2147483648, -100]}, False],
['inputs:max', {'type': 'int', 'value': 2147483647}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'int[2]', 'value': [-2147483648, 1629773655]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 3280530163, False],
['inputs:min', {'type': 'int', 'value': -2147483648}, False],
['inputs:max', {'type': 'int[2]', 'value': [2147483647, 99]}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'int[2]', 'value': [2147483647, -2146948710]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 8280086, False],
['inputs:min', {'type': 'float', 'value': 0}, False],
['inputs:max', {'type': 'float', 'value': 1}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'float', 'value': 0}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 17972581, False],
['inputs:min', {'type': 'float[]', 'value': [0, -10]}, False],
['inputs:max', {'type': 'float', 'value': 1}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'float[]', 'value': [0.5, -6.7663326]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 15115159, False],
['inputs:min', {'type': 'float', 'value': 0}, False],
['inputs:max', {'type': 'float[]', 'value': [1, 10]}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'float[]', 'value': [0.9999999403953552, 4.0452986]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 14092058508772706262, False],
['inputs:min', {'type': 'uint64', 'value': 0}, False],
['inputs:max', {'type': 'uint64', 'value': 18446744073709551615}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint64', 'value': 0}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 9302349107990861236, False],
['inputs:min', {'type': 'uint64', 'value': 0}, False],
['inputs:max', {'type': 'uint64', 'value': 18446744073709551615}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint64', 'value': 9223372036854775808}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 1955209015103813879, False],
['inputs:min', {'type': 'uint64', 'value': 0}, False],
['inputs:max', {'type': 'uint64', 'value': 18446744073709551615}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint64', 'value': 18446744073709551615}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 123456789, False],
['inputs:min', {'type': 'uint64', 'value': 1099511627776}, False],
['inputs:max', {'type': 'uint64', 'value': 1125899906842624}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint64', 'value': 923489197424953}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 1955209015103813879, False],
['inputs:min', {'type': 'double[2][]', 'value': [[0, -10], [10, 0]]}, False],
['inputs:max', {'type': 'double', 'value': 1}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'double[2][]', 'value': [[0, 0.28955788], [7.98645811, 0.09353537]]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 123456789, False],
['inputs:min', {'type': 'half[]', 'value': [0, -100]}, False],
['inputs:max', {'type': 'half[]', 'value': [1, 100]}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'half[]', 'value': [0.17993164, -76.375]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 0, False],
['inputs:min', {'type': 'uchar[]', 'value': [0, 100]}, False],
['inputs:max', {'type': 'uchar[]', 'value': [255, 200]}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uchar[]', 'value': [153, 175]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 9302349107990861236, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'double', 'value': 0.5}, False],
['outputs:execOut', 1, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_RandomNumeric", "omni.graph.nodes.RandomNumeric", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.RandomNumeric User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_RandomNumeric","omni.graph.nodes.RandomNumeric", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.RandomNumeric User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_RandomNumeric", "omni.graph.nodes.RandomNumeric", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.RandomNumeric User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnRandomNumericDatabase import OgnRandomNumericDatabase
test_file_name = "OgnRandomNumericTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_RandomNumeric")
database = OgnRandomNumericDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:isNoise"))
attribute = test_node.get_attribute("inputs:isNoise")
db_value = database.inputs.isNoise
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:useSeed"))
attribute = test_node.get_attribute("inputs:useSeed")
db_value = database.inputs.useSeed
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
self.assertTrue(test_node.get_attribute_exists("state:gen"))
attribute = test_node.get_attribute("state:gen")
db_value = database.state.gen
| 15,030 | Python | 43.602374 | 199 | 0.499135 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnGatherByPath.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
import os
class TestOgn(ogts.OmniGraphTestCase):
async def test_generated(self):
test_data = [{'inputs': [['inputs:primPaths', ['/Xform1', '/Xform2'], False], ['inputs:attributes', '_translate', False], ['inputs:allAttributes', False, False]], 'outputs': [['outputs:gatheredPaths', ['/Xform1', '/Xform2'], False], ['outputs:gatherId', 1, False]], 'setup': {'create_nodes': [['TestNode', 'omni.graph.nodes.GatherByPath']], 'create_prims': [['Empty', {}], ['Xform1', {'_translate': ['pointd[3]', [1, 2, 3]]}], ['Xform2', {'_translate': ['pointd[3]', [4, 5, 6]]}], ['XformTagged1', {'foo': ['token', ''], '_translate': ['pointd[3]', [1, 2, 3]]}], ['Tagged1', {'foo': ['token', '']}]]}}, {'inputs': [['inputs:primPaths', ['/XformTagged1', '/Xform2', '/Xform1'], False], ['inputs:attributes', '_translate', False], ['inputs:allAttributes', False, False]], 'outputs': [['outputs:gatheredPaths', ['/XformTagged1', '/Xform1', '/Xform2'], False]], 'setup': {}}]
test_node = None
test_graph = None
for i, test_run in enumerate(test_data):
inputs = test_run.get('inputs', [])
outputs = test_run.get('outputs', [])
state_set = test_run.get('state_set', [])
state_get = test_run.get('state_get', [])
setup = test_run.get('setup', None)
if setup is None or setup:
await omni.usd.get_context().new_stage_async()
test_graph = None
elif not setup:
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test")
if setup:
(test_graph, test_nodes, _, _) = og.Controller.edit("/TestGraph", setup)
self.assertTrue(test_nodes)
test_node = test_nodes[0]
elif setup is None:
if test_graph is None:
test_graph = og.Controller.create_graph("/TestGraph")
self.assertTrue(test_graph is not None and test_graph.is_valid())
test_node = og.Controller.create_node(
("TestNode_omni_graph_nodes_GatherByPath", test_graph), "omni.graph.nodes.GatherByPath"
)
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test graph invalid")
self.assertTrue(test_node is not None and test_node.is_valid(), "Test node invalid")
await og.Controller.evaluate(test_graph)
values_to_set = inputs + state_set
if values_to_set:
for attribute_name, attribute_value, _ in inputs + state_set:
og.Controller((attribute_name, test_node)).set(attribute_value)
await og.Controller.evaluate(test_graph)
for attribute_name, expected_value, _ in outputs + state_get:
attribute = og.Controller.attribute(attribute_name, test_node)
actual_output = og.Controller.get(attribute)
expected_type = None
if isinstance(expected_value, dict):
expected_type = expected_value["type"]
expected_value = expected_value["value"]
ogts.verify_values(expected_value, actual_output, f"omni.graph.nodes.GatherByPath User test case #{i+1}: {attribute_name} attribute value error")
if expected_type:
tp = og.AttributeType.type_from_ogn_type_name(expected_type)
actual_type = attribute.get_resolved_type()
if tp != actual_type:
raise ValueError(f"omni.graph.nodes.GatherByPath User tests - {attribute_name}: Expected {expected_type}, saw {actual_type.get_ogn_type_name()}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnGatherByPathDatabase import OgnGatherByPathDatabase
test_file_name = "OgnGatherByPathTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_GatherByPath")
database = OgnGatherByPathDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:allAttributes"))
attribute = test_node.get_attribute("inputs:allAttributes")
db_value = database.inputs.allAttributes
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:attributes"))
attribute = test_node.get_attribute("inputs:attributes")
db_value = database.inputs.attributes
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:checkResyncAttributes"))
attribute = test_node.get_attribute("inputs:checkResyncAttributes")
db_value = database.inputs.checkResyncAttributes
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:forceExportToHistory"))
attribute = test_node.get_attribute("inputs:forceExportToHistory")
db_value = database.inputs.forceExportToHistory
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:hydraFastPath"))
attribute = test_node.get_attribute("inputs:hydraFastPath")
db_value = database.inputs.hydraFastPath
expected_value = "Disabled"
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:primPaths"))
attribute = test_node.get_attribute("inputs:primPaths")
db_value = database.inputs.primPaths
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:shouldWriteBack"))
attribute = test_node.get_attribute("inputs:shouldWriteBack")
db_value = database.inputs.shouldWriteBack
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:gatherId"))
attribute = test_node.get_attribute("outputs:gatherId")
db_value = database.outputs.gatherId
self.assertTrue(test_node.get_attribute_exists("outputs:gatheredPaths"))
attribute = test_node.get_attribute("outputs:gatheredPaths")
db_value = database.outputs.gatheredPaths
| 8,500 | Python | 60.158273 | 879 | 0.639529 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnReadPrimAttribute.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnReadPrimAttributeDatabase import OgnReadPrimAttributeDatabase
(_, (test_node,), _, _) = og.Controller.edit("/TestGraph", {
og.Controller.Keys.CREATE_NODES: ("Template_omni_graph_nodes_ReadPrimAttribute", "omni.graph.nodes.ReadPrimAttribute")
})
database = OgnReadPrimAttributeDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 3)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:name"))
attribute = test_node.get_attribute("inputs:name")
db_value = database.inputs.name
expected_value = ""
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:usdTimecode"))
attribute = test_node.get_attribute("inputs:usdTimecode")
db_value = database.inputs.usdTimecode
expected_value = float("NaN")
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:usePath"))
attribute = test_node.get_attribute("inputs:usePath")
db_value = database.inputs.usePath
expected_value = False
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("state:correctlySetup"))
attribute = test_node.get_attribute("state:correctlySetup")
db_value = database.state.correctlySetup
self.assertTrue(test_node.get_attribute_exists("state:importPath"))
attribute = test_node.get_attribute("state:importPath")
db_value = database.state.importPath
self.assertTrue(test_node.get_attribute_exists("state:srcAttrib"))
attribute = test_node.get_attribute("state:srcAttrib")
db_value = database.state.srcAttrib
self.assertTrue(test_node.get_attribute_exists("state:srcPath"))
attribute = test_node.get_attribute("state:srcPath")
db_value = database.state.srcPath
self.assertTrue(test_node.get_attribute_exists("state:srcPathAsToken"))
attribute = test_node.get_attribute("state:srcPathAsToken")
db_value = database.state.srcPathAsToken
self.assertTrue(test_node.get_attribute_exists("state:time"))
attribute = test_node.get_attribute("state:time")
db_value = database.state.time
| 3,252 | Python | 46.838235 | 130 | 0.696187 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnMakeVector3.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:x', {'type': 'float', 'value': 42.0}, False],
['inputs:y', {'type': 'float', 'value': 1.0}, False],
['inputs:z', {'type': 'float', 'value': 0.0}, False],
],
'outputs': [
['outputs:tuple', {'type': 'float[3]', 'value': [42.0, 1.0, 0.0]}, False],
],
},
{
'inputs': [
['inputs:x', {'type': 'float', 'value': 42.0}, False],
],
'outputs': [
['outputs:tuple', {'type': 'float[3]', 'value': [42.0, 0.0, 0.0]}, False],
],
},
{
'inputs': [
['inputs:x', {'type': 'float[]', 'value': [42, 1, 0]}, False],
['inputs:y', {'type': 'float[]', 'value': [0, 1, 2]}, False],
['inputs:z', {'type': 'float[]', 'value': [0, 2, 4]}, False],
],
'outputs': [
['outputs:tuple', {'type': 'float[3][]', 'value': [[42, 0, 0], [1, 1, 2], [0, 2, 4]]}, False],
],
},
{
'inputs': [
['inputs:x', {'type': 'int', 'value': 42}, False],
['inputs:y', {'type': 'int', 'value': -42}, False],
['inputs:z', {'type': 'int', 'value': 5}, False],
],
'outputs': [
['outputs:tuple', {'type': 'int[3]', 'value': [42, -42, 5]}, False],
],
},
{
'inputs': [
['inputs:x', {'type': 'double', 'value': 42.0}, False],
['inputs:y', {'type': 'double', 'value': 1.0}, False],
['inputs:z', {'type': 'double', 'value': 0.0}, False],
],
'outputs': [
['outputs:tuple', {'type': 'pointd[3]', 'value': [42.0, 1.0, 0.0]}, False],
],
'setup': {'create_nodes': [['TestNode', 'omni.graph.nodes.MakeVector3'], ['ConstPoint3d', 'omni.graph.nodes.ConstantPoint3d']], 'connect': [['TestNode.outputs:tuple', 'ConstPoint3d.inputs:value']]} },
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_MakeVector3", "omni.graph.nodes.MakeVector3", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.MakeVector3 User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_MakeVector3","omni.graph.nodes.MakeVector3", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.MakeVector3 User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_MakeVector3", "omni.graph.nodes.MakeVector3", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.MakeVector3 User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnMakeVector3Database import OgnMakeVector3Database
test_file_name = "OgnMakeVector3Template.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_MakeVector3")
database = OgnMakeVector3Database(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
| 5,922 | Python | 47.950413 | 219 | 0.565181 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnMakeTransform.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:rotationXYZ', [0, 0, 0], False],
['inputs:translation', [0, 0, 0], False],
],
'outputs': [
['outputs:transform', [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], False],
],
},
{
'inputs': [
['inputs:rotationXYZ', [0, 0, 0], False],
['inputs:translation', [1, 2, 3], False],
],
'outputs': [
['outputs:transform', [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1], False],
],
},
{
'inputs': [
['inputs:rotationXYZ', [20, 0, 30], False],
['inputs:translation', [1, -2, 3], False],
],
'outputs': [
['outputs:transform', [0.866025404, 0.5, 4.16333634e-17, 0.0, -0.46984631, 0.813797681, 0.342020143, 0.0, 0.171010072, -0.296198133, 0.939692621, 0.0, 1.0, -2.0, 3.0, 1.0], False],
],
},
{
'inputs': [
['inputs:scale', [10, 5, 2], False],
],
'outputs': [
['outputs:transform', [10, 0, 0, 0, 0, 5, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1], False],
],
},
{
'inputs': [
['inputs:translation', [1, -2, 3], False],
['inputs:rotationXYZ', [20, 0, 30], False],
['inputs:scale', [10, 5, 2], False],
],
'outputs': [
['outputs:transform', [8.66025404, 5.0, 0.0, 0.0, -2.34923155, 4.06898841, 1.71010072, 0.0, 0.34202014, -0.59239627, 1.87938524, 0.0, 1.0, -2.0, 3.0, 1.0], False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_MakeTransform", "omni.graph.nodes.MakeTransform", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.MakeTransform User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_MakeTransform","omni.graph.nodes.MakeTransform", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.MakeTransform User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_MakeTransform", "omni.graph.nodes.MakeTransform", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.MakeTransform User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnMakeTransformDatabase import OgnMakeTransformDatabase
test_file_name = "OgnMakeTransformTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_MakeTransform")
database = OgnMakeTransformDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:rotationXYZ"))
attribute = test_node.get_attribute("inputs:rotationXYZ")
db_value = database.inputs.rotationXYZ
expected_value = [0, 0, 0]
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:scale"))
attribute = test_node.get_attribute("inputs:scale")
db_value = database.inputs.scale
expected_value = [1, 1, 1]
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:translation"))
attribute = test_node.get_attribute("inputs:translation")
db_value = database.inputs.translation
expected_value = [0, 0, 0]
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:transform"))
attribute = test_node.get_attribute("outputs:transform")
db_value = database.outputs.transform
| 7,006 | Python | 46.99315 | 199 | 0.611476 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnCurveTubePositions.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnCurveTubePositionsDatabase import OgnCurveTubePositionsDatabase
test_file_name = "OgnCurveTubePositionsTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_CurveTubePositions")
database = OgnCurveTubePositionsDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:cols"))
attribute = test_node.get_attribute("inputs:cols")
db_value = database.inputs.cols
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:curvePoints"))
attribute = test_node.get_attribute("inputs:curvePoints")
db_value = database.inputs.curvePoints
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexCounts"))
attribute = test_node.get_attribute("inputs:curveVertexCounts")
db_value = database.inputs.curveVertexCounts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexStarts"))
attribute = test_node.get_attribute("inputs:curveVertexStarts")
db_value = database.inputs.curveVertexStarts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:out"))
attribute = test_node.get_attribute("inputs:out")
db_value = database.inputs.out
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:tubePointStarts"))
attribute = test_node.get_attribute("inputs:tubePointStarts")
db_value = database.inputs.tubePointStarts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:up"))
attribute = test_node.get_attribute("inputs:up")
db_value = database.inputs.up
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:width"))
attribute = test_node.get_attribute("inputs:width")
db_value = database.inputs.width
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:points"))
attribute = test_node.get_attribute("outputs:points")
db_value = database.outputs.points
| 5,214 | Python | 51.676767 | 100 | 0.691024 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnGetGatheredAttribute.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
import os
class TestOgn(ogts.OmniGraphTestCase):
async def test_generated(self):
test_data = [{'inputs': [['inputs:name', '_translate', False]], 'outputs': [['outputs:value', {'type': 'pointd[3][]', 'value': [[1, 2, 3], [4, 5, 6]]}, False]], 'setup': {'create_nodes': [['TestNode', 'omni.graph.nodes.GetGatheredAttribute'], ['GatherByPath', 'omni.graph.nodes.GatherByPath']], 'create_prims': [['Empty', {}], ['Xform1', {'_translate': ['pointd[3]', [1, 2, 3]]}], ['Xform2', {'_translate': ['pointd[3]', [4, 5, 6]]}], ['XformTagged1', {'foo': ['token', ''], '_translate': ['pointd[3]', [1, 2, 3]]}], ['Tagged1', {'foo': ['token', '']}]], 'connect': [['GatherByPath.outputs:gatherId', 'TestNode.inputs:gatherId']], 'set_values': [['GatherByPath.inputs:primPaths', ['/Xform1', '/Xform2']], ['GatherByPath.inputs:attributes', '_translate'], ['GatherByPath.inputs:allAttributes', False]]}}]
test_node = None
test_graph = None
for i, test_run in enumerate(test_data):
inputs = test_run.get('inputs', [])
outputs = test_run.get('outputs', [])
state_set = test_run.get('state_set', [])
state_get = test_run.get('state_get', [])
setup = test_run.get('setup', None)
if setup is None or setup:
await omni.usd.get_context().new_stage_async()
test_graph = None
elif not setup:
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test")
if setup:
(test_graph, test_nodes, _, _) = og.Controller.edit("/TestGraph", setup)
self.assertTrue(test_nodes)
test_node = test_nodes[0]
elif setup is None:
if test_graph is None:
test_graph = og.Controller.create_graph("/TestGraph")
self.assertTrue(test_graph is not None and test_graph.is_valid())
test_node = og.Controller.create_node(
("TestNode_omni_graph_nodes_GetGatheredAttribute", test_graph), "omni.graph.nodes.GetGatheredAttribute"
)
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test graph invalid")
self.assertTrue(test_node is not None and test_node.is_valid(), "Test node invalid")
await og.Controller.evaluate(test_graph)
values_to_set = inputs + state_set
if values_to_set:
for attribute_name, attribute_value, _ in inputs + state_set:
og.Controller((attribute_name, test_node)).set(attribute_value)
await og.Controller.evaluate(test_graph)
for attribute_name, expected_value, _ in outputs + state_get:
attribute = og.Controller.attribute(attribute_name, test_node)
actual_output = og.Controller.get(attribute)
expected_type = None
if isinstance(expected_value, dict):
expected_type = expected_value["type"]
expected_value = expected_value["value"]
ogts.verify_values(expected_value, actual_output, f"omni.graph.nodes.GetGatheredAttribute User test case #{i+1}: {attribute_name} attribute value error")
if expected_type:
tp = og.AttributeType.type_from_ogn_type_name(expected_type)
actual_type = attribute.get_resolved_type()
if tp != actual_type:
raise ValueError(f"omni.graph.nodes.GetGatheredAttribute User tests - {attribute_name}: Expected {expected_type}, saw {actual_type.get_ogn_type_name()}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnGetGatheredAttributeDatabase import OgnGetGatheredAttributeDatabase
test_file_name = "OgnGetGatheredAttributeTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_GetGatheredAttribute")
database = OgnGetGatheredAttributeDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:gatherId"))
attribute = test_node.get_attribute("inputs:gatherId")
db_value = database.inputs.gatherId
expected_value = 0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:name"))
attribute = test_node.get_attribute("inputs:name")
db_value = database.inputs.name
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
| 5,780 | Python | 62.527472 | 811 | 0.614879 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnLengthAlongCurve.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:curveVertexStarts', [0], False],
['inputs:curveVertexCounts', [4], False],
['inputs:curvePoints', [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 4.0, 4.0], [12.0, 13.0, 4.0]], False],
['inputs:normalize', False, False],
],
'outputs': [
['outputs:length', [0.0, 1.0, 6.0, 21.0], False],
],
},
{
'inputs': [
['inputs:curveVertexStarts', [0], False],
['inputs:curveVertexCounts', [3], False],
['inputs:curvePoints', [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0]], False],
['inputs:normalize', True, False],
],
'outputs': [
['outputs:length', [0.0, 0.5, 1.0], False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_LengthAlongCurve", "omni.graph.nodes.LengthAlongCurve", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.LengthAlongCurve User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_LengthAlongCurve","omni.graph.nodes.LengthAlongCurve", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.LengthAlongCurve User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_LengthAlongCurve", "omni.graph.nodes.LengthAlongCurve", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.LengthAlongCurve User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnLengthAlongCurveDatabase import OgnLengthAlongCurveDatabase
test_file_name = "OgnLengthAlongCurveTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_LengthAlongCurve")
database = OgnLengthAlongCurveDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:curvePoints"))
attribute = test_node.get_attribute("inputs:curvePoints")
db_value = database.inputs.curvePoints
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexCounts"))
attribute = test_node.get_attribute("inputs:curveVertexCounts")
db_value = database.inputs.curveVertexCounts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexStarts"))
attribute = test_node.get_attribute("inputs:curveVertexStarts")
db_value = database.inputs.curveVertexStarts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normalize"))
attribute = test_node.get_attribute("inputs:normalize")
db_value = database.inputs.normalize
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:length"))
attribute = test_node.get_attribute("outputs:length")
db_value = database.outputs.length
| 6,622 | Python | 49.557252 | 205 | 0.657505 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnBundleInspector.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'outputs': [
['outputs:count', 0, False],
['outputs:names', [], False],
['outputs:types', [], False],
['outputs:roles', [], False],
['outputs:arrayDepths', [], False],
['outputs:tupleCounts', [], False],
['outputs:values', [], False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_BundleInspector", "omni.graph.nodes.BundleInspector", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.BundleInspector User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_BundleInspector","omni.graph.nodes.BundleInspector", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.BundleInspector User test case #{i+1}", 16)
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnBundleInspectorDatabase import OgnBundleInspectorDatabase
test_file_name = "OgnBundleInspectorTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_BundleInspector")
database = OgnBundleInspectorDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 3)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:bundle"))
attribute = test_node.get_attribute("inputs:bundle")
db_value = database.inputs.bundle
self.assertTrue(test_node.get_attribute_exists("inputs:inspectDepth"))
attribute = test_node.get_attribute("inputs:inspectDepth")
db_value = database.inputs.inspectDepth
expected_value = 1
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:print"))
attribute = test_node.get_attribute("inputs:print")
db_value = database.inputs.print
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:arrayDepths"))
attribute = test_node.get_attribute("outputs:arrayDepths")
db_value = database.outputs.arrayDepths
self.assertTrue(test_node.get_attribute_exists("outputs:attributeCount"))
attribute = test_node.get_attribute("outputs:attributeCount")
db_value = database.outputs.attributeCount
self.assertTrue(test_node.get_attribute_exists("outputs_bundle"))
attribute = test_node.get_attribute("outputs_bundle")
db_value = database.outputs.bundle
self.assertTrue(test_node.get_attribute_exists("outputs:childCount"))
attribute = test_node.get_attribute("outputs:childCount")
db_value = database.outputs.childCount
self.assertTrue(test_node.get_attribute_exists("outputs:count"))
attribute = test_node.get_attribute("outputs:count")
db_value = database.outputs.count
self.assertTrue(test_node.get_attribute_exists("outputs:names"))
attribute = test_node.get_attribute("outputs:names")
db_value = database.outputs.names
self.assertTrue(test_node.get_attribute_exists("outputs:roles"))
attribute = test_node.get_attribute("outputs:roles")
db_value = database.outputs.roles
self.assertTrue(test_node.get_attribute_exists("outputs:tupleCounts"))
attribute = test_node.get_attribute("outputs:tupleCounts")
db_value = database.outputs.tupleCounts
self.assertTrue(test_node.get_attribute_exists("outputs:types"))
attribute = test_node.get_attribute("outputs:types")
db_value = database.outputs.types
self.assertTrue(test_node.get_attribute_exists("outputs:values"))
attribute = test_node.get_attribute("outputs:values")
db_value = database.outputs.values
| 6,031 | Python | 48.04065 | 184 | 0.666556 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnInterpolateTo.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:current', {'type': 'float', 'value': 0.0}, False],
['inputs:target', {'type': 'float', 'value': 10.0}, False],
['inputs:deltaSeconds', 0.1, False],
],
'outputs': [
['outputs:result', {'type': 'float', 'value': 1.9}, False],
],
},
{
'inputs': [
['inputs:current', {'type': 'double[3]', 'value': [0.0, 1.0, 2.0]}, False],
['inputs:target', {'type': 'double[3]', 'value': [10.0, 11.0, 12.0]}, False],
['inputs:deltaSeconds', 0.1, False],
],
'outputs': [
['outputs:result', {'type': 'double[3]', 'value': [1.9, 2.9, 3.9]}, False],
],
},
{
'inputs': [
['inputs:current', {'type': 'float[]', 'value': [0.0, 1.0, 2.0]}, False],
['inputs:target', {'type': 'float[]', 'value': [10.0, 11.0, 12.0]}, False],
['inputs:deltaSeconds', 0.1, False],
],
'outputs': [
['outputs:result', {'type': 'float[]', 'value': [1.9, 2.9, 3.9]}, False],
],
},
{
'inputs': [
['inputs:current', {'type': 'double[3][]', 'value': [[0.0, 1.0, 2.0], [0.0, 1.0, 2.0]]}, False],
['inputs:target', {'type': 'double[3][]', 'value': [[10.0, 11.0, 12.0], [10.0, 11.0, 12.0]]}, False],
['inputs:deltaSeconds', 0.1, False],
],
'outputs': [
['outputs:result', {'type': 'double[3][]', 'value': [[1.9, 2.9, 3.9], [1.9, 2.9, 3.9]]}, False],
],
},
{
'inputs': [
['inputs:current', {'type': 'quatd[4]', 'value': [0, 0, 0, 1]}, False],
['inputs:target', {'type': 'quatd[4]', 'value': [0.7071068, 0, 0, 0.7071068]}, False],
['inputs:deltaSeconds', 0.5, False],
['inputs:exponent', 1, False],
],
'outputs': [
['outputs:result', {'type': 'quatd[4]', 'value': [0.3826834, 0, 0, 0.9238795]}, False],
],
},
{
'inputs': [
['inputs:current', {'type': 'quatf[4]', 'value': [0, 0, 0, 1]}, False],
['inputs:target', {'type': 'quatf[4]', 'value': [0.7071068, 0, 0, 0.7071068]}, False],
['inputs:deltaSeconds', 0.5, False],
['inputs:exponent', 1, False],
],
'outputs': [
['outputs:result', {'type': 'quatf[4]', 'value': [0.3826834, 0, 0, 0.9238795]}, False],
],
},
{
'inputs': [
['inputs:current', {'type': 'float[4]', 'value': [0, 0, 0, 1]}, False],
['inputs:target', {'type': 'float[4]', 'value': [0.7071068, 0, 0, 0.7071068]}, False],
['inputs:deltaSeconds', 0.5, False],
['inputs:exponent', 1, False],
],
'outputs': [
['outputs:result', {'type': 'float[4]', 'value': [0.3535534, 0, 0, 0.8535534]}, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_InterpolateTo", "omni.graph.nodes.InterpolateTo", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.InterpolateTo User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_InterpolateTo","omni.graph.nodes.InterpolateTo", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.InterpolateTo User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_InterpolateTo", "omni.graph.nodes.InterpolateTo", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.InterpolateTo User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnInterpolateToDatabase import OgnInterpolateToDatabase
test_file_name = "OgnInterpolateToTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_InterpolateTo")
database = OgnInterpolateToDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 2)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:deltaSeconds"))
attribute = test_node.get_attribute("inputs:deltaSeconds")
db_value = database.inputs.deltaSeconds
expected_value = 0.0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:exponent"))
attribute = test_node.get_attribute("inputs:exponent")
db_value = database.inputs.exponent
expected_value = 2.0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:speed"))
attribute = test_node.get_attribute("inputs:speed")
db_value = database.inputs.speed
expected_value = 1.0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
| 8,282 | Python | 47.723529 | 199 | 0.570514 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnRpResourceExampleDeformer.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnRpResourceExampleDeformerDatabase import OgnRpResourceExampleDeformerDatabase
test_file_name = "OgnRpResourceExampleDeformerTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_RpResourceExampleDeformer")
database = OgnRpResourceExampleDeformerDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:deformScale"))
attribute = test_node.get_attribute("inputs:deformScale")
db_value = database.inputs.deformScale
expected_value = 1.0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:displacementAxis"))
attribute = test_node.get_attribute("inputs:displacementAxis")
db_value = database.inputs.displacementAxis
expected_value = 0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointCountCollection"))
attribute = test_node.get_attribute("inputs:pointCountCollection")
db_value = database.inputs.pointCountCollection
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:positionScale"))
attribute = test_node.get_attribute("inputs:positionScale")
db_value = database.inputs.positionScale
expected_value = 1.0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:primPathCollection"))
attribute = test_node.get_attribute("inputs:primPathCollection")
db_value = database.inputs.primPathCollection
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:resourcePointerCollection"))
attribute = test_node.get_attribute("inputs:resourcePointerCollection")
db_value = database.inputs.resourcePointerCollection
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:runDeformerKernel"))
attribute = test_node.get_attribute("inputs:runDeformerKernel")
db_value = database.inputs.runDeformerKernel
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:stream"))
attribute = test_node.get_attribute("inputs:stream")
db_value = database.inputs.stream
expected_value = 0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:timeScale"))
attribute = test_node.get_attribute("inputs:timeScale")
db_value = database.inputs.timeScale
expected_value = 0.01
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:verbose"))
attribute = test_node.get_attribute("inputs:verbose")
db_value = database.inputs.verbose
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:pointCountCollection"))
attribute = test_node.get_attribute("outputs:pointCountCollection")
db_value = database.outputs.pointCountCollection
self.assertTrue(test_node.get_attribute_exists("outputs:primPathCollection"))
attribute = test_node.get_attribute("outputs:primPathCollection")
db_value = database.outputs.primPathCollection
self.assertTrue(test_node.get_attribute_exists("outputs:reload"))
attribute = test_node.get_attribute("outputs:reload")
db_value = database.outputs.reload
self.assertTrue(test_node.get_attribute_exists("outputs:resourcePointerCollection"))
attribute = test_node.get_attribute("outputs:resourcePointerCollection")
db_value = database.outputs.resourcePointerCollection
self.assertTrue(test_node.get_attribute_exists("outputs:stream"))
attribute = test_node.get_attribute("outputs:stream")
db_value = database.outputs.stream
self.assertTrue(test_node.get_attribute_exists("state:sequenceCounter"))
attribute = test_node.get_attribute("state:sequenceCounter")
db_value = database.state.sequenceCounter
| 7,336 | Python | 53.348148 | 114 | 0.705153 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/_impl/extension.py | """Support required by the Carbonite extension loader - no visible API exists."""
from contextlib import suppress
import omni.ext
from omni.graph.nodes.bindings._omni_graph_nodes import acquire_interface as _acquire_interface
from omni.graph.nodes.bindings._omni_graph_nodes import release_interface as _release_interface
__all__ = []
"""This module has no public API"""
class _PublicExtension(omni.ext.IExt):
"""Object that tracks the lifetime of the Python part of the extension loading"""
def __init__(self):
super().__init__()
self.__interface = None
with suppress(ImportError):
import omni.kit.app # noqa: PLW0621
app = omni.kit.app.get_app()
manager = app.get_extension_manager()
# This is a bit of a hack to make the template directory visible to the OmniGraph UI extension
# if it happens to already be enabled. The "hack" part is that this logic really should be in
# omni.graph.ui, but it would be much more complicated there, requiring management of extensions
# that both do and do not have dependencies on omni.graph.ui.
if manager.is_extension_enabled("omni.graph.ui"):
import omni.graph.ui # noqa: PLW0621
omni.graph.ui.ComputeNodeWidget.get_instance().add_template_path(__file__)
def on_startup(self):
"""Set up initial conditions for the Python part of the extension"""
self.__interface = _acquire_interface()
def on_shutdown(self):
"""Shutting down this part of the extension prepares it for hot reload"""
if self.__interface is not None:
_release_interface(self.__interface)
self.__interface = None
| 1,754 | Python | 40.785713 | 108 | 0.657925 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/_impl/templates/template_omni.graph.nodes.ConstructArray.py | # 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.
#
from pathlib import Path
import omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.window.property.templates import HORIZONTAL_SPACING
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.controller = og.Controller()
self.add_button = None
self.remove_button = None
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = self.controller.node(self.node_prim_path)
def _retrieve_existing_inputs(self):
# Retrieve all existing attributes of the form "inputs:input{num}"
# Also find the largest suffix among all such attributes
# Returned largest suffix = -1 if there are no such attributes
input_attribs = [attrib for attrib in self.node.get_attributes() if attrib.get_name()[:12] == "inputs:input"]
largest_suffix = -1
for attrib in input_attribs:
largest_suffix = max(largest_suffix, int(attrib.get_name()[12:]))
return (input_attribs, largest_suffix)
def _on_click_add(self):
(_, largest_suffix) = self._retrieve_existing_inputs()
prev_attrib = self.node.get_attribute(f"inputs:input{largest_suffix}")
self.controller.create_attribute(
self.node,
f"inputs:input{largest_suffix + 1}",
"any",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
None,
og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY,
).set_resolved_type(prev_attrib.get_resolved_type())
# Bump the array size if it can't accomodate the new input.
array_size_attr = self.node.get_attribute("inputs:arraySize")
array_size = array_size_attr.get()
if array_size <= largest_suffix:
array_size_attr.set(array_size + 1)
self.remove_button.enabled = True
self.compute_node_widget.rebuild_window()
def _on_click_remove(self):
(input_attribs, largest_suffix) = self._retrieve_existing_inputs()
if not input_attribs:
return
attrib_to_remove = self.node.get_attribute(f"inputs:input{largest_suffix}")
self.controller.remove_attribute(attrib_to_remove)
self.remove_button.enabled = len(input_attribs) > 2
self.compute_node_widget.rebuild_window()
def _controls_build_fn(self, *args):
(input_attribs, _) = self._retrieve_existing_inputs()
icons_path = Path(__file__).absolute().parent.parent.parent.parent.parent.parent.joinpath("icons")
with ui.HStack(height=0, spacing=HORIZONTAL_SPACING):
ui.Spacer()
self.add_button = ui.Button(
image_url=f"{icons_path.joinpath('add.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
clicked_fn=self._on_click_add,
tooltip_fn=lambda: ui.Label("Add New Input"),
)
self.remove_button = ui.Button(
image_url=f"{icons_path.joinpath('remove.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
enabled=(len(input_attribs) > 1),
clicked_fn=self._on_click_remove,
tooltip_fn=lambda: ui.Label("Remove Input"),
)
def apply(self, props):
# Called by compute_node_widget to apply UI when selection changes
def find_prop(name):
return next((p for p in props if p.prop_name == name), None)
frame = CustomLayoutFrame(hide_extra=True)
(input_attribs, _) = self._retrieve_existing_inputs()
with frame:
with CustomLayoutGroup("Inputs"):
prop = find_prop("inputs:arraySize")
if prop is not None:
CustomLayoutProperty(prop.prop_name)
prop = find_prop("inputs:arrayType")
if prop is not None:
CustomLayoutProperty(prop.prop_name)
for attrib in input_attribs:
prop = find_prop(attrib.get_name())
if prop is not None:
CustomLayoutProperty(prop.prop_name)
CustomLayoutProperty(None, None, build_fn=self._controls_build_fn)
prop = find_prop("outputs:array")
if prop is not None:
with CustomLayoutGroup("Outputs"):
CustomLayoutProperty(prop.prop_name)
return frame.apply(props)
| 5,150 | Python | 41.570248 | 117 | 0.615534 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/_impl/templates/template_omni.graph.core.WriteVariable.py | from omni.graph.ui.scripts.graph_variable_custom_layout import GraphVariableCustomLayout
class CustomLayout(GraphVariableCustomLayout):
_value_is_output = False
| 167 | Python | 26.999996 | 88 | 0.826347 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/scripts/ui_utils.py | # 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.
#
import string
from pathlib import Path
from typing import Callable
import omni.graph.core as og
import omni.ui as ui
from omni.kit.window.property.templates import HORIZONTAL_SPACING
__string_cache = []
def _get_attribute_ui_name(name: str) -> str:
"""
Takes a raw name and formats it for use as the corresponding nice name in the UI.
o (For attribute names) Standard namespaces ('inputs', 'outputs', 'state') are stripped off the front.
o (For attribute names) Any remaining namespaces are converted to words within the name.
o Underscores are converted to spaces.
o Mixed-case words are broken into separate words (e.g. 'primaryRGBColor' -> 'primary RGB Color').
o Words which are all lower-case are capitalized (e.g. 'primary' -> 'Primary').
"""
# Replace '_' with ':' so they will be split
name.replace("_", ":")
# Split out namespaces
words = name.split(":")
# If the first namespace is one of our standard ones, get rid of it.
if len(words) > 1 and words[0] in ("inputs", "outputs", "state"):
words.pop(0)
words_out = []
for word in words:
# if word is all lower or all upper append it
if word.islower() or word.isupper():
words_out.append(word)
continue
# Mixed case.
# Lower-case followed by upper-case breaks between them. E.g. 'usdPrim' -> 'usd Prim'
# Upper-case followed by lower-case breaks before them. E.g: 'USDPrim' -> 'USD Prim'
# Combined example: abcDEFgHi -> abc DE Fg Hi
sub_word = ""
uppers = ""
for c in word:
if c.isupper():
if not uppers and sub_word:
words_out.append(sub_word)
sub_word = ""
uppers += c
else:
if len(uppers) > 1:
words_out.append(uppers[:-1])
sub_word += uppers[-1:] + c
uppers = ""
if sub_word:
words_out.append(sub_word)
elif uppers:
words_out.append(uppers)
# Title-case any words which are all lower case.
return " ".join([word.title() if word.islower() else word for word in words_out])
def _get_string_permutation(n: int) -> str:
"""
Gets the name of the attribute at the given index,
assuming the name is n-th permutation of the letters of the alphabet,
starting from single characters.
Args:
n: the index of the permutation
Return:
str: the n-th string in lexicographical order.
"""
max_index = len(__string_cache)
if max_index <= n:
for i in range(max_index, n + 1):
__string_cache.append(_convert_index_to_string_permutation(i + 1))
return __string_cache[n]
def _convert_index_to_string_permutation(index: int) -> str:
"""Converts a 1-based index to an alphabetical string which is a permutation of the letters of the alphabet.
For example:
1 = a
2 = b
...
26 = z
27 = aa
28 = ab
...
Args:
index: The number to convert to a string. Represents the index in the lexicographical sequence of generated strings.
Returns:
str: index'th string in lexicographic order.
"""
if index <= 0:
return ""
alphabet = list(string.ascii_lowercase)
size = len(alphabet)
result = ""
while index > 0:
r = index % size # noqa: S001
if r == 0:
r = size
index = (int)((index - r) / size)
result += alphabet[r - 1]
return result[::-1]
def _retrieve_existing_numeric_dynamic_inputs(node: og.Node) -> tuple[list[og.Attribute], int]:
"""
Retrieves the node inputs which follow the 'inputs:input{num}' naming convention.
Args:
node: the node reflected in the property panel
Return:
([og.Attribute], int): Tuple with the list of input attributes and the largest input index.
"""
# Retrieve all existing attributes of the form "inputs:input{num}"
# Also find the largest suffix among all such attributes
# Returned largest suffix = -1 if there are no such attributes
input_attribs = [attrib for attrib in node.get_attributes() if attrib.get_name()[:12] == "inputs:input"]
largest_suffix = -1
if not input_attribs:
return ([], largest_suffix)
for attrib in input_attribs:
largest_suffix = max(largest_suffix, int(attrib.get_name()[12:]))
return (input_attribs, largest_suffix)
def _retrieve_existing_alphabetic_dynamic_inputs(node: og.Node) -> tuple[list[og.Attribute], int]:
"""
Retrieves the node inputs which follow the 'inputs:abc' naming convention.
The sequence "abc" is a permutation of the letters of the alphabet,
generated sequentially starting with single characters.
Args:
node: the node reflected in the property panel
Return:
([og.Attribute], int): Tuple with the list of input attributes and the largest input index.
"""
# Retrieve all existing attributes of the form "inputs:abc
# The sequence "abc" represents the n-th permutation of the letters of the alphabet,
# starting from single characters
input_attribs = [attrib for attrib in node.get_attributes() if attrib.get_name()[:7] == "inputs:"]
if not input_attribs:
return ([], -1)
largest_index = len(input_attribs) - 1
return (input_attribs, largest_index)
def _retrieve_existing_alphabetic_dynamic_outputs(node: og.Node) -> tuple[list[og.Attribute], int]:
"""
Retrieves the node outputs which follow the 'outputs:abc' naming convention.
The sequence "abc" is a permutation of the letters of the alphabet,
generated sequentially starting with single characters.
Args:
node: the node reflected in the property panel
Return:
([og.Attribute], int): Tuple with the list of outputs attributes and the largest output index.
"""
# Retrieve all existing attributes of the form "outputs:abc
# The sequence "abc" represents the n-th permutation of the letters of the alphabet,
# starting from single characters
output_attribs = [attrib for attrib in node.get_attributes() if attrib.get_name()[:8] == "outputs:"]
if not output_attribs:
return ([], -1)
largest_index = len(output_attribs) - 1
return (output_attribs, largest_index)
def _build_add_remove_buttons(
layout, on_add_fn: Callable, on_remove_fn: Callable, on_remove_enabled_fn: Callable[[], bool]
):
"""
Creates the add (+) / remove (-) buttons for the property panel list control.
Args:
layout: the property panel layout instance
on_add_fn: callback invoked when the add button is pushed
on_remove_fn: callback invoked when the remove button is pushed
on_remove_enabled_fn: callback invoked when creating the remove button to check if the button is enabled or not
"""
icons_path = Path(__file__).absolute().parent.parent.parent.parent.parent.joinpath("icons")
with ui.HStack(height=0, spacing=HORIZONTAL_SPACING):
ui.Spacer()
layout.add_button = ui.Button(
image_url=f"{icons_path.joinpath('add.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
clicked_fn=on_add_fn,
tooltip_fn=lambda: ui.Label("Add New Input"),
)
layout.remove_button = ui.Button(
image_url=f"{icons_path.joinpath('remove.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
enabled=on_remove_enabled_fn(),
clicked_fn=on_remove_fn,
tooltip_fn=lambda: ui.Label("Remove Input"),
)
| 8,212 | Python | 35.502222 | 124 | 0.636142 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/scripts/layer_identifier_widget_builder.py | # 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.
#
from enum import Enum, auto
from typing import Dict, List, Mapping, Type, Union
import carb.events
import omni.client.utils as clientutils
import omni.kit.usd.layers as layers
import omni.ui as ui
import omni.usd
from omni.graph.ui import OmniGraphPropertiesWidgetBuilder, OmniGraphTfTokenAttributeModel
from omni.kit.window.property.templates import HORIZONTAL_SPACING
from pxr import Pcp, Sdf, Usd
CURRENT_AUTHORING_LAYER_TAG = "<Current Authoring Layer>"
SESSION_LAYER_TAG = "<Session Layer>"
ROOT_LAYER_TAG = "<Root Layer>"
INVALID_LAYER_TAG = "<Invalid Layer>"
def get_strongest_opinion_layer_from_node(node: Pcp.NodeRef, attr_name: str):
layer_stack = node.layerStack
spec_path = node.path.AppendProperty(attr_name)
for layer in layer_stack.layers:
attr_spec = layer.GetAttributeAtPath(spec_path)
if attr_spec and attr_spec.HasInfo("default"):
return layer
for child_node in node.children:
layer = get_strongest_opinion_layer_from_node(child_node, attr_name)
if layer:
return layer
return None
def get_strongest_opinion_layer(stage: Usd.Stage, prim_path: Union[Sdf.Path, str], attr_name: str):
prim = stage.GetPrimAtPath(prim_path)
prim_index = prim.GetPrimIndex()
return get_strongest_opinion_layer_from_node(prim_index.rootNode, attr_name)
class LayerType(Enum):
CURRENT_AUTHORING_LAYER = auto()
SESSION_LAYER = auto()
ROOT_LAYER = auto()
OTHER = auto()
INVALID = auto()
class LayerItem(ui.AbstractItem):
def __init__(self, layer: Union[Sdf.Layer, str], stage: Usd.Stage):
super().__init__()
self.layer = layer
if layer is None:
self.token = ""
self.model = ui.SimpleStringModel(CURRENT_AUTHORING_LAYER_TAG)
self.layer_type = LayerType.CURRENT_AUTHORING_LAYER
else:
prefix = ""
suffix = ""
if isinstance(layer, Sdf.Layer):
if layer == stage.GetRootLayer():
self.layer_type = LayerType.ROOT_LAYER
self.token = ROOT_LAYER_TAG
suffix = f" {layer.identifier}"
elif layer == stage.GetSessionLayer():
self.layer_type = LayerType.SESSION_LAYER
self.token = SESSION_LAYER_TAG
suffix = f" {layer.identifier}"
else:
self.layer_type = LayerType.OTHER
# make the layer identifier relative to CURRENT EDIT TARGET layer
self.token = clientutils.make_relative_url_if_possible(
stage.GetEditTarget().GetLayer().realPath, layer.identifier
)
elif isinstance(layer, str):
self.token = layer
self.layer_type = LayerType.INVALID
prefix = f"{INVALID_LAYER_TAG} "
self.model = ui.SimpleStringModel(prefix + self.token + suffix)
class LayerModel(OmniGraphTfTokenAttributeModel):
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict):
super().__init__(stage, attribute_paths, self_refresh, metadata)
usd_context = omni.usd.get_context_from_stage(stage)
self._layers = layers.get_layers(usd_context)
self._layers_event_subscription = self._layers.get_event_stream().create_subscription_to_pop(
self._on_layer_events, name="WritePrims Node Layers Model"
)
def clean(self):
self._layers_event_subscription = None
super().clean()
def _update_allowed_token(self, token_item=LayerItem):
self._allowed_tokens = [ # noqa PLW0201
LayerItem(None, self._stage)
] # empty entry, meaning do not change target layer
current_value_in_list = self._allowed_tokens[-1].token == self._value
layer_stack = self._stage.GetLayerStack()
for layer in layer_stack:
self._allowed_tokens.append(LayerItem(layer, self._stage))
if not current_value_in_list and self._is_value_equal_url(self._allowed_tokens[-1]):
current_value_in_list = True
if not current_value_in_list:
layer = self._get_value_strongest_layer()
self._allowed_tokens.append(
LayerItem(clientutils.make_absolute_url_if_possible(layer.realPath, self._value), self._stage)
)
def _on_layer_events(self, event: carb.events.IEvent):
payload = layers.get_layer_event_payload(event)
if not payload:
return
if payload.event_type == layers.LayerEventType.SUBLAYERS_CHANGED:
self._update_value(force=True)
self._item_changed(None)
def _update_index(self):
index = -1
for i, token in enumerate(self._allowed_tokens):
if self._is_value_equal_url(token):
index = i
break
return index
def _is_value_equal_url(self, layer_item: LayerItem) -> bool:
if layer_item.layer_type == LayerType.CURRENT_AUTHORING_LAYER:
return self._value == ""
if layer_item.layer_type == LayerType.SESSION_LAYER:
return self._value == SESSION_LAYER_TAG
if layer_item.layer_type == LayerType.ROOT_LAYER:
return self._value == ROOT_LAYER_TAG
identifier = layer_item.layer if layer_item.layer_type == LayerType.INVALID else layer_item.layer.identifier
layer = self._get_value_strongest_layer()
return clientutils.make_absolute_url_if_possible(
self._stage.GetEditTarget().GetLayer().realPath, identifier
) == clientutils.make_absolute_url_if_possible(layer.realPath, self._value)
def _get_value_strongest_layer(self):
attributes = self._get_attributes()
# only process the last entry for now
attr_path = attributes[-1].GetPath()
prim_path = attr_path.GetPrimPath()
attr_name = attr_path.name
return get_strongest_opinion_layer(attributes[-1].GetStage(), prim_path, attr_name)
class LayerIdentifierWidgetBuilder:
@classmethod
def build(
cls,
stage: Usd.Stage,
attr_name: str,
metadata: Mapping,
property_type: Type,
prim_paths: List[Sdf.Path],
additional_label_kwargs: Dict = None,
additional_widget_kwargs: Dict = None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
label_kwargs = {}
if additional_label_kwargs:
label_kwargs.update(additional_label_kwargs)
label = OmniGraphPropertiesWidgetBuilder.create_label(attr_name, metadata, label_kwargs)
model = LayerModel(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata)
widget_kwargs = {"name": "choices"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.ComboBox(model, **widget_kwargs)
mixed_overlay = OmniGraphPropertiesWidgetBuilder.create_mixed_text_overlay()
OmniGraphPropertiesWidgetBuilder.create_control_state(
model=model, value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
| 7,837 | Python | 39.402062 | 116 | 0.633406 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_read_prims_dirty_push.py | import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
from pxr import Usd, UsdGeom
class TestReadPrimsDirtyPush(ogts.OmniGraphTestCase):
"""Unit tests for dirty push behavior of the ReadPrimsV2 node in this extension"""
async def test_read_prims_dirty_push(self):
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
test_graph_path = "/World/TestGraph"
controller = og.Controller()
keys = og.Controller.Keys
tree = UsdGeom.Xform.Define(stage, "/tree")
branch = UsdGeom.Xform.Define(stage, "/tree/branch")
leaf = ogts.create_cube(stage, "tree/branch/leaf", (1, 0, 0))
# Set initial values
UsdGeom.XformCommonAPI(branch).SetTranslate((0, 0, 0))
leaf.GetAttribute("size").Set(1)
(graph, [read_prims_node, _], _, _) = controller.edit(
{"graph_path": test_graph_path, "evaluator_name": "dirty_push"},
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Inspector", "omni.graph.nodes.BundleInspector"),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Inspector.inputs:bundle"),
],
keys.SET_VALUES: [
("Read.inputs:computeBoundingBox", True),
("Inspector.inputs:print", False),
],
},
)
graph_context = graph.get_default_graph_context()
bundle = None
async def update_bundle(expected_child_count=1):
nonlocal bundle
await controller.evaluate()
container = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
self.assertTrue(container.valid)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), expected_child_count)
bundle = child_bundles[0] if len(child_bundles) == 1 else None
# Helpers
def assert_bundle_attr(name, expected_value):
attr = bundle.get_attribute_by_name(name)
if expected_value is None:
self.assertFalse(attr.is_valid())
else:
actual_value = attr.get()
if isinstance(expected_value, list):
actual_value = actual_value.tolist()
self.assertEqual(actual_value, expected_value)
# Observe the branch
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"),
targets=[branch.GetPath()],
)
# Initial update
await update_bundle()
assert_bundle_attr("xformOp:translate", [0, 0, 0])
assert_bundle_attr("bboxMaxCorner", [0.5, 0.5, 0.5])
assert_bundle_attr("worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])
# Change the USD stage on the branch (a tracked prim)
UsdGeom.XformCommonAPI(branch).SetTranslate((1, 2, 3))
# The lazy node should compute
await update_bundle()
# Check the output bundle
assert_bundle_attr("xformOp:translate", [1, 2, 3])
assert_bundle_attr("bboxMaxCorner", [1.5, 2.5, 3.5])
assert_bundle_attr("worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1])
# Change the leaf cube (a descendant of the tracked prim)
leaf.GetAttribute("size").Set(2)
# The lazy node should compute
await update_bundle()
assert_bundle_attr("xformOp:translate", [1, 2, 3])
assert_bundle_attr("bboxMaxCorner", [2.0, 3.0, 4.0])
assert_bundle_attr("worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1])
# Change the tree (an ancestor of the tracked prim)
UsdGeom.XformCommonAPI(tree).SetTranslate((-1, -2, -3))
# The lazy node should compute
await update_bundle()
assert_bundle_attr("xformOp:translate", [1, 2, 3])
assert_bundle_attr("bboxMaxCorner", [1.0, 1.0, 1.0])
assert_bundle_attr("worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])
# Create a new attribute on the tracked prim
UsdGeom.XformCommonAPI(branch).SetScale((10, 10, 10))
# The lazy node should compute
await update_bundle()
assert_bundle_attr("xformOp:translate", [1, 2, 3])
assert_bundle_attr("xformOp:scale", [10, 10, 10])
assert_bundle_attr("bboxMaxCorner", [10.0, 10.0, 10.0])
assert_bundle_attr("worldMatrix", [10, 0, 0, 0, 0, 10, 0, 0, 0, 0, 10, 0, 0, 0, 0, 1])
# Delete the branch
stage.RemovePrim(branch.GetPath())
# The lazy node should compute
await update_bundle(0)
self.assertEqual(bundle, None)
| 4,908 | Python | 37.054263 | 95 | 0.57172 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_omnigraph_utility_nodes.py | """Test the node that inspects attribute bundles"""
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.graph.nodes.tests as ognts
ROLES = [
"none",
"vector",
"normal",
"point",
"color",
"texcoord",
"quat",
"transform",
"frame",
"timecode",
"text",
"appliedSchema",
"prim",
"execution",
"matrix",
"objectId",
]
"""Mapping of OGN role name to the AttributeRole index used in Type.h"""
MATRIX_ROLES = ["frame", "transform", "matrix"]
"""Special roles that indicate a matrix type"""
BASE_TYPES = [
"none",
"bool",
"uchar",
"int",
"uint",
"int64",
"uint64",
"half",
"float",
"double",
"token",
]
"""Mapping of raw OGN base type name to the BaseDataType index in Type.h"""
# ======================================================================
class TestOmniGraphUtilityNodes(ogts.OmniGraphTestCase):
"""Run a simple unit test that exercises graph functionality"""
# ----------------------------------------------------------------------
async def test_attr_type(self):
"""Test the AttrType node with some pre-made input bundle contents"""
keys = og.Controller.Keys
(_, [attr_type_node, _], [prim], _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: ("AttrTypeNode", "omni.graph.nodes.AttributeType"),
keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()),
keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"),
keys.CONNECT: [
("TestPrimExtract.outputs_primBundle", "AttrTypeNode.inputs:data"),
],
},
)
await og.Controller.evaluate()
(_, bundle_values) = ognts.get_bundle_with_all_results(str(prim.GetPrimPath()))
name_attr = og.Controller.attribute("inputs:attrName", attr_type_node)
type_attr = og.Controller.attribute("outputs:baseType", attr_type_node)
tuple_count_attr = og.Controller.attribute("outputs:componentCount", attr_type_node)
array_depth_attr = og.Controller.attribute("outputs:arrayDepth", attr_type_node)
role_attr = og.Controller.attribute("outputs:role", attr_type_node)
full_type_attr = og.Controller.attribute("outputs:fullType", attr_type_node)
# Test data consisting of the input attrName followed by the expected output values
test_data = [["notExisting", -1, -1, -1, -1]]
for attribute_name, (type_name, tuple_count, array_depth, role, _) in bundle_values.items():
base_index = BASE_TYPES.index(type_name)
role_index = ROLES.index(role)
# Matrix types have 2d tuple counts
if role_index in MATRIX_ROLES:
tuple_count *= tuple_count
test_data.append([attribute_name, base_index, tuple_count, array_depth, role_index])
for (name, base_type, tuple_count, array_depth, role) in test_data:
og.Controller.set(name_attr, name)
await og.Controller.evaluate()
full_type = -1
if base_type >= 0:
# This is the bitfield computation used in Type.h
full_type = base_type + (tuple_count << 8) + (array_depth << 16) + (role << 24)
self.assertEqual(base_type, og.Controller.get(type_attr), f"Type of {name}")
self.assertEqual(tuple_count, og.Controller.get(tuple_count_attr), f"Tuple Count of {name}")
self.assertEqual(array_depth, og.Controller.get(array_depth_attr), f"Array Depth of {name}")
self.assertEqual(role, og.Controller.get(role_attr), f"Role of {name}")
self.assertEqual(full_type, og.Controller.get(full_type_attr), f"Full type of {name}")
# ----------------------------------------------------------------------
async def test_has_attr(self):
"""Test the HasAttr node with some pre-made input bundle contents"""
keys = og.Controller.Keys
(_, [has_attr_node, _], [prim], _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("HasAttrNode", "omni.graph.nodes.HasAttribute"),
],
keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()),
keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"),
keys.CONNECT: [("TestPrimExtract.outputs_primBundle", "HasAttrNode.inputs:data")],
},
)
await og.Controller.evaluate()
expected_results = ognts.get_bundle_with_all_results(str(prim.GetPrimPath()))
# Test data consisting of the input attrName followed by the expected output values
test_data = [("notExisting", 0)]
for name in expected_results[1].keys():
test_data.append((name, True))
name_attribute = og.Controller.attribute("inputs:attrName", has_attr_node)
output_attribute = og.Controller.attribute("outputs:output", has_attr_node)
for attribute_name, existence in test_data:
og.Controller.set(name_attribute, attribute_name)
await og.Controller.evaluate()
self.assertEqual(existence, og.Controller.get(output_attribute), f"Has {attribute_name}")
# ----------------------------------------------------------------------
async def test_get_attr_names(self):
"""Test the GetAttrNames node with some pre-made input bundle contents"""
keys = og.Controller.Keys
(_, [get_names_node, _], [prim], _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: ("GetAttrNamesNode", "omni.graph.nodes.GetAttributeNames"),
keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()),
keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"),
keys.CONNECT: [
("TestPrimExtract.outputs_primBundle", "GetAttrNamesNode.inputs:data"),
],
},
)
await og.Controller.evaluate()
(_, all_bundle_values) = ognts.get_bundle_with_all_results(
str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName())
)
attr_names = list(all_bundle_values.keys())
for is_sorted in [False, True]:
og.Controller.set(("inputs:sort", get_names_node), is_sorted)
await og.Controller.evaluate()
actual_results = og.Controller.get(("outputs:output", get_names_node))
if is_sorted:
self.assertEqual(sorted(attr_names), actual_results, "Comparing sorted lists")
else:
self.assertCountEqual(attr_names, actual_results, "Comparing unsorted lists")
# ----------------------------------------------------------------------
async def test_array_length(self):
"""Test the ArrayLength node with some pre-made input bundle contents"""
keys = og.Controller.Keys
(_, [length_node, _], [prim], _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: ("ArrayLengthNode", "omni.graph.nodes.ArrayLength"),
keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()),
keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "TestPrim", "TestPrimExtract"),
keys.CONNECT: [
("TestPrimExtract.outputs_primBundle", "ArrayLengthNode.inputs:data"),
],
},
)
await og.Controller.evaluate()
expected_results = ognts.get_bundle_with_all_results(str(prim.GetPrimPath()))
# Test data consisting of the input attrName followed by the expected output values
test_data = [("notExisting", 0)]
for name, (_, _, array_length, _, value) in expected_results[1].items():
test_data.append((name, len(value) if array_length > 0 else 1))
name_attribute = og.Controller.attribute("inputs:attrName", length_node)
output_attribute = og.Controller.attribute("outputs:length", length_node)
for attribute_name, expected_length in test_data:
og.Controller.set(name_attribute, attribute_name)
await og.Controller.evaluate()
self.assertEqual(expected_length, og.Controller.get(output_attribute), f"{attribute_name} array length")
# ----------------------------------------------------------------------
async def test_copy_attr(self):
"""Test the CopyAttr node with some pre-made input bundle contents on the partialData input"""
keys = og.Controller.Keys
(_, [copy_node, inspector_node, _], [prim], _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("CopyAttrNode", "omni.graph.nodes.CopyAttribute"),
("Inspector", "omni.graph.nodes.BundleInspector"),
],
keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()),
keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"),
keys.CONNECT: [
# Connect the same prim to both inputs to avoid the overhead of creating two prims
("TestPrimExtract.outputs_primBundle", "CopyAttrNode.inputs:fullData"),
("TestPrimExtract.outputs_primBundle", "CopyAttrNode.inputs:partialData"),
("CopyAttrNode.outputs_data", "Inspector.inputs:bundle"),
],
},
)
await og.Controller.evaluate()
input_names_attr = og.Controller.attribute("inputs:inputAttrNames", copy_node)
output_names_attr = og.Controller.attribute("inputs:outputAttrNames", copy_node)
expected_results = ognts.get_bundle_with_all_results(
str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName())
)
# Use sorted names so that the test is predictable
sorted_names = sorted(expected_results[1].keys())
# Restrict to a small subset as a representative test
old_names = sorted_names[0:3]
new_names = [f"COPIED_{name}" for name in sorted_names[0:3]]
copied_results = dict(expected_results[1].items())
copied_results.update(
{f"COPIED_{key}": value for key, value in expected_results[1].items() if key in old_names}
)
expected_copied_results = (expected_results[0] + len(old_names), copied_results)
test_data = [
("", "", expected_results),
(old_names, new_names, expected_copied_results),
]
for (to_copy, copied_to, expected_output) in test_data:
og.Controller.set(input_names_attr, ",".join(to_copy))
og.Controller.set(output_names_attr, ",".join(copied_to))
await og.Controller.evaluate()
results = ognts.bundle_inspector_results(inspector_node)
try:
# FIXME: OM-44667: Values do not get copied correctly. When they do, check_values=False can be removed
ognts.verify_bundles_are_equal(results, expected_output, check_values=False)
except ValueError as error:
self.assertTrue(False, error)
# ----------------------------------------------------------------------
async def test_rename_attr(self):
"""Test the RenameAttr node with some pre-made input bundle contents"""
keys = og.Controller.Keys
(_, [rename_node, inspector_node, _], [prim], _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("RenameAttrNode", "omni.graph.nodes.RenameAttribute"),
("Inspector", "omni.graph.nodes.BundleInspector"),
],
keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()),
keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"),
keys.CONNECT: [
("TestPrimExtract.outputs_primBundle", "RenameAttrNode.inputs:data"),
("RenameAttrNode.outputs_data", "Inspector.inputs:bundle"),
],
keys.SET_VALUES: [
("RenameAttrNode.inputs:inputAttrNames", ""),
("RenameAttrNode.inputs:outputAttrNames", ""),
],
},
)
await og.Controller.evaluate()
input_names_attr = og.Controller.attribute("inputs:inputAttrNames", rename_node)
output_names_attr = og.Controller.attribute("inputs:outputAttrNames", rename_node)
expected_results = ognts.get_bundle_with_all_results(
str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName())
)
# Use sorted names so that the test is predictable
sorted_names = sorted(expected_results[1].keys())
# Restrict to a small subset as a representative test
old_names = sorted_names[0:3]
new_names = [f"RENAMED_{name}" for name in sorted_names[0:3]]
renamed_results = {key: value for key, value in expected_results[1].items() if key not in old_names}
renamed_results.update(
{f"RENAMED_{key}": value for key, value in expected_results[1].items() if key in old_names}
)
expected_renamed_results = (expected_results[0], renamed_results)
test_data = [
("", "", expected_results),
(old_names, new_names, expected_renamed_results),
]
for (to_rename, renamed_to, expected_output) in test_data:
og.Controller.set(input_names_attr, ",".join(to_rename))
og.Controller.set(output_names_attr, ",".join(renamed_to))
await og.Controller.evaluate()
results = ognts.bundle_inspector_results(inspector_node)
try:
# FIXME: OM-44667: Values do not get copied correctly. When they do, check_values=False can be removed
ognts.verify_bundles_are_equal(results, expected_output, check_values=False)
except ValueError as error:
self.assertTrue(False, error)
# ----------------------------------------------------------------------
async def test_remove_attr(self):
"""Test the RemoveAttr node with some pre-made input bundle contents"""
keys = og.Controller.Keys
(_, [remove_node, inspector_node, _], [prim], _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("RemoveAttrNode", "omni.graph.nodes.RemoveAttribute"),
("Inspector", "omni.graph.nodes.BundleInspector"),
],
keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()),
keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"),
keys.CONNECT: [
("TestPrimExtract.outputs_primBundle", "RemoveAttrNode.inputs:data"),
("RemoveAttrNode.outputs_data", "Inspector.inputs:bundle"),
],
keys.SET_VALUES: [
("RemoveAttrNode.inputs:attrNamesToRemove", ""),
],
},
)
await og.Controller.evaluate()
(expected_count, expected_results) = ognts.get_bundle_with_all_results(
str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName())
)
# Use sorted names so that the test is predictable
sorted_names = sorted(expected_results.keys())
removal = [
sorted_names[0:2],
sorted_names[3:6],
]
test_data = [
("", (expected_count, expected_results)),
(
",".join(removal[0]),
(
expected_count - len(removal[0]),
{key: value for key, value in expected_results.items() if key not in removal[0]},
),
),
(
",".join(removal[1]),
(
expected_count - len(removal[1]),
{key: value for key, value in expected_results.items() if key not in removal[1]},
),
),
]
removal_attribute = og.Controller.attribute("inputs:attrNamesToRemove", remove_node)
for (names, expected_output) in test_data:
og.Controller.set(removal_attribute, names)
await og.Controller.evaluate()
results = ognts.bundle_inspector_results(inspector_node)
try:
# FIXME: OM-44667: Values do not get copied correctly. When they do, check_values=False can be removed
ognts.verify_bundles_are_equal(results, expected_output, check_values=False)
except ValueError as error:
self.assertTrue(False, error)
# ----------------------------------------------------------------------
async def test_insert_attr(self):
"""Test the InsertAttr node with some pre-made input bundle contents"""
double_array = [(1.2, -1.2), (3.4, -5.6)]
new_name = "newInsertedAttributeName"
keys = og.Controller.Keys
(_, [_, inspector_node, _], [prim], _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("InsertAttrNode", "omni.graph.nodes.InsertAttribute"),
("Inspector", "omni.graph.nodes.BundleInspector"),
],
keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()),
keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"),
keys.CONNECT: [
("TestPrimExtract.outputs_primBundle", "InsertAttrNode.inputs:data"),
("InsertAttrNode.outputs_data", "Inspector.inputs:bundle"),
],
keys.SET_VALUES: [
("InsertAttrNode.inputs:outputAttrName", new_name),
("InsertAttrNode.inputs:attrToInsert", double_array, "double[2][]"),
],
},
)
await og.Controller.evaluate()
results = ognts.bundle_inspector_results(inspector_node)
(expected_count, expected_results) = ognts.get_bundle_with_all_results(
str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName())
)
expected_results[new_name] = ("double", 2, 1, "none", double_array)
expected_values = (expected_count + 1, expected_results)
try:
# FIXME: OM-44667: The values do not get copied correctly. When they do, check_values=False can be removed
ognts.verify_bundles_are_equal(results, expected_values, check_values=False)
except ValueError as error:
self.assertTrue(False, error)
# ----------------------------------------------------------------------
async def test_extract_attr(self):
"""Test the ExtractAttr node with some pre-made input bundle contents"""
keys = og.Controller.Keys
(_, [extract_node, _, _], [prim], _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("ExtractAttrNode", "omni.graph.nodes.ExtractAttribute"),
("AddArray", "omni.graph.nodes.Add"),
],
keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()),
keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"),
keys.CONNECT: [
("TestPrimExtract.outputs_primBundle", "ExtractAttrNode.inputs:data"),
("ExtractAttrNode.outputs:output", "AddArray.inputs:a"),
],
keys.SET_VALUES: [
("ExtractAttrNode.inputs:attrName", "IntArrayAttr"),
],
},
)
await og.Controller.evaluate()
(_, expected_values) = ognts.get_bundle_with_all_results(str(prim.GetPrimPath()))
self.assertCountEqual(
expected_values["IntArrayAttr"][ognts.BundleResultKeys.VALUE_IDX],
og.Controller.get(("outputs:output", extract_node)),
)
# ----------------------------------------------------------------------
async def test_bundle_constructor(self):
"""Test simple operations in the BundleConstructor node.
Only a minimal set of attribute types are tested here; just enough to confirm all code paths. The
full test of all data types is done in a test node specially constructed for that purpose (OgnTestAllDataTypes)
"""
keys = og.Controller.Keys
(_, [constructor_node, inspector_node], _, _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("Constructor", "omni.graph.nodes.BundleConstructor"),
("Inspector", "omni.graph.nodes.BundleInspector"),
],
keys.CONNECT: ("Constructor.outputs_bundle", "Inspector.inputs:bundle"),
},
)
await og.Controller.evaluate()
empty_bundle_output = (0, {})
# Test data consists of a list of test configurations containing:
# Parameters to create_attribute() for dynamic attribute to be added (None if no additions)
# Parameters to remove_attribute() for dynamic attribute to be removed (None if no removals)
# Expected dictionary of values from the inspector after evaluation of the constructor node
test_data = [
# Initial state with an empty bundle
[
None,
None,
empty_bundle_output,
],
# Add a simple float[3] attribute
[
{
"attributeName": "xxx",
"attributeType": og.AttributeType.type_from_ogn_type_name("float[3]"),
"portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
"value": [1.0, 2.0, 3.0],
"extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR,
"unionTypes": "",
},
None,
# TODO: Should be [1,2,3] when dynamic attribute defaults work
(1, {"xxx": ("float", 3, 0, "none", (0.0, 0.0, 0.0))}),
],
# Remove the attribute that was just added to get back to empty
[
None,
{"attributeName": "inputs:xxx"},
empty_bundle_output,
],
# Adding an "any" type that will not show up in the output bundle
[
{
"attributeName": "xxAny",
"attributeType": og.AttributeType.type_from_ogn_type_name("any"),
"portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
"value": None,
"extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY,
"unionTypes": "",
},
None,
empty_bundle_output,
],
# Adding a "bundle" type that will not show up in the output bundle
[
{
"attributeName": "xxBundle",
"attributeType": og.AttributeType.type_from_ogn_type_name("bundle"),
"portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
"value": None,
"extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR,
"unionTypes": "",
},
None,
empty_bundle_output,
],
# Adding an output float attribute that will not show up in the output bundle
[
{
"attributeName": "xxFloat",
"attributeType": og.AttributeType.type_from_ogn_type_name("float"),
"portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
"value": 5.0,
"extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR,
"unionTypes": "",
},
None,
empty_bundle_output,
],
# Adding a colord[3] and a float[] attribute, one at a time.
[
{
"attributeName": "xxColor",
"attributeType": og.AttributeType.type_from_ogn_type_name("colord[3]"),
"portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
"value": [1.0, 2.0, 3.0],
"extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR,
"unionTypes": "",
},
None,
# TODO: Should be [1.0, 2.0, 3.0] when dynamic attribute defaults work
(1, {"xxColor": ("double", 3, 0, "color", (0.0, 0.0, 0.0))}),
],
[
{
"attributeName": "xxFloatArray",
"attributeType": og.AttributeType.type_from_ogn_type_name("float[]"),
"portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
"value": [],
"extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR,
"unionTypes": "",
},
None,
# TODO: Should be [1.0, 2.0, 3.0] when dynamic attribute defaults work
(
2,
{
"xxColor": ("double", 3, 0, "color", (0.0, 0.0, 0.0)),
"xxFloatArray": ("float", 1, 1, "none", []),
},
),
],
# Remove the colord[3] that was added before the remaining float[] attribute
[
None,
{"attributeName": "inputs:xxColor"},
(1, {"xxFloatArray": ("float", 1, 1, "none", [])}),
],
]
for attribute_construction, attribute_removal, expected_results in test_data:
if attribute_construction is not None:
if attribute_construction[
"extendedType"
] == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY or attribute_construction[
"attributeType"
].base_type in [
og.BaseDataType.RELATIONSHIP,
]:
with ogts.ExpectedError():
constructor_node.create_attribute(**attribute_construction)
else:
constructor_node.create_attribute(**attribute_construction)
if attribute_removal is not None:
constructor_node.remove_attribute(**attribute_removal)
await og.Controller.evaluate()
# FIXME: OM-44667: Bug with the bundle copy means the full bundle doesn't come over with its values
# Remove this when the bug is fixed.
ignore = ["fullInt", "floatArray"]
ignore = []
try:
ognts.verify_bundles_are_equal(
ognts.filter_bundle_inspector_results(
ognts.bundle_inspector_results(inspector_node), ignore, filter_for_inclusion=False
),
ognts.filter_bundle_inspector_results(expected_results, ignore, filter_for_inclusion=False),
)
except ValueError as error:
self.assertTrue(False, error)
| 28,187 | Python | 46.53457 | 119 | 0.539752 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/_1_15.py | """Backward compatible module for omni.graph.nodes version 1.15.
Revert your access to the earlier package to this version:
import omni.graph.nodes._1_15 as on
Or import both and cherry-pick which versions of specific APIs you want to use
import omni.graph.nodes as on
import omni.graph.nodes._1_15 as on1_15
if i_want_v1_15:
on1_15.old_function()
else:
on.old_function()
"""
import ast
import json
from tempfile import NamedTemporaryFile
from typing import Any, Dict, List, Optional, Tuple, Union
from unittest import TestCase
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.graph.tools as ogt
from omni.kit.app import get_app
from pxr import Usd
__all__ = [
"bundle_inspector_outputs",
"bundle_inspector_values_as_dictionary",
"compare_bundle_contents",
"compare_bundle_inspector_results",
"computed_bundle_values",
"create_prim_with_everything",
"graph_node_path",
"inspected_bundle_values",
"inspector_node_definition",
"prim_node_definition",
"set_up_test_stage",
]
# ======================================================================
# Type of data coming from a bundle inspector output
BundleInspectorOutputType = Tuple[int, List[str], List[str], List[str], List[int], List[int], List[Any]]
# ======================================================================
# Attribute information for bundle inspector nodes
BUNDLE_INSPECTOR_ATTRIBUTES = [
("uint64", "outputs:count"),
("token[]", "outputs:names"),
("token[]", "outputs:types"),
("token[]", "outputs:roles"),
("int[]", "outputs:arrayDepths"),
("int[]", "outputs:tupleCounts"),
("token[]", "outputs:values"),
("bundle", "outputs_bundle"),
("bool", "inputs:print"),
]
# ======================================================================
# Feed data for constructing sample data with all attribute types in it. This is a list of
# (ATTRIBUTE_TYPE, ATTRIBUTE_SAMPLE_VALUE) that can be used to populate bundles. Tuple counts are
# lifted from the sample value type information and arrays are constructed explicitly from this simple data.
# (Be careful with the half values; they have lower resolution and are better tested in fractionaly powers of 2.)
# fmt: off
PRIM_SAMPLE_VALUES = [
("int", 1),
("int64", 2),
("half", 3.5),
("float", 5.6),
("double", 7.8),
("bool", 1),
("token", "goofy"),
("uchar", 9),
("uint", 10),
("uint64", 11),
("int", (12, -13)),
("half", (14.5, -16.5)),
("float", (18.19, 20.21)),
("double", (22.23, 24.25)),
("int", (26, -27, 28)),
("half", (29.5, -31.5, 33.5)),
("float", (35.36, -37.38, 39.40)),
("double", (41.42, -43.44, 45.46)),
("int", (47, -48, 49, -50)),
("half", (51.5, -53.5, 55.5, -57.5)),
("float", (59.60, -61.62, 63.64, -65.66)),
("double", (67.68, -69.70, 71.72, -73.74)),
("quath", (75.5, -77.5, 79.5, -81.5)),
("quatf", (83.84, -85.86, 87.88, -89.90)),
("quatd", (91.92, -93.94, 95.96, -97.98)),
("matrixd", ((1.1, -1.2), (2.1, -2.2))),
("matrixd", ((1.1, -1.2, 1.3), (2.1, -2.2, 2.3), (3.1, -3.2, 3.3))),
("matrixd", ((1.1, -1.2, 1.3, 1.4), (2.1, -2.2, 2.3, -2.4), (3.1, -3.2, 3.3, -3.4), (4.1, -4.2, 4.3, -4.4))),
]
# fmt: on
# ======================================================================
# Data types used for the node description conversions (set as simple type definitions because you can differentiate
# between the two of them just by checking size)
PrimAttributeValueType = List[Union[Tuple[str, Any], Tuple[str, str, Any]]]
OmniGraphNodeDefinitionType = Tuple[str, str, List[str], List[Tuple[str, str]]]
PrimNodeDefinitionType = Tuple[str, Dict[str, Tuple[str, Any, int]]]
# ======================================================================
@ogt.deprecated_function("Use og.Controller.create_prim()")
def prim_node_definition(prim_name: str, data: PrimAttributeValueType, as_usd: bool = True) -> PrimNodeDefinitionType:
"""Returns the data as a USD definition compatible with what is needed for node definitions in set_up_test_stage
Args:
prim_name: Name of the prim to be defined
data: List of prim attribute values. The members of the list come in two forms:
(TYPE, VALUE) : Creates attributes and arrays of those attributes with names derived from the type
roughly ("float", 3) -> "float floatAttr = 3.0", "float[] floatAttrArray = [3.0, 3.0, 3.0]"
(TYPE, NAME, VALUE): Creates an attribute with the given name, type, and value
roughly ("float", "myFloat", 3) -> "float myFloat = 3.0"
as_usd: If True then create the definition with USD ordering (i.e. quaternions reordered)
"""
definition = {}
for attribute_info in data:
if len(attribute_info) == 2:
(attribute_type, value) = attribute_info
if isinstance(value, str) or (not isinstance(value, list) and not isinstance(value, tuple)):
tuple_count = 1
attribute_name = f"{attribute_type}Attr"
else:
tuple_count = len(value)
attribute_name = f"{attribute_type}{tuple_count}Attr"
# In all of the user-facing data the quaternions are specified as I,J,K,R, however in the USD file and
# quaternion constructor they expect R,I,J,K so reorder for consistency
if as_usd and attribute_type.find("quat") == 0:
the_value = (value[3], value[0], value[1], value[2])
else:
the_value = value
definition[attribute_name] = (f"{attribute_type}", the_value, False, tuple_count)
definition[f"{attribute_name}Array"] = (f"{attribute_type}", [the_value] * 3, True, tuple_count)
else:
(attribute_type, attribute_name, value) = attribute_info
is_array = False
the_value = value
if isinstance(value, str) or (not isinstance(value, list) and not isinstance(value, tuple)):
tuple_count = 1
elif isinstance(value, list) and value:
is_array = True
if isinstance(value[0], str) or (not isinstance(value[0], list) and not isinstance(value[0], tuple)):
tuple_count = 1
else:
tuple_count = len(value[0])
# In all of the user-facing data the quaternions are specified as I,J,K,R, however in the USD file
# and quaternion constructor they expect R,I,J,K so reorder for consistency
if as_usd and attribute_type.find("quat") == 0:
the_value = tuple((member[3], member[0], member[1], member[2]) for member in value)
elif isinstance(value, tuple):
tuple_count = len(value)
# In all of the user-facing data the quaternions are specified as I,J,K,R, however in the USD file and
# quaternion constructor they expect R,I,J,K so reorder for consistency
if as_usd and attribute_type.find("quat") == 0:
the_value = (value[3], value[0], value[1], value[2])
definition[attribute_name] = (f"{attribute_type}", the_value, is_array, tuple_count)
return (prim_name, definition)
# ======================================================================
@ogt.deprecated_function("Use og.Controller.create_prim()")
def _write_usd_prim_definition(attribute_information: PrimNodeDefinitionType, out):
"""Write out a USD Prim definition using the attribute information
Args:
attribute_information: Tuple(prim_name, Dict of ATTRIBUTE_NAME: (USD_TYPE, USD_VALUE, TUPLE_COUNT))
e.g. a float[3] named foo defaulted to zeroes would be { "foo": ("float", [0.0, 0.0, 0.0], 3) }
out: Output object to which the definition will be written
"""
out.write(f'def Output "{attribute_information[0]}"')
if out.indent("{"):
for attribute_name, (type_name, attribute_value, is_array, tuple_count) in attribute_information[1].items():
usd_type = ogt.usd_type_name(type_name, tuple_count, is_array)
value = attribute_value
if usd_type.startswith("token") or usd_type.startswith("string"):
value = json.dumps(attribute_value)
out.write(f"{usd_type} {attribute_name} = {value}")
out.exdent("}")
# ======================================================================
@ogt.deprecated_function("Use og.Controller.create_node()")
def inspector_node_definition(node_name: str, source_bundle: str) -> Tuple[str, str, List[str]]:
"""Returns the entry in a node definition list for a bundle inspector node connected to the given source"""
return (
node_name,
"omni.graph.nodes.BundleInspector",
[f"rel inputs:bundle = [<{source_bundle}>]"] + ogt.attributes_as_usd(BUNDLE_INSPECTOR_ATTRIBUTES),
BUNDLE_INSPECTOR_ATTRIBUTES,
)
# ======================================================================
@ogt.deprecated_function("Use omni.graph.nodes.test.bundle_inspector_results()")
def inspected_bundle_values(bundle_data) -> List[Any]:
"""Returns a list of attribute values expected on the bundle inspector when applied to the bundle data.
The list ordering should correspond to what is in BUNDLE_INSPECTOR_ATTRIBUTES, for efficiency.
Args:
bundle_data: Raw output of all the output attributes the bundle inspector provides
"""
names = []
type_names = []
role_names = []
array_flags = []
tuple_counts = []
values = []
# Sorting by name is the easiest way to produce a predictable ordering for the expected bundle values
for name in sorted(bundle_data.keys()):
(raw_type_name, value, is_array, tuple_count) = bundle_data[name]
names.append(name)
(type_name, role_name) = ogt.separate_ogn_role_and_type(raw_type_name)
type_names.append(type_name)
role_names.append(role_name)
array_flags.append(is_array)
tuple_counts.append(tuple_count * tuple_count if role_name in ["frame", "matrix", "transform"] else tuple_count)
values.append(value)
return [len(bundle_data), names, type_names, role_names, array_flags, tuple_counts, values]
# ======================================================================
@ogt.deprecated_function("Use omni.graph.nodes.test.bundle_inspector_results()")
def computed_bundle_values(inspector_attributes: List[Any]) -> BundleInspectorOutputType:
"""Returns attribute values computed from a bundle inspector in the same form as inspected_bundle_values
Args:
inspector_attributes: List of the Attribute objects on the node in the order of BUNDLE_INSPECTOR_ATTRIBUTES
"""
# Have to keep these separated because the first attribute is a single value while the rest are lists of strings
size = og.Controller.get(inspector_attributes[0])
if size == 0:
return (0, [], [], [], [], [], [])
results = []
for attribute_index in range(1, 7):
attribute_values = og.Controller.get(inspector_attributes[attribute_index])
if attribute_index == 6:
# Bundled values are formatted as strings but are actually a mixture of types
attribute_values = [
ast.literal_eval(value) if value != "__unsupported__" else "__unsupported__"
for value in attribute_values
]
results.append(attribute_values)
# If these aren't sorted it will be more difficult to compare them
zipped = list(zip(results[0], results[1], results[2], results[3], results[4], results[5]))
zipped.sort()
results = list(zip(*zipped))
return tuple([size] + results)
# ======================================================================
@ogt.deprecated_function("Use omni.graph.nodes.test.bundle_inspector_results()")
def bundle_inspector_outputs(bundle_inspector: og.NODE_TYPE_HINTS) -> BundleInspectorOutputType:
"""Returns attribute values computed from a bundle inspector in the same form as inspected_bundle_values
Args:
bundle_inspector: Node from which the output is to be extracted
"""
raw_values = [
og.Controller.get(og.Controller.attribute(name, bundle_inspector))
for (attr_type, name) in BUNDLE_INSPECTOR_ATTRIBUTES
if attr_type != "bundle" and name.startswith("outputs:")
]
size = raw_values[0]
if size == 0:
return (0, [], [], [], [], [], [])
results = []
for attribute_name in [name for (_, name) in BUNDLE_INSPECTOR_ATTRIBUTES[1:] if name.startswith("outputs:")]:
results.append(og.Controller.get(og.Controller.attribute(attribute_name, bundle_inspector)))
# Bundled values are formatted as strings but are actually a mixture of types
results[-1] = [
ast.literal_eval(value) if value != "__unsupported__" else "__unsupported__" for value in results[-1]
]
# If these aren't sorted it will be more difficult to compare them
zipped = list(zip(results[0], results[1], results[2], results[3], results[4], results[5]))
zipped.sort()
results = [list(x) for x in zip(*zipped)]
return tuple([size] + results)
# ======================================================================
@ogt.deprecated_function("Use omni.graph.nodes.test.bundle_inspector_results()")
def bundle_inspector_values_as_dictionary(inspected_values: List[Any]) -> Dict[str, Tuple[str, str, bool, int, Any]]:
"""Converts the results from a list of bundle inspector results into a dictionary of all of the array attributes
The dictionary is useful for sorting as the key values will be unique.
Args:
inspected_values: List of bundle inspector outputs in the format produced by inspected_bundle_values()
Returns:
Dictionary of { Bundled Attribute Name : (TYPE, ROLE, IS_ARRAY, TUPLE_COUNT, VALUE) }
TYPE: Attribute base type name
ROLE: Attribute role name
IS_ARRAY: Is the attribute an array type?
TUPLE_COUNT: How many tuple elements in the attribute? (1 if simple data)
VALUE: Value of the attribute extracted from the bundle
"""
inspector_dictionary = {}
for index in range(inspected_values[0]):
inspector_dictionary[inspected_values[1][index]] = tuple(inspected_values[i][index] for i in range(2, 7))
return inspector_dictionary
# ======================================================================
@ogt.deprecated_function("Use graph and/or node reference directly")
def graph_node_path(node_name: str) -> str:
"""Returns the full graph node prim path for the OmniGraph node of the given name in the test scene"""
return f"/defaultPrim/graph/{node_name}"
# ======================================================================
@ogt.deprecated_function("Use og.Controller.create_prim()")
def _generate_test_file(
node_definitions: List[Union[PrimNodeDefinitionType, OmniGraphNodeDefinitionType]], debug: bool = False
):
"""
Generate a USDA file with data and connections that can exercise the bundle inspection node.
The file could have be put into the data/ directory but it is easier to understand and modify here,
especially since it is only useful in this test.
Normally you wouldn't call this directly, you'd use set_up_test_stage() to do the next steps to load the scene.
Args:
node_definitions: List of USD node definitions for nodes in the test, not including the bundle source
if the type is OmniGraphNodeDefinitionType then the values are tuples with OmniGraph node information:
(NODE_NAME, NODE_TYPE, ATTRIBUTE_LINES, ATTRIBUTE_INFO)
NODE_NAME: Local name of node in the graph
NODE_TYPE: OmniGraph node type name
ATTRIBUTE_LINES: List of the node's attribute declarations in USD form, including connections
ATTRIBUTE_INFO: List of (TYPE:NAME) for attributes in the node
else if the type is PrimNodeDefinitionType it contains data in the format for _write_usd_prim_definition
debug: If True then alll bundle inspector nodes are put into debug mode, printing their computed results
Returns:
Path to the generated USDA file. The caller is responsible for deleting the file when done.
"""
temp_fd = NamedTemporaryFile(mode="w+", suffix=".usda", delete=False) # noqa: PLR1732
out = ogt.IndentedOutput(temp_fd)
# Start with a basic scene containing two cubes and a gather node
out.write("#usda 1.0")
out.write("(")
out.write(' doc = """Bundle Inspection Node Test"""')
out.write(")")
out.write('def Xform "defaultPrim"')
if out.indent("{"):
for node_data in node_definitions:
if len(node_data) == 2:
_write_usd_prim_definition(node_data, out)
out.write('def ComputeGraph "graph"')
if out.indent("{"):
out.write('def ComputeGraphSettings "computegraphSettings"')
if out.indent("{"):
out.write('custom token evaluator:type = "dirty_push"')
out.exdent("}")
for node_data in node_definitions:
if len(node_data) != 4:
continue
(node_name, node_type, attribute_lines, _) = node_data
out.write(f'def ComputeNode "{node_name}"')
if out.indent("{"):
out.write(f'custom token node:type = "{node_type}"')
out.write("custom int node:typeVersion = 1")
for attribute_line in attribute_lines:
assign = " = true" if debug and attribute_line.find("inputs:print") >= 0 else ""
out.write(f"{attribute_line}{assign}")
out.exdent("}")
out.exdent("}")
out.exdent("}")
return temp_fd.name
# ======================================================================
@ogt.deprecated_function("Use og.Controller.edit() to set up a test scene")
async def set_up_test_stage(
node_definitions: List[Union[PrimNodeDefinitionType, OmniGraphNodeDefinitionType]], debug: bool = False
):
"""Set up an initial stage based on a specific node type and its attributes
Args:
node_definitions: List of (NODE_NAME, NODE_TYPE_NAME, LIST_OF_USD_ATTRIBUTE_DECLARATIONS, ATTRIBUTE_INFO)
debug: If True then all bundle inspector nodes are put into debug mode, printing their computed results
Returns:
Dictionary by name of a list of "Attribute" objects corresponding to the named attributes
"""
path_to_file = _generate_test_file(node_definitions, debug)
(result, error) = await ogts.load_test_file(path_to_file)
if not result:
raise ValueError(f"{error} on {path_to_file}")
attributes = {}
for node_data in node_definitions:
node_name = node_data[0]
test_node = og.get_current_graph().get_node(graph_node_path(node_name))
if len(node_data) == 4:
attribute_info = node_data[3]
attributes[node_name] = [
test_node.get_attribute(name) for attr_type, name in attribute_info if attr_type != "bundle"
]
await get_app().next_update_async()
return attributes
# ======================================================================
@ogt.deprecated_function("Use omni.graph.nodes.test.verify_bundles_are_equal()")
def compare_bundle_contents(inspector_attributes: List, bundle_inspector_output: Union[Dict[str, Any], List[Any]]):
"""Helper to compare the contents of two bundled attribute sets
Args:
inspector_attributes: Attribute list for the bundle inspector node
bundle_inspector_output: Outputs retrieved from the inspector in the format generated by
inspected_bundle_values() if it's a list, or the format generated by
bundle_inspector_values_as_dictionary() if it's a dictionary
Raises:
ValueError if any of the bundle output values do not match the expected ones
"""
# Mutating to a dictionary makes it easier to compare lists of lists
if isinstance(bundle_inspector_output, list):
bundled_size = bundle_inspector_output[0]
bundled_data = bundle_inspector_values_as_dictionary(bundle_inspector_output)
else:
# If the data is already in dictionary form no conversion is needed
bundled_size = len(bundle_inspector_output)
bundled_data = bundle_inspector_output
bundle_inspector_values = computed_bundle_values(inspector_attributes)
if bundled_size != bundle_inspector_values[0]:
raise ValueError(f"Bundled Count expected {bundled_size}, got {bundle_inspector_values[0]}")
computed_values = bundle_inspector_values_as_dictionary(bundle_inspector_values)
for attribute_name, attribute_values in computed_values.items():
expected_attribute_values = bundled_data[attribute_name]
for attribute_index, computed_value in enumerate(attribute_values):
# Bundled attribute types not yet supported by the bundle inspector are silently ignored
if isinstance(computed_value, (list, tuple)):
if "__unsupported__" in computed_value:
continue
else:
if computed_value == "__unsupported__":
continue
error_msg = f"Unexpected value on attribute {inspector_attributes[attribute_index + 2].get_name()}"
ogts.verify_values(expected_attribute_values[attribute_index], computed_value, error_msg)
# ======================================================================
@ogt.deprecated_function("Use omni.graph.nodes.test.verify_bundles_are_equal()")
def compare_bundle_inspector_results(
expected: BundleInspectorOutputType, actual: BundleInspectorOutputType, test: Optional[TestCase] = None
):
"""Helper to compare the expected outputs from a bundle inspector node
This uses the unit test framework for the comparisons.
Args:
expected: Values expected to be retrieved from the bundle inspector's outputs
actual: Outputs retrieved from the inspector
test: If not None then use it to report errors found, otherwise use a locally constructed TestCase
Raises:
ValueError if any of the bundle output values do not match the expected ones
"""
if test is None:
test = TestCase()
# Breaking open the tuples helps to clarify the operation being performed
(
expected_count,
expected_names,
expected_types,
expected_roles,
expected_array_depths,
expected_tuple_counts,
expected_values,
) = expected
(
actual_count,
actual_names,
actual_types,
actual_roles,
actual_array_depths,
actual_tuple_counts,
actual_values,
) = actual
test.assertEqual(actual_count, expected_count)
test.assertCountEqual(actual_names, expected_names)
test.assertCountEqual(actual_types, expected_types)
test.assertCountEqual(actual_roles, expected_roles)
test.assertCountEqual(actual_array_depths, expected_array_depths)
test.assertCountEqual(actual_tuple_counts, expected_tuple_counts)
for one_actual, one_expected in zip(actual_values, expected_values):
if isinstance(one_actual, list):
test.assertCountEqual(one_actual, one_expected)
else:
test.assertEqual(one_actual, one_expected)
# ==============================================================================================================
@ogt.deprecated_function("Use og.Controller.create_prim or og.Controller.edit for creating prims")
def create_prim_with_everything(prim_path: Optional[str] = None) -> Tuple[Usd.Prim, Dict[str, Any]]:
"""Deprecated function; should no longer be called"""
return (None, {})
| 24,152 | Python | 45.717601 | 120 | 0.611544 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_legacy_write_prims_node.py | r"""
_____ ______ _____ _____ ______ _____ _______ ______ _____
| __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \
| | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | |
| | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | |
| |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| |
|_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/
OgnWritePrims is deprecated. Use WritePrimsV2 instead.
Unit tests for the OgnWritePrims (Legacy) node, kept for maintaining backward compatibility.
For updated tests for OgnWritePrimsV2, find test_write_prims_node.py.
"""
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.commands
import omni.kit.stage_templates
import omni.kit.test
import omni.timeline
import omni.usd
from pxr import Usd, UsdGeom
from usdrt import Usd as UsdRT
# ======================================================================
class TestLegacyWritePrimNodes(ogts.OmniGraphTestCase):
TEST_GRAPH_PATH = "/World/TestGraph"
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_mpib(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims MPiB without bundle modification"""
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
controller = og.Controller()
keys = og.Controller.Keys
cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0))
cube2_prim = ogts.create_cube(stage, "Cube2", (0, 1, 0))
(graph, [read_prims_node, _], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrims"),
("Write", "omni.graph.nodes.WritePrims"),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube1_prim.GetPath(),
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube2_prim.GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph)
# Reading the prim into a bundle again must leave the attributes intact, as we didn't modify anything
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph)
graph_context = graph.get_default_graph_context()
output_prims_bundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
self.assertTrue(output_prims_bundle.valid)
child_bundles = output_prims_bundle.get_child_bundles()
self.assertEqual(len(child_bundles), 2)
expected_colors = {
"/Cube1": [[1.0, 0.0, 0.0]],
"/Cube2": [[0.0, 1.0, 0.0]],
}
for bundle in child_bundles:
path = bundle.get_attribute_by_name("sourcePrimPath").get()
expected_color = expected_colors[path]
self.assertNotEqual(expected_color, None)
# Check bundle values
self.assertListEqual(bundle.get_attribute_by_name("primvars:displayColor").get().tolist(), expected_color)
# Check USD prim values
prim = stage.GetPrimAtPath(path)
self.assertEqual([rgb[:] for rgb in prim.GetAttribute("primvars:displayColor").Get()], expected_color)
# Check Fabric prim values
prim_rt = stage_rt.GetPrimAtPath(path)
self.assertEqual([rgb[:] for rgb in prim_rt.GetAttribute("primvars:displayColor").Get()], expected_color)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_spib(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims SPiB without bundle modification"""
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
controller = og.Controller()
keys = og.Controller.Keys
cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0))
(graph, [read_prims_node, _, _], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrims"),
("ExtractCube1", "omni.graph.nodes.ExtractPrim"),
("Write", "omni.graph.nodes.WritePrims"),
],
keys.SET_VALUES: [
("ExtractCube1.inputs:primPath", "/Cube1"),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "ExtractCube1.inputs:prims"),
("ExtractCube1.outputs_primBundle", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube1_prim.GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph)
# Reading the prim into a bundle again must leave the attributes intact, as we didn't modify anything
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph)
graph_context = graph.get_default_graph_context()
output_prims_bundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
self.assertTrue(output_prims_bundle.valid)
child_bundles = output_prims_bundle.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
expected_colors = {
"/Cube1": [[1.0, 0.0, 0.0]],
}
for bundle in child_bundles:
path = bundle.get_attribute_by_name("sourcePrimPath").get()
expected_color = expected_colors[path]
self.assertNotEqual(expected_color, None)
# Check bundle values
self.assertListEqual(bundle.get_attribute_by_name("primvars:displayColor").get().tolist(), expected_color)
# Check USD prim values
prim = stage.GetPrimAtPath(path)
self.assertEqual([rgb[:] for rgb in prim.GetAttribute("primvars:displayColor").Get()], expected_color)
# Check Fabric prim values
prim_rt = stage_rt.GetPrimAtPath(path)
self.assertEqual([rgb[:] for rgb in prim_rt.GetAttribute("primvars:displayColor").Get()], expected_color)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_int_to_fabric(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims for an integer attribute, Fabric only"""
await self._read_write_prims_int(False)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_int_to_usd(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims for an integer attribute, writing back to USD"""
await self._read_write_prims_int(True)
# ----------------------------------------------------------------------
async def _read_write_prims_int(self, usd_write_back: bool):
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
controller = og.Controller()
keys = og.Controller.Keys
cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0))
cube2_prim = ogts.create_cube(stage, "Cube2", (0, 1, 0))
(graph, [extract_cube1, extract_cube2, *_], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ExtractCube1", "omni.graph.nodes.ExtractPrim"),
("ExtractCube2", "omni.graph.nodes.ExtractPrim"),
("Read", "omni.graph.nodes.ReadPrims"),
("Write", "omni.graph.nodes.WritePrims"),
("SizeCube1", "omni.graph.nodes.ConstantDouble"),
("SizeCube2", "omni.graph.nodes.ConstantDouble"),
("InsertSizeCube1", "omni.graph.nodes.InsertAttribute"),
("InsertSizeCube2", "omni.graph.nodes.InsertAttribute"),
],
keys.SET_VALUES: [
("ExtractCube1.inputs:primPath", "/Cube1"),
("ExtractCube2.inputs:primPath", "/Cube2"),
("SizeCube1.inputs:value", 200),
("SizeCube2.inputs:value", 300),
("InsertSizeCube1.inputs:outputAttrName", "size"),
("InsertSizeCube2.inputs:outputAttrName", "size"),
("Write.inputs:usdWriteBack", usd_write_back),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "ExtractCube1.inputs:prims"),
("Read.outputs_primsBundle", "ExtractCube2.inputs:prims"),
("SizeCube1.inputs:value", "InsertSizeCube1.inputs:attrToInsert"),
("SizeCube2.inputs:value", "InsertSizeCube2.inputs:attrToInsert"),
("ExtractCube1.outputs_primBundle", "InsertSizeCube1.inputs:data"),
("ExtractCube2.outputs_primBundle", "InsertSizeCube2.inputs:data"),
("InsertSizeCube1.outputs_data", "Write.inputs:primsBundle"),
("InsertSizeCube2.outputs_data", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube1_prim.GetPath(),
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube2_prim.GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph)
graph_context = graph.get_default_graph_context()
# Because we have feedback, the extract_cube1 bundle should have picked up the written attributes.
# TODO: Feedback will become optional one day!
cube1_bundle = graph_context.get_output_bundle(extract_cube1, "outputs_primBundle")
self.assertTrue(cube1_bundle.valid)
self.assertEqual(cube1_bundle.get_attribute_by_name("size").get(), 200)
# Because we have feedback, the extract_cube2 bundle should have picked up the written attributes.
# TODO: Feedback will become optional one day!
cube2_bundle = graph_context.get_output_bundle(extract_cube2, "outputs_primBundle")
self.assertTrue(cube2_bundle.valid)
self.assertEqual(cube2_bundle.get_attribute_by_name("size").get(), 300)
# Check USD write-back
self.assertEqual(cube1_prim.GetAttribute("size").Get(), 200 if usd_write_back else 1)
self.assertEqual(cube2_prim.GetAttribute("size").Get(), 300 if usd_write_back else 1)
# Check Fabric values
self.assertEqual(stage_rt.GetPrimAtPath("/Cube1").GetAttribute("size").Get(), 200)
self.assertEqual(stage_rt.GetPrimAtPath("/Cube2").GetAttribute("size").Get(), 300)
# Make sure the prim-bundle internal attributes are not written to the USD prim
for attr_name in ["sourcePrimPath", "sourcePrimType"]:
self.assertEqual(cube1_prim.HasAttribute(attr_name), False)
self.assertEqual(cube2_prim.HasAttribute(attr_name), False)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_translate_only(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims using an attribute pattern to just translate"""
await self._test_read_write_prims_patterns(
"xformOp:trans*",
None,
None,
[
[(1.0, 2.0, 3.0), (0.0, 0.0, 0.0)],
[(4.0, 5.0, 6.0), (0.0, 0.0, 0.0)],
],
)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_rotate_only(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims using an attribute pattern to just rotate"""
await self._test_read_write_prims_patterns(
"xformOp:rotate*",
None,
None,
[
[(0.0, 0.0, 0.0), (7.0, 8.0, 9.0)],
[(0.0, 0.0, 0.0), (10.0, 11.0, 12.0)],
],
)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_xform_only(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims using an attribute pattern to translate and rotate"""
await self._test_read_write_prims_patterns(
"xformOp:*",
None,
None,
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_shape1_only(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims using an path pattern to limit writing to Shape1 only"""
await self._test_read_write_prims_patterns(
None,
"/Shape1",
None,
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
],
)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_shape2_only(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims using an path pattern to limit writing to Shape2 only"""
await self._test_read_write_prims_patterns(
None,
"/Shape2",
None,
[
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_both_shapes(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims using an path pattern to write to both shapes"""
await self._test_read_write_prims_patterns(
None,
"/Shape*",
None,
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_cube_only(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims using an path pattern to limit writing to cubes only"""
await self._test_read_write_prims_patterns(
None,
None,
"Cube",
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
],
)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_cone_only(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims using an type pattern to limit writing to cones only"""
await self._test_read_write_prims_patterns(
None,
None,
"Cone",
[
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_cube_and_cone(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims using an type pattern to write to both cubes and cones"""
await self._test_read_write_prims_patterns(
None,
None,
"Cone;Cube",
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
)
# ----------------------------------------------------------------------
async def _test_read_write_prims_patterns(self, attr_pattern, path_pattern, type_pattern, expected_prim_values):
# No need to test USD write back in this unit tests, other tests do this.
usd_write_back = False
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
controller = og.Controller()
keys = og.Controller.Keys
cube_prim = ogts.create_cube(stage, "Shape1", (1, 0, 0))
cone_prim = ogts.create_cone(stage, "Shape2", (0, 1, 0))
# add transforms with double precision
xform_precision = UsdGeom.XformOp.PrecisionDouble
for prim in [cube_prim, cone_prim]:
UsdGeom.Xformable(prim).AddTranslateOp(xform_precision).Set((0, 0, 0))
UsdGeom.Xformable(prim).AddRotateXYZOp(xform_precision).Set((0, 0, 0))
UsdGeom.Xformable(prim).AddScaleOp(xform_precision).Set((1, 1, 1))
set_values = [
("ExtractCube.inputs:primPath", "/Shape1"),
("ExtractCone.inputs:primPath", "/Shape2"),
("TranslateCube.inputs:value", (1, 2, 3)),
("TranslateCone.inputs:value", (4, 5, 6)),
("RotateCube.inputs:value", (7, 8, 9)),
("RotateCone.inputs:value", (10, 11, 12)),
("InsertTranslateCube.inputs:outputAttrName", "xformOp:translate"),
("InsertTranslateCone.inputs:outputAttrName", "xformOp:translate"),
("InsertRotateCube.inputs:outputAttrName", "xformOp:rotateXYZ"),
("InsertRotateCone.inputs:outputAttrName", "xformOp:rotateXYZ"),
("Write.inputs:usdWriteBack", usd_write_back),
]
if attr_pattern:
set_values.append(("Write.inputs:attrNamesToExport", attr_pattern))
if path_pattern:
set_values.append(("Write.inputs:pathPattern", path_pattern))
if type_pattern:
set_values.append(("Write.inputs:typePattern", type_pattern))
(graph, [extract_cube, extract_cone, *_], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ExtractCube", "omni.graph.nodes.ExtractPrim"),
("ExtractCone", "omni.graph.nodes.ExtractPrim"),
("Read", "omni.graph.nodes.ReadPrims"),
("Write", "omni.graph.nodes.WritePrims"),
("TranslateCube", "omni.graph.nodes.ConstantDouble3"),
("TranslateCone", "omni.graph.nodes.ConstantDouble3"),
("RotateCube", "omni.graph.nodes.ConstantDouble3"),
("RotateCone", "omni.graph.nodes.ConstantDouble3"),
("InsertTranslateCube", "omni.graph.nodes.InsertAttribute"),
("InsertTranslateCone", "omni.graph.nodes.InsertAttribute"),
("InsertRotateCube", "omni.graph.nodes.InsertAttribute"),
("InsertRotateCone", "omni.graph.nodes.InsertAttribute"),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "ExtractCube.inputs:prims"),
("Read.outputs_primsBundle", "ExtractCone.inputs:prims"),
("TranslateCube.inputs:value", "InsertTranslateCube.inputs:attrToInsert"),
("TranslateCone.inputs:value", "InsertTranslateCone.inputs:attrToInsert"),
("RotateCube.inputs:value", "InsertRotateCube.inputs:attrToInsert"),
("RotateCone.inputs:value", "InsertRotateCone.inputs:attrToInsert"),
("ExtractCube.outputs_primBundle", "InsertTranslateCube.inputs:data"),
("ExtractCone.outputs_primBundle", "InsertTranslateCone.inputs:data"),
("InsertTranslateCube.outputs_data", "InsertRotateCube.inputs:data"),
("InsertTranslateCone.outputs_data", "InsertRotateCone.inputs:data"),
("InsertRotateCube.outputs_data", "Write.inputs:primsBundle"),
("InsertRotateCone.outputs_data", "Write.inputs:primsBundle"),
],
keys.SET_VALUES: set_values,
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube_prim.GetPath(),
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cone_prim.GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph)
graph_context = graph.get_default_graph_context()
cube_bundle = graph_context.get_output_bundle(extract_cube, "outputs_primBundle")
cone_bundle = graph_context.get_output_bundle(extract_cone, "outputs_primBundle")
prim_bundles = [cube_bundle, cone_bundle]
prim_paths = ["/Shape1", "/Shape2"]
# We will check these attributes
attr_names = ["xformOp:translate", "xformOp:rotateXYZ"]
# We need two lists of values, one for each prim
self.assertEqual(len(expected_prim_values), 2)
for prim_index, prim_bundle in enumerate(prim_bundles):
expected_values = expected_prim_values[prim_index]
# All attribute values must be passed
self.assertEqual(len(expected_values), len(attr_names))
prim_rt = stage_rt.GetPrimAtPath(prim_paths[prim_index])
# Check attributes values in prim bundle
for attr_index, expected_value in enumerate(expected_values):
attr_name = attr_names[attr_index]
# Because we have feedback, the bundle should have picked up the written attributes.
# TODO: Feedback will become optional one day!
actual_value = tuple(prim_bundle.get_attribute_by_name(attr_name).get())
self.assertEqual(actual_value, expected_value)
# Check Fabric values
actual_value_rt = tuple(prim_rt.GetAttribute(attr_name).Get())
self.assertEqual(actual_value_rt, expected_value)
# Make sure the prim-bundle internal attributes are not written to the USD prim
for attr_name in ["sourcePrimPath", "sourcePrimType"]:
self.assertEqual(cube_prim.HasAttribute(attr_name), False)
self.assertEqual(cone_prim.HasAttribute(attr_name), False)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_array_new_attr_to_fabric(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims for a new array attribute, Fabric only"""
await self._test_read_write_prims_vec3_array(False, False)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_array_new_attr_to_usd(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims for a new array attribute, writing back to USD"""
await self._test_read_write_prims_vec3_array(True, False)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_array_attr_to_fabric(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims for an existing array attribute, Fabric only"""
await self._test_read_write_prims_vec3_array(False, True)
# ----------------------------------------------------------------------
async def test_legacy_read_write_prims_array_attr_to_usd(self):
"""Test omni.graph.nodes.ReadPrims and WritePrims for an existing array attribute, writing back to USD"""
await self._test_read_write_prims_vec3_array(True, True)
# ----------------------------------------------------------------------
async def _test_read_write_prims_vec3_array(self, usd_write_back: bool, add_new_attr: bool):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
cube_prim = ogts.create_cube(stage, "Cube", (1, 0, 0))
controller = og.Controller()
keys = og.Controller.Keys
attr_name = "new_array_attr" if add_new_attr else "primvars:displayColor"
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrims"),
("Write", "omni.graph.nodes.WritePrims"),
("ExtractCube", "omni.graph.nodes.ExtractPrim"),
("MakeArray", "omni.graph.nodes.ConstructArray"),
("InsertAttribute", "omni.graph.nodes.InsertAttribute"),
],
keys.SET_VALUES: [
("ExtractCube.inputs:primPath", "/Cube"),
("MakeArray.inputs:arraySize", 1),
("MakeArray.inputs:arrayType", "float[3][]"),
("MakeArray.inputs:input0", [0.25, 0.50, 0.75]),
("InsertAttribute.inputs:outputAttrName", attr_name),
("Write.inputs:usdWriteBack", usd_write_back),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "ExtractCube.inputs:prims"),
("ExtractCube.outputs_primBundle", "InsertAttribute.inputs:data"),
("MakeArray.outputs:array", "InsertAttribute.inputs:attrToInsert"),
("InsertAttribute.outputs_data", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube_prim.GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph)
graph_context = graph.get_default_graph_context()
cube_bundle = graph_context.get_output_bundle(nodes[2], "outputs_primBundle")
self.assertTrue(cube_bundle.valid)
# Because we have feedback, the bundle should have picked up the written attributes.
# TODO: Feedback will become optional one day!
feedback_values = cube_bundle.get_attribute_by_name(attr_name).get()
self.assertEqual(len(feedback_values), 1)
self.assertEqual(tuple(feedback_values[0]), (0.25, 0.50, 0.75))
# Check Fabric values
fabric_values = stage_rt.GetPrimAtPath("/Cube").GetAttribute(attr_name).Get()
self.assertEqual(len(fabric_values), 1)
self.assertEqual(tuple(fabric_values[0]), (0.25, 0.50, 0.75))
if usd_write_back:
# With USD write back, the existing attribute should be updated in USD
usd_values = stage.GetPrimAtPath("/Cube").GetAttribute(attr_name).Get()
self.assertEqual(len(usd_values), 1)
self.assertEqual(tuple(usd_values[0]), (0.25, 0.50, 0.75))
elif add_new_attr:
# Without USD write back, the new attribute should not exist in USD.
self.assertFalse(stage.GetPrimAtPath("/Cube").HasAttribute(attr_name))
else:
# Without USD write back, the existing attribute should not be updated in USD
usd_values = stage.GetPrimAtPath("/Cube").GetAttribute(attr_name).Get()
self.assertEqual(len(usd_values), 1)
self.assertEqual(tuple(usd_values[0]), (1, 0, 0))
# ----------------------------------------------------------------------
# Helpers
def _assert_no_compute_messages(self, graph):
graph_nodes = graph.get_nodes()
for severity in [og.WARNING, og.ERROR]:
for node in graph_nodes:
self.assertEqual(node.get_compute_messages(severity), [])
async def _evaluate_graph(self, graph, controller):
await omni.kit.app.get_app().next_update_async()
await controller.evaluate(graph)
| 29,141 | Python | 44.820755 | 118 | 0.540887 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_write_prims_node.py | # noqa: PLC0302
"""Unit tests for the OgnWritePrims node in this extension"""
import fnmatch
import os
import tempfile
import carb
import omni.graph.core as og
import omni.graph.core.autonode as oga
import omni.graph.core.tests as ogts
import omni.kit.commands
import omni.kit.stage_templates
import omni.kit.test
import omni.timeline
import omni.usd
from pxr import Sdf, Usd, UsdGeom
from usdrt import Sdf as SdfRT
from usdrt import Usd as UsdRT
# Define a test node that has one relationship in the bundle
# This will be used to test WritePrimsV2 node's Relationship exporting
REL_BUNDLE_TRL_NAME = "test_rel"
REL_BUNDLE_TARGETS = [Sdf.Path("/Foo/bar"), Sdf.Path("/Foo/baz")]
REL_BUNDLE_TARGETS_RT = [SdfRT.Path(path.pathString) for path in REL_BUNDLE_TARGETS]
@oga.AutoFunc(module_name="__test_write_prims_v2__", pure=True)
def relationship_bundle() -> og.Bundle:
bundle = og.Bundle("return", False)
bundle.create_attribute(REL_BUNDLE_TRL_NAME, og.Type(og.BaseDataType.RELATIONSHIP, 1, 1)).value = REL_BUNDLE_TARGETS
return bundle
# ======================================================================
# because the child bundle's order inside of bundle is non-deterministic, WritePrims node sort the bundle content
# according to sourcePrimPath when scatter_under_targets mode is off
def sort_child_bundles(child_bundles, scatter_under_targets: bool):
# do not sort if scatter_under_targets
if scatter_under_targets:
return child_bundles
child_bundles.sort(key=lambda x: x.get_attribute_by_name("sourcePrimPath").get())
return child_bundles
# ======================================================================
class TestWritePrimNodes(ogts.OmniGraphTestCase):
TEST_GRAPH_PATH = "/World/TestGraph"
# ----------------------------------------------------------------------
async def test_read_write_prims_mpib(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB without bundle modification and output to targets"""
await self._test_read_write_prims_mpib_impl(False)
# ----------------------------------------------------------------------
async def test_read_write_prims_mpib_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB without bundle modification and scatter under targets"""
await self._test_read_write_prims_mpib_impl(True)
# ----------------------------------------------------------------------
async def _test_read_write_prims_mpib_impl(self, scatter_under_targets: bool):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB without bundle modification"""
target_prim_paths = ["/target0", "/target1"]
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
controller = og.Controller()
keys = og.Controller.Keys
cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0))
cube2_prim = ogts.create_cube(stage, "Cube2", (0, 1, 0))
(graph, [read_prims_node, _], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("Write.inputs:scatterUnderTargets", scatter_under_targets),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
targets=[cube1_prim.GetPath(), cube2_prim.GetPath()],
)
for target_path in target_prim_paths:
target_xform = UsdGeom.Xform.Define(stage, target_path)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
target=target_xform.GetPrim().GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# Reading the prim into a bundle again must leave the attributes intact, as we didn't modify anything
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
graph_context = graph.get_default_graph_context()
output_prims_bundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
self.assertTrue(output_prims_bundle.valid)
child_bundles = output_prims_bundle.get_child_bundles()
self.assertEqual(len(child_bundles), 2)
expected_colors = {
"/Cube1": [[1.0, 0.0, 0.0]],
"/Cube2": [[0.0, 1.0, 0.0]],
}
child_bundles = sort_child_bundles(child_bundles, scatter_under_targets)
for i, bundle in enumerate(child_bundles):
path = bundle.get_attribute_by_name("sourcePrimPath").get()
expected_color = expected_colors[path]
self.assertNotEqual(expected_color, None)
# Check bundle values
self.assertListEqual(bundle.get_attribute_by_name("primvars:displayColor").get().tolist(), expected_color)
def check_prim_values(source_prim_path, target_prim_path, expected_color):
# Check USD prim values
prim = stage.GetPrimAtPath(source_prim_path)
self.assertEqual([rgb[:] for rgb in prim.GetAttribute("primvars:displayColor").Get()], expected_color)
# Check Fabric prim values
prim_rt = stage_rt.GetPrimAtPath(source_prim_path)
self.assertTrue(prim_rt.IsValid())
self.assertEqual(
[rgb[:] for rgb in prim_rt.GetAttribute("primvars:displayColor").Get()], expected_color
)
# Check target Fabric prim values
prim_rt = stage_rt.GetPrimAtPath(target_prim_path)
self.assertTrue(prim_rt.IsValid())
self.assertEqual(
[rgb[:] for rgb in prim_rt.GetAttribute("primvars:displayColor").Get()], expected_color
)
if scatter_under_targets:
for target_prim_path in target_prim_paths:
check_prim_values(path, target_prim_path + path, expected_color)
else:
check_prim_values(path, target_prim_paths[i], expected_color)
# ----------------------------------------------------------------------
async def test_read_write_prims_spib(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims SPiB without bundle modification and output to targets"""
await self._test_read_write_prims_spib_impl(False)
# ----------------------------------------------------------------------
async def test_read_write_prims_spib_no_source_prim_info(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims SPiB without bundle modification and output to targets"""
await self._test_read_write_prims_spib_impl(False, True)
# ----------------------------------------------------------------------
async def test_read_write_prims_spib_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims SPiB without bundle modification and scatter under targets"""
await self._test_read_write_prims_spib_impl(True)
# ----------------------------------------------------------------------
async def _test_read_write_prims_spib_impl(
self, scatter_under_targets: bool, remove_source_prim_info: bool = False
):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims SPiB without bundle modification"""
target_prim_paths = ["/target0", "/target1"]
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
controller = og.Controller()
keys = og.Controller.Keys
cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0))
(graph, [read_prims_node, *_], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("ExtractCube1", "omni.graph.nodes.ExtractPrim"),
("RemoveAttrs", "omni.graph.nodes.RemoveAttribute"),
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("ExtractCube1.inputs:primPath", "/Cube1"),
("RemoveAttrs.inputs:allowRemovePrimInternal", True),
(
"RemoveAttrs.inputs:attrNamesToRemove",
"sourcePrimPath;sourcePrimType" if remove_source_prim_info else "",
),
("Write.inputs:scatterUnderTargets", scatter_under_targets),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "ExtractCube1.inputs:prims"),
("ExtractCube1.outputs_primBundle", "RemoveAttrs.inputs:data"),
("RemoveAttrs.outputs_data", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube1_prim.GetPath(),
)
for target_path in target_prim_paths:
target_xform = UsdGeom.Xform.Define(stage, target_path)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
target=target_xform.GetPrim().GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# Reading the prim into a bundle again must leave the attributes intact, as we didn't modify anything
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
graph_context = graph.get_default_graph_context()
output_prims_bundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
self.assertTrue(output_prims_bundle.valid)
child_bundles = output_prims_bundle.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
expected_colors = {
"/Cube1": [[1.0, 0.0, 0.0]],
}
child_bundles = sort_child_bundles(child_bundles, scatter_under_targets)
for i, bundle in enumerate(child_bundles):
path = bundle.get_attribute_by_name("sourcePrimPath").get()
expected_color = expected_colors[path]
self.assertNotEqual(expected_color, None)
# Check bundle values
self.assertListEqual(bundle.get_attribute_by_name("primvars:displayColor").get().tolist(), expected_color)
def check_prim_values(target_prim_path, expected_color):
# Check Target USD prim values
prim = stage.GetPrimAtPath(target_prim_path)
# if source prim info is removed, the target prim type should not change. Otherwise it changes from Xform to Cube
self.assertEqual(prim.GetTypeName(), "Xform" if remove_source_prim_info else "Cube")
self.assertEqual([rgb[:] for rgb in prim.GetAttribute("primvars:displayColor").Get()], expected_color)
# Check Target Fabric prim values
prim_rt = stage_rt.GetPrimAtPath(target_prim_path)
self.assertEqual(
[rgb[:] for rgb in prim_rt.GetAttribute("primvars:displayColor").Get()], expected_color
)
if scatter_under_targets:
for target_prim_path in target_prim_paths:
check_prim_values(target_prim_path + path, expected_color)
else:
check_prim_values(target_prim_paths[i], expected_color)
# ----------------------------------------------------------------------
async def test_read_write_prims_int_to_fabric(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an integer attribute, Fabric only"""
await self._read_write_prims_int(False, False)
# ----------------------------------------------------------------------
async def test_read_write_prims_int_to_fabric_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an integer attribute, Fabric only"""
await self._read_write_prims_int(False, True)
# ----------------------------------------------------------------------
async def test_read_write_prims_int_to_usd(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an integer attribute, writing back to USD"""
await self._read_write_prims_int(True, False)
# ----------------------------------------------------------------------
async def test_read_write_prims_int_to_usd_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an integer attribute, writing back to USD"""
await self._read_write_prims_int(True, True)
# ----------------------------------------------------------------------
async def _read_write_prims_int(self, usd_write_back: bool, scatter_under_targets: bool):
target_prim_paths = ["/target0", "/target1"]
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
controller = og.Controller()
keys = og.Controller.Keys
cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0))
cube2_prim = ogts.create_cube(stage, "Cube2", (0, 1, 0))
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ExtractCube1", "omni.graph.nodes.ExtractPrim"),
("ExtractCube2", "omni.graph.nodes.ExtractPrim"),
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Write", "omni.graph.nodes.WritePrimsV2"),
("SizeCube1", "omni.graph.nodes.ConstantDouble"),
("SizeCube2", "omni.graph.nodes.ConstantDouble"),
("InsertSizeCube1", "omni.graph.nodes.InsertAttribute"),
("InsertSizeCube2", "omni.graph.nodes.InsertAttribute"),
],
keys.SET_VALUES: [
("ExtractCube1.inputs:primPath", "/Cube1"),
("ExtractCube2.inputs:primPath", "/Cube2"),
("SizeCube1.inputs:value", 200),
("SizeCube2.inputs:value", 300),
("InsertSizeCube1.inputs:outputAttrName", "size"),
("InsertSizeCube2.inputs:outputAttrName", "size"),
("Write.inputs:usdWriteBack", usd_write_back),
("Write.inputs:scatterUnderTargets", scatter_under_targets),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "ExtractCube1.inputs:prims"),
("Read.outputs_primsBundle", "ExtractCube2.inputs:prims"),
("SizeCube1.inputs:value", "InsertSizeCube1.inputs:attrToInsert"),
("SizeCube2.inputs:value", "InsertSizeCube2.inputs:attrToInsert"),
("ExtractCube1.outputs_primBundle", "InsertSizeCube1.inputs:data"),
("ExtractCube2.outputs_primBundle", "InsertSizeCube2.inputs:data"),
("InsertSizeCube1.outputs_data", "Write.inputs:primsBundle"),
("InsertSizeCube2.outputs_data", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
targets=[cube1_prim.GetPath(), cube2_prim.GetPath()],
)
for target_path in target_prim_paths:
target_xform = UsdGeom.Xform.Define(stage, target_path)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
target=target_xform.GetPrim().GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
def check_prim_values(cube_1_path, cube_2_path):
if usd_write_back:
# Check USD write-back
cube1_prim_target = stage.GetPrimAtPath(cube_1_path)
cube2_prim_target = stage.GetPrimAtPath(cube_2_path)
self.assertEqual(cube1_prim_target.GetAttribute("size").Get(), 200 if usd_write_back else 1)
self.assertEqual(cube2_prim_target.GetAttribute("size").Get(), 300 if usd_write_back else 1)
# Make sure the prim-bundle internal attributes are not written to the USD prim
for attr_name in ["sourcePrimPath", "sourcePrimType"]:
self.assertEqual(cube1_prim_target.HasAttribute(attr_name), False)
self.assertEqual(cube2_prim_target.HasAttribute(attr_name), False)
# Check Fabric values
self.assertEqual(stage_rt.GetPrimAtPath(cube_1_path).GetAttribute("size").Get(), 200)
self.assertEqual(stage_rt.GetPrimAtPath(cube_2_path).GetAttribute("size").Get(), 300)
if scatter_under_targets:
for target_prim_path in target_prim_paths:
check_prim_values(target_prim_path + "/Cube1", target_prim_path + "/Cube2")
else:
check_prim_values(target_prim_paths[0], target_prim_paths[1])
# ----------------------------------------------------------------------
async def test_read_write_prims_translate_only(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to just translate"""
await self._test_read_write_prims_patterns(
"xformOp:trans*",
None,
None,
[
[(1.0, 2.0, 3.0), (0.0, 0.0, 0.0)],
[(4.0, 5.0, 6.0), (0.0, 0.0, 0.0)],
],
False,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_translate_only_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to just translate"""
await self._test_read_write_prims_patterns(
"xformOp:trans*",
None,
None,
[
[(1.0, 2.0, 3.0), (0.0, 0.0, 0.0)],
[(4.0, 5.0, 6.0), (0.0, 0.0, 0.0)],
],
True,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_rotate_only(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to just rotate"""
await self._test_read_write_prims_patterns(
"xformOp:rotate*",
None,
None,
[
[(0.0, 0.0, 0.0), (7.0, 8.0, 9.0)],
[(0.0, 0.0, 0.0), (10.0, 11.0, 12.0)],
],
False,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_rotate_only_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to just rotate"""
await self._test_read_write_prims_patterns(
"xformOp:rotate*",
None,
None,
[
[(0.0, 0.0, 0.0), (7.0, 8.0, 9.0)],
[(0.0, 0.0, 0.0), (10.0, 11.0, 12.0)],
],
True,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_xform_only(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to translate and rotate"""
await self._test_read_write_prims_patterns(
"xformOp:*",
None,
None,
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
False,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_xform_only_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to translate and rotate"""
await self._test_read_write_prims_patterns(
"xformOp:*",
None,
None,
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
True,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_shape1_only(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to Shape1 only"""
await self._test_read_write_prims_patterns(
None,
"/Shape1",
None,
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
],
False,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_shape1_only_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to Shape1 only"""
await self._test_read_write_prims_patterns(
None,
"/Shape1",
None,
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
],
True,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_shape2_only(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to Shape2 only"""
await self._test_read_write_prims_patterns(
None,
"/Shape2",
None,
[
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
False,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_shape2_only_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to Shape2 only"""
await self._test_read_write_prims_patterns(
None,
"/Shape2",
None,
[
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
True,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_both_shapes(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to write to both shapes"""
await self._test_read_write_prims_patterns(
None,
"/Shape*",
None,
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
False,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_both_shapes_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to write to both shapes"""
await self._test_read_write_prims_patterns(
None,
"/Shape*",
None,
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
True,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_cube_only(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to cubes only"""
await self._test_read_write_prims_patterns(
None,
None,
"Cube",
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
],
False,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_cube_only_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to cubes only"""
await self._test_read_write_prims_patterns(
None,
None,
"Cube",
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
],
True,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_cone_only(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an type pattern to limit writing to cones only"""
await self._test_read_write_prims_patterns(
None,
None,
"Cone",
[
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
False,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_cone_only_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an type pattern to limit writing to cones only"""
await self._test_read_write_prims_patterns(
None,
None,
"Cone",
[
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
True,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_cube_and_cone(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an type pattern to write to both cubes and cones"""
await self._test_read_write_prims_patterns(
None,
None,
"Cone;Cube",
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
False,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_cube_and_cone_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an type pattern to write to both cubes and cones"""
await self._test_read_write_prims_patterns(
None,
None,
"Cone;Cube",
[
[(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)],
[(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)],
],
True,
)
# ----------------------------------------------------------------------
async def _test_read_write_prims_patterns(
self, attr_pattern, path_pattern, type_pattern, expected_prim_values, scatter_under_targets: bool
):
target_prim_paths = ["/target0", "/target1"]
# test USD write back since it's the main workflow currently
usd_write_back = True
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
controller = og.Controller()
keys = og.Controller.Keys
cube_prim = ogts.create_cube(stage, "Shape1", (1, 0, 0))
cone_prim = ogts.create_cone(stage, "Shape2", (0, 1, 0))
# add transforms with double precision
xform_precision = UsdGeom.XformOp.PrecisionDouble
for prim in [cube_prim, cone_prim]:
UsdGeom.Xformable(prim).AddTranslateOp(xform_precision).Set((0, 0, 0))
UsdGeom.Xformable(prim).AddRotateXYZOp(xform_precision).Set((0, 0, 0))
UsdGeom.Xformable(prim).AddScaleOp(xform_precision).Set((1, 1, 1))
set_values = [
("ExtractCube.inputs:primPath", "/Shape1"),
("ExtractCone.inputs:primPath", "/Shape2"),
("TranslateCube.inputs:value", (1, 2, 3)),
("TranslateCone.inputs:value", (4, 5, 6)),
("RotateCube.inputs:value", (7, 8, 9)),
("RotateCone.inputs:value", (10, 11, 12)),
("InsertTranslateCube.inputs:outputAttrName", "xformOp:translate"),
("InsertTranslateCone.inputs:outputAttrName", "xformOp:translate"),
("InsertRotateCube.inputs:outputAttrName", "xformOp:rotateXYZ"),
("InsertRotateCone.inputs:outputAttrName", "xformOp:rotateXYZ"),
("Write.inputs:usdWriteBack", usd_write_back),
("Write.inputs:scatterUnderTargets", scatter_under_targets),
]
if attr_pattern:
set_values.append(("Write.inputs:attrNamesToExport", attr_pattern))
if path_pattern:
set_values.append(("Write.inputs:pathPattern", path_pattern))
if type_pattern:
set_values.append(("Write.inputs:typePattern", type_pattern))
(graph, [extract_cube, extract_cone, *_], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ExtractCube", "omni.graph.nodes.ExtractPrim"),
("ExtractCone", "omni.graph.nodes.ExtractPrim"),
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Write", "omni.graph.nodes.WritePrimsV2"),
("TranslateCube", "omni.graph.nodes.ConstantDouble3"),
("TranslateCone", "omni.graph.nodes.ConstantDouble3"),
("RotateCube", "omni.graph.nodes.ConstantDouble3"),
("RotateCone", "omni.graph.nodes.ConstantDouble3"),
("InsertTranslateCube", "omni.graph.nodes.InsertAttribute"),
("InsertTranslateCone", "omni.graph.nodes.InsertAttribute"),
("InsertRotateCube", "omni.graph.nodes.InsertAttribute"),
("InsertRotateCone", "omni.graph.nodes.InsertAttribute"),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "ExtractCube.inputs:prims"),
("Read.outputs_primsBundle", "ExtractCone.inputs:prims"),
("TranslateCube.inputs:value", "InsertTranslateCube.inputs:attrToInsert"),
("TranslateCone.inputs:value", "InsertTranslateCone.inputs:attrToInsert"),
("RotateCube.inputs:value", "InsertRotateCube.inputs:attrToInsert"),
("RotateCone.inputs:value", "InsertRotateCone.inputs:attrToInsert"),
("ExtractCube.outputs_primBundle", "InsertTranslateCube.inputs:data"),
("ExtractCone.outputs_primBundle", "InsertTranslateCone.inputs:data"),
("InsertTranslateCube.outputs_data", "InsertRotateCube.inputs:data"),
("InsertTranslateCone.outputs_data", "InsertRotateCone.inputs:data"),
("InsertRotateCube.outputs_data", "Write.inputs:primsBundle"),
("InsertRotateCone.outputs_data", "Write.inputs:primsBundle"),
],
keys.SET_VALUES: set_values,
},
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
targets=[cube_prim.GetPath(), cone_prim.GetPath()],
)
for target_path in target_prim_paths:
target_xform = UsdGeom.Xform.Define(stage, target_path)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
target=target_xform.GetPrim().GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
graph_context = graph.get_default_graph_context()
cube_bundle = graph_context.get_output_bundle(extract_cube, "outputs_primBundle")
cone_bundle = graph_context.get_output_bundle(extract_cone, "outputs_primBundle")
prim_bundles = [cube_bundle, cone_bundle]
prim_paths = ["/Shape1", "/Shape2"]
prim_types = ["Cube", "Cone"]
# We will check these attributes
attr_names = ["xformOp:translate", "xformOp:rotateXYZ"]
# We need two lists of values, one for each prim
self.assertEqual(len(expected_prim_values), 2)
attr_pattern_tokens = attr_pattern.split(";") if attr_pattern else []
path_pattern_tokens = path_pattern.split(";") if path_pattern else []
type_pattern_tokens = type_pattern.split(";") if type_pattern else []
for prim_index, _prim_bundle in enumerate(prim_bundles):
expected_values = expected_prim_values[prim_index]
# All attribute values must be passed
self.assertEqual(len(expected_values), len(attr_names))
# Check attributes values in prim bundle
for attr_index, expected_value in enumerate(expected_values):
attr_name = attr_names[attr_index]
def check_prim_values(source_prim_path, target_prim_path, prim_type, attr_name, expected_value):
if usd_write_back:
prim = stage.GetPrimAtPath(target_prim_path)
else:
prim = stage_rt.GetPrimAtPath(target_prim_path)
# to emulate matcher behavior
attr_matched = True
if attr_pattern_tokens:
attr_matched = False
for token in attr_pattern_tokens:
attr_matched |= fnmatch.fnmatch(attr_name, token)
if attr_matched:
break
prim_matched = True
if path_pattern_tokens:
path_matched = False
for token in path_pattern_tokens:
path_matched |= fnmatch.fnmatch(source_prim_path, token)
prim_matched &= path_matched
if type_pattern_tokens:
type_matched = False
for token in type_pattern_tokens:
type_matched |= fnmatch.fnmatch(prim_type, token)
prim_matched &= type_matched
# Check values
if prim_matched:
if usd_write_back:
# usdrt syncs usd prim type if only change the type in fabric
self.assertEqual(prim.GetTypeName(), prim_type)
if attr_matched:
actual_value_rt = tuple(prim.GetAttribute(attr_name).Get())
self.assertEqual(actual_value_rt, expected_value)
else:
# if attribute does not match, it won't be exported
self.assertFalse(prim.GetAttribute(attr_name).IsValid())
else:
if scatter_under_targets:
# if unmatched, the target prim won't exist if filter failed
self.assertFalse(prim.IsValid())
else:
# if unmatched, the prim type won't change from xform to cube/cone
self.assertTrue(prim.IsValid())
self.assertEqual(prim.GetTypeName(), "Xform")
if scatter_under_targets:
for target_prim_path in target_prim_paths:
check_prim_values(
prim_paths[prim_index],
target_prim_path + prim_paths[prim_index],
prim_types[prim_index],
attr_name,
expected_value,
)
else:
check_prim_values(
prim_paths[prim_index],
target_prim_paths[prim_index],
prim_types[prim_index],
attr_name,
expected_value,
)
# ----------------------------------------------------------------------
async def test_read_write_prims_array_new_attr_to_fabric(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for a new array attribute, Fabric only"""
await self._test_read_write_prims_vec3_array(False, False, False)
# ----------------------------------------------------------------------
async def test_read_write_prims_array_new_attr_to_fabric_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for a new array attribute, Fabric only"""
await self._test_read_write_prims_vec3_array(False, False, True)
# ----------------------------------------------------------------------
async def test_read_write_prims_array_new_attr_to_usd(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for a new array attribute, writing back to USD"""
await self._test_read_write_prims_vec3_array(True, False, False)
# ----------------------------------------------------------------------
async def test_read_write_prims_array_new_attr_to_usd_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for a new array attribute, writing back to USD"""
await self._test_read_write_prims_vec3_array(True, False, True)
# ----------------------------------------------------------------------
async def test_read_write_prims_array_attr_to_fabric(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an existing array attribute, Fabric only"""
await self._test_read_write_prims_vec3_array(False, True, False)
# ----------------------------------------------------------------------
async def test_read_write_prims_array_attr_to_fabric_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an existing array attribute, Fabric only"""
await self._test_read_write_prims_vec3_array(False, True, True)
# ----------------------------------------------------------------------
async def test_read_write_prims_array_attr_to_usd(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an existing array attribute, writing back to USD"""
await self._test_read_write_prims_vec3_array(True, True, False)
# ----------------------------------------------------------------------
async def test_read_write_prims_array_attr_to_usd_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an existing array attribute, writing back to USD"""
await self._test_read_write_prims_vec3_array(True, True, True)
# ----------------------------------------------------------------------
async def _test_read_write_prims_vec3_array(
self, usd_write_back: bool, add_new_attr: bool, scatter_under_targets: bool
):
target_prim_paths = ["/target0", "/target1"]
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
cube_prim = ogts.create_cube(stage, "Cube", (1, 0, 0))
attr_name = "new_array_attr"
if not add_new_attr:
# if graph is not going to add a new attr, make the attr now with USD API so it exists before graph execution.
# Cannot reuse primvars:displayColor because it's a color3f[], not a strict float3[], and ConstructArray node
# cannot set role.
cube_prim.CreateAttribute(attr_name, Sdf.ValueTypeNames.Float3Array).Set([(1, 0, 0)])
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Write", "omni.graph.nodes.WritePrimsV2"),
("ExtractCube", "omni.graph.nodes.ExtractPrim"),
("MakeArray", "omni.graph.nodes.ConstructArray"),
("InsertAttribute", "omni.graph.nodes.InsertAttribute"),
],
keys.SET_VALUES: [
("ExtractCube.inputs:primPath", "/Cube"),
("MakeArray.inputs:arraySize", 1),
("MakeArray.inputs:arrayType", "float[3][]"),
("MakeArray.inputs:input0", [0.25, 0.50, 0.75]),
("InsertAttribute.inputs:outputAttrName", attr_name),
("Write.inputs:usdWriteBack", usd_write_back),
("Write.inputs:scatterUnderTargets", scatter_under_targets),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "ExtractCube.inputs:prims"),
("ExtractCube.outputs_primBundle", "InsertAttribute.inputs:data"),
("MakeArray.outputs:array", "InsertAttribute.inputs:attrToInsert"),
("InsertAttribute.outputs_data", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube_prim.GetPath(),
)
for target_path in target_prim_paths:
target_xform = UsdGeom.Xform.Define(stage, target_path)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
target=target_xform.GetPrim().GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
graph_context = graph.get_default_graph_context()
cube_bundle = graph_context.get_output_bundle(nodes[2], "outputs_primBundle")
self.assertTrue(cube_bundle.valid)
cube_path = "/Cube"
def check_prim_values(source_prim_path, target_prim_path):
# Check Fabric values
fabric_values = stage_rt.GetPrimAtPath(target_prim_path).GetAttribute(attr_name).Get()
self.assertEqual(len(fabric_values), 1)
self.assertEqual(tuple(fabric_values[0]), (0.25, 0.50, 0.75))
if usd_write_back:
# With USD write back, the existing attribute should be updated in USD
usd_values = stage.GetPrimAtPath(target_prim_path).GetAttribute(attr_name).Get()
self.assertEqual(len(usd_values), 1)
self.assertEqual(tuple(usd_values[0]), (0.25, 0.50, 0.75))
else:
if scatter_under_targets:
self.assertFalse(stage.GetPrimAtPath(target_prim_path).IsValid())
if scatter_under_targets:
for target_prim_path in target_prim_paths:
check_prim_values(cube_path, target_prim_path + cube_path)
else:
# only one source
check_prim_values(cube_path, target_prim_paths[0])
async def test_read_write_prims_remove_missing_to_usd(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB with remove missing attributes and prims matching to USD"""
await self._test_read_write_prims_remove_missing(True, False)
async def test_read_write_prims_remove_missing_to_usd_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB with remove missing attributes and prims matching to USD"""
await self._test_read_write_prims_remove_missing(True, True)
async def test_read_write_prims_remove_missing_to_fabric(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB with remove missing attributes and prims matching to Fabric"""
await self._test_read_write_prims_remove_missing(False, False)
async def test_read_write_prims_remove_missing_to_fabric_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB with remove missing attributes and prims matching to Fabric"""
await self._test_read_write_prims_remove_missing(False, True)
# ----------------------------------------------------------------------
async def _test_read_write_prims_remove_missing(self, usd_write_back: bool, scatter_under_targets: bool):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB with exact attributes and prims matching"""
usd_context = omni.usd.get_context()
stage_usd: Usd.Stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
controller = og.Controller()
keys = og.Controller.Keys
# Stage hierarchy:
#
# /Xform
# /Xform
# /Cube2
# /Cube1
# /target0
# /target1
stage_usd.DefinePrim("/Xform", "Xform")
stage_usd.DefinePrim("/Xform/Xform", "Xform")
cube1_prim = stage_usd.DefinePrim("/Xform/Cube1", "Cube")
cube2_prim = stage_usd.DefinePrim("/Xform/Xform/Cube2", "Cube")
test_attr_name = "test_attr"
test_target_existing_attr_name = "test_attr2"
test_both_existing_attr_name = "test_attr3"
cube1_prim.CreateAttribute(test_attr_name, Sdf.ValueTypeNames.Float3)
cube2_prim.CreateAttribute(test_attr_name, Sdf.ValueTypeNames.Float3)
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("Write.inputs:usdWriteBack", usd_write_back),
("Write.inputs:scatterUnderTargets", scatter_under_targets),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage_usd.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
targets=[cube1_prim.GetPath(), cube2_prim.GetPath()],
)
target_prim_paths = ["/target0", "/target1"]
for target_path in target_prim_paths:
target_xform = UsdGeom.Cube.Define(stage_usd, target_path)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage_usd.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
target=target_xform.GetPrim().GetPath(),
)
# put a Sphere under the target. This should NOT be removed by removeMissingPrims later, as it doesn't exist in the upstream bundle
stage_usd.DefinePrim(target_path + "/Sphere", "Sphere")
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# check attributes are exported correctly and setup the test scenario for removeMissingAttrs
# Add test_target_existing_attr_name to target prims only
# Add test_both_existing_attr_name to both source and target prims
for i, path in enumerate([cube1_prim.GetPath(), cube2_prim.GetPath()]):
def check_initial_prim(target_prim_path):
for stage in [stage_rt, stage_usd]:
# Check prim
prim = stage.GetPrimAtPath(target_prim_path)
self.assertTrue(prim.IsValid())
# Check attribute
attr = prim.GetAttribute(test_attr_name)
self.assertTrue(attr.IsValid())
# skip stage_usd check if usd_write_back is off
if not usd_write_back:
break
def add_attribute_to_source(source_prim_path):
# creates additional attributes on output prims.
# these attribute should not be removed, as there did not exist in upstream bundle
for stage, sdf in [(stage_rt, SdfRT), (stage_usd, Sdf)]:
prim = stage.GetPrimAtPath(source_prim_path)
prim.CreateAttribute(test_both_existing_attr_name, sdf.ValueTypeNames.Float2, True)
if not usd_write_back:
break
def add_attribute_to_target_output(target_prim_path):
# creates additional attributes on output prims.
# these attribute should not be removed, as there did not exist in upstream bundle
for stage, sdf in [(stage_rt, SdfRT), (stage_usd, Sdf)]:
prim = stage.GetPrimAtPath(target_prim_path)
prim.CreateAttribute(test_target_existing_attr_name, sdf.ValueTypeNames.Float2, True)
prim.CreateAttribute(test_both_existing_attr_name, sdf.ValueTypeNames.Float2, True)
if not usd_write_back:
break
if scatter_under_targets:
for target_prim_path in target_prim_paths:
check_initial_prim(target_prim_path + path.pathString)
add_attribute_to_target_output(target_prim_path + path.pathString)
else:
check_initial_prim(target_prim_paths[i])
add_attribute_to_target_output(target_prim_paths[i])
add_attribute_to_source(path.pathString)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# --------------------------- test removeMissingAttrs -----------------------------------------
# remove the test_attr from source and tick the graph, it must be removed from target too
cube1_prim.RemoveProperty(test_attr_name)
cube2_prim.RemoveProperty(test_attr_name)
# remove the test_attr from source and tick the graph, it must be removed from target too
cube1_prim.RemoveProperty(test_both_existing_attr_name)
cube2_prim.RemoveProperty(test_both_existing_attr_name)
# TODO ReadPrims node won't clear the attributes from output bundle due to lack of USD change tracking,
# has to set attrNamesToImport to force a re-evaluation
# FIXME when ReadPrims node properly tracks USD changes.
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: [
# changing filter from '*' to '**' applies same filter but forces node to re-evaluate to remove deleted attributes
("Read.inputs:attrNamesToImport", "**"),
],
},
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
for i, path in enumerate([cube1_prim.GetPath(), cube2_prim.GetPath()]):
def check_prim_attr_matched(source_prim_path, target_prim_path):
for stage in [stage_rt, stage_usd]:
prim = stage.GetPrimAtPath(target_prim_path)
self.assertTrue(prim.IsValid())
# Check attribute, it should be gone
attr = prim.GetAttribute(test_attr_name)
self.assertFalse(attr.IsValid())
# Check pre-existing attribute that has not been written to, it should stay
attr = prim.GetAttribute(test_target_existing_attr_name)
self.assertTrue(attr.IsValid())
# Check pre-existing attribute that has been written to, it should stay
attr = prim.GetAttribute(test_both_existing_attr_name)
self.assertTrue(attr.IsValid())
# skip stage_usd check if usd_write_back is off
if not usd_write_back:
break
if scatter_under_targets:
for target_prim_path in target_prim_paths:
check_prim_attr_matched(path, target_prim_path + path.pathString)
else:
check_prim_attr_matched(path, target_prim_paths[i])
# ------------------------- test removeMissingPrims ---------------------------------
# remove the /Cube1 from source and tick the graph, it must be removed from target too
omni.kit.commands.execute(
"RemoveRelationshipTarget",
relationship=stage_usd.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube2_prim.GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
def check_prim_matched(target_root_path, prim_path, valid: bool):
# Check USD and fabric prim, "Cube2" should be removed, "Cube1" stays
target_prim_path = target_root_path + prim_path
for stage in [stage_rt, stage_usd]:
prim = stage.GetPrimAtPath(target_prim_path)
self.assertEqual(prim.IsValid(), valid)
# The pre-existing Sphere prim should still exist
self.assertTrue(stage.GetPrimAtPath(target_root_path + "/Sphere").IsValid())
# The stub prim /targetN/Xform/Xform should also be removed
self.assertFalse(stage.GetPrimAtPath(target_root_path + "/Xform/Xform").IsValid())
# skip stage_usd check if usd_write_back is off
if not usd_write_back:
break
if scatter_under_targets:
for i, path in enumerate([cube1_prim.GetPath(), cube2_prim.GetPath()]):
for target_prim_path in target_prim_paths:
check_prim_matched(target_prim_path, path.pathString, i == 0)
else:
check_prim_matched(target_prim_paths[0], "", True)
# test removeMissingPrims with no prim input
# remove all prims from ReadPrims node, and the target should be empty
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage_usd.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
targets=[],
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# target prims should have only the "Sphere" prim as child
for target_prim_path in target_prim_paths:
target_prim = stage_usd.GetPrimAtPath(target_prim_path)
self.assertEqual(target_prim.GetAllChildrenNames(), ["Sphere"])
async def test_read_write_prims_remove_schema_properties(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB that removes attributes defined within schema"""
await self._test_read_write_prims_remove_schema_properties(False)
async def test_read_write_prims_remove_schema_properties_scatter(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB that removes attributes defined within schema"""
await self._test_read_write_prims_remove_schema_properties(True)
# ----------------------------------------------------------------------
async def _test_read_write_prims_remove_schema_properties(self, scatter_under_targets: bool):
"""
Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB that removes attributes defined within schema
This is a USD-only test as Fabric doesn't have the schema concept yet
"""
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
# Stage hierarchy:
#
# /Xform
# /target
xform_prim = stage.DefinePrim("/Xform", "Xform")
# both are schema properties of Xformable
test_attr_name = UsdGeom.Tokens.visibility
test_rel_name = UsdGeom.Tokens.proxyPrim
xform_prim.GetAttribute(UsdGeom.Tokens.visibility).Set(UsdGeom.Tokens.invisible)
xform_prim.GetRelationship(test_rel_name).AddTarget("/Foo/bar")
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("Write.inputs:usdWriteBack", True),
("Write.inputs:scatterUnderTargets", scatter_under_targets),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
targets=[xform_prim.GetPath()],
)
target_xform = UsdGeom.Xform.Define(stage, "/target")
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
target=target_xform.GetPrim().GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
def check_initial_prim(target_prim_path):
# Check prim
prim = stage.GetPrimAtPath(target_prim_path)
self.assertTrue(prim.IsValid())
# Check attribute
# It should be both valid and authored for target prim
attr = prim.GetAttribute(test_attr_name)
self.assertTrue(attr.IsAuthored())
self.assertEqual(attr.Get(), UsdGeom.Tokens.invisible)
# Check relationship
# It should be both valid and authored for target prim
rel = prim.GetRelationship(test_rel_name)
self.assertTrue(rel.IsAuthored())
self.assertListEqual(rel.GetTargets(), ["/Foo/bar"])
if scatter_under_targets:
check_initial_prim("/target/Xform")
else:
check_initial_prim("/target")
# Remove spec for both properties
# XXX cannot use RemoveProperty due to change tracking not working properly in ReadPrimsV2 node
# set attrNamesToImport to empty instead to clear the attributes from ReadPrimsV2 output bundle
# xform_prim.RemoveProperty(test_attr_name)
# xform_prim.RemoveProperty(test_rel_name)
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("Read.inputs:attrNamesToImport", "")})
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
def check_ticked_prim(target_prim_path):
# Check prim
prim = stage.GetPrimAtPath(target_prim_path)
self.assertTrue(prim.IsValid())
# Check attribute
# It should still exits but be reverted to unauthored schema value
attr = prim.GetAttribute(test_attr_name)
self.assertTrue(attr.IsValid())
self.assertFalse(attr.IsAuthored())
self.assertEqual(attr.Get(), UsdGeom.Tokens.inherited)
# Check relationship
# It should still exits but be reverted to unauthored schema value
rel = prim.GetRelationship(test_rel_name)
self.assertTrue(rel.IsValid())
self.assertFalse(rel.IsAuthored())
self.assertListEqual(rel.GetTargets(), [])
if scatter_under_targets:
check_ticked_prim("/target/Xform")
else:
check_ticked_prim("/target")
# ----------------------------------------------------------------------
async def test_read_write_prims_fill_usd_hierarchy_gap(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims when some prim along target hierarchy does not fully exist"""
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
UsdGeom.Xform.Define(stage, "/Xform")
scope = UsdGeom.Scope.Define(stage, "/Xform/Scope")
cube = UsdGeom.Cube.Define(stage, "/Xform/Scope/Cube")
target_xform = UsdGeom.Xform.Define(stage, "/Target")
(graph, [_, _], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("Write.inputs:usdWriteBack", True),
("Write.inputs:scatterUnderTargets", True),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube.GetPrim().GetPath(),
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
target=target_xform.GetPrim().GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# check the target hierarchy was created, all missing prims has the type Xform
self.assertTrue(UsdGeom.Xform.Get(stage, "/Target/Xform"))
self.assertTrue(UsdGeom.Xform.Get(stage, "/Target/Xform/Scope"))
self.assertTrue(UsdGeom.Cube.Get(stage, "/Target/Xform/Scope/Cube"))
# add /Xform/Scope to import targets
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=scope.GetPrim().GetPath(),
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# check the target hierarchy was created, because "/Xform/Scope" is also exported,
# the type should be changed from Xform to Scope
self.assertTrue(UsdGeom.Xform.Get(stage, "/Target/Xform"))
self.assertTrue(UsdGeom.Scope.Get(stage, "/Target/Xform/Scope"))
self.assertFalse(UsdGeom.Xform.Get(stage, "/Target/Xform/Scope"))
self.assertTrue(UsdGeom.Cube.Get(stage, "/Target/Xform/Scope/Cube"))
# ----------------------------------------------------------------------
async def test_read_write_prims_find_prims_loop_guard(self):
await self._test_read_write_prims_find_prims_loop_guard(False)
# ----------------------------------------------------------------------
async def test_read_write_prims_find_prims_loop_guard_scatter(self):
await self._test_read_write_prims_find_prims_loop_guard(True)
# ----------------------------------------------------------------------
async def _test_read_write_prims_find_prims_loop_guard(self, scatter_under_targets: bool):
"""Test omni.graph.nodes.ReadPrimsV2 find prims tracker and WritePrims that loop can be detect and prevented"""
logging = carb.logging.acquire_logging()
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
xform = UsdGeom.Xform.Define(stage, "/Xform")
xform_xform = UsdGeom.Xform.Define(stage, "/Xform/Xform")
xform2 = UsdGeom.Xform.Define(stage, "/Xform2")
xform2_xform = UsdGeom.Xform.Define(stage, "/Xform2/Xform")
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Read2", "omni.graph.nodes.ReadPrimsV2"),
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("Read.inputs:pathPattern", "*"),
("Write.inputs:usdWriteBack", True),
("Write.inputs:scatterUnderTargets", scatter_under_targets),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Write.inputs:primsBundle"),
],
},
)
# ------------ test path tracker on connected Read node ------------
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=xform.GetPrim().GetPath(),
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
target=xform_xform.GetPrim().GetPath(),
)
log_was_enabled = logging.is_log_enabled()
# turn off carb logging so the error does not trigger test failure
# og logging still works and logs node error message.
logging.set_log_enabled(False)
await self._evaluate_graph(graph, controller)
error_message = self._get_node_messages(graph, og.ERROR)
# check the error is logged
self.assertEqual(
error_message,
[
"[/World/TestGraph] Target prim '/Xform/Xform' is a descendant of FindPrims/ReadPrims source '/Xform', writing to the target may mutate the input state. Please choose a different target"
],
)
# check the target prim is NOT created
if scatter_under_targets:
self.assertFalse(stage.GetPrimAtPath("/Xform/Xform/Xform").IsValid())
# ------------ test path tracker on unconnected Read node ------------
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: [
("Read2.inputs:pathPattern", "*"),
]
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read2.inputs:prims"),
target=xform2.GetPrim().GetPath(),
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
targets=[xform2_xform.GetPrim().GetPath()],
)
await self._evaluate_graph(graph, controller)
error_message = self._get_node_messages(graph, og.ERROR)
# check the error is logged
self.assertEqual(
error_message,
[
"[/World/TestGraph] Target prim '/Xform2/Xform' is a descendant of FindPrims/ReadPrims source '/Xform2', writing to the target may mutate the input state. Please choose a different target"
],
)
# check the target prim is NOT created
if scatter_under_targets:
self.assertFalse(stage.GetPrimAtPath("/Xform2/Xform/Xform").IsValid())
logging.set_log_enabled(log_was_enabled)
# ----------------------------------------------------------------------
async def test_write_prims_empty_bundle(self):
"""Test warnings and errors issued by omni.graph.nodes.WritePrimsV2 when its input bundle is empty"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("bundle_ctor", "omni.graph.nodes.BundleConstructor"),
("write_prims", "omni.graph.nodes.WritePrimsV2"),
],
keys.CONNECT: [
("bundle_ctor.outputs_bundle", "write_prims.inputs:primsBundle"),
],
},
)
with self.CarbLogSuppressor():
await self._evaluate_graph(graph, controller)
# no warning or errors messages are expected
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# ----------------------------------------------------------------------
async def test_write_prims_source_prim_path_validation_str(self):
"""Test warnings and errors issued by omni.graph.nodes.WritePrimsV2 when a string sourcePrimPath is detected"""
await self._test_write_prims_attribute_validation_impl(
"sourcePrimPath", "foo", "String", "sourcePrimPath attribute must hold a token"
)
async def test_write_prims_source_prim_path_validation_int(self):
"""Test warnings and errors issued by omni.graph.nodes.WritePrimsV2 when an integer sourcePrimPath is detected"""
await self._test_write_prims_attribute_validation_impl(
"sourcePrimPath", 42, "Int", "sourcePrimPath attribute must hold a token"
)
async def test_write_prims_source_prim_type_validation_str(self):
"""Test warnings and errors issued by omni.graph.nodes.WritePrimsV2 when a string sourcePrimType is detected"""
await self._test_write_prims_attribute_validation_impl(
"sourcePrimType", "bar", "String", "sourcePrimType attribute must hold a token"
)
async def test_write_prims_source_prim_type_validation_int(self):
"""Test warnings and errors issued by omni.graph.nodes.WritePrimsV2 when an integer rsourcePrimType is detected"""
await self._test_write_prims_attribute_validation_impl(
"sourcePrimType", 42, "Int", "sourcePrimType attribute must hold a token"
)
async def _test_write_prims_attribute_validation_impl(
self, attr_name, attr_value, attr_type, expected_error_message
):
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
ogts.create_cube(stage, "Cube", (1, 0, 0))
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("CreateEmptyBundle", "omni.graph.nodes.BundleConstructor"),
("WritePrims", "omni.graph.nodes.WritePrimsV2"),
("ConstSourcePrimPath", f"omni.graph.nodes.Constant{attr_type}"),
("InsertSourcePrimPath", "omni.graph.nodes.InsertAttribute"),
],
keys.SET_VALUES: [
("ConstSourcePrimPath.inputs:value", attr_value),
("InsertSourcePrimPath.inputs:outputAttrName", attr_name),
],
keys.CONNECT: [
("ConstSourcePrimPath.inputs:value", "InsertSourcePrimPath.inputs:attrToInsert"),
("CreateEmptyBundle.outputs_bundle", "InsertSourcePrimPath.inputs:data"),
("InsertSourcePrimPath.outputs_data", "WritePrims.inputs:primsBundle"),
],
},
)
target_xform = UsdGeom.Xform.Define(stage, "/Targets")
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/WritePrims.inputs:prims"),
target=target_xform.GetPrim().GetPath(),
)
with self.CarbLogSuppressor():
await self._evaluate_graph(graph, controller)
# check the error is logged
expected_message = f"[{self.TEST_GRAPH_PATH}] Bundle '{self.TEST_GRAPH_PATH}/__runtime_data/InsertSourcePrimPath_outputs_data' was skipped because it was invalid! {expected_error_message}"
self.assertEqual(self._get_node_messages(graph, og.WARNING), [expected_message])
# no warning message is expected
self._assert_no_compute_messages(graph, [og.ERROR])
# ----------------------------------------------------------------------
async def test_read_write_prims_to_layer(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB to a different layer"""
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
session_layer = stage.GetSessionLayer()
sub_layer = Sdf.Layer.CreateAnonymous()
sub_layer2 = Sdf.Layer.CreateAnonymous()
root_layer = stage.GetRootLayer()
root_layer.subLayerPaths.append(sub_layer.identifier)
root_layer.subLayerPaths.append(sub_layer2.identifier)
test_layers = [session_layer, sub_layer, sub_layer2, root_layer]
# switch edit target to sub_layer2
with Usd.EditContext(stage, sub_layer2):
def create_scope_with_test_attrs(prim_path: str):
scope = UsdGeom.Scope.Define(stage, prim_path)
scope_prim = scope.GetPrim()
scope_prim.CreateAttribute("test_attr_0", Sdf.ValueTypeNames.Bool).Set(True)
scope_prim.CreateAttribute("test_attr_1", Sdf.ValueTypeNames.Bool).Set(True)
scope_prim.CreateAttribute("test_attr_2", Sdf.ValueTypeNames.Bool).Set(True)
scope_prim.CreateAttribute("test_attr_3", Sdf.ValueTypeNames.Bool).Set(True)
return scope_prim
test_layer_count = len(test_layers)
source_prims = []
for i in range(test_layer_count):
source_prims.append(create_scope_with_test_attrs(f"/Scope{i}"))
# make a graph to Read from scope_prim_N, Write to scope_N_out prim with only test_attr_N to layer index N
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read0", "omni.graph.nodes.ReadPrimsV2"),
("Read1", "omni.graph.nodes.ReadPrimsV2"),
("Read2", "omni.graph.nodes.ReadPrimsV2"),
("Read3", "omni.graph.nodes.ReadPrimsV2"),
("Write0", "omni.graph.nodes.WritePrimsV2"),
("Write1", "omni.graph.nodes.WritePrimsV2"),
("Write2", "omni.graph.nodes.WritePrimsV2"),
("Write3", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("Write0.inputs:layerIdentifier", "<Session Layer>"),
("Write1.inputs:layerIdentifier", sub_layer.identifier),
("Write2.inputs:layerIdentifier", ""), # write to current edit target (sub_layer2 in this case)
("Write3.inputs:layerIdentifier", "<Root Layer>"),
("Write0.inputs:attrNamesToExport", "test_attr_0"),
("Write1.inputs:attrNamesToExport", "test_attr_1"),
("Write2.inputs:attrNamesToExport", "test_attr_2"),
("Write3.inputs:attrNamesToExport", "test_attr_3"),
],
keys.CONNECT: [
("Read0.outputs_primsBundle", "Write0.inputs:primsBundle"),
("Read1.outputs_primsBundle", "Write1.inputs:primsBundle"),
("Read2.outputs_primsBundle", "Write2.inputs:primsBundle"),
("Read3.outputs_primsBundle", "Write3.inputs:primsBundle"),
],
},
)
for i in range(test_layer_count):
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read{i}.inputs:prims"),
targets=[source_prims[i].GetPath()],
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write{i}.inputs:prims"),
targets=[f"/Scope_{i}_out"],
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# Scope_0_out should only exist on test_layers[0] with test_attr_0
# Scope_1_out should only exist on test_layers[1] with test_attr_1
# Scope_2_out should only exist on test_layers[2] with test_attr_2
# Scope_3_out should only exist on test_layers[3] with test_attr_3
for layer_idx, layer in enumerate(test_layers):
for prim_idx in range(test_layer_count):
prim_out_spec = layer.GetPrimAtPath(f"/Scope_{prim_idx}_out")
if prim_idx == layer_idx:
self.assertTrue(prim_out_spec)
self.assertEqual(prim_out_spec.specifier, Sdf.SpecifierDef)
for attr_idx in range(test_layer_count):
attr_out_spec = layer.GetAttributeAtPath(f"/Scope_{prim_idx}_out.test_attr_{attr_idx}")
if attr_idx == layer_idx:
self.assertTrue(attr_out_spec)
self.assertTrue(attr_out_spec.default)
else:
self.assertFalse(attr_out_spec)
else:
self.assertFalse(prim_out_spec)
#############################################################
# Change the target to session layer and check `over` spec
test_layer_index = 2
# change value from True to False
source_prims[test_layer_index].GetAttribute(f"test_attr_{test_layer_index}").Set(False)
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: [
(f"Write{test_layer_index}.inputs:layerIdentifier", "<Session Layer>"),
],
},
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
prim_out_spec = session_layer.GetPrimAtPath(f"/Scope_{test_layer_index}_out")
self.assertTrue(prim_out_spec)
self.assertEqual(prim_out_spec.specifier, Sdf.SpecifierOver)
attr_out_spec = session_layer.GetAttributeAtPath(
f"/Scope_{test_layer_index}_out.test_attr_{test_layer_index}"
)
self.assertTrue(attr_out_spec)
self.assertFalse(attr_out_spec.default) # value should be set to False because we changed it
prev_attr_out_spec = test_layers[test_layer_index].GetAttributeAtPath(
f"/Scope_{test_layer_index}_out.test_attr_{test_layer_index}"
)
self.assertTrue(prev_attr_out_spec)
self.assertTrue(
prev_attr_out_spec.default
) # the value should still be True as it should not be written to anymore
# ----------------------------------------------------------------------
async def test_read_write_prims_layer_identifier_resolver(self):
"""
Test omni.graph.nodes.ReadPrimsV2 and WritePrimsV2 layer identifier resolver
Construct file hierarchy like this:
/Ref/ref.usda
/Ref/ref_sublayer.usda
/main.usda
/Ref/ref_sublayer.usda is a sublayer of /Ref/ref.usda
A graph with WritePrimsV2 node is in /Ref/ref.usda, with a layerIdentifier to ./ref_sublayer.usda
If /Ref/ref.usda is opened in Kit and graph executes, the output should be written to /Ref/ref_sublayer.usda
/Ref/ref_sublayer.usda is also a sublayer of /main.usda
/main.usda also references /Ref/ref.usda
If /main.usda is opened in Kit and graph executes, the relative layerIdentifier of ./ref_sublayer.usda should
still be resolved to /Ref/ref_sublayer.usda, but not /ref_sublayer.usda, and graph out put on that layer.
"""
with tempfile.TemporaryDirectory() as tmpdirname:
usd_context = omni.usd.get_context()
controller = og.Controller()
keys = og.Controller.Keys
ref_dir = os.path.join(tmpdirname, "Ref")
ref_sublayer_fn = os.path.join(ref_dir, "ref_sub_layer.usda")
ref_sublayer = Sdf.Layer.CreateNew(ref_sublayer_fn)
ref_sublayer.Save()
ref_fn = os.path.join(ref_dir, "ref.usda")
Sdf.Layer.CreateNew(ref_fn).Save()
success, error = await usd_context.open_stage_async(str(ref_fn))
self.assertTrue(success, error)
stage = usd_context.get_stage()
root_layer = stage.GetRootLayer()
root_layer.subLayerPaths.append("./ref_sub_layer.usda")
world = UsdGeom.Xform.Define(stage, "/World")
stage.SetDefaultPrim(world.GetPrim())
source = UsdGeom.Scope.Define(stage, "/World/Source")
source_prim = source.GetPrim()
source_prim.CreateAttribute("test_attr", Sdf.ValueTypeNames.Bool).Set(True)
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("Write.inputs:layerIdentifier", "./ref_sub_layer.usda"),
("Write.inputs:attrNamesToExport", "test_attr"),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
targets=["/World/Source"],
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
targets=["/World/Target"],
)
# Block saving the stage first before graph ticking. The ticked result should not be saved and discard later
result = usd_context.save_stage()
self.assertTrue(result)
# Tick the graph to make sure the layerIdentifier is resolved correctly within /Ref/ref.usda stage
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
prim_out_spec = ref_sublayer.GetPrimAtPath("/World/Target")
self.assertTrue(prim_out_spec)
self.assertEqual(prim_out_spec.specifier, Sdf.SpecifierDef)
attr_out_spec = ref_sublayer.GetAttributeAtPath("/World/Target.test_attr")
self.assertTrue(attr_out_spec)
self.assertTrue(attr_out_spec.default)
prim_out_spec = root_layer.GetPrimAtPath("/World/Target")
self.assertFalse(prim_out_spec)
# close the stage and release layer ref to discard all temporary changes.
await omni.usd.get_context().close_stage_async()
ref_sublayer = None
# Now make the main.usda, add Ref/ref.usda as a reference and tick graph
main_fn = os.path.join(tmpdirname, "main.usda")
Sdf.Layer.CreateNew(main_fn).Save()
success, error = await usd_context.open_stage_async(str(main_fn))
self.assertTrue(success, error)
stage = usd_context.get_stage()
# Add "./Ref/ref_sub_layer.usda" again as a local sublayer so graph can resolve and write to it on this new stage
root_layer = stage.GetRootLayer()
root_layer.subLayerPaths.append("./Ref/ref_sub_layer.usda")
# For whatever reason need to make an empty graph otherwise test crashes when referencing in "./Ref/ref.usda"
# same code does NOT crash while executed within Kit Script Editor without the dummy graph
controller.edit("/dummy", {})
ref_prim = stage.DefinePrim("/Ref")
refs = ref_prim.GetReferences()
refs.AddReference("./Ref/ref.usda")
# reopen Ref/ref_sublayer.usda
ref_sublayer = Sdf.Layer.FindOrOpen(ref_sublayer_fn)
self.assertTrue(ref_sublayer)
# double check the target spec does not exist before tick the graph
self.assertFalse(ref_sublayer.GetPrimAtPath("/Ref/Target"))
# let OG populate the referenced graph
await omni.kit.app.get_app().next_update_async()
# Tick the graph to make sure the layerIdentifier is resolved correctly when referencing /Ref/ref.usda
graph = og.get_graph_by_path("/Ref/TestGraph")
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# the references graph should be able to resolve layerIdentifier even if the relative path anchors differently
prim_out_spec = ref_sublayer.GetPrimAtPath("/Ref/Target")
self.assertTrue(prim_out_spec)
self.assertEqual(prim_out_spec.specifier, Sdf.SpecifierDef)
attr_out_spec = ref_sublayer.GetAttributeAtPath("/Ref/Target.test_attr")
self.assertTrue(attr_out_spec)
self.assertTrue(attr_out_spec.default)
prim_out_spec = root_layer.GetPrimAtPath("/Ref/Target")
self.assertFalse(prim_out_spec)
# ----------------------------------------------------------------------
async def test_write_prims_relationship(self):
"""Test WritePrims MPiB to export a relationship"""
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id())
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("RelBundle", "__test_write_prims_v2__.relationship_bundle"),
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.CONNECT: [
("RelBundle.outputs_out_0", "Write.inputs:primsBundle"),
],
},
)
target_path = "/Target"
target_xform = UsdGeom.Xform.Define(stage, target_path)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
targets=[target_xform.GetPrim().GetPath()],
)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
# Check USD prim relationship
prim = stage.GetPrimAtPath(target_path)
rel = prim.GetRelationship(REL_BUNDLE_TRL_NAME)
self.assertTrue(rel)
self.assertListEqual(REL_BUNDLE_TARGETS, rel.GetTargets())
# Check Fabric prim relationship
prim_rt = stage_rt.GetPrimAtPath(target_path)
rel_rt = prim_rt.GetRelationship(REL_BUNDLE_TRL_NAME)
self.assertTrue(rel_rt)
self.assertListEqual(REL_BUNDLE_TARGETS_RT, rel_rt.GetTargets())
# ----------------------------------------------------------------------
async def test_write_prims_interpolation(self):
"""Test writing interpolation metadata through omni.graph.nodes.WritePrimsV2"""
target_prim_path = "/target"
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
xform_prim = UsdGeom.Xform.Define(stage, target_prim_path)
cube_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0))
(graph, [_, _], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("Write.inputs:scatterUnderTargets", True),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Write.inputs:primsBundle"),
],
},
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
targets=[cube_prim.GetPath()],
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"),
target=xform_prim.GetPrim().GetPath(),
)
# Set the interpolation on a primvar
interpolation = "uniform"
primvar = UsdGeom.Primvar(cube_prim.GetAttribute("primvars:displayColor"))
self.assertTrue(primvar)
primvar.SetInterpolation(interpolation)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
target_prim_path = xform_prim.GetPath().AppendPath(
cube_prim.GetPath().MakeRelativePath(Sdf.Path.absoluteRootPath)
)
target_prim = stage.GetPrimAtPath(target_prim_path)
self.assertTrue(target_prim)
attr = target_prim.GetAttribute("primvars:displayColor")
self.assertTrue(attr)
primvar = UsdGeom.Primvar(attr)
self.assertTrue(primvar)
self.assertEqual(primvar.GetInterpolation(), interpolation)
# Change the interpolation of the input prim, then evaluate the graph again...
interpolation = "constant"
primvar = UsdGeom.Primvar(cube_prim.GetAttribute("primvars:displayColor"))
self.assertTrue(primvar)
primvar.SetInterpolation(interpolation)
await self._evaluate_graph(graph, controller)
self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR])
target_prim = stage.GetPrimAtPath(target_prim_path)
self.assertTrue(target_prim)
attr = target_prim.GetAttribute("primvars:displayColor")
self.assertTrue(attr)
primvar = UsdGeom.Primvar(attr)
self.assertTrue(primvar)
self.assertEqual(primvar.GetInterpolation(), interpolation)
# Finally, clear the metadata on the input prim and ensure that the metadata is cleared on the output prim
attr = cube_prim.GetAttribute("primvars:displayColor")
attr.ClearMetadata("interpolation")
await self._evaluate_graph(graph, controller)
# Just check for errors here; we do expect to get a warning that the metadata field no longer exists
self._assert_no_compute_messages(graph, [og.ERROR])
target_prim = stage.GetPrimAtPath(target_prim_path)
self.assertTrue(target_prim)
attr = target_prim.GetAttribute("primvars:displayColor")
self.assertTrue(attr)
self.assertFalse(attr.HasMetadata("interpolation"))
# ----------------------------------------------------------------------
# Helpers
def _assert_no_compute_messages(self, graph, severity_list):
graph_nodes = graph.get_nodes()
for severity in severity_list:
for node in graph_nodes:
self.assertEqual(node.get_compute_messages(severity), [])
async def _evaluate_graph(self, graph, controller):
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
def _get_node_messages(self, graph, severity):
error_message = []
graph_nodes = graph.get_nodes()
for node in graph_nodes:
error = node.get_compute_messages(severity)
if error:
error_message += error
return error_message
class CarbLogSuppressor:
def __init__(self):
self.logging = carb.logging.acquire_logging()
self.log_was_enabled = self.logging.is_log_enabled()
def __enter__(self):
# turn off carb logging so the error does not trigger test failure
# og logging still works and logs node error message.
self.logging.set_log_enabled(False)
return self
def __exit__(self, *_):
# restore carb logging
self.logging.set_log_enabled(self.log_was_enabled)
| 94,944 | Python | 44.51534 | 204 | 0.552441 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_read_prim_node.py | # noqa: PLC0302
from math import isnan
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
from pxr import Sdf, Usd, UsdGeom
# Tests for ReadPrim (singular) node
class TestReadPrimNode(ogts.OmniGraphTestCase):
"""Unit tests for ReadPrim node in this extension"""
async def test_read_prim_node_v1(self):
"""Validate backward compatibility for legacy versions of ReadPrim node."""
# load the test scene which contains a ReadPrim V1 node
(result, error) = await ogts.load_test_file("TestReadPrimNode_v1.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
test_graph_path = "/World/TestGraph"
test_graph = og.get_graph_by_path(test_graph_path)
read_prim_node = test_graph.get_node(test_graph_path + "/read_prim")
self.assertTrue(read_prim_node.is_valid())
# validate new attributes can be automatically created with their default value set.
self.assertTrue(read_prim_node.get_attribute_exists("inputs:computeBoundingBox"))
self.assertFalse(read_prim_node.get_attribute("inputs:computeBoundingBox").get())
self.assertTrue(read_prim_node.get_attribute_exists("inputs:usdTimecode"))
self.assertTrue(isnan(read_prim_node.get_attribute("inputs:usdTimecode").get()))
# Tests for ReadPrimBundle node
class TestReadPrimsBundle(ogts.OmniGraphTestCase):
"""Unit tests for ReadPrimBundle node in this extension"""
async def test_read_prims_bundle_node_target_mpib(self):
"""Validate backward compatibility for legacy versions of ReadPrim node."""
(result, error) = await ogts.load_test_file("TestReadPrimNode_targetMPiB.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
test_graph_path = "/TestGraph"
test_graph = og.get_graph_by_path(test_graph_path)
test_context = test_graph.get_default_graph_context()
read_prim_bundle_node = test_graph.get_node(test_graph_path + "/read_prims_into_bundle")
self.assertTrue(read_prim_bundle_node.is_valid())
factory = og.IBundleFactory.create()
output_bundle = test_context.get_output_bundle(read_prim_bundle_node, "outputs_primsBundle")
output_bundle2 = factory.get_bundle(test_context, output_bundle)
self.assertTrue(output_bundle2.valid)
self.assertTrue(output_bundle2.get_child_bundle_count(), 2)
child0 = output_bundle2.get_child_bundle(0)
child1 = output_bundle2.get_child_bundle(1)
self.assertTrue(child0.valid)
self.assertTrue(child1.valid)
self.assertTrue("size" in child0.get_attribute_names())
self.assertTrue("size" in child1.get_attribute_names())
async def test_read_prims_bundle_node_path_mpib(self):
"""Load multiple primitives into a bundle through input path"""
(result, error) = await ogts.load_test_file("TestReadPrimNode_pathMPiB.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
test_graph_path = "/TestGraph"
test_graph = og.get_graph_by_path(test_graph_path)
test_context = test_graph.get_default_graph_context()
read_prim_bundle_node = test_graph.get_node(test_graph_path + "/read_prims_into_bundle")
self.assertTrue(read_prim_bundle_node.is_valid())
factory = og.IBundleFactory.create()
output_bundle = test_context.get_output_bundle(read_prim_bundle_node, "outputs_primsBundle")
output_bundle2 = factory.get_bundle(test_context, output_bundle)
self.assertTrue(output_bundle2.valid)
self.assertTrue(output_bundle2.get_child_bundle_count(), 2)
child0 = output_bundle2.get_child_bundle(0)
child1 = output_bundle2.get_child_bundle(1)
self.assertTrue(child0.valid)
self.assertTrue(child1.valid)
self.assertTrue("size" in child0.get_attribute_names())
self.assertTrue("size" in child1.get_attribute_names())
# Tests for both ReadPrims (legacy) and ReadPrimsV2 node
# Must be inherited by a child test class to be tested
class TestReadPrimsCommon:
"""Unit tests for both ReadPrims (legacy) and ReadPrimsV2 node in this extension"""
def __init__(self, read_prims_node_type):
self._read_prims_node_type = read_prims_node_type
async def test_import_matrix_and_bbox(self):
"""Verify that bounding box and matrix are correctly computed by ReadPrim."""
controller = og.Controller()
keys = og.Controller.Keys
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# create 500 cubes to feed ReadPrims and trigger its concurrent collection of prims
cube_paths = []
cubes = []
for i in range(500):
cube_path = "/World/Cube" + str(i)
cube = ogts.create_cube(stage, cube_path[1:], (1, 1, 1))
UsdGeom.Xformable(cube).AddTranslateOp()
cube_paths.append(cube_path)
cubes.append(cube)
self.assertEqual(cube.GetPath(), cube_path) # noqa: PLE1101
(_, nodes, _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("ReadPrims", self._read_prims_node_type),
("ExtractPrim", "omni.graph.nodes.ExtractPrim"),
("ExtractBundle", "omni.graph.nodes.ExtractBundle"),
("Inv", "omni.graph.nodes.OgnInvertMatrix"),
("Const0", "omni.graph.nodes.ConstantDouble3"),
("Const1", "omni.graph.nodes.ConstantDouble3"),
],
keys.SET_VALUES: [
("ExtractPrim.inputs:primPath", cube_paths[0]),
],
keys.CONNECT: [
("ReadPrims.outputs_primsBundle", "ExtractPrim.inputs:prims"),
("ExtractPrim.outputs_primBundle", "ExtractBundle.inputs:bundle"),
],
},
)
# add target prim
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath("/TestGraph/ReadPrims.inputs:prims"),
targets=cube_paths,
)
# get initial output attributes
await controller.evaluate()
# connect the matrix
controller.edit("/TestGraph", {keys.CONNECT: ("ExtractBundle.outputs:worldMatrix", "Inv.inputs:matrix")})
await controller.evaluate()
read_prims_node = nodes[0]
extract_bundle = nodes[2]
# We did not ask for BBox
self.assertFalse(read_prims_node.get_attribute_exists("outputs:bboxMinCorner")) # noqa: PLE1101
self.assertFalse(read_prims_node.get_attribute_exists("outputs:bboxMaxCorner")) # noqa: PLE1101
self.assertFalse(read_prims_node.get_attribute_exists("outputs:bboxTransform")) # noqa: PLE1101
# but we should have the default matrix
mat_attr = extract_bundle.get_attribute("outputs:worldMatrix")
mat = mat_attr.get()
self.assertTrue((mat == [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]).all()) # noqa: PLE1101
# move the cube, check the new matrix
pos = cubes[0].GetAttribute("xformOp:translate")
pos.Set((2, 2, 2))
await controller.evaluate()
mat = mat_attr.get()
self.assertTrue((mat == [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 2, 2, 1]).all()) # noqa: PLE1101
# now ask for bbox, and check its value
controller.edit(
"/TestGraph",
{
keys.SET_VALUES: ("ReadPrims.inputs:computeBoundingBox", True),
},
)
await controller.evaluate()
self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxMinCorner")) # noqa: PLE1101
self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxMaxCorner")) # noqa: PLE1101
self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxTransform")) # noqa: PLE1101
# connect the bbox
controller.edit(
"/TestGraph",
{
keys.CONNECT: [
("ExtractBundle.outputs:bboxMinCorner", "Const0.inputs:value"),
("ExtractBundle.outputs:bboxMaxCorner", "Const1.inputs:value"),
]
},
)
await controller.evaluate()
bbox_min = extract_bundle.get_attribute("outputs:bboxMinCorner")
bbox_max = extract_bundle.get_attribute("outputs:bboxMaxCorner")
bbox_min_val = bbox_min.get()
bbox_max_val = bbox_max.get()
self.assertTrue((bbox_min_val == [-0.5, -0.5, -0.5]).all()) # noqa: PLE1101
self.assertTrue((bbox_max_val == [0.5, 0.5, 0.5]).all()) # noqa: PLE1101
# then resize the cube, and check new bbox
ext = cubes[0].GetAttribute("extent")
ext.Set([(-10, -10, -10), (10, 10, 10)])
await controller.evaluate()
bbox_min_val = bbox_min.get()
bbox_max_val = bbox_max.get()
self.assertTrue((bbox_min_val == [-10, -10, -10]).all()) # noqa: PLE1101
self.assertTrue((bbox_max_val == [10, 10, 10]).all()) # noqa: PLE1101
async def _test_apply_skel_binding_on_skinned_model(self, test_scene):
"""shared function to validate applying skel binding on a model which has SkelBindingAPI schema."""
# load test scene which contains a mesh that is bound with a skeleton and a skel animation
(result, error) = await ogts.load_test_file(test_scene, use_caller_subdirectory=True)
self.assertTrue(result, error) # noqa: PLE1101
controller = og.Controller()
keys = og.Controller.Keys
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
bundle_factory = og.IBundleFactory.create()
# create a ReadPrims node
(test_graph, [read_prims_node], _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("read_prims", self._read_prims_node_type),
],
},
)
# add target prim
cylinder_path = "/Root/group1/pCylinder1_Skinned"
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath("/TestGraph/read_prims.inputs:prims"),
target=cylinder_path,
)
await controller.evaluate()
# validate a single child bundle is created when applySkelBinding is not enabled yet.
test_context = test_graph.get_default_graph_context()
output_bundle = test_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
output_bundle = bundle_factory.get_bundle(test_context, output_bundle)
self.assertTrue(output_bundle.valid) # noqa: PLE1101
child_bundles = output_bundle.get_child_bundles()
self.assertTrue(len(child_bundles), 1) # noqa: PLE1101
single_prim_in_bundle = child_bundles[0]
self.assertTrue(single_prim_in_bundle.valid) # noqa: PLE1101
source_prim_path_str = "sourcePrimPath"
source_prim_path_attr = single_prim_in_bundle.get_attribute_by_name(source_prim_path_str)
self.assertTrue(source_prim_path_attr.is_valid()) # noqa: PLE1101
self.assertEqual(source_prim_path_attr.get(), cylinder_path) # noqa: PLE1101
attributes_without_skel_binding = set(single_prim_in_bundle.get_attribute_names())
self.assertTrue("points" in attributes_without_skel_binding) # noqa: PLE1101
self.assertTrue("normals" in attributes_without_skel_binding) # noqa: PLE1101
# apply skel binding
controller.edit(
"/TestGraph",
{
keys.SET_VALUES: ("read_prims.inputs:applySkelBinding", True),
},
)
await controller.evaluate()
# validate child bundles are created for cylinder, skeleton and skel animation.
child_bundles = output_bundle.get_child_bundles()
self.assertEqual(len(child_bundles), 3) # noqa: PLE1101
cylinder_bundle = None
skeleton_bundle = None
skelanim_bundle = None
for child_bundle in child_bundles:
source_prim_path_attr = child_bundle.get_attribute_by_name(source_prim_path_str)
if source_prim_path_attr.get() == cylinder_path:
cylinder_bundle = child_bundle
else:
source_prim_type_attr = child_bundle.get_attribute_by_name("sourcePrimType")
source_prim_type = source_prim_type_attr.get()
if source_prim_type == "Skeleton":
skeleton_bundle = child_bundle
elif source_prim_type == "SkelAnimation":
skelanim_bundle = child_bundle
self.assertIsNotNone(cylinder_bundle) # noqa: PLE1101
self.assertIsNotNone(skeleton_bundle) # noqa: PLE1101
self.assertIsNotNone(skelanim_bundle) # noqa: PLE1101
# the cylinder bundle has the skel:skeleton attribute that stores the link to the Skeleton bundle
skeleton_path_attr = cylinder_bundle.get_attribute_by_name("skel:skeleton")
self.assertTrue(skeleton_path_attr.is_valid()) # noqa: PLE1101
source_prim_path_attr = skeleton_bundle.get_attribute_by_name(source_prim_path_str)
self.assertTrue(source_prim_path_attr.is_valid()) # noqa: PLE1101
skeleton_path = skeleton_path_attr.get()
self.assertEqual(source_prim_path_attr.get(), skeleton_path) # noqa: PLE1101
# the skeleton bundle has the skel:animationSource attribute that stores the link to the SkelAnimation bundle
skelanim_path_attr = skeleton_bundle.get_attribute_by_name("skel:animationSource")
self.assertTrue(skelanim_path_attr.is_valid()) # noqa: PLE1101
source_prim_path_attr = skelanim_bundle.get_attribute_by_name(source_prim_path_str)
self.assertTrue(source_prim_path_attr.is_valid()) # noqa: PLE1101
skelanim_path = skelanim_path_attr.get()
self.assertEqual(source_prim_path_attr.get(), skelanim_path) # noqa: PLE1101
# validate additional skel attributes added to the cylinder bundle
attributes_with_skel_binding = set(cylinder_bundle.get_attribute_names())
self.assertTrue(attributes_without_skel_binding.issubset(attributes_with_skel_binding)) # noqa: PLE1101
additional_skel_attributes = attributes_with_skel_binding.difference(attributes_without_skel_binding)
self.assertTrue("points:default" in additional_skel_attributes) # noqa: PLE1101
self.assertTrue("normals:default" in additional_skel_attributes) # noqa: PLE1101
# validate the joints attribute
joints_attr = skeleton_bundle.get_attribute_by_name("joints")
self.assertTrue(joints_attr.is_valid()) # noqa: PLE1101
num_joints = joints_attr.size()
# validate the rest pose
matrix_attr_type = og.Type(og.BaseDataType.DOUBLE, 16, 1, og.AttributeRole.MATRIX)
rest_transforms_attr = skeleton_bundle.get_attribute_by_name("restTransforms")
self.assertTrue(rest_transforms_attr.is_valid()) # noqa: PLE1101
self.assertEqual(rest_transforms_attr.get_type(), matrix_attr_type) # noqa: PLE1101
self.assertEqual(rest_transforms_attr.size(), num_joints) # noqa: PLE1101
# validate the animated pose which is stored at the "jointLocalTransforms" attribute
joint_local_transforms_attr = skeleton_bundle.get_attribute_by_name("jointLocalTransforms")
self.assertTrue(joint_local_transforms_attr.is_valid()) # noqa: PLE1101
self.assertEqual(joint_local_transforms_attr.get_type(), matrix_attr_type) # noqa: PLE1101
self.assertEqual(joint_local_transforms_attr.size(), num_joints) # noqa: PLE1101
async def test_apply_skel_binding_on_authored_skeletal_relationships(self):
"""validate applying skel binding on a prim that has SkelBindingAPI schema and authored skeletal relationships."""
await self._test_apply_skel_binding_on_skinned_model("skelcylinder.usda")
async def test_apply_skel_binding_on_inherited_skeletal_relationships(self):
"""validate applying skel binding on a prim that has SkelBindingAPI schema and inherited skeletal relationships."""
await self._test_apply_skel_binding_on_skinned_model("skelcylinder_inherited_skeleton.usda")
async def test_apply_skel_binding_on_model_without_normals(self):
"""validate applying skel binding on a model which has SkelBindingAPI schema and no normals."""
# load test scene which contains a mesh that is bound with a skeleton and a skel animation
(result, error) = await ogts.load_test_file("skel_model_without_normals.usda", use_caller_subdirectory=True)
self.assertTrue(result, error) # noqa: PLE1101
controller = og.Controller()
keys = og.Controller.Keys
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
bundle_factory = og.IBundleFactory.create()
# create a ReadPrims node
(test_graph, [read_prims_node], _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("read_prims", self._read_prims_node_type),
],
keys.SET_VALUES: [
# Remove the normals attribute from the list of attributes to import, because ReadPrims
# imports normals by default, and we want to test the SkelBinding when the normals are not
# imported.
("read_prims.inputs:attrNamesToImport", "* ^normals")
],
},
)
# add target prim
mesh_path = "/Model/Arm"
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath("/TestGraph/read_prims.inputs:prims"),
target=mesh_path,
)
await controller.evaluate()
# validate a single child bundle is created when applySkelBinding is not enabled yet.
test_context = test_graph.get_default_graph_context()
output_bundle = test_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
output_bundle = bundle_factory.get_bundle(test_context, output_bundle)
self.assertTrue(output_bundle.valid) # noqa: PLE1101
child_bundles = output_bundle.get_child_bundles()
self.assertTrue(len(child_bundles), 1) # noqa: PLE1101
mesh_bundle = child_bundles[0]
self.assertTrue(mesh_bundle.valid) # noqa: PLE1101
# the mesh bundle has points but no normals
attributes_without_skel_binding = set(mesh_bundle.get_attribute_names())
self.assertTrue("points" in attributes_without_skel_binding) # noqa: PLE1101
self.assertFalse("normals" in attributes_without_skel_binding) # noqa: PLE1101
# apply skel binding
controller.edit(
"/TestGraph",
{
keys.SET_VALUES: ("read_prims.inputs:applySkelBinding", True),
},
)
await controller.evaluate()
# there will be three bundles and we need to get the mesh bundles
child_bundles = output_bundle.get_child_bundles()
self.assertEqual(len(child_bundles), 3) # noqa: PLE1101
mesh_bundle = None
for child_bundle in child_bundles:
source_prim_path_attr = child_bundle.get_attribute_by_name("sourcePrimPath")
if source_prim_path_attr.get() == mesh_path:
mesh_bundle = child_bundle
break
self.assertIsNotNone(mesh_bundle) # noqa: PLE1101
# validate additional skel attributes added to the cylinder bundle
attributes_with_skel_binding = set(mesh_bundle.get_attribute_names())
self.assertTrue(attributes_without_skel_binding.issubset(attributes_with_skel_binding)) # noqa: PLE1101
additional_skel_attributes = attributes_with_skel_binding.difference(attributes_without_skel_binding)
self.assertTrue("points:default" in additional_skel_attributes) # noqa: PLE1101
self.assertFalse("normals:default" in additional_skel_attributes) # noqa: PLE1101
async def test_apply_skel_binding_on_prim_without_required_schema(self):
"""validate applying skel binding to a simple cube which has no SkelBindingAPI schema."""
controller = og.Controller()
keys = og.Controller.Keys
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
bundle_factory = og.IBundleFactory.create()
# create a ReadPrims node
(test_graph, [read_prims_node], _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("read_prims", self._read_prims_node_type),
],
},
)
# add target prim
cube = ogts.create_cube(stage, "World/Cube", (1, 1, 1))
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath("/TestGraph/read_prims.inputs:prims"),
target=cube.GetPath(),
)
await controller.evaluate()
# validate a single child bundle is created before applying skel binding.
test_context = test_graph.get_default_graph_context()
output_bundle = test_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
output_bundle = bundle_factory.get_bundle(test_context, output_bundle)
self.assertTrue(output_bundle.valid) # noqa: PLE1101
child_bundles = output_bundle.get_child_bundles()
self.assertTrue(len(child_bundles), 1) # noqa: PLE1101
child_bundle_before_skel_binding = child_bundles[0]
self.assertTrue(child_bundle_before_skel_binding.valid) # noqa: PLE1101
source_prim_path_str = "sourcePrimPath"
source_prim_path_attr = child_bundle_before_skel_binding.get_attribute_by_name(source_prim_path_str)
self.assertTrue(source_prim_path_attr.is_valid()) # noqa: PLE1101
self.assertEqual(source_prim_path_attr.get(), cube.GetPath()) # noqa: PLE1101
attributes_before_skel_binding = set(child_bundle_before_skel_binding.get_attribute_names())
# apply skel binding
controller.edit(
"/TestGraph",
{
keys.SET_VALUES: ("read_prims.inputs:applySkelBinding", True),
},
)
await controller.evaluate()
# validate no additional child bundle is created after applying skel binding.
child_bundles = output_bundle.get_child_bundles()
self.assertEqual(len(child_bundles), 1) # noqa: PLE1101
child_bundle_after_skel_binding = child_bundles[0]
self.assertTrue(child_bundle_after_skel_binding.valid) # noqa: PLE1101
source_prim_path_attr = child_bundle_after_skel_binding.get_attribute_by_name(source_prim_path_str)
self.assertTrue(source_prim_path_attr.is_valid()) # noqa: PLE1101
self.assertEqual(source_prim_path_attr.get(), cube.GetPath()) # noqa: PLE1101
# validate no additional attributes have been added to the bundle
attributes_after_skel_binding = set(child_bundle_after_skel_binding.get_attribute_names())
self.assertEqual(attributes_before_skel_binding, attributes_after_skel_binding) # noqa: PLE1101
async def _test_apply_skel_binding_on_joint_ordering(self, test_scene, path_skinned_mesh, path_baked_mesh):
"""shared function to validate applying skel binding on joint ordering."""
test_graph_path = "/TestGraph"
time_code_range = range(1, 30)
# load test scene which contains a mesh that is bound with a skeleton and a skel animation
(result, error) = await ogts.load_test_file(test_scene, use_caller_subdirectory=True)
self.assertTrue(result, error) # noqa: PLE1101
controller = og.Controller()
keys = og.Controller.Keys
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
bundle_factory = og.IBundleFactory.create()
(test_graph, (_, extracter_0, extracter_1), _, _) = controller.edit(
test_graph_path,
{
keys.CREATE_NODES: [
("ReadPrims", self._read_prims_node_type),
("ExtractPrim_SkelBinding", "omni.graph.nodes.ExtractPrim"),
("ExtractPrim_BakeSkinning", "omni.graph.nodes.ExtractPrim"),
],
keys.SET_VALUES: [
("ReadPrims.inputs:applySkelBinding", True),
("ExtractPrim_SkelBinding.inputs:primPath", path_skinned_mesh),
("ExtractPrim_BakeSkinning.inputs:primPath", path_baked_mesh),
],
keys.CONNECT: [
("ReadPrims.outputs_primsBundle", "ExtractPrim_SkelBinding.inputs:prims"),
("ReadPrims.outputs_primsBundle", "ExtractPrim_BakeSkinning.inputs:prims"),
],
},
)
# Assign the target prims to the import node.
cylinder_paths = [path_skinned_mesh, path_baked_mesh]
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(test_graph_path + "/ReadPrims.inputs:prims"),
targets=cylinder_paths,
)
# get initial output attributes
await controller.evaluate()
# fetch skinned points
test_context = test_graph.get_default_graph_context()
output_bundle = test_context.get_output_bundle(extracter_0, "outputs_primBundle")
bundle = bundle_factory.get_bundle(test_context, output_bundle)
self.assertTrue(bundle.valid) # noqa: PLE1101
skinned_points_attr = bundle.get_attribute_by_name("points")
self.assertTrue(skinned_points_attr.is_valid()) # noqa: PLE1101
# fetch baked points
test_context = test_graph.get_default_graph_context()
output_bundle = test_context.get_output_bundle(extracter_1, "outputs_primBundle")
bundle = bundle_factory.get_bundle(test_context, output_bundle)
self.assertTrue(bundle.valid) # noqa: PLE1101
baked_points_attr = bundle.get_attribute_by_name("points")
self.assertTrue(baked_points_attr.is_valid()) # noqa: PLE1101
# playback and compare the two lists of points
for time_code in time_code_range:
controller.edit(
test_graph_path,
{keys.SET_VALUES: ("ReadPrims.inputs:usdTimecode", time_code)},
)
await og.Controller.evaluate(test_graph)
skinned_points = skinned_points_attr.get().tolist()
self.assertTrue(isinstance(skinned_points, list)) # noqa: PLE1101
self.assertTrue(len(skinned_points) != 0) # noqa: PLE1101
baked_points = baked_points_attr.get().tolist()
self.assertTrue(isinstance(baked_points, list)) # noqa: PLE1101
self.assertTrue(len(baked_points) != 0) # noqa: PLE1101
self.assertTrue(skinned_points == baked_points) # noqa: PLE1101
async def test_apply_skel_binding_on_joint_ordering(self):
"""validate applying skel binding on joint ordering which is defined on skeleton but may or may not be overridden by skinned mesh"""
# The skinned meshes are baked offline with the following script. Then we can compare the computation result of the
# `ReadPrims` node with the baked meshes.
#
# from pxr import Gf, Usd, UsdSkel
#
# testFile = "lbs.usda"
# stage = Usd.Stage.Open(testFile)
#
# UsdSkel.BakeSkinning(stage.Traverse())
#
# stage.GetRootLayer().Export("lbs.baked.usda")
# Each tuple is (test_scene, path_skinned_mesh, path_baked_mesh)
test_cases = [
("lbs.usda", "/Root/Mesh_Skinned", "/Root/Mesh_Baked"),
("lbs_custom_joint_ordering.usda", "/Root/Mesh_Skinned", "/Root/Mesh_Baked"),
("skelcylinder.usda", "/Root/group1/pCylinder1_Skinned", "/Root/group1/pCylinder1_Baked"),
(
"skelcylinder_custom_joint_ordering.usda",
"/Root/group1/pCylinder1_Skinned",
"/Root/group1/pCylinder1_Baked",
),
]
for test_case in test_cases:
await self._test_apply_skel_binding_on_joint_ordering(*test_case)
async def test_read_prims_attribute_filter(self):
"""Validate the attribute filter functionality of ReadPrim."""
await self._test_attribute_filter(self._read_prims_node_type)
async def _test_attribute_filter(self, node_type):
"""Shared function to validate the attribute filter functionality of ReadPrimBundle and ReadPrim."""
controller = og.Controller()
keys = og.Controller.Keys
test_graph_path = "/TestGraph"
(test_graph, [read_prims_node], _, _) = controller.edit(
test_graph_path,
{
keys.CREATE_NODES: [("read_prims_node", node_type)],
},
)
# Create a cube and connect it as the input prim.
stage = omni.usd.get_context().get_stage()
cube = ogts.create_cube(stage, "World/Cube", (1, 1, 1))
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(test_graph_path + "/read_prims_node.inputs:prims"),
target=cube.GetPath(),
)
await controller.evaluate()
# Get the output bundle.
test_context = test_graph.get_default_graph_context()
output_bundle = test_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
bundle_factory = og.IBundleFactory.create()
output_bundle = bundle_factory.get_bundle(test_context, output_bundle)
self.assertTrue(output_bundle.valid) # noqa: PLE1101
self.assertEqual(output_bundle.get_child_bundle_count(), 1) # noqa: PLE1101
# Get the only child bundle.
child_bundle = output_bundle.get_child_bundle(0)
self.assertTrue(child_bundle.valid) # noqa: PLE1101
# The "size" attribute is expected for a cube by default.
default_attribute_names = child_bundle.get_attribute_names()
self.assertTrue("size" in default_attribute_names) # noqa: PLE1101
# The filtered attribute names will be the same as the default.
attr_filters = ["*", "* dummy", "dummy *"]
for attr_filter in attr_filters:
controller.edit(
test_graph_path,
{
keys.SET_VALUES: ("read_prims_node.inputs:attrNamesToImport", attr_filter),
},
)
await controller.evaluate()
self.assertEqual(set(child_bundle.get_attribute_names()), set(default_attribute_names)) # noqa: PLE1101
# The filtered attribute names will contain "size" only.
attr_filters = [
"size",
"size dummy",
"dummy size",
"????",
"s???",
"?ize",
"?i?e",
"*z?",
"?im* ?ix* ?iz*",
"???? dummy",
"dummy ????",
]
# "sourcePrimPath", "sourcePrimType" and "worldMatrix" are additional attributes created by the node.
expected_attribute_names = {"sourcePrimPath", "sourcePrimType", "worldMatrix", "size"}
for attr_filter in attr_filters:
controller.edit(
test_graph_path,
{
keys.SET_VALUES: ("read_prims_node.inputs:attrNamesToImport", attr_filter),
},
)
await controller.evaluate()
self.assertEqual(set(child_bundle.get_attribute_names()), expected_attribute_names) # noqa: PLE1101
# The filtered attribute names will not contain "size".
attr_filters = [
" ",
"Size",
"SIZE",
"dummy",
"sizedummy",
"dummysize",
"size:dummy",
"dummy:size",
"size&dummy",
"dummy&size",
"*:dummy",
"dummy:*",
"???",
"??",
"?",
"????:dummy",
"dummy:????",
]
# "sourcePrimPath", "sourcePrimType" and "worldMatrix" are additional attributes created by the node.
expected_attribute_names = {"sourcePrimPath", "sourcePrimType", "worldMatrix"}
for attr_filter in attr_filters:
controller.edit(
test_graph_path,
{
keys.SET_VALUES: ("read_prims_node.inputs:attrNamesToImport", attr_filter),
},
)
await controller.evaluate()
self.assertEqual(set(child_bundle.get_attribute_names()), expected_attribute_names) # noqa: PLE1101
async def test_read_prims_time_code_mpib(self):
"""Test whether points and normals keep consistent after modifying time code."""
controller = og.Controller()
keys = og.Controller.Keys
bundle_factory = og.IBundleFactory.create()
stage = omni.usd.get_context().get_stage()
# Create two cubes, whose types are Mesh and Cube respectively.
cube_paths = ["/cube_mesh", "/cube_shape"]
_, default_cube_mesh_path = omni.kit.commands.execute("CreateMeshPrim", prim_type="Cube")
omni.kit.commands.execute("MovePrim", path_from=default_cube_mesh_path, path_to=cube_paths[0])
og.Controller.create_prim(cube_paths[1], {}, "Cube")
# Create a graph that reads the two prims and extract the bundle of the cube mesh
test_graph_path = "/TestGraph"
(test_graph, [_, extract_prim_node], _, _,) = controller.edit(
test_graph_path,
{
keys.CREATE_NODES: [
("read_prims", self._read_prims_node_type),
("extract_prim", "omni.graph.nodes.ExtractPrim"),
],
keys.SET_VALUES: [
("extract_prim.inputs:primPath", cube_paths[0]),
],
keys.CONNECT: [
("read_prims.outputs_primsBundle", "extract_prim.inputs:prims"),
],
},
)
# Assign the target prims to the import node.
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(test_graph_path + "/read_prims.inputs:prims"),
targets=cube_paths,
)
await og.Controller.evaluate(test_graph)
# Get output bundle.
test_context = test_graph.get_default_graph_context()
output_bundle = test_context.get_output_bundle(extract_prim_node, "outputs_primBundle")
bundle = bundle_factory.get_bundle(test_context, output_bundle)
self.assertTrue(bundle.valid) # noqa: PLE1101
# Get points
points_attr = bundle.get_attribute_by_name("points")
self.assertTrue(points_attr.is_valid()) # noqa: PLE1101
points = points_attr.get().tolist()
self.assertTrue(isinstance(points, list)) # noqa: PLE1101
self.assertTrue(len(points) != 0) # noqa: PLE1101
# Get normals
normals_attr = bundle.get_attribute_by_name("normals")
self.assertTrue(normals_attr.is_valid()) # noqa: PLE1101
normals = normals_attr.get().tolist()
self.assertTrue(isinstance(normals, list)) # noqa: PLE1101
self.assertTrue(len(normals) != 0) # noqa: PLE1101
# Modify timecode and trigger evaluation. Run 60 times to eliminate random factor.
for timecode in range(60):
controller.edit(
test_graph_path,
{keys.SET_VALUES: ("read_prims.inputs:usdTimecode", timecode)},
)
await og.Controller.evaluate(test_graph)
# Test whether the points data keep consistent
points_attr = bundle.get_attribute_by_name("points")
self.assertTrue(points_attr.is_valid()) # noqa: PLE1101
self.assertSequenceEqual(points_attr.get().tolist(), points) # noqa: PLE1101
# Test whether the points data keep consistent
normals_attr = bundle.get_attribute_by_name("normals")
self.assertTrue(normals_attr.is_valid()) # noqa: PLE1101
self.assertSequenceEqual(normals_attr.get().tolist(), normals) # noqa: PLE1101
async def test_read_prims_attribute_interpolation(self):
controller = og.Controller()
keys = og.Controller.Keys
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# Create Mesh and Primvar with interpolation
mesh = ogts.create_grid_mesh(stage, "/Mesh")
sts_primvar = UsdGeom.PrimvarsAPI(mesh).CreatePrimvar("st", Sdf.ValueTypeNames.Float2Array)
sts_primvar.SetInterpolation("faceVarying")
# Create Read Prim with test node to test if interpolation was read
test_graph_path = "/TestGraph"
(test_graph, [_, attr_interp], _, _,) = controller.edit(
test_graph_path,
{
keys.CREATE_NODES: [
("read_prims", self._read_prims_node_type),
("attr_interp", "omni.graph.test.TestBundleAttributeInterpolation"),
],
keys.SET_VALUES: ("attr_interp.inputs:attribute", "primvars:st"),
keys.CONNECT: ("read_prims.outputs_primsBundle", "attr_interp.inputs:prims"),
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(test_graph_path + "/read_prims.inputs:prims"),
target=mesh.GetPath(),
)
await og.Controller.evaluate(test_graph)
# Confirm the interpolation is carried properly from Read Prims and Bundle Prims
self.assertEqual(attr_interp.get_attribute("outputs:interpolation").get(), "faceVarying") # noqa: PLE1101
async def test_read_prim_nodes_have_nan_defaults(self):
"""Validates that manually created prim nodes have nan as default"""
controller = og.Controller()
keys = og.Controller.Keys
test_graph_path = "/TestGraph"
(_, nodes, _, _) = controller.edit(
test_graph_path,
{
keys.CREATE_NODES: [
("ReadPrims", self._read_prims_node_type),
("ReadPrimAttr", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrimAttrs", "omni.graph.nodes.ReadPrimAttributes"),
("ReadPrimsBundle", "omni.graph.nodes.ReadPrimsBundle"),
],
},
)
for node in nodes:
self.assertTrue(isnan(node.get_attribute("inputs:usdTimecode").get())) # noqa: PLE1101
async def test_read_prim_have_no_errors_on_creation(self):
"""Validates that creating ReadPrimAttribute nodes with default values doesn't throw errors"""
controller = og.Controller()
keys = og.Controller.Keys
test_graph_path = "/TestGraph"
(test_graph, nodes, _, _) = controller.edit(
{"graph_path": test_graph_path},
{
keys.CREATE_NODES: [
("ReadPrimAttr", "omni.graph.nodes.ReadPrimAttribute"),
],
keys.SET_VALUES: [
("ReadPrimAttr.inputs:name", ""),
],
},
)
self.assertEqual(len(nodes[0].get_compute_messages(og.ERROR)), 0) # noqa: PLE1101
nodes[0].clear_old_compute_messages()
with ogts.ExpectedError():
await og.Controller.evaluate(test_graph)
self.assertEqual(len(nodes[0].get_compute_messages(og.ERROR)), 1) # noqa: PLE1101
# Tests for ReadPrims (legacy) node only + all tests in TestReadPrimsCommon
class TestReadPrimsNode(ogts.OmniGraphTestCase, TestReadPrimsCommon):
"""
Unit tests for ReadPrims (legacy) node in this extension
It also inherits all tests from TestReadPrimsCommon unless explicitly opted out
"""
def __init__(self, *args, **kwargs):
ogts.OmniGraphTestCase.__init__(self, *args, **kwargs)
TestReadPrimsCommon.__init__(self, read_prims_node_type="omni.graph.nodes.ReadPrims")
async def test_read_prims_node_v1(self):
"""Validate backward compatibility for legacy versions of ReadPrims node."""
# load the test scene which contains a ReadPrims V1 node
(result, error) = await ogts.load_test_file("TestReadPrimsNode_v1.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
test_graph_path = "/World/TestGraph"
test_graph = og.get_graph_by_path(test_graph_path)
read_prim_node = test_graph.get_node(test_graph_path + "/read_prims")
self.assertTrue(read_prim_node.is_valid())
# validate new attributes can be automatically created with their default value set.
attr_names_and_values = [
("inputs:applySkelBinding", False),
]
for attr_name, attr_value in attr_names_and_values:
self.assertTrue(read_prim_node.get_attribute_exists(attr_name))
self.assertTrue(read_prim_node.get_attribute(attr_name).get() == attr_value)
# this is a test for ReadPrimBundle, to utilize _test_attribute_filter, thus it is not in TestReadPrimsBundle
async def test_read_prims_bundle_attribute_filter(self):
"""Validate the attribute filter functionality of ReadPrimBundle."""
await self._test_attribute_filter("omni.graph.nodes.ReadPrimsBundle")
# Tests for ReadPrimsV2 node only + all tests in TestReadPrimsCommon
class TestReadPrimsV2Node(ogts.OmniGraphTestCase, TestReadPrimsCommon):
"""
Unit tests for ReadPrimsV2 node in this extension
It also inherits all tests from TestReadPrimsCommon unless explicitly opted out
"""
def __init__(self, *args, **kwargs):
ogts.OmniGraphTestCase.__init__(self, *args, **kwargs)
TestReadPrimsCommon.__init__(self, read_prims_node_type="omni.graph.nodes.ReadPrimsV2")
async def test_read_prims_root_prims_targets(self):
"""Test omni.graph.nodes.ReadPrims with rootPrims targets"""
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
test_graph_path = "/World/TestGraph"
controller = og.Controller()
keys = og.Controller.Keys
root1 = stage.DefinePrim("/Root1", "Xform")
stage.DefinePrim("/Root1/Xform", "Xform")
stage.DefinePrim("/Root1/Xform/Cube", "Cube")
stage.DefinePrim("/Root2", "Xform")
stage.DefinePrim("/Root2/Xform", "Xform")
stage.DefinePrim("/Root2/Xform/Sphere", "Sphere")
root3 = stage.DefinePrim("/Root3", "Xform")
stage.DefinePrim("/Root3/Xform", "Xform")
stage.DefinePrim("/Root3/Xform/Cone", "Cone")
(graph, [read_prims_node], _, _) = controller.edit(
test_graph_path,
{
keys.CREATE_NODES: [
("Read", self._read_prims_node_type),
],
keys.SET_VALUES: [
("Read.inputs:pathPattern", "*"),
],
},
)
# connect /Root1 and /Root3 to inputs:rootPrims
# The node should find all prims under them, but not /Root2
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"),
targets=[root1.GetPath(), root3.GetPath()],
)
await controller.evaluate()
graph_context = graph.get_default_graph_context()
output_prims_bundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
self.assertTrue(output_prims_bundle.valid)
expected_matched_prim_paths = {
"/Root1",
"/Root1/Xform",
"/Root1/Xform/Cube",
"/Root3",
"/Root3/Xform",
"/Root3/Xform/Cone",
}
child_bundles = output_prims_bundle.get_child_bundles()
self.assertEqual(len(child_bundles), len(expected_matched_prim_paths))
for bundle in child_bundles:
path = bundle.get_attribute_by_name("sourcePrimPath").get()
expected_matched_prim_paths.remove(path)
# no exception should raise when remove a path in the loop above
# after the loop, all paths should have been removed
self.assertEqual(len(expected_matched_prim_paths), 0)
| 45,040 | Python | 42.64438 | 140 | 0.61714 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_timeline_nodes.py | """Unit tests for the timeline playback nodes in this extension"""
import carb.events
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.commands
import omni.kit.stage_templates
import omni.kit.test
import omni.timeline
import omni.usd
# ======================================================================
class TestTimelineNodes(ogts.OmniGraphTestCase):
TEST_GRAPH_PATH = "/World/TestGraph"
FRAME_RATE = 64 # power of two so that FRAME_DURATION is an exact binary number
FRAME_DURATION = 1.0 / FRAME_RATE
START_FRAME = 10
END_FRAME = 20
START_TIME = START_FRAME * FRAME_DURATION
END_TIME = END_FRAME * FRAME_DURATION
TEST_MESSAGE_NAME = "omni.graph.nodes/triggerTimelineNode"
TEST_MESSAGE_EVENT = carb.events.type_from_string(TEST_MESSAGE_NAME)
def flush(self):
# The timeline is async, we need to commit any pending changes before we can read its last state.
self._timeline.commit()
def current_time(self):
self.flush()
return self._timeline.get_current_time()
def current_frame(self):
return self._timeline.time_to_time_code(self.current_time())
def assert_from_start(self, frame: int, message: str):
self.assertEqual(self.current_frame(), self.START_FRAME + frame, message)
def is_playing(self):
self.flush()
return self._timeline.is_playing()
def is_looping(self):
self.flush()
return self._timeline.is_looping()
def dump(self, header=""):
self.flush()
tl = self._timeline
print(
f"""
Timeline {header}
tick:{tl.get_current_tick()}
time:{tl.get_current_time()}
start:{tl.get_start_time()}
end:{tl.get_end_time()}
playing:{tl.is_playing()}
looping:{tl.is_looping()}
"""
)
async def tick(self):
await omni.kit.app.get_app().next_update_async()
async def fire(self):
app = omni.kit.app.get_app()
message_bus = app.get_message_bus_event_stream()
message_bus.push(self.TEST_MESSAGE_EVENT)
await self.tick()
# ----------------------------------------------------------------------
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
fps = self.FRAME_RATE
# make sure we put the global timeline in the same initial state
self._timeline = omni.timeline.get_timeline_interface()
self._timeline.stop()
self._timeline.set_current_time(0)
self._timeline.set_end_time(self.END_TIME)
self._timeline.set_start_time(self.START_TIME)
self._timeline.set_time_codes_per_second(fps)
self._timeline.set_looping(False)
self._timeline.set_fast_mode(False)
self._timeline.set_prerolling(True)
self._timeline.set_auto_update(True)
self._timeline.set_play_every_frame(True)
self._timeline.set_ticks_per_frame(1)
self._timeline.set_target_framerate(fps)
self._timeline.commit()
# ----------------------------------------------------------------------
async def test_timeline_start_node(self):
"""Test OgnTimelineStart node"""
# convert to action graph
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnMessage", "omni.graph.action.OnMessageBusEvent"),
("StartTimeline", "omni.graph.nodes.StartTimeline"),
],
keys.CONNECT: [
("OnMessage.outputs:execOut", "StartTimeline.inputs:execIn"),
],
keys.SET_VALUES: [
("OnMessage.inputs:onlyPlayback", False),
("OnMessage.inputs:eventName", self.TEST_MESSAGE_NAME),
],
},
)
# Initialize
await self.tick()
self.assertFalse(self.is_playing(), "Should not have started yet")
# Trigger the node
await self.fire()
self.assertTrue(self.is_playing(), "Should have started")
self.assert_from_start(0, "Should have started at frame 0 from start")
await self.tick()
self.assert_from_start(1, "Should have advanced one frame after starting")
# Trigger the node again
await self.fire()
self.assert_from_start(2, "Should not have restarted after starting twice")
# Pause the timeline
self._timeline.pause()
self._timeline.commit()
await self.tick()
self.assert_from_start(2, "Should have been paused at frame 2")
# Start again
await self.fire()
self.assert_from_start(2, "Should be at frame 2 after paused and starting again")
await self.tick()
self.assert_from_start(3, "Should be at frame 3 after paused and playing for one frame")
# ----------------------------------------------------------------------
async def test_timeline_stop_node(self):
"""Test OgnTimelineStop node"""
# convert to action graph
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnMessage", "omni.graph.action.OnMessageBusEvent"),
("StopTimeline", "omni.graph.nodes.StopTimeline"),
],
keys.CONNECT: [
("OnMessage.outputs:execOut", "StopTimeline.inputs:execIn"),
],
keys.SET_VALUES: [
("OnMessage.inputs:onlyPlayback", False),
("OnMessage.inputs:eventName", self.TEST_MESSAGE_NAME),
],
},
)
# Initialize
await self.tick()
self.assertFalse(self.is_playing(), "Should not have started")
# Trigger the node
await self.fire()
await self.tick()
# Stopping a stopped timeline has no effect
self.assertTrue(self.current_frame() == 0, "Should not have started when stopping")
# Start the timeline
self._timeline.play()
self.assertTrue(self.is_playing(), "Should have started")
play_frames = 5
# Advance the timeline N frames
for _ in range(play_frames):
await self.tick()
self.assert_from_start(play_frames, f"Should have played {play_frames} frames")
# Trigger the node
await self.fire()
stop_frame = play_frames + 1
self.assertFalse(self.is_playing(), "Should have stopped")
self.assert_from_start(stop_frame, f"Should have stopped at frame {stop_frame}")
await self.tick()
self.assert_from_start(
stop_frame,
f"Should still be at frame {stop_frame} after stopped one frame",
)
# Trigger the node again
await self.fire()
# Should still be at the current frame
self.assert_from_start(
stop_frame,
f"Should still be at frame {stop_frame} after stopping twice",
)
# ----------------------------------------------------------------------
async def test_timeline_loop_node(self):
"""Test OgnTimelineLoop node"""
# convert to action graph
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnMessage", "omni.graph.action.OnMessageBusEvent"),
("LoopTimeline", "omni.graph.nodes.LoopTimeline"),
],
keys.CONNECT: [
("OnMessage.outputs:execOut", "LoopTimeline.inputs:execIn"),
],
keys.SET_VALUES: [
("OnMessage.inputs:onlyPlayback", False),
("OnMessage.inputs:eventName", self.TEST_MESSAGE_NAME),
],
},
)
def set_looping(value):
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: [
("LoopTimeline.inputs:loop", value),
],
},
)
# Initialize
await self.tick()
self.assertFalse(self.is_looping(), "Should not be looping yet")
# Enable looping
set_looping(True)
await self.fire()
self.assertTrue(self.is_looping(), "Should be looping")
# Disable looping
set_looping(False)
await self.fire()
self.assertFalse(self.is_looping(), "Should not be looping")
# ----------------------------------------------------------------------
async def test_timeline_get_node(self):
"""Test OgnTimelineGet node"""
# convert to push graph
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "push"})
controller = og.Controller()
keys = og.Controller.Keys
(_, [node], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("GetTimeline", "omni.graph.nodes.GetTimeline"),
],
},
)
def get_attr_value(name):
attr = og.Controller.attribute(f"outputs:{name}", node)
return og.Controller(attr).get()
def assert_attr_value(name, value):
self.assertEqual(get_attr_value(name), value, name)
async def assert_node_values(playing, looping):
await self.tick()
assert_attr_value("time", self._timeline.get_current_time())
assert_attr_value("frame", self.current_frame())
assert_attr_value("startTime", self.START_TIME)
assert_attr_value("startFrame", self.START_FRAME)
assert_attr_value("endTime", self.END_TIME)
assert_attr_value("endFrame", self.END_FRAME)
assert_attr_value("framesPerSecond", self.FRAME_RATE)
assert_attr_value("isPlaying", playing)
assert_attr_value("isLooping", looping)
await assert_node_values(playing=False, looping=False)
self._timeline.pause()
await assert_node_values(playing=False, looping=False)
self._timeline.play()
await assert_node_values(playing=True, looping=False)
await assert_node_values(playing=True, looping=False)
self._timeline.set_looping(True)
await assert_node_values(playing=True, looping=True)
await assert_node_values(playing=True, looping=True)
# ----------------------------------------------------------------------
async def test_timeline_set_node(self):
"""Test OgnTimelineSet node"""
# convert to push graph
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "push"})
controller = og.Controller()
keys = og.Controller.Keys
(_, [node], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("SetTimeline", "omni.graph.nodes.SetTimeline"),
],
},
)
def get_attr_value(name):
attr = og.Controller.attribute(f"outputs:{name}", node)
return og.Controller(attr).get()
async def set_node_property(property_name, property_value):
attr = og.Controller.attribute("inputs:propName", node)
attr.set(property_name)
attr = og.Controller.attribute("inputs:propValue", node)
attr.set(property_value)
await self.tick()
self.flush()
async def assert_set_position(target_frame, expected_frame, clamped):
await set_node_property("Frame", target_frame)
self.assertEqual(self.current_frame(), expected_frame, "Wrong Frame")
self.assertEqual(get_attr_value("clamped"), clamped, "Wrong clamping")
target_time = target_frame * self.FRAME_DURATION
expected_time = expected_frame * self.FRAME_DURATION
await set_node_property("Time", target_time)
self.assertEqual(self.current_time(), expected_time, "Wrong Time")
self.assertEqual(get_attr_value("clamped"), clamped, "Wrong clamping")
for f in range(self.START_FRAME, self.END_FRAME):
await assert_set_position(f, f, False)
await assert_set_position(self.START_FRAME - 1, self.START_FRAME, True)
await assert_set_position(self.END_FRAME + 1, self.END_FRAME, True)
await set_node_property("StartTime", 0)
self.assertEqual(self._timeline.get_start_time(), 0, "Wrong StartTime")
await set_node_property("StartFrame", 1)
self.assertEqual(self._timeline.get_start_time(), self.FRAME_DURATION, "Wrong StartFrame")
await set_node_property("EndTime", 10)
self.assertEqual(self._timeline.get_end_time(), 10, "Wrong EndTime")
await set_node_property("EndFrame", 2)
self.assertEqual(self._timeline.get_end_time(), 2 * self.FRAME_DURATION, "Wrong EndFrame")
await set_node_property("FramesPerSecond", 30)
self.assertEqual(self._timeline.get_time_codes_per_seconds(), 30, "Wrong FramesPerSecond")
# ----------------------------------------------------------------------
| 13,858 | Python | 33.135468 | 105 | 0.558161 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_bundle_inspector.py | """Test the node that inspects attribute bundles"""
import omni.graph.core as og
import omni.graph.core.tests as ogts
from .bundle_test_utils import (
bundle_inspector_results,
get_bundle_with_all_results,
prim_with_everything_definition,
verify_bundles_are_equal,
)
# ======================================================================
class TestBundleInspector(ogts.test_case_class()):
"""Run a simple unit test that exercises graph functionality"""
# ----------------------------------------------------------------------
async def test_node_with_contents(self):
"""Test the node with some pre-made input bundle contents"""
prim_definition = prim_with_everything_definition()
keys = og.Controller.Keys
(_, [inspector_node, _], [prim], _) = og.Controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("Inspector", "omni.graph.nodes.BundleInspector"),
],
keys.CREATE_PRIMS: ("TestPrim", prim_definition),
keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"),
keys.CONNECT: [
("TestPrimExtract.outputs_primBundle", "Inspector.inputs:bundle"),
],
},
)
await og.Controller.evaluate()
results = bundle_inspector_results(inspector_node)
expected_values = get_bundle_with_all_results(str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName()))
try:
verify_bundles_are_equal(results, expected_values)
except ValueError as error:
self.assertTrue(False, error)
async def test_bundle_inspector_node_v2(self):
"""Validate backward compatibility for legacy versions of BundleInspector node."""
# load the test scene which contains a ReadPrim V1 node
(result, error) = await ogts.load_test_file("TestBundleInspectorNode_v2.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
test_graph_path = "/TestGraph"
test_graph = og.get_graph_by_path(test_graph_path)
read_prim_node = test_graph.get_node(test_graph_path + "/Inspector")
self.assertTrue(read_prim_node.is_valid())
# validate new attributes can be automatically created with their default value set.
attr_names_and_values = [
("inputs:inspectDepth", 1),
]
for (attr_name, attr_value) in attr_names_and_values:
self.assertTrue(read_prim_node.get_attribute_exists(attr_name))
self.assertTrue(read_prim_node.get_attribute(attr_name).get() == attr_value)
| 2,707 | Python | 41.984126 | 120 | 0.596601 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_variant_nodes.py | """Testing the stability of the API in this module"""
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from pxr import Sdf
# ======================================================================
class TestVariantNodes(ogts.OmniGraphTestCase):
def __init__(self, arg):
super().__init__(arg)
self.usda_file = "variant_sets.usda"
self.input_prim = "/InputPrim"
@staticmethod
def set_variant_selection(prim_path, variant_set_name, variant_name): # noqa: C901
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(prim_path)
variant_set = prim.GetVariantSet(variant_set_name)
variant_names = variant_set.GetVariantNames()
if variant_name not in variant_names:
variant_set.AddVariant(variant_name)
variant_set.SetVariantSelection(variant_name)
def set_up_variant_sets(self):
for prim_path in [self.input_prim]:
stage = omni.usd.get_context().get_stage()
prim = stage.DefinePrim(prim_path, "Xform")
attr = prim.CreateAttribute("primvars:displayColor", Sdf.ValueTypeNames.Color3f)
variant_set_name = "color"
variant_sets = prim.GetVariantSets()
variant_set = variant_sets.GetVariantSet(variant_set_name)
variant_set.AddVariant("red")
variant_set.AddVariant("green")
variant_set.AddVariant("blue")
variant_set.SetVariantSelection("red")
with variant_set.GetVariantEditContext():
attr.Set((1, 0, 0))
variant_set.SetVariantSelection("green")
with variant_set.GetVariantEditContext():
attr.Set((0, 1, 0))
variant_set.SetVariantSelection("blue")
with variant_set.GetVariantEditContext():
attr.Set((0, 0, 1))
variant_set.SetVariantSelection("default_color")
variant_set_name = "size"
variant_sets = prim.GetVariantSets()
variant_set = variant_sets.GetVariantSet(variant_set_name)
variant_set.AddVariant("small")
variant_set.AddVariant("medium")
variant_set.AddVariant("large")
variant_set.SetVariantSelection("default_size")
def get_variant_selection(self, prim_path, variant_set_name):
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(prim_path)
variant_set = prim.GetVariantSet(variant_set_name)
return variant_set.GetVariantSelection()
async def _test_variant_node(
self,
node_type,
node_attrs,
expected_values,
expected_variants=None,
expected_attr_values=None,
read_file=True,
use_connected_prim=False,
variant_selection=None,
):
await omni.usd.get_context().new_stage_async()
if read_file:
(result, error) = await ogts.load_test_file(self.usda_file, use_caller_subdirectory=True)
self.assertTrue(result, error)
else:
self.set_up_variant_sets()
if variant_selection:
prim_path, variant_set_name, variant_name = variant_selection
self.set_variant_selection(prim_path, variant_set_name, variant_name)
keys = og.Controller.Keys
controller = og.Controller()
graph = "/TestGraph"
variant_node = "VariantNode"
values = [(f"{variant_node}.{key}", value) for key, value in node_attrs.items()]
controller.edit(
graph,
{
keys.CREATE_NODES: [
(variant_node, node_type),
],
keys.SET_VALUES: values,
},
)
stage = omni.usd.get_context().get_stage()
# use a prim path connection instead of setting the value directly
if use_connected_prim:
(_, (_prim_at_path, _), _, _) = controller.edit(
graph,
{
keys.CREATE_NODES: [
("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
],
keys.CONNECT: [
("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"),
("GetPrimAtPath.outputs:prims", f"{variant_node}.inputs:prim"),
],
keys.SET_VALUES: [
("ConstToken.inputs:value", self.input_prim),
],
},
)
else:
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{graph}/{variant_node}.inputs:prim"),
target=self.input_prim,
)
await controller.evaluate()
for output in expected_values.keys():
test_attribute = controller.attribute(output, f"{graph}/{variant_node}")
actual_value = controller.get(attribute=test_attribute)
if isinstance(expected_values[output], list):
actual_value = list(actual_value)
self.assertTrue(
actual_value == expected_values[output],
f"actual_value: {actual_value}, expected_value: {expected_values[output]}",
)
if expected_variants:
for prim_path, variant_set_name, expected_variant_name in expected_variants:
actual_value = self.get_variant_selection(prim_path, variant_set_name)
self.assertTrue(
actual_value == expected_variant_name,
f"actual_value: {actual_value}, expected_value: {expected_variant_name}",
)
if expected_attr_values:
for prim_path, attr_name, expected_value in expected_attr_values:
test_attribute = stage.GetPropertyAtPath(f"{prim_path}.{attr_name}")
actual_value = test_attribute.Get()
self.assertTrue(
actual_value == expected_value,
f"actual_value: {actual_value}, expected_value: {expected_value}",
)
async def test_get_variant_names_1(self):
node_type = "omni.graph.nodes.GetVariantNames"
node_attrs = {
"inputs:variantSetName": "color",
}
expected_values = {"outputs:variantNames": ["blue", "green", "red"]}
await self._test_variant_node(node_type, node_attrs, expected_values)
async def test_get_variant_names_2(self):
node_type = "omni.graph.nodes.GetVariantNames"
node_attrs = {
"inputs:variantSetName": "color",
}
expected_values = {"outputs:variantNames": ["blue", "green", "red"]}
await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=False)
await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=True)
async def test_get_variant_selection(self):
node_type = "omni.graph.nodes.GetVariantSelection"
node_attrs = {
"inputs:variantSetName": "color",
}
expected_values = {"outputs:variantName": "default_color"}
await self._test_variant_node(node_type, node_attrs, expected_values)
async def test_get_variant_selection_2(self):
node_type = "omni.graph.nodes.GetVariantSelection"
node_attrs = {
"inputs:variantSetName": "color",
}
expected_values = {"outputs:variantName": "green"}
variant_selection = (self.input_prim, "color", "green")
await self._test_variant_node(
node_type,
node_attrs,
expected_values,
variant_selection=variant_selection,
use_connected_prim=False,
)
await self._test_variant_node(
node_type,
node_attrs,
expected_values,
variant_selection=variant_selection,
use_connected_prim=True,
)
async def test_get_variant_set_names(self):
node_type = "omni.graph.nodes.GetVariantSetNames"
node_attrs = {}
expected_values = {"outputs:variantSetNames": ["color", "size"]}
await self._test_variant_node(node_type, node_attrs, expected_values)
async def test_get_variant_set_names_2(self):
node_type = "omni.graph.nodes.GetVariantSetNames"
node_attrs = {}
expected_values = {"outputs:variantSetNames": ["color", "size"]}
await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=False)
await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=True)
async def test_has_variant_set_1(self):
node_type = "omni.graph.nodes.HasVariantSet"
node_attrs = {
"inputs:variantSetName": "color",
}
expected_values = {"outputs:exists": True}
await self._test_variant_node(node_type, node_attrs, expected_values)
async def test_has_variant_set_2(self):
node_type = "omni.graph.nodes.HasVariantSet"
node_attrs = {
"inputs:variantSetName": "flavor",
}
expected_values = {"outputs:exists": False}
await self._test_variant_node(node_type, node_attrs, expected_values)
async def test_has_variant_set_3(self):
node_type = "omni.graph.nodes.HasVariantSet"
node_attrs = {
"inputs:variantSetName": "flavor",
}
expected_values = {"outputs:exists": False}
await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=False)
await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=True)
async def test_clear_variant_set_with_default(self):
node_type = "omni.graph.nodes.ClearVariantSelection"
node_attrs = {
"inputs:variantSetName": "color",
}
expected_values = {}
expected_variants = [(self.input_prim, "color", "default_color")]
await self._test_variant_node(node_type, node_attrs, expected_values, expected_variants)
async def test_clear_variant_set(self):
node_type = "omni.graph.nodes.ClearVariantSelection"
node_attrs = {
"inputs:variantSetName": "color",
}
expected_values = {}
expected_variants = [(self.input_prim, "color", "default_color")]
await self._test_variant_node(node_type, node_attrs, expected_values, expected_variants, read_file=False)
async def test_clear_variant_set_2(self):
node_type = "omni.graph.nodes.ClearVariantSelection"
node_attrs = {
"inputs:variantSetName": "color",
}
expected_values = {}
expected_variants = [(self.input_prim, "color", "default_color")]
await self._test_variant_node(
node_type,
node_attrs,
expected_values,
expected_variants,
read_file=False,
use_connected_prim=False,
)
await self._test_variant_node(
node_type,
node_attrs,
expected_values,
expected_variants,
read_file=False,
use_connected_prim=True,
)
async def test_set_variant_selection(self):
node_type = "omni.graph.nodes.SetVariantSelection"
node_attrs = {
"inputs:setVariant": True,
"inputs:variantSetName": "color",
"inputs:variantName": "red",
}
expected_values = {}
expected_variants = [(self.input_prim, "color", "red")]
await self._test_variant_node(node_type, node_attrs, expected_values, expected_variants)
async def test_set_variant_selection_2(self):
node_type = "omni.graph.nodes.SetVariantSelection"
node_attrs = {
"inputs:setVariant": True,
"inputs:variantSetName": "color",
"inputs:variantName": "red",
}
expected_values = {}
expected_variants = [(self.input_prim, "color", "red")]
await self._test_variant_node(
node_type,
node_attrs,
expected_values,
expected_variants,
use_connected_prim=False,
)
await self._test_variant_node(
node_type,
node_attrs,
expected_values,
expected_variants,
use_connected_prim=True,
)
async def test_blend_variants(self):
node_type = "omni.graph.nodes.BlendVariants"
node_attrs = {
"inputs:variantSetName": "color",
"inputs:blend": 0.5,
"inputs:variantNameA": "red",
"inputs:variantNameB": "green",
}
expected_values = {}
expected_variants = []
expected_attr_values = [(self.input_prim, "primvars:displayColor", [0.5, 0.5, 0.0])]
await self._test_variant_node(
node_type,
node_attrs,
expected_values,
expected_variants,
expected_attr_values,
read_file=False,
)
| 13,333 | Python | 35.531507 | 113 | 0.572114 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_timer_node.py | # 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.
#
import asyncio
from pathlib import Path
from typing import Tuple
import omni.graph.core as og
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.kit.ui_test as ui_test
import omni.usd
from carb.input import KeyboardInput as Key
class TestTimerNode(omni.kit.test.AsyncTestCase):
async def setUp(self):
extension_root_folder = Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
self._test_files = extension_root_folder.joinpath("data/tests/usd")
await self._load_stage()
async def tearDown(self):
await omni.usd.get_context().close_stage_async()
async def test_timer_node(self):
await self._test_timer_node_impl()
async def _load_stage(self):
usd_context = omni.usd.get_context()
filename = "timer.usda"
test_file_path = self._test_files.joinpath(filename).absolute()
await usd_context.open_stage_async(str(test_file_path))
print(f"Loaded: {test_file_path}")
self._stage = usd_context.get_stage()
async def _test_timer_node_impl(self):
node = self._stage.GetPrimAtPath("/World/ActionGraph/Timer")
graph = self._stage.GetPrimAtPath("/World/ActionGraph")
self.assertEqual(graph.GetTypeName(), "OmniGraph")
await ui_test.emulate_keyboard_press(Key.A)
await omni.kit.app.get_app().next_update_async()
await self._test_time_and_range(node, [(0, (0, 0.1)), (1, (0.4, 0.6)), (2.5, (1, 1))])
async def _test_time_and_range(self, node: og.Node, time_range: Tuple[float, Tuple[float, float]]):
for (time, (min_value, max_value)) in time_range:
print("Time: ", time, "Range: ", min_value, max_value)
if time > 0:
print("sleeping for ", time, " seconds")
await asyncio.sleep(time)
print("sleeping done")
self._test_y_within_range(node, min_value, max_value)
# because asyncio.sleep(1) does not sleep for exactly that amount of time, check the result in an range
def _test_y_within_range(self, node: og.Node, min_value: float, max_value: float):
actual_value = og.Controller.get(f"{node.GetPath()}.outputs:value")
print(f"min_value: {min_value}, max_value: {max_value} actual_value: {actual_value}")
self.assertGreaterEqual(actual_value, min_value)
self.assertLessEqual(actual_value, max_value)
| 2,905 | Python | 38.808219 | 107 | 0.667814 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_read_prims_incremental.py | # noqa: PLC0302
from typing import List
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
from pxr import Sdf, Usd, UsdGeom
_debug = False
class TestReadPrimsIncremental(ogts.OmniGraphTestCase):
"""Unit tests for incremental behavior of the ReadPrimsV2 node in this extension"""
async def test_read_prims_change_tracking_path_targets(self):
"""Test change tracking of omni.graph.nodes.ReadPrimsV2 using path targets"""
await self._test_read_prims_change_tracking_impl(False)
async def test_read_prims_change_tracking_path_pattern(self):
"""Test change tracking of omni.graph.nodes.ReadPrimsV2 using path pattern"""
await self._test_read_prims_change_tracking_impl(True)
async def _test_read_prims_change_tracking_impl(self, use_path_pattern):
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
test_graph_path = "/World/TestGraph"
controller = og.Controller()
keys = og.Controller.Keys
xcube = UsdGeom.Xform.Define(stage, "/XCube")
UsdGeom.Xform.Define(stage, "/XCone")
cube = ogts.create_cube(stage, "XCube/Cube", (1, 0, 0))
cone = ogts.create_cone(stage, "XCone/Cone", (0, 1, 0))
cube.GetAttribute("size").Set(100)
cone.GetAttribute("radius").Set(50)
cone.GetAttribute("height").Set(10)
cube_path = str(cube.GetPath())
cone_path = str(cone.GetPath())
(graph, [read_prims_node, _], _, _) = controller.edit(
test_graph_path,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Inspector", "omni.graph.nodes.BundleInspector"),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Inspector.inputs:bundle"),
],
keys.SET_VALUES: [
("Inspector.inputs:print", False),
],
},
)
if use_path_pattern:
controller.edit(
test_graph_path,
{
keys.SET_VALUES: [
("Read.inputs:pathPattern", "/X*/C*"),
],
},
)
else:
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"),
targets=[cube_path, cone_path],
)
def get_attr(bundle, name):
return bundle.get_attribute_by_name(name)
def get_attr_value(bundle, name):
return get_attr(bundle, name).get()
def assert_attr_value(bundle, name, value):
if isinstance(value, list):
self.assertEqual(get_attr_value(bundle, name).tolist(), value)
else:
self.assertEqual(get_attr_value(bundle, name), value)
def assert_attr_missing(bundle, name):
self.assertFalse(get_attr(bundle, name).is_valid())
def assert_stamp(bundle, stamp):
assert_attr_value(bundle, "_debugStamp", stamp)
def assert_stamp_missing(bundle):
assert_attr_missing(bundle, "_debugStamp")
def set_stamp(stamp):
if _debug:
print(f"### Setting debug stamp to {stamp}")
controller.edit(test_graph_path, {keys.SET_VALUES: ("Read.inputs:_debugStamp", stamp)})
def set_change_tracking(enable):
controller.edit(test_graph_path, {keys.SET_VALUES: ("Read.inputs:enableChangeTracking", enable)})
def get_expected_prim_attributes_count(prim, debug_stamp=False, bbox=False):
n = len(prim.GetPropertyNames())
n += 3 # sourcePrimPath, sourcePrimType, worldMatrix
n -= 1 # remove "proxyPrim" which is skipped unless it has targets
if debug_stamp:
n += 1 # _debugStamp
if bbox:
n += 3 # bboxTransform, bboxCenter, bboxSize
return n
id_mat = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
# initial update
set_stamp(10)
await controller.evaluate()
graph_context = graph.get_default_graph_context()
container_rwbundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
self.assertTrue(container_rwbundle.valid)
self.assertFalse(container_rwbundle.is_read_only())
bundle_factory = og.IBundleFactory.create()
container = bundle_factory.get_const_bundle_from_path(graph_context, container_rwbundle.get_path())
self.assertTrue(container.is_read_only())
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 2)
# check initial bundle output
# full updates will have negative debug stamps on the container bundle
assert_stamp(container, -10)
cube_bundle = None
cone_bundle = None
for bundle in child_bundles:
# reading attribute values from writable bundle will bump dirty ids, so make sure it is a read-only bundle.
self.assertTrue(bundle.is_read_only())
assert_stamp_missing(bundle)
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
path = get_attr_value(bundle, "sourcePrimPath")
if path == cube_path:
cube_bundle = bundle
n_attrs = get_expected_prim_attributes_count(cube)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "size", 100)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]])
elif path == cone_path:
cone_bundle = bundle
n_attrs = get_expected_prim_attributes_count(cone)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_attr_value(bundle, "sourcePrimType", "Cone")
assert_attr_value(bundle, "radius", 50)
assert_attr_value(bundle, "height", 10)
assert_attr_value(bundle, "primvars:displayColor", [[0, 1, 0]])
else:
self.fail(path)
self.assertIsNotNone(cube_bundle)
self.assertIsNotNone(cone_bundle)
# empty update
set_stamp(15)
await controller.evaluate()
# nothing should have been updated.
assert_stamp(container, -10)
container_bundle_name = container.get_name()
cube_bundle_name = cube_bundle.get_name()
cone_bundle_name = cone_bundle.get_name()
dirtyid_interface = og._og_unstable.IDirtyID2.create(graph_context) # noqa: PLW0212
self.assertIsNotNone(dirtyid_interface)
# dirty tracking is not activated for the output bundle
entries = [container]
entry_names = [container_bundle_name]
for bundle in child_bundles:
bundle_name = bundle.get_name()
attrs = bundle.get_attributes()
entries.append(bundle)
entries.extend(attrs)
entry_names.append(bundle_name)
entry_names.extend([bundle_name + "." + attr.get_name() for attr in attrs])
# invalid dirty ids expected
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid_validity(dirtyid_interface, entry_names, curr_dirtyids, False)
# activate dirty tracking
controller.edit(
test_graph_path,
{
keys.SET_VALUES: [
("Read.inputs:enableBundleChangeTracking", True),
],
},
)
await controller.evaluate()
# valid dirty ids expected
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid_validity(dirtyid_interface, entry_names, curr_dirtyids, True)
for bundle in child_bundles:
assert_stamp_missing(bundle)
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
path = get_attr_value(bundle, "sourcePrimPath")
if path == cube_path:
n_attrs = get_expected_prim_attributes_count(cube)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "size", 100)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]])
elif path == cone_path:
n_attrs = get_expected_prim_attributes_count(cone)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_attr_value(bundle, "sourcePrimType", "Cone")
assert_attr_value(bundle, "radius", 50)
assert_attr_value(bundle, "height", 10)
assert_attr_value(bundle, "primvars:displayColor", [[0, 1, 0]])
else:
self.fail(path)
# no change before this evaluation
await controller.evaluate()
# the dirty ids shouldn't be bumped when there is no change
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, [])
# change just the cube size
set_stamp(20)
cube.GetAttribute("size").Set(200)
await controller.evaluate()
# check that only the cube bundle was updated
assert_stamp(container, 20)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 2)
for bundle in child_bundles:
path = get_attr_value(bundle, "sourcePrimPath")
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
if path == cube_path:
n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]])
elif path == cone_path:
n_attrs = get_expected_prim_attributes_count(cone)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "sourcePrimType", "Cone")
assert_attr_value(bundle, "radius", 50)
assert_attr_value(bundle, "height", 10)
assert_attr_value(bundle, "primvars:displayColor", [[0, 1, 0]])
else:
self.fail(path)
# only the changed entries will have the dirty ids bumped
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
changed_entry_names = [container_bundle_name, cube_bundle_name, cube_bundle_name + ".size"]
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, changed_entry_names)
# change just the cone radius and height
set_stamp(30)
cone.GetAttribute("radius").Set(300)
cone.GetAttribute("height").Set(20)
await controller.evaluate()
# check that only the cone bundle was updated
assert_stamp(container, 30)
for bundle in child_bundles:
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
path = get_attr_value(bundle, "sourcePrimPath")
if path == cube_path:
n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp(bundle, 20)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]])
elif path == cone_path:
n_attrs = get_expected_prim_attributes_count(cone, debug_stamp=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp(bundle, 30)
assert_attr_value(bundle, "sourcePrimType", "Cone")
assert_attr_value(bundle, "radius", 300)
assert_attr_value(bundle, "height", 20)
assert_attr_value(bundle, "primvars:displayColor", [[0, 1, 0]])
else:
self.fail(path)
# only the changed entries will have the dirty ids bumped
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
changed_entry_names = [
container_bundle_name,
cone_bundle_name,
cone_bundle_name + ".radius",
cone_bundle_name + ".height",
]
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, changed_entry_names)
# delete the cone, full update will be triggered for now
set_stamp(40)
removed_entries = []
removed_entry_names = []
for bundle in child_bundles:
bundle_path = get_attr_value(bundle, "sourcePrimPath")
if bundle_path == cone_path:
bundle_name = bundle.get_name()
attrs = bundle.get_attributes()
removed_entries.append(bundle)
removed_entries.extend(attrs)
removed_entry_names.append(bundle_name)
removed_entry_names.extend([bundle_name + "." + attr.get_name() for attr in attrs])
stage.RemovePrim(cone_path)
await controller.evaluate()
# for now, deleting does a full update
assert_stamp(container, -40)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]])
# invalid dirty ids expected for removed entries
self.assert_dirtyid_validity(
dirtyid_interface, removed_entry_names, dirtyid_interface.get(removed_entries), False
)
# the dirty ids should be bumped for all remaining entries
remaining_prev_dirtyids = []
remaining_entries = []
remaining_entry_names = []
num_entries = len(entries)
for i in range(num_entries):
if entry_names[i] not in removed_entry_names:
remaining_prev_dirtyids.append(curr_dirtyids[i])
remaining_entries.append(entries[i])
remaining_entry_names.append(entry_names[i])
remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries)
self.assert_dirtyid(
dirtyid_interface,
remaining_entry_names,
remaining_curr_dirtyids,
remaining_prev_dirtyids,
remaining_entry_names,
)
# create the cone again, using blue color now
set_stamp(50)
cone = ogts.create_cone(stage, "XCone/Cone", (0, 0, 1))
cone.GetAttribute("radius").Set(400)
cone.GetAttribute("height").Set(40)
await controller.evaluate()
# for now, creation does a full update
assert_stamp(container, -50)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 2)
for bundle in child_bundles:
assert_stamp_missing(bundle)
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
path = get_attr_value(bundle, "sourcePrimPath")
if path == cube_path:
n_attrs = get_expected_prim_attributes_count(cube)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]])
elif path == cone_path:
n_attrs = get_expected_prim_attributes_count(cone)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_attr_value(bundle, "radius", 400)
assert_attr_value(bundle, "height", 40)
assert_attr_value(bundle, "sourcePrimType", "Cone")
assert_attr_value(bundle, "primvars:displayColor", [[0, 0, 1]])
else:
self.fail(path)
# for now, creation does a full update
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names)
# create a new cube attribute
set_stamp(60)
dummy_attr_name = "dummy"
cube.CreateAttribute(dummy_attr_name, Sdf.ValueTypeNames.Float3Array).Set([(1, 2, 3)])
await controller.evaluate()
# only the cube should update, and should contain the new attribute
assert_stamp(container, 60)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 2)
for bundle in child_bundles:
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
path = get_attr_value(bundle, "sourcePrimPath")
if path == cube_path:
n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp(bundle, 60)
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]])
self.assertListEqual(get_attr_value(bundle, dummy_attr_name).tolist(), [[1, 2, 3]])
elif path == cone_path:
n_attrs = get_expected_prim_attributes_count(cone)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "radius", 400)
assert_attr_value(bundle, "height", 40)
assert_attr_value(bundle, "sourcePrimType", "Cone")
assert_attr_value(bundle, "primvars:displayColor", [[0, 0, 1]])
else:
self.fail(path)
dummy_attr = get_attr(cube_bundle, dummy_attr_name)
self.assertTrue(dummy_attr.is_valid())
dummy_entry_name = cube_bundle_name + "." + dummy_attr_name
dummy_dirtyids = dirtyid_interface.get([dummy_attr])
self.assert_dirtyid_validity(dirtyid_interface, [dummy_entry_name], dummy_dirtyids, True)
dummy_entries = entries + [dummy_attr]
dummy_entry_names = entry_names + [dummy_entry_name]
dummy_prev_dirtyids = curr_dirtyids + dummy_dirtyids
dummy_curr_dirtyids = dirtyid_interface.get(dummy_entries)
self.assert_dirtyid(
dirtyid_interface,
dummy_entry_names,
dummy_curr_dirtyids,
dummy_prev_dirtyids,
[container_bundle_name, cube_bundle_name],
)
# clear new cube attribute
set_stamp(70)
cube.GetAttribute(dummy_attr_name).Clear()
await controller.evaluate()
# only the cube should update, and should contain the cleared attribute
assert_stamp(container, 70)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 2)
for bundle in child_bundles:
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
path = get_attr_value(bundle, "sourcePrimPath")
if path == cube_path:
n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp(bundle, 70)
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]])
self.assertListEqual(get_attr_value(bundle, dummy_attr_name).tolist(), [])
elif path == cone_path:
n_attrs = get_expected_prim_attributes_count(cone)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "radius", 400)
assert_attr_value(bundle, "height", 40)
assert_attr_value(bundle, "sourcePrimType", "Cone")
assert_attr_value(bundle, "primvars:displayColor", [[0, 0, 1]])
else:
self.fail(path)
dummy_attr = get_attr(cube_bundle, dummy_attr_name)
self.assertTrue(dummy_attr.is_valid())
dummy_prev_dirtyids = curr_dirtyids + dummy_dirtyids
dummy_curr_dirtyids = dirtyid_interface.get(dummy_entries)
self.assert_dirtyid(
dirtyid_interface,
dummy_entry_names,
dummy_curr_dirtyids,
dummy_prev_dirtyids,
[container_bundle_name, cube_bundle_name, dummy_entry_name],
)
# remove the new cube attribute
set_stamp(80)
cube.RemoveProperty(dummy_attr_name)
await controller.evaluate()
# only the cube should update, and should not contain the new attribute anymore
assert_stamp(container, 80)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 2)
for bundle in child_bundles:
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
path = get_attr_value(bundle, "sourcePrimPath")
if path == cube_path:
n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp(bundle, 80)
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]])
assert_attr_missing(bundle, dummy_attr_name)
elif path == cone_path:
n_attrs = get_expected_prim_attributes_count(cone)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "radius", 400)
assert_attr_value(bundle, "height", 40)
assert_attr_value(bundle, "sourcePrimType", "Cone")
assert_attr_value(bundle, "primvars:displayColor", [[0, 0, 1]])
else:
self.fail(path)
dummy_attr = get_attr(cube_bundle, dummy_attr_name)
self.assertFalse(dummy_attr.is_valid())
prev_dirtyids = dummy_prev_dirtyids[:-1]
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(
dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, [container_bundle_name, cube_bundle_name]
)
curr_dummy_dirtyids = dirtyid_interface.get([dummy_attr])
self.assert_dirtyid_validity(dirtyid_interface, [dummy_entry_name], curr_dummy_dirtyids, False)
# remove the cone from the input paths
if use_path_pattern:
controller.edit(
test_graph_path,
{
keys.SET_VALUES: [
("Read.inputs:pathPattern", cube_path),
],
},
)
else:
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"),
targets=[cube.GetPath()],
)
set_stamp(90)
await controller.evaluate()
# for now, changing inputs:prims does a full update
assert_stamp(container, -90)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]])
# invalid dirty ids expected for removed entries
self.assert_dirtyid_validity(
dirtyid_interface, removed_entry_names, dirtyid_interface.get(removed_entries), False
)
# the dirty ids should be bumped for all remaining entries
remaining_prev_dirtyids = []
remaining_entries = []
remaining_entry_names = []
num_entries = len(entries)
for i in range(num_entries):
if entry_names[i] not in removed_entry_names:
remaining_prev_dirtyids.append(curr_dirtyids[i])
remaining_entries.append(entries[i])
remaining_entry_names.append(entry_names[i])
remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries)
self.assert_dirtyid(
dirtyid_interface,
remaining_entry_names,
remaining_curr_dirtyids,
remaining_prev_dirtyids,
remaining_entry_names,
)
# add the cone again to the input paths
if use_path_pattern:
controller.edit(
test_graph_path,
{
keys.SET_VALUES: [
("Read.inputs:pathPattern", "/X*/C*"),
],
},
)
else:
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"),
targets=[cube.GetPath(), cone.GetPath()],
)
set_stamp(100)
await controller.evaluate()
# for now, changing inputs:prims does a full update
assert_stamp(container, -100)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 2)
for bundle in child_bundles:
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
path = get_attr_value(bundle, "sourcePrimPath")
if path == cube_path:
n_attrs = get_expected_prim_attributes_count(cube)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "sourcePrimType", "Cube")
elif path == cone_path:
n_attrs = get_expected_prim_attributes_count(cone)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "radius", 400)
assert_attr_value(bundle, "height", 40)
assert_attr_value(bundle, "sourcePrimType", "Cone")
# for now, changing inputs:prims does a full update
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names)
# modify, delete and create again, but don't evaluate the graph yet.
set_stamp(110)
cube.GetAttribute("size").Set(1000)
cone.GetAttribute("height").Set(10)
stage.RemovePrim(cube_path)
cone.GetAttribute("radius").Set(10)
stage.RemovePrim(cone_path)
cube = ogts.create_cube(stage, "XCube/Cube", (0, 1, 1))
cube.GetAttribute("size").Set(100)
removed_entries = []
removed_entry_names = []
for bundle in child_bundles:
bundle_path = get_attr_value(bundle, "sourcePrimPath")
if bundle_path == cone_path:
bundle_name = bundle.get_name()
attrs = bundle.get_attributes()
removed_entries.append(bundle)
removed_entries.extend(attrs)
removed_entry_names.append(bundle_name)
removed_entry_names.extend([bundle_name + "." + attr.get_name() for attr in attrs])
await controller.evaluate()
# the multiple changes should have be collected together
# but for now, deleting and creation does a full update unfortunately
assert_stamp(container, -110)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "size", 100)
assert_attr_value(bundle, "primvars:displayColor", [[0, 1, 1]])
# invalid dirty ids expected for removed entries
self.assert_dirtyid_validity(
dirtyid_interface, removed_entry_names, dirtyid_interface.get(removed_entries), False
)
# the dirty ids should be bumped for all remaining entries
remaining_prev_dirtyids = []
remaining_entries = []
remaining_entry_names = []
num_entries = len(entries)
for i in range(num_entries):
if entry_names[i] not in removed_entry_names:
remaining_prev_dirtyids.append(curr_dirtyids[i])
remaining_entries.append(entries[i])
remaining_entry_names.append(entry_names[i])
remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries)
self.assert_dirtyid(
dirtyid_interface,
remaining_entry_names,
remaining_curr_dirtyids,
remaining_prev_dirtyids,
remaining_entry_names,
)
# remove the Cube parent xform
# this should remove the Cube from the bundle
set_stamp(120)
stage.RemovePrim("/XCube")
await controller.evaluate()
if use_path_pattern:
# The path pattern matcher will not find any prim matches,
# so the input paths will be empty.
# In this case, the output bundle is just cleared.
assert_stamp_missing(container)
else:
# The relationship still has a path to the delete cone
# So the input paths won't change, but the deletion
# will be detected by the change tracker
assert_stamp(container, -120)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 0)
container_prev_dirtyids = [remaining_curr_dirtyids[0]]
container_curr_dirtyids = dirtyid_interface.get([container])
self.assert_dirtyid(
dirtyid_interface,
[container_bundle_name],
container_curr_dirtyids,
container_prev_dirtyids,
[container_bundle_name],
)
# create the cube again
set_stamp(130)
xcube = UsdGeom.Xform.Define(stage, "/XCube")
cube = ogts.create_cube(stage, "XCube/Cube", (1, 0, 1))
cube.GetAttribute("size").Set(100)
await controller.evaluate()
# for now creation of prims results in a full update
assert_stamp(container, -130)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", id_mat)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "size", 100)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
remaining_prev_dirtyids = remaining_curr_dirtyids
remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries)
self.assert_dirtyid(
dirtyid_interface,
remaining_entry_names,
remaining_curr_dirtyids,
remaining_prev_dirtyids,
remaining_entry_names,
)
# translate the cube through its parent xform
set_stamp(140)
UsdGeom.XformCommonAPI(xcube).SetTranslate((10.0, 10.0, 10.0))
await controller.evaluate()
# the cube bundle wordMatrix should have updated
assert_stamp(container, 140)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp(bundle, 10000140) # 1e7 means only world matrix was updated
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_missing(bundle, "bboxMaxCorner")
assert_attr_missing(bundle, "bboxMinCorner")
assert_attr_missing(bundle, "bboxTransform")
assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1])
assert_attr_value(bundle, "size", 100)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
remaining_prev_dirtyids = remaining_curr_dirtyids
remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries)
self.assert_dirtyid(
dirtyid_interface,
remaining_entry_names,
remaining_curr_dirtyids,
remaining_prev_dirtyids,
[container_bundle_name, cube_bundle_name, cube_bundle_name + ".worldMatrix"],
)
# request bounding boxes
set_stamp(150)
controller.edit(
test_graph_path,
{
keys.SET_VALUES: ("Read.inputs:computeBoundingBox", True),
},
)
await controller.evaluate()
# changing the computeBoundingBox causes a full update
assert_stamp(container, -150)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube, bbox=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "bboxMaxCorner", [50, 50, 50])
assert_attr_value(bundle, "bboxMinCorner", [-50, -50, -50])
assert_attr_value(bundle, "bboxTransform", id_mat)
assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1])
assert_attr_value(bundle, "size", 100)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
remaining_prev_dirtyids = remaining_curr_dirtyids
remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries)
self.assert_dirtyid(
dirtyid_interface,
remaining_entry_names,
remaining_curr_dirtyids,
remaining_prev_dirtyids,
remaining_entry_names,
)
bbox_entries = [
get_attr(cube_bundle, "bboxMaxCorner"),
get_attr(cube_bundle, "bboxMinCorner"),
get_attr(cube_bundle, "bboxTransform"),
]
bbox_entry_names = [
cube_bundle_name + ".bboxMaxCorner",
cube_bundle_name + ".bboxMinCorner",
cube_bundle_name + ".bboxTransform",
]
bbox_curr_dirtyids = dirtyid_interface.get(bbox_entries)
self.assert_dirtyid_validity(dirtyid_interface, bbox_entry_names, bbox_curr_dirtyids, True)
# modify bounding box
set_stamp(160)
cube.GetAttribute("size").Set(200)
await controller.evaluate()
# check incremental update
assert_stamp(container, 160)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True, bbox=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp(bundle, 160)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "bboxMaxCorner", [100, 100, 100])
assert_attr_value(bundle, "bboxMinCorner", [-100, -100, -100])
assert_attr_value(bundle, "bboxTransform", id_mat)
assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1])
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
entries = remaining_entries + bbox_entries
entry_names = remaining_entry_names + bbox_entry_names
prev_dirtyids = remaining_curr_dirtyids + bbox_curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(
dirtyid_interface,
entry_names,
curr_dirtyids,
prev_dirtyids,
[
container_bundle_name,
cube_bundle_name,
cube_bundle_name + ".size",
cube_bundle_name + ".bboxMaxCorner",
cube_bundle_name + ".bboxMinCorner",
],
)
# evaluate bbox without modification
set_stamp(170)
await controller.evaluate()
# check nothing was updated
assert_stamp(container, 160)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True, bbox=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp(bundle, 160)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "bboxMaxCorner", [100, 100, 100])
assert_attr_value(bundle, "bboxMinCorner", [-100, -100, -100])
assert_attr_value(bundle, "bboxTransform", id_mat)
assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1])
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, [])
# animate
for timecode in range(10):
set_stamp(180 + timecode)
controller.edit(test_graph_path, {keys.SET_VALUES: ("Read.inputs:usdTimecode", timecode)})
await controller.evaluate()
# check a full update is done
assert_stamp(container, -(180 + timecode))
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube, bbox=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "bboxMaxCorner", [100, 100, 100])
assert_attr_value(bundle, "bboxMinCorner", [-100, -100, -100])
assert_attr_value(bundle, "bboxTransform", id_mat)
assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1])
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names)
# switch back to non-animating
set_stamp(200)
controller.edit(test_graph_path, {keys.SET_VALUES: ("Read.inputs:usdTimecode", float("nan"))})
# changes to the cube should not trigger an incremental update when switching
cube.GetAttribute("size").Set(100)
await controller.evaluate()
# check a full update is done
assert_stamp(container, -200)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube, bbox=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "bboxMaxCorner", [50, 50, 50])
assert_attr_value(bundle, "bboxMinCorner", [-50, -50, -50])
assert_attr_value(bundle, "bboxTransform", id_mat)
assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1])
assert_attr_value(bundle, "size", 100)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names)
# change the cube again
set_stamp(210)
# changes to the cube should now trigger an incremental update
cube.GetAttribute("size").Set(200)
await controller.evaluate()
# an incremental update should be done
assert_stamp(container, 210)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True, bbox=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp(bundle, 210)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "bboxMaxCorner", [100, 100, 100])
assert_attr_value(bundle, "bboxMinCorner", [-100, -100, -100])
assert_attr_value(bundle, "bboxTransform", id_mat)
assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1])
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
# disable change tracking
set_change_tracking(False)
set_stamp(220)
await controller.evaluate()
# the input change should trigger a full update
assert_stamp(container, -220)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube, bbox=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "bboxMaxCorner", [100, 100, 100])
assert_attr_value(bundle, "bboxMinCorner", [-100, -100, -100])
assert_attr_value(bundle, "bboxTransform", id_mat)
assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1])
assert_attr_value(bundle, "size", 200)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names)
# change the cube again, with change tracking disabled
set_stamp(230)
# changes to the cube should now trigger a full update
cube.GetAttribute("size").Set(100)
await controller.evaluate()
assert_stamp(container, -230)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube, bbox=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "bboxMaxCorner", [50, 50, 50])
assert_attr_value(bundle, "bboxMinCorner", [-50, -50, -50])
assert_attr_value(bundle, "bboxTransform", id_mat)
assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1])
assert_attr_value(bundle, "size", 100)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names)
# enable change tracking again
set_change_tracking(True)
set_stamp(250)
await controller.evaluate()
# the input change should trigger a full update
assert_stamp(container, -250)
for bundle in child_bundles:
n_attrs = get_expected_prim_attributes_count(cube, bbox=True)
self.assertEqual(bundle.get_attribute_count(), n_attrs)
assert_stamp_missing(bundle)
assert_attr_value(bundle, "sourcePrimPath", cube_path)
assert_attr_value(bundle, "sourcePrimType", "Cube")
assert_attr_value(bundle, "bboxMaxCorner", [50, 50, 50])
assert_attr_value(bundle, "bboxMinCorner", [-50, -50, -50])
assert_attr_value(bundle, "bboxTransform", id_mat)
assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1])
assert_attr_value(bundle, "size", 100)
assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]])
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names)
# create, remove and create the cone, in one go
set_stamp(260)
cone = ogts.create_cube(stage, "XCone/Cone", (1, 1, 1))
stage.RemovePrim(cone_path)
cone = ogts.create_cube(stage, "XCone/Cone", (1, 1, 1))
await controller.evaluate()
# the second removal should not cancel the last creation
assert_stamp(container, -260)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 2)
prev_dirtyids = curr_dirtyids
curr_dirtyids = dirtyid_interface.get(entries)
self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names)
async def test_read_prims_change_tracking_no_debug_stamps(self):
"""omni.graph.nodes.ReadPrimsV2 change tracking should not add debug stamps unless requested"""
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
test_graph_path = "/World/TestGraph"
controller = og.Controller()
keys = og.Controller.Keys
xcube = UsdGeom.Xform.Define(stage, "/XCube")
cube = ogts.create_cube(stage, "XCube/Cube", (1, 0, 0))
cube.GetAttribute("size").Set(100)
(graph, [read_prims_node, _], _, _) = controller.edit(
test_graph_path,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
("Inspector", "omni.graph.nodes.BundleInspector"),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "Inspector.inputs:bundle"),
],
keys.SET_VALUES: [
("Inspector.inputs:print", False),
],
},
)
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"),
targets=[cube.GetPath()],
)
def get_attr(bundle, name):
return bundle.get_attribute_by_name(name)
def assert_attr_missing(bundle, name):
self.assertFalse(get_attr(bundle, name).is_valid())
def assert_stamp_missing(bundle):
assert_attr_missing(bundle, "_debugStamp")
# initial update
await controller.evaluate()
graph_context = graph.get_default_graph_context()
container = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
self.assertTrue(container.valid)
# no stamps should be added
assert_stamp_missing(container)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
assert_stamp_missing(bundle)
# trigger incremental empty update
await controller.evaluate()
# no stamps should be added
assert_stamp_missing(container)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
assert_stamp_missing(bundle)
# move the xform
UsdGeom.XformCommonAPI(xcube).SetTranslate((10.0, 10.0, 10.0))
# trigger incremental update, world matrices should be updated
await controller.evaluate()
# but no stamps should be added
assert_stamp_missing(container)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), 1)
for bundle in child_bundles:
assert_stamp_missing(bundle)
def assert_dirtyid_validity(
self, dirtyid_interface: og._og_unstable.IDirtyID2, entry_names: List[str], curr_dirtyids: list, is_valid: bool
):
self.assertEqual(len(entry_names), len(curr_dirtyids))
if _debug:
print()
for entry_name, curr_dirty_id in zip(entry_names, curr_dirtyids):
print(entry_name, curr_dirty_id)
for entry_name, curr_dirty_id in zip(entry_names, curr_dirtyids):
self.assertEqual(dirtyid_interface.is_valid(curr_dirty_id), is_valid, entry_name)
def assert_dirtyid(
self,
dirtyid_interface: og._og_unstable.IDirtyID2,
entry_names: List[str],
curr_dirtyids: list,
prev_dirtyids: list,
changed_entry_names: List[str],
):
self.assertEqual(len(entry_names), len(curr_dirtyids))
self.assertEqual(len(entry_names), len(prev_dirtyids))
if _debug:
print()
for entry_name, curr_dirty_id, prev_dirty_id in zip(entry_names, curr_dirtyids, prev_dirtyids):
print(entry_name, curr_dirty_id, prev_dirty_id)
for entry_name, curr_dirty_id, prev_dirty_id in zip(entry_names, curr_dirtyids, prev_dirtyids):
self.assertTrue(dirtyid_interface.is_valid(curr_dirty_id), entry_name)
self.assertTrue(dirtyid_interface.is_valid(prev_dirty_id), entry_name)
if entry_name in changed_entry_names:
self.assertGreater(curr_dirty_id, prev_dirty_id, entry_name)
else:
self.assertEqual(curr_dirty_id, prev_dirty_id, entry_name)
| 55,642 | Python | 41.281915 | 119 | 0.593257 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_dynamic_nodes.py | """Tests for nodes with dynamic attributes""" # noqa: PLC0302
import unittest
from typing import Any, Dict
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.usd
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene, _test_verify_scene, _TestGraphAndNode
from pxr import OmniGraphSchemaTools
DYN_ATTRIBUTE_FORMAT = "inputs:"
# ======================================================================
class TestDynamicNodes(ogts.OmniGraphTestCase):
"""Unit tests for nodes with dynamic attributes"""
PERSISTENT_SETTINGS_PREFIX = "/persistent"
TEST_GRAPH_PATH = "/World/TestGraph"
# This method is copied from the module omnigraph_test_utils and is modified to support the "dynamicInputs" keyword
# in test data. Once the dynamic inputs can directly be tested in .ogn files, this implementation should be replaced
# with the standard implementation.
async def _test_setup_scene(
tc: unittest.TestCase, # noqa: N805
controller: og.Controller,
test_graph_name: str,
test_node_name: str,
test_node_type: str,
test_run: Dict[str, Any],
last_test_info: _TestGraphAndNode,
instance_count=0,
) -> _TestGraphAndNode:
"""Setup the scene based on given test run dictionary
Args:
tc: Unit test case executing this method. Used to raise errors
controller: Controller object to use when constructing the scene (e.g. may have undo support disabled)
test_graph_name: Graph name to use when constructing the scene
test_node_name: Node name to use when constructing the scene without "setup" explicitly provided in test_run
test_node_type: Node type to use when constructing the scene without "setup" explicitly provided in test_run
test_run: Dictionary of consist of four sub-lists and a dictionary:
- values for input attributes, set before the test starts
- values for output attributes, checked after the test finishes
- initial values for state attributes, set before the test starts
- final values for state attributes, checked after the test finishes
- setup to be used for populating the scene via controller
For complete implementation see generate_user_test_data.
last_test_info: When executing multiple tests cases for the same node, this represents graph and node used in previous run
instance_count: number of instances to create assotiated to this graph, in order to test vectorized compute
Returns:
Graph and node to use in current execution of the test
"""
test_info = last_test_info
setup = test_run.get("setup", None)
if setup:
(test_info.graph, test_nodes, _, _) = controller.edit(test_graph_name, setup)
tc.assertTrue(test_nodes)
test_info.node = test_nodes[0]
elif setup is None:
test_info.graph = controller.create_graph(test_graph_name)
test_info.node = controller.create_node((test_node_name, test_info.graph), test_node_type)
else:
tc.assertTrue(
test_info.graph is not None and test_info.graph.is_valid(),
"Test is misconfigured - empty setup cannot be in the first test",
)
tc.assertTrue(test_info.graph is not None and test_info.graph.is_valid(), "Test graph invalid")
tc.assertTrue(test_info.node is not None and test_info.node.is_valid(), "Test node invalid")
await controller.evaluate(test_info.graph)
inputs = test_run.get("inputs", [])
state_set = test_run.get("state_set", [])
values_to_set = inputs + state_set
if values_to_set:
for attribute_name, attribute_value, _ in values_to_set:
controller.set(attribute=(attribute_name, test_info.node), value=attribute_value)
dynamic_inputs = test_run.get("dynamicInputs", [])
if dynamic_inputs:
for attribute_name, attribute_value, _ in dynamic_inputs:
controller.create_attribute(
test_info.node,
attribute_name,
attribute_value["type"],
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
attribute_value["value"],
)
# create some instance prims, and apply the graph on it
if instance_count != 0:
stage = omni.usd.get_context().get_stage()
for i in range(instance_count):
prim_name = f"/World/Test_Instance_Prim_{i}"
stage.DefinePrim(prim_name)
OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, test_graph_name)
return test_info
async def test_node_is_updated_when_dynamic_attributes_are_added_or_removed(self):
"""Tests that the node database is notified and updated when dynamic attributes are added or removed"""
# Arrange: create an Add node and add two dynamic attributes on it
controller = og.Controller()
keys = og.Controller.Keys
(graph, (add_node, _, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Add", "omni.graph.nodes.Add"),
("Const1", "omni.graph.nodes.ConstantFloat"),
("Const2", "omni.graph.nodes.ConstantFloat"),
],
keys.CONNECT: [
("Const1.inputs:value", "Add.inputs:a"),
("Const2.inputs:value", "Add.inputs:b"),
],
keys.SET_VALUES: [
("Const1.inputs:value", 2.0),
("Const2.inputs:value", 3.0),
],
},
)
# Evaluate the graph once to ensure the node has a Database created
await controller.evaluate(graph)
controller.create_attribute(
add_node,
"inputs:input0",
og.Type(og.BaseDataType.FLOAT),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
5, # the default value will be applied in the computation
)
controller.create_attribute(
add_node,
"inputs:input1",
og.Type(og.BaseDataType.FLOAT),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
7, # the default value will be applied in the computation
)
# Act: evaluate the graph
await controller.evaluate(graph)
# Assert: read the sum output and test that the dynamic attributes were included in the computation
sum_attr = controller.attribute("outputs:sum", add_node)
self.assertEqual(17, controller.get(sum_attr), "The dynamic attributes were not included in the computation")
# Arrange 2: remove one of the dynamic inputs
input0_attr = controller.attribute("inputs:input0", add_node)
controller.remove_attribute(input0_attr)
# Act 2: evaluate the graph
await controller.evaluate(graph)
# Assert 2: assert that only one of the dynamic inputs were used in the computation
sum_attr = controller.attribute("outputs:sum", add_node)
self.assertEqual(
12, og.Controller.get(sum_attr), "The node was not notified of the removal of a dynamic attribute"
)
TEST_DATA_ADD = [
{
"inputs": [
["inputs:a", {"type": "float[2]", "value": [1.0, 2.0]}, False],
["inputs:b", {"type": "float[2]", "value": [0.5, 1.0]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "float[2]", "value": [3.0, 4.0]}, False],
["inputs:d", {"type": "float[2]", "value": [0.1, 0.1]}, False],
],
"outputs": [
["outputs:sum", {"type": "float[2]", "value": [4.6, 7.1]}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "int64", "value": 10}, False],
["inputs:b", {"type": "int64", "value": 6}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int64", "value": 4}, False],
["inputs:d", {"type": "int64", "value": 20}, False],
],
"outputs": [
["outputs:sum", {"type": "int64", "value": 40}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False],
["inputs:b", {"type": "double[2]", "value": [5, 5]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "double[2]", "value": [5, 5]}, False],
["inputs:d", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False],
],
"outputs": [
["outputs:sum", {"type": "double[2][]", "value": [[30, 20], [12, 12]]}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False],
["inputs:b", {"type": "double", "value": 5}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "double[2]", "value": [5, 5]}, False],
["inputs:d", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False],
],
"outputs": [
["outputs:sum", {"type": "double[2][]", "value": [[30, 20], [12, 12]]}, False],
],
},
]
async def test_add(self):
"""Validates the node OgnAdd with dynamic inputs"""
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_ADD):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller, "/TestGraph", "TestNode_omni_graph_nodes_Add", "omni.graph.nodes.Add", test_run, test_info
)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.Add User test case #{i+1}")
async def test_add_vectorized(self):
"""Validates the node OgnAdd with dynamic inputs - vectorized computation"""
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_ADD):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_Add",
"omni.graph.nodes.Add",
test_run,
test_info,
16,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.Add User test case #{i+1}", 16)
TEST_DATA_SUBTRACT = [
{ # 1
"inputs": [
["inputs:a", {"type": "double", "value": 10.0}, False],
["inputs:b", {"type": "double", "value": 0.5}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "double", "value": 1.0}, False],
["inputs:d", {"type": "double", "value": 0.5}, False],
],
"outputs": [
["outputs:difference", {"type": "double", "value": 8}, False],
],
},
{ # 2
"inputs": [
["inputs:a", {"type": "float", "value": 10.0}, False],
["inputs:b", {"type": "float", "value": 0.5}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "float", "value": 1.0}, False],
["inputs:d", {"type": "float", "value": 0.5}, False],
],
"outputs": [
["outputs:difference", {"type": "float", "value": 8}, False],
],
},
{ # 3
"inputs": [
["inputs:a", {"type": "half", "value": 10.0}, False],
["inputs:b", {"type": "half", "value": 0.5}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "half", "value": 1.0}, False],
["inputs:d", {"type": "half", "value": 0.5}, False],
],
"outputs": [
["outputs:difference", {"type": "half", "value": 8.0}, False],
],
},
{ # 4
"inputs": [
["inputs:a", {"type": "int", "value": 10}, False],
["inputs:b", {"type": "int", "value": 6}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int", "value": 1}, False],
["inputs:d", {"type": "int", "value": 2}, False],
],
"outputs": [
["outputs:difference", {"type": "int", "value": 1}, False],
],
},
{ # 5
"inputs": [
["inputs:a", {"type": "int64", "value": 10}, False],
["inputs:b", {"type": "int64", "value": 6}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int64", "value": 1}, False],
["inputs:d", {"type": "int64", "value": 2}, False],
],
"outputs": [
["outputs:difference", {"type": "int64", "value": 1}, False],
],
},
{ # 6
"inputs": [
["inputs:a", {"type": "uchar", "value": 10}, False],
["inputs:b", {"type": "uchar", "value": 6}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "uchar", "value": 1}, False],
["inputs:d", {"type": "uchar", "value": 2}, False],
],
"outputs": [
["outputs:difference", {"type": "uchar", "value": 1}, False],
],
},
{ # 7
"inputs": [
["inputs:a", {"type": "uint", "value": 10}, False],
["inputs:b", {"type": "uint", "value": 6}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "uint", "value": 1}, False],
["inputs:d", {"type": "uint", "value": 2}, False],
],
"outputs": [
["outputs:difference", {"type": "uint", "value": 1}, False],
],
},
{ # 8
"inputs": [
["inputs:a", {"type": "uint64", "value": 10}, False],
["inputs:b", {"type": "uint64", "value": 6}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "uint64", "value": 1}, False],
["inputs:d", {"type": "uint64", "value": 2}, False],
],
"outputs": [
["outputs:difference", {"type": "uint64", "value": 1}, False],
],
},
{ # 9
"inputs": [
["inputs:a", {"type": "float[2]", "value": [10.0, 20.0]}, False],
["inputs:b", {"type": "float[2]", "value": [0.5, 1.0]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "float[2]", "value": [1.0, 2.0]}, False],
["inputs:d", {"type": "float[2]", "value": [3.0, 4.0]}, False],
],
"outputs": [
["outputs:difference", {"type": "float[2]", "value": [5.5, 13.0]}, False],
],
},
{ # 10
"inputs": [
["inputs:a", {"type": "float[3]", "value": [10.0, 20.0, 30.0]}, False],
["inputs:b", {"type": "float[3]", "value": [0.5, 1.0, 1.5]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "float[3]", "value": [1.0, 2.0, 3.0]}, False],
["inputs:d", {"type": "float[3]", "value": [0.5, 1.0, 1.5]}, False],
],
"outputs": [
["outputs:difference", {"type": "float[3]", "value": [8.0, 16.0, 24.0]}, False],
],
},
{ # 11
"inputs": [
["inputs:a", {"type": "float[4]", "value": [10.0, 20.0, 30.0, 40.0]}, False],
["inputs:b", {"type": "float[4]", "value": [0.5, 1.0, 1.5, 2.0]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "float[4]", "value": [1.0, 2.0, 3.0, 4.0]}, False],
["inputs:d", {"type": "float[4]", "value": [0.5, 0.5, 0.5, 0.5]}, False],
],
"outputs": [
["outputs:difference", {"type": "float[4]", "value": [8.0, 16.5, 25.0, 33.5]}, False],
],
},
{ # 12
"inputs": [
["inputs:a", {"type": "float[2]", "value": [2.0, 3.0]}, False],
["inputs:b", {"type": "float", "value": 1.0}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "float[2]", "value": [0.5, 0.5]}, False],
["inputs:d", {"type": "float", "value": 1.0}, False],
],
"outputs": [
["outputs:difference", {"type": "float[2]", "value": [-0.5, 0.5]}, False],
],
},
{ # 13
"inputs": [
["inputs:a", {"type": "float", "value": 1.0}, False],
["inputs:b", {"type": "float[2]", "value": [1.0, 2.0]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "float", "value": 1.0}, False],
["inputs:d", {"type": "float[2]", "value": [1.0, 2.0]}, False],
],
"outputs": [
["outputs:difference", {"type": "float[2]", "value": [-2.0, -4.0]}, False],
],
},
{ # 14
"inputs": [
["inputs:a", {"type": "float[]", "value": [2.0, 3.0]}, False],
["inputs:b", {"type": "float", "value": 1.0}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "float[]", "value": [2.0, 3.0]}, False],
["inputs:d", {"type": "float", "value": 1.0}, False],
],
"outputs": [
["outputs:difference", {"type": "float[]", "value": [-2.0, -2.0]}, False],
],
},
{ # 15
"inputs": [
["inputs:a", {"type": "float", "value": 1.0}, False],
["inputs:b", {"type": "float[]", "value": [1.0, 2.0]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "float", "value": 1.0}, False],
["inputs:d", {"type": "float[]", "value": [1.0, 2.0]}, False],
],
"outputs": [
["outputs:difference", {"type": "float[]", "value": [-2.0, -4.0]}, False],
],
},
{ # 16
"inputs": [
["inputs:a", {"type": "int64[]", "value": [10]}, False],
["inputs:b", {"type": "int64[]", "value": [5]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int64[]", "value": [1]}, False],
["inputs:d", {"type": "int64[]", "value": [2]}, False],
],
"outputs": [
["outputs:difference", {"type": "int64[]", "value": [2]}, False],
],
},
{ # 17
"inputs": [
["inputs:a", {"type": "int64[]", "value": [10, 20]}, False],
["inputs:b", {"type": "int64[]", "value": [5, 10]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int64[]", "value": [1, 2]}, False],
["inputs:d", {"type": "int64[]", "value": [3, 4]}, False],
],
"outputs": [
["outputs:difference", {"type": "int64[]", "value": [1, 4]}, False],
],
},
{ # 18
"inputs": [
["inputs:a", {"type": "int64[]", "value": [10, 20, 30]}, False],
["inputs:b", {"type": "int64[]", "value": [5, 10, 15]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int64[]", "value": [10, 20, 30]}, False],
["inputs:d", {"type": "int64[]", "value": [5, 10, 15]}, False],
],
"outputs": [
["outputs:difference", {"type": "int64[]", "value": [-10, -20, -30]}, False],
],
},
{ # 19
"inputs": [
["inputs:a", {"type": "int64[]", "value": [10, 20, 30, 40]}, False],
["inputs:b", {"type": "int64[]", "value": [5, 10, 15, 20]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int64[]", "value": [10, 20, 30, 40]}, False],
["inputs:d", {"type": "int64[]", "value": [5, 10, 15, 20]}, False],
],
"outputs": [
["outputs:difference", {"type": "int64[]", "value": [-10, -20, -30, -40]}, False],
],
},
{ # 20
"inputs": [
["inputs:a", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False],
["inputs:b", {"type": "int[3]", "value": [5, 10, 15]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False],
["inputs:d", {"type": "int[3]", "value": [5, 10, 15]}, False],
],
"outputs": [
[
"outputs:difference",
{"type": "int[3][]", "value": [[-10, -20, -30], [-10, -20, -30]]},
False,
], # output an array with a single int3 element
],
},
{ # 21 dynamic arrays mirror the default attributes - should give the same result as previous test
"inputs": [
["inputs:a", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False],
["inputs:b", {"type": "int[3]", "value": [5, 10, 15]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int[3]", "value": [5, 10, 15]}, False],
["inputs:d", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False],
],
"outputs": [
["outputs:difference", {"type": "int[3][]", "value": [[-10, -20, -30], [-10, -20, -30]]}, False],
],
},
{ # 22
"inputs": [
["inputs:a", {"type": "int[3]", "value": [5, 10, 15]}, False],
["inputs:b", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int[3]", "value": [5, 10, 15]}, False],
["inputs:d", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False],
],
"outputs": [
["outputs:difference", {"type": "int[3][]", "value": [[-20, -40, -60], [-80, -100, -120]]}, False],
],
},
{ # 23
"inputs": [
["inputs:a", {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, False],
["inputs:b", {"type": "int[2]", "value": [5, 10]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, False],
["inputs:d", {"type": "int[2]", "value": [5, 10]}, False],
],
"outputs": [
["outputs:difference", {"type": "int[2][]", "value": [[-10, -20], [-10, -20], [-10, -20]]}, False],
],
},
{ # 24
"inputs": [
["inputs:a", {"type": "int[2]", "value": [5, 10]}, False],
["inputs:b", {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "int[2]", "value": [5, 10]}, False],
["inputs:d", {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, False],
],
"outputs": [
["outputs:difference", {"type": "int[2][]", "value": [[-20, -40], [-60, -80], [-100, -120]]}, False],
],
},
]
async def test_subtract(self):
"""Validates the node OgnSubtract with dynamic inputs"""
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_SUBTRACT):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_Subtract",
"omni.graph.nodes.Subtract",
test_run,
test_info,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.Subtract User test case #{i+1}"
)
async def test_subtract_vectorized(self):
"""Validates the node OgnSubtract with dynamic inputs - vectorized computation"""
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_SUBTRACT):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_Subtract",
"omni.graph.nodes.Subtract",
test_run,
test_info,
16,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.Subtract User test case #{i+1}", 16
)
TEST_DATA_MULTIPLY = [
{
"inputs": [
["inputs:a", {"type": "float", "value": 42.0}, False],
["inputs:b", {"type": "float", "value": 2.0}, False],
],
"outputs": [
["outputs:product", {"type": "float", "value": 84.0}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "double[2]", "value": [1.0, 42.0]}, False],
["inputs:b", {"type": "double[2]", "value": [2.0, 1.0]}, False],
],
"outputs": [
["outputs:product", {"type": "double[2]", "value": [2.0, 42.0]}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "double[]", "value": [1.0, 42.0]}, False],
["inputs:b", {"type": "double", "value": 2.0}, False],
],
"outputs": [
["outputs:product", {"type": "double[]", "value": [2.0, 84.0]}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False],
["inputs:b", {"type": "double[2]", "value": [5, 5]}, False],
],
"outputs": [
["outputs:product", {"type": "double[2][]", "value": [[50, 25], [5, 5]]}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False],
["inputs:b", {"type": "double", "value": 2}, False],
],
"outputs": [
["outputs:product", {"type": "double[2][]", "value": [[20, 10], [2, 2]]}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "double[2]", "value": [10, 5]}, False],
["inputs:b", {"type": "double", "value": 2}, False],
],
"outputs": [
["outputs:product", {"type": "double[2]", "value": [20, 10]}, False],
],
},
]
async def test_multiply(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_MULTIPLY):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_Multiply",
"omni.graph.nodes.Multiply",
test_run,
test_info,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.Multiply User test case #{i+1}"
)
async def test_multiply_vectorized(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_MULTIPLY):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_Multiply",
"omni.graph.nodes.Multiply",
test_run,
test_info,
16,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.Multiply User test case #{i+1}", 16
)
TEST_DATA_AND = [
{
"inputs": [
["inputs:a", {"type": "bool", "value": False}, False],
["inputs:b", {"type": "bool", "value": True}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool", "value": True}, False],
],
"outputs": [
["outputs:result", False, False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool", "value": True}, False],
["inputs:b", {"type": "bool", "value": True}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": True}, False],
["inputs:d", {"type": "bool", "value": True}, False],
],
"outputs": [
["outputs:result", True, False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, False, True, True]}, False],
["inputs:b", {"type": "bool[]", "value": [False, True, False, True]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": True}, False],
["inputs:d", {"type": "bool[]", "value": [False, True, False, True]}, False],
],
"outputs": [
["outputs:result", [False, False, False, True], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool", "value": False}, False],
["inputs:b", {"type": "bool[]", "value": [False, True]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool[]", "value": [False, True]}, False],
],
"outputs": [
["outputs:result", [False, False], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, True]}, False],
["inputs:b", {"type": "bool", "value": False}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool[]", "value": [False, True]}, False],
["inputs:d", {"type": "bool", "value": False}, False],
],
"outputs": [
["outputs:result", [False, False], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, True]}, False],
["inputs:b", {"type": "bool", "value": True}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool[]", "value": [False, True]}, False],
["inputs:d", {"type": "bool", "value": True}, False],
],
"outputs": [
["outputs:result", [False, True], False],
],
},
]
async def test_boolean_and(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_AND):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_BooleanAnd",
"omni.graph.nodes.BooleanAnd",
test_run,
test_info,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.BooleanAnd User test case #{i+1}"
)
async def test_boolean_and_vectorized(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_AND):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_BooleanAnd",
"omni.graph.nodes.BooleanAnd",
test_run,
test_info,
16,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.BooleanAnd User test case #{i+1}", 16
)
TEST_DATA_OR = [
{
"inputs": [
["inputs:a", {"type": "bool", "value": False}, False],
["inputs:b", {"type": "bool", "value": True}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool", "value": True}, False],
],
"outputs": [
["outputs:result", True, False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, False, True, True]}, False],
["inputs:b", {"type": "bool[]", "value": [False, True, False, True]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool", "value": True}, False],
],
"outputs": [
["outputs:result", {"type": "bool[]", "value": [True, True, True, True]}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool", "value": False}, False],
["inputs:b", {"type": "bool[]", "value": [False, True]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool", "value": True}, False],
],
"outputs": [
["outputs:result", [True, True], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, True]}, False],
["inputs:b", {"type": "bool", "value": False}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool[]", "value": [False, True]}, False],
],
"outputs": [
["outputs:result", [False, True], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, True]}, False],
["inputs:b", {"type": "bool", "value": False}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool[]", "value": [False, True]}, False],
],
"outputs": [
["outputs:result", {"type": "bool[]", "value": [False, True]}, False],
],
},
]
async def test_boolean_or(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_OR):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_BooleanOr",
"omni.graph.nodes.BooleanOr",
test_run,
test_info,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.BooleanOr User test case #{i+1}"
)
async def test_boolean_or_vectorized(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_OR):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_BooleanOr",
"omni.graph.nodes.BooleanOr",
test_run,
test_info,
16,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.BooleanOr User test case #{i+1}", 16
)
TEST_DATA_NAND = [
{
"inputs": [
["inputs:a", {"type": "bool", "value": False}, False],
["inputs:b", {"type": "bool", "value": True}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool", "value": True}, False],
],
"outputs": [
["outputs:result", True, False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, False, True, True]}, False],
["inputs:b", {"type": "bool[]", "value": [False, True, False, True]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool[]", "value": [False, False, True, True]}, False],
["inputs:d", {"type": "bool[]", "value": [False, True, False, True]}, False],
],
"outputs": [
["outputs:result", [True, True, True, False], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool", "value": False}, False],
["inputs:b", {"type": "bool[]", "value": [False, True]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool[]", "value": [False, True]}, False],
],
"outputs": [
["outputs:result", [True, True], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool", "value": False}, False],
["inputs:b", {"type": "bool[]", "value": [False, True]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool[]", "value": [False, True]}, False],
["inputs:d", {"type": "bool", "value": False}, False],
],
"outputs": [
["outputs:result", [True, True], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, True]}, False],
["inputs:b", {"type": "bool", "value": True}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool[]", "value": [False, True]}, False],
["inputs:d", {"type": "bool[]", "value": [False, True]}, False],
],
"outputs": [
["outputs:result", [True, False], False],
],
},
]
async def test_boolean_nand(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_NAND):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_BooleanNand",
"omni.graph.nodes.BooleanNand",
test_run,
test_info,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.BooleanNand User test case #{i+1}"
)
async def test_boolean_nand_vectorized(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_NAND):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_BooleanNand",
"omni.graph.nodes.BooleanNand",
test_run,
test_info,
16,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.BooleanNand User test case #{i+1}", 16
)
TEST_DATA_NOR = [
{
"inputs": [
["inputs:a", {"type": "bool", "value": False}, False],
["inputs:b", {"type": "bool", "value": True}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool", "value": True}, False],
],
"outputs": [
["outputs:result", False, False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool", "value": False}, False],
["inputs:b", {"type": "bool", "value": False}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
],
"outputs": [
["outputs:result", True, False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, False, True, True]}, False],
["inputs:b", {"type": "bool[]", "value": [False, True, False, True]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool[]", "value": [False, False, True, True]}, False],
["inputs:d", {"type": "bool[]", "value": [False, True, False, True]}, False],
],
"outputs": [
["outputs:result", [True, False, False, False], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, False, True, True]}, False],
["inputs:b", {"type": "bool[]", "value": [False, True, False, True]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool[]", "value": [False, True, False, True]}, False],
["inputs:d", {"type": "bool[]", "value": [False, False, True, True]}, False],
],
"outputs": [
["outputs:result", [True, False, False, False], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool", "value": False}, False],
["inputs:b", {"type": "bool[]", "value": [False, True]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool", "value": False}, False],
["inputs:d", {"type": "bool[]", "value": [False, True]}, False],
],
"outputs": [
["outputs:result", [True, False], False],
],
},
{
"inputs": [
["inputs:a", {"type": "bool[]", "value": [False, True]}, False],
["inputs:b", {"type": "bool", "value": False}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "bool[]", "value": [False, True]}, False],
["inputs:d", {"type": "bool", "value": False}, False],
],
"outputs": [
["outputs:result", [True, False], False],
],
},
]
async def test_boolean_nor(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_NOR):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_BooleanNor",
"omni.graph.nodes.BooleanNor",
test_run,
test_info,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.BooleanNor User test case #{i+1}"
)
async def test_boolean_nor_vectorized(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_NOR):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller,
"/TestGraph",
"TestNode_omni_graph_nodes_BooleanNor",
"omni.graph.nodes.BooleanNor",
test_run,
test_info,
16,
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.BooleanNor User test case #{i+1}", 16
)
TEST_DATA_APPEND_STRING = [
{
"inputs": [
["inputs:a", {"type": "token", "value": "/"}, False],
["inputs:b", {"type": "token", "value": "foo"}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "token", "value": "/"}, False],
["inputs:d", {"type": "token", "value": "bar"}, False],
],
"outputs": [
["outputs:value", {"type": "token", "value": "/foo/bar"}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "token[]", "value": ["/World", "/World2"]}, False],
["inputs:b", {"type": "token", "value": "/foo"}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "token", "value": "/"}, False],
["inputs:d", {"type": "token", "value": "bar"}, False],
],
"outputs": [
["outputs:value", {"type": "token[]", "value": ["/World/foo/bar", "/World2/foo/bar"]}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "token[]", "value": ["/World", "/World2"]}, False],
["inputs:b", {"type": "token[]", "value": ["/foo", "/bar"]}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "token[]", "value": ["/", "baz"]}, False],
["inputs:d", {"type": "token[]", "value": ["/", "biz"]}, False],
],
"outputs": [
["outputs:value", {"type": "token[]", "value": ["/World/foo//", "/World2/barbazbiz"]}, False],
],
},
{
"inputs": [
["inputs:a", {"type": "string", "value": "/"}, False],
["inputs:b", {"type": "string", "value": "foo"}, False],
],
"dynamicInputs": [
["inputs:c", {"type": "string", "value": "/"}, False],
["inputs:d", {"type": "string", "value": "bar"}, False],
],
"outputs": [
["outputs:value", {"type": "string", "value": "/foo/bar"}, False],
],
},
]
async def test_append_string(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA_APPEND_STRING):
await _test_clear_scene(self, test_run)
test_info = await self._test_setup_scene(
controller, "/TestGraph", "AppendString", "omni.graph.nodes.BuildString", test_run, test_info
)
await controller.evaluate(test_info.graph)
_test_verify_scene(
self, controller, test_run, test_info, f"omni.graph.nodes.BuildString User test case #{i+1}"
)
| 50,042 | Python | 40.187654 | 134 | 0.430878 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_nodes.py | # noqa: PLC0302
"""Misc collection of tests for nodes in this extension"""
import math
import os
from functools import partial
from math import isnan
from typing import Callable, Set
import carb
import carb.settings
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.commands
import omni.kit.stage_templates
import omni.kit.test
import omni.timeline
import omni.usd
import usdrt
from omni.graph.core import ThreadsafetyTestUtils
from pxr import Gf, OmniGraphSchemaTools, Sdf, Usd, UsdGeom, UsdShade
# ======================================================================
class TestNodes(ogts.OmniGraphTestCase):
"""Unit tests nodes in this extension"""
PERSISTENT_SETTINGS_PREFIX = "/persistent"
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
# Ensure that Xform prims are created with the full set of xformOp attributes with consistent behavior.
settings = carb.settings.get_settings()
settings.set(self.PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps", True)
settings.set(
self.PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType", "Scale, Rotate, Translate"
)
settings.set(self.PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder", "XYZ")
settings.set(
self.PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder",
"xformOp:translate, xformOp:rotate, xformOp:scale",
)
settings.set(self.PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision", "Double")
# ----------------------------------------------------------------------
async def test_getprimrelationship(self):
"""Test GetPrimRelationship node"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
(graph, (get_node,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: ("Get", "omni.graph.nodes.GetPrimRelationship"),
keys.CREATE_PRIMS: [("RelHolder", {}), ("TestPrimA", {}), ("TestPrimB", {})],
keys.SET_VALUES: [("Get.inputs:name", "test_rel"), ("Get.inputs:usePath", False)],
},
)
await controller.evaluate(graph)
prim = stage.GetPrimAtPath("/RelHolder")
rel = prim.CreateRelationship("test_rel")
for prim_path in ("/TestPrimA", "/TestPrimB"):
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=Sdf.Path(prim_path))
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Get.inputs:prim"),
target=prim.GetPath(),
)
await controller.evaluate(graph)
rel_paths = og.Controller.get(controller.attribute("outputs:paths", get_node))
self.assertEqual(rel_paths, rel.GetTargets())
controller.edit(
self.TEST_GRAPH_PATH,
{keys.SET_VALUES: [("Get.inputs:path", "/RelHolder"), ("Get.inputs:usePath", True)]},
)
await controller.evaluate(graph)
rel_paths = og.Controller.get(controller.attribute("outputs:paths", get_node))
self.assertEqual(rel_paths, rel.GetTargets())
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_get_prim_path(self, test_instance_id: int = 0):
"""Test GetPrimPath node"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
prim_path = "/World/TestPrim"
ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim(prim_path))
controller = og.Controller()
keys = og.Controller.Keys
(_, (get_node,), _, _) = controller.edit(
graph_path,
{keys.CREATE_NODES: ("GetPrimPath", "omni.graph.nodes.GetPrimPath")},
)
rel = stage.GetPropertyAtPath(f"{graph_path}/GetPrimPath.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_path)
yield ThreadsafetyTestUtils.EVALUATION_ALL_GRAPHS
rel_paths = og.Controller.get(controller.attribute("outputs:primPath", get_node))
self.assertEqual(rel_paths, prim_path)
ThreadsafetyTestUtils.single_evaluation_last_test_instance(
test_instance_id, lambda: stage.RemovePrim(prim_path)
)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_get_prim_paths(self, test_instance_id: int = 0):
"""Test GetPrimPaths node"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
prim_paths = ["/World/TestPrim1", "/World/TestPrim2"]
ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim(prim_paths[0]))
ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim(prim_paths[1]))
controller = og.Controller()
keys = og.Controller.Keys
(_, (get_node,), _, _) = controller.edit(
graph_path,
{keys.CREATE_NODES: ("GetPrimPaths", "omni.graph.nodes.GetPrimPaths")},
)
rel = stage.GetPropertyAtPath(f"{graph_path}/GetPrimPaths.inputs:prims")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_paths[0])
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_paths[1])
yield ThreadsafetyTestUtils.EVALUATION_ALL_GRAPHS
rel_paths = og.Controller.get(controller.attribute("outputs:primPaths", get_node))
self.assertEqual(rel_paths, prim_paths)
ThreadsafetyTestUtils.single_evaluation_last_test_instance(
test_instance_id, lambda: stage.RemovePrim(prim_paths[0])
)
ThreadsafetyTestUtils.single_evaluation_last_test_instance(
test_instance_id, lambda: stage.RemovePrim(prim_paths[1])
)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_get_prims_at_path(self, test_instance_id: int = 0):
"""Test GetPrimAtPath node"""
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
controller = og.Controller()
prim_path = "/World/foo/bar"
keys = og.Controller.Keys
(_, (get_prim_at_path, get_prims_at_path, _, _), _, _) = controller.edit(
graph_path,
{
keys.CREATE_NODES: [
("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("GetPrimsAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("MakeArray", "omni.graph.nodes.ConstructArray"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
],
keys.CONNECT: [
("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"),
("MakeArray.outputs:array", "GetPrimsAtPath.inputs:path"),
],
keys.SET_VALUES: [
("MakeArray.inputs:arraySize", 3),
("MakeArray.inputs:arrayType", "token[]"),
("MakeArray.inputs:input0", prim_path),
("ConstToken.inputs:value", prim_path),
],
},
)
yield ThreadsafetyTestUtils.EVALUATION_ALL_GRAPHS
out_path = og.Controller.get(controller.attribute("outputs:prims", get_prim_at_path))
self.assertEqual(out_path, [usdrt.Sdf.Path(prim_path)])
out_paths = og.Controller.get(controller.attribute("outputs:prims", get_prims_at_path))
self.assertEqual(out_paths, [usdrt.Sdf.Path(prim_path)] * 3)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_constant_prims(self, test_instance_id: int = 0):
"""Test ConstantPrims node"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
prim_paths = ["/World/TestPrim1", "/World/TestPrim2"]
for prim_path in prim_paths:
ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim(prim_path))
controller = og.Controller()
keys = og.Controller.Keys
(_, (_const_prims, prim_paths_node), _, _) = controller.edit(
graph_path,
{
keys.CREATE_NODES: [
("ConstantPrims", "omni.graph.nodes.ConstantPrims"),
("GetPrimPath", "omni.graph.nodes.GetPrimPaths"),
],
keys.CONNECT: [("ConstantPrims.inputs:value", "GetPrimPath.inputs:prims")],
},
)
rel = stage.GetPropertyAtPath(f"{graph_path}/ConstantPrims.inputs:value")
for prim_path in prim_paths:
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_path)
yield ThreadsafetyTestUtils.EVALUATION_ALL_GRAPHS
out_paths = og.Controller.get(controller.attribute("outputs:primPaths", prim_paths_node))
self.assertEqual(out_paths, prim_paths)
for prim_path in prim_paths:
ThreadsafetyTestUtils.single_evaluation_last_test_instance(
test_instance_id, partial(stage.RemovePrim, prim_path)
)
# ----------------------------------------------------------------------
async def test_constant_prims_loads_from_file(self):
"""
Validation that connections are maintained when loading a graph from a file which uses ConstantPrims -
which uses a target input attribute as its output
"""
await ogts.load_test_file("TestConstantPrims.usda", use_caller_subdirectory=True)
self.assertTrue(og.Controller.graph("/World/PushGraph").is_valid())
self.assertTrue(og.Controller.node("/World/PushGraph/constant_prims").is_valid())
self.assertTrue(og.Controller.node("/World/PushGraph/get_prim_paths").is_valid())
attr_dst = og.Controller.attribute("/World/PushGraph/get_prim_paths.inputs:prims")
attr_src = og.Controller.attribute("/World/PushGraph/constant_prims.inputs:value")
self.assertTrue(attr_dst.is_valid())
self.assertTrue(attr_src.is_valid())
self.assertTrue(attr_dst.is_connected(attr_src))
self.assertEqual(attr_dst.get_upstream_connection_count(), 1)
self.assertEqual(attr_dst.get_upstream_connections()[0].get_path(), attr_src.get_path())
actual_result = og.Controller.get(attr_dst)
expected_result = [usdrt.Sdf.Path("/Environment"), usdrt.Sdf.Path("/Environment/defaultLight")]
self.assertEqual(expected_result, actual_result)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_get_parent_prims(self, test_instance_id: int = 0):
"""Test ConstantPrims node"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
prim_paths = ["/World/Test", "/World/Test/Test"]
prim_parents = ["/World", "/World/Test"]
for prim_path in prim_paths:
ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim(prim_path))
controller = og.Controller()
keys = og.Controller.Keys
(_, (get_parent_prims,), _, _) = controller.edit(
graph_path, {keys.CREATE_NODES: ("GetParentPrims", "omni.graph.nodes.GetParentPrims")}
)
rel = stage.GetPropertyAtPath(f"{graph_path}/GetParentPrims.inputs:prims")
for prim_path in prim_paths:
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_path)
yield ThreadsafetyTestUtils.EVALUATION_ALL_GRAPHS
out_paths = og.Controller.get(controller.attribute("outputs:parentPrims", get_parent_prims))
self.assertEqual(out_paths, [usdrt.Sdf.Path(p) for p in prim_parents])
for prim_path in prim_paths:
ThreadsafetyTestUtils.single_evaluation_last_test_instance(
test_instance_id, partial(stage.RemovePrim, prim_path)
)
# ----------------------------------------------------------------------
async def test_prim_relationship_load(self):
"""Test that a prim relationship when loading does not create OgnPrim node"""
async def do_test():
await ogts.load_test_file("TestPrimRelationshipLoad.usda", use_caller_subdirectory=True)
# Cube and Capsule are driving Sphere, Cylinder, Cone by various methods
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
graph = og.get_graph_by_path("/World/PushGraph")
controller = og.Controller()
nodes = graph.get_nodes()
node_paths = [n.get_prim_path() for n in nodes]
# These prims are only connected by relationship, so should not show up in OG
self.assertNotIn("/World/Cube", node_paths)
self.assertNotIn("/World/Sphere", node_paths)
self.assertNotIn("/World/Cylinder", node_paths)
self.assertNotIn("/World/Cone", node_paths)
# Sanity check that the rotate connections are working
for p in ("Sphere", "Capsule", "Cylinder", "Cone"):
rotate_xyz = stage.GetPrimAtPath("/World/" + p).GetAttribute("xformOp:rotateXYZ").Get()
self.assertEqual(rotate_xyz[0], 0)
self.assertEqual(rotate_xyz[1], 0)
stage.GetPrimAtPath("/World/Cube").GetAttribute("xformOp:rotateXYZ").Set((100, 0, 0))
stage.GetPrimAtPath("/World/Capsule").GetAttribute("xformOp:rotateXYZ").Set((100, 0, 0))
await controller.evaluate(graph)
for p in ("Sphere", "Cylinder", "Cone"):
rotate_xyz = stage.GetPrimAtPath("/World/" + p).GetAttribute("xformOp:rotateXYZ").Get()
if p == "Cone":
# /World/Cone is not loaded into Flatcache, so we expect this part of the
# graph to be non-functional (Cone will not change)
self.assertEqual(rotate_xyz[0], 0)
self.assertEqual(rotate_xyz[1], 0)
await do_test()
# ----------------------------------------------------------------------
@staticmethod
def _get_expected_read_prims_property_names(prim) -> Set[str]:
properties = set(prim.GetAuthoredPropertyNames())
properties.update({"worldMatrix", "sourcePrimPath", "sourcePrimType"})
return properties
# ----------------------------------------------------------------------
@staticmethod
def _get_expected_read_prims_v2_property_names(prim) -> Set[str]:
properties = set(prim.GetPropertyNames())
properties.remove("proxyPrim") # remove "proxyPrim" which is skipped unless it has targets
properties.update({"worldMatrix", "sourcePrimPath", "sourcePrimType"})
return properties
# ----------------------------------------------------------------------
async def test_read_prims_write_prim(self):
"""Test omni.graph.nodes.ReadPrims and WritePrim"""
await self._read_prims_write_prim(
"omni.graph.nodes.ReadPrims",
False,
compute_expected_property_names=self._get_expected_read_prims_property_names,
)
# ----------------------------------------------------------------------
async def test_read_prims_write_prim_with_target(self):
await self._read_prims_write_prim(
"omni.graph.nodes.ReadPrims",
True,
compute_expected_property_names=self._get_expected_read_prims_property_names,
)
# ----------------------------------------------------------------------
async def test_read_prims_v2_write_prim(self):
"""Test omni.graph.nodes.ReadPrimsV2 and WritePrim"""
await self._read_prims_write_prim(
"omni.graph.nodes.ReadPrimsV2",
False,
compute_expected_property_names=self._get_expected_read_prims_v2_property_names,
)
# ----------------------------------------------------------------------
async def test_read_prims_v2_write_prim_with_target(self):
await self._read_prims_write_prim(
"omni.graph.nodes.ReadPrimsV2",
True,
compute_expected_property_names=self._get_expected_read_prims_v2_property_names,
)
# ----------------------------------------------------------------------
async def test_read_prims_bundle_write_prim(self):
"""Test omni.graph.nodes.ReadPrimsBundle and WritePrim"""
await self._read_prims_write_prim(
"omni.graph.nodes.ReadPrimsBundle",
False,
compute_expected_property_names=self._get_expected_read_prims_property_names,
)
# ----------------------------------------------------------------------
async def test_read_prims_bundle_write_prim_with_target(self):
await self._read_prims_write_prim(
"omni.graph.nodes.ReadPrimsBundle",
True,
compute_expected_property_names=self._get_expected_read_prims_property_names,
)
# ----------------------------------------------------------------------
async def _read_prims_write_prim(
self, read_prims_type, use_target_inputs, compute_expected_property_names: Callable
):
"""
use_target_inputs will use the prim target input for the ExtractPrim nodes rather than the prim path input
"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
cube_prim = ogts.create_cube(stage, "Cube", (1, 1, 1))
(graph, (read_node, write_node, _, _, extract_bundle_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", read_prims_type),
("Write", "omni.graph.nodes.WritePrim"),
("Add", "omni.graph.nodes.Add"),
("ExtractPrim", "omni.graph.nodes.ExtractPrim"),
("ExtractBundle", "omni.graph.nodes.ExtractBundle"),
],
keys.SET_VALUES: [
("ExtractPrim.inputs:primPath", "/Cube"),
],
keys.CONNECT: [
("Read.outputs_primsBundle", "ExtractPrim.inputs:prims"),
("ExtractPrim.outputs_primBundle", "ExtractBundle.inputs:bundle"),
],
},
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube_prim.GetPath(),
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prim"),
target=cube_prim.GetPath(),
)
await controller.evaluate(graph)
if use_target_inputs:
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/ExtractPrim.inputs:prim"),
target=cube_prim.GetPath(),
)
await controller.evaluate(graph)
factory = og.IBundleFactory.create()
# Check MPiB output for Read
bundle = graph.get_default_graph_context().get_output_bundle(read_node, "outputs_primsBundle")
output_bundle2 = factory.get_bundle(graph.get_default_graph_context(), bundle)
self.assertEqual(output_bundle2.get_child_bundle_count(), 1)
# Attribute Count:
# 2 - node: type, typeVersion,
# 3 - inputs: bundle
# 2 - outputs: passThrough,
n_static_attribs_extract_bundle = 4
# Attribute Count:
# 2 - node: type, typeVersion,
# 3 - inputs: prim, execIn, usdWriteBack
# 1 - outputs: execOut,
n_static_attribs_write = 6
extract_bundle_name = "outputs_passThrough"
attribs = extract_bundle_node.get_attributes()
found_size_attrib = False
for attrib in attribs:
if attrib.get_name() == "outputs:size" and attrib.get_resolved_type().base_type == og.BaseDataType.DOUBLE:
found_size_attrib = True
self.assertTrue(found_size_attrib)
expected_property_names = compute_expected_property_names(cube_prim)
bundle = graph.get_default_graph_context().get_output_bundle(extract_bundle_node, extract_bundle_name)
attribute_names = set(bundle.get_attribute_names())
self.assertEqual(attribute_names, expected_property_names)
# Check we have the expected bundle attributes
self.assertIn("size", attribute_names)
self.assertIn("sourcePrimPath", attribute_names)
self.assertIn("sourcePrimType", attribute_names)
self.assertIn("worldMatrix", attribute_names)
self.assertIn("primvars:displayColor", attribute_names)
attribute_datas = bundle.get_attribute_data(False)
self.assertEqual(
next((a for a in attribute_datas if a.get_name() == "sourcePrimPath")).get(),
cube_prim.GetPath().pathString,
)
# Check we have the expected dynamic attrib on WritePrim
attribs = write_node.get_attributes()
found_size_attrib = False
for attrib in attribs:
if attrib.get_name() == "inputs:size" and attrib.get_resolved_type().base_type == og.BaseDataType.DOUBLE:
found_size_attrib = True
self.assertTrue(found_size_attrib)
# check that evaluations propagate in a read/write cycle as expected
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CONNECT: [
("ExtractBundle.outputs:size", "Add.inputs:a"),
("ExtractBundle.outputs:size", "Add.inputs:b"),
("Add.outputs:sum", "Write.inputs:size"),
]
},
)
await controller.evaluate(graph)
attr = controller.attribute("outputs:size", extract_bundle_node)
# it is now 2 on prim, but read node as not been executed after the write, so still has the old value
self.assertEqual(og.Controller.get(attr), 1)
await controller.evaluate(graph)
# now it is 4 on the prim, and /Read as 2
self.assertEqual(og.Controller.get(attr), 2)
await controller.evaluate(graph)
# now it is 8 on the prim, and /Read as 4
self.assertEqual(og.Controller.get(attr), 4)
# ReadPrim: Clear the inputs:prim attribute to trigger a reset of the ReadPrim node
omni.kit.commands.execute(
"RemoveRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"),
target=cube_prim.GetPath(),
)
await controller.evaluate(graph)
# Verify that the stale dynamic and bundle attributes have been removed
attribs = extract_bundle_node.get_attributes()
self.assertEqual(len(attribs), n_static_attribs_extract_bundle)
bundle = graph.get_default_graph_context().get_output_bundle(extract_bundle_node, extract_bundle_name)
self.assertEqual(bundle.get_attribute_data_count(), 0)
# WritePrim: Clear the inputs:prim attribute to trigger a reset of the WritePrim node
omni.kit.commands.execute(
"RemoveRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prim"),
target=cube_prim.GetPath(),
)
await controller.evaluate(graph)
# Verify that the stale dynamic and bundle attributes have been removed
attribs = write_node.get_attributes()
self.assertEqual(len(attribs), n_static_attribs_write)
# Set it up again and re-verify things work
omni.kit.undo.undo() # Undo remove target from Write Prim
# Following step is to undo disconnected and removed dynamic attributes inside of Extract Bundle.
# When Extract Bundle's input change or recompute is called, we record
omni.kit.undo.undo() # Call to undo dynamic attribute removal and disconnection on read prim (compute)
omni.kit.undo.undo() # Call to undo dynamic attribute removal and disconnection on read prim (compute)
omni.kit.undo.undo() # Call to undo dynamic attribute removal and disconnection on read prim into bundle (compute)
omni.kit.undo.undo() # Call to undo dynamic attribute removal and disconnection on read prim into bundle (compute)
await controller.evaluate(graph)
# Check if MPiB is back to the output of ReadPrimIntoBundle
bundle = graph.get_default_graph_context().get_output_bundle(read_node, "outputs_primsBundle")
output_bundle2 = factory.get_bundle(graph.get_default_graph_context(), bundle)
self.assertEqual(output_bundle2.get_child_bundle_count(), 1)
# Verify we have the size attribute back and our bundle attribs
attribs = write_node.get_attributes()
found_size_attrib = False
for attrib in attribs:
if attrib.get_name() == "inputs:size" and attrib.get_resolved_type().base_type == og.BaseDataType.DOUBLE:
found_size_attrib = True
self.assertTrue(found_size_attrib)
# Check output bundle attributes of ExtractBundle
bundle = graph.get_default_graph_context().get_output_bundle(extract_bundle_node, extract_bundle_name)
attribute_datas = bundle.get_attribute_data(False)
attribute_names = [a.get_name() for a in attribute_datas]
self.assertIn("size", attribute_names)
self.assertIn("sourcePrimPath", attribute_names)
self.assertIn("worldMatrix", attribute_names)
self.assertIn("primvars:displayColor", attribute_names)
attribs = extract_bundle_node.get_attributes()
self.assertEqual(len(attribs) - n_static_attribs_extract_bundle, len(attribute_datas))
# Reset the underlying prim attrib value and check the plumbing is still working
cube_prim.GetAttribute("size").Set(1)
await controller.evaluate(graph)
attr = controller.attribute("outputs:size", extract_bundle_node)
self.assertEqual(og.Controller.get(attr), 1)
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(attr), 2)
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(attr), 4)
# ----------------------------------------------------------------------
async def test_findprims(self):
"""Test omni.graph.nodes.FindPrims corner cases"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
cube_prim = ogts.create_cube(stage, "Cube1", (1, 1, 1))
cube_prim2 = ogts.create_cube(stage, "Cube2", (1, 1, 1))
cube_prim3 = ogts.create_cube(stage, "Cube3", (1, 1, 1))
cube_prim3.CreateRelationship("test_rel").AddTarget(cube_prim.GetPrimPath())
(graph, (read_node,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: ("FindPrims", "omni.graph.nodes.FindPrims"),
keys.SET_VALUES: ("FindPrims.inputs:namePrefix", "Cube"),
},
)
await controller.evaluate(graph)
paths_attr = controller.attribute("outputs:primPaths", read_node)
paths = og.Controller.get(paths_attr)
self.assertListEqual(paths, [p.GetPrimPath() for p in (cube_prim, cube_prim2, cube_prim3)])
# set cube to inactive and verify it doesn't show up in the list
cube_prim.SetActive(False)
await controller.evaluate(graph)
paths = og.Controller.get(paths_attr)
self.assertListEqual(paths, [p.GetPrimPath() for p in (cube_prim2, cube_prim3)])
# Test the relationship requirement works
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: [
("FindPrims.inputs:requiredRelationship", "test_rel"),
# Not the right target
("FindPrims.inputs:requiredRelationshipTarget", cube_prim2.GetPrimPath().pathString),
]
},
)
await controller.evaluate(graph)
paths = og.Controller.get(paths_attr)
self.assertTrue(len(paths) == 0)
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: [
# The right target
("FindPrims.inputs:requiredRelationshipTarget", cube_prim.GetPrimPath().pathString),
]
},
)
await controller.evaluate(graph)
paths = og.Controller.get(paths_attr)
self.assertListEqual(paths, [p.GetPrimPath() for p in (cube_prim3,)])
# ----------------------------------------------------------------------
async def test_findprims_path_pattern(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
ogts.create_cube(stage, "Cube1", (1, 1, 1))
ogts.create_cube(stage, "Cube2", (1, 1, 1))
ogts.create_cube(stage, "Cube3", (1, 1, 1))
ogts.create_cube(stage, "Cube44", (1, 1, 1))
ogts.create_cube(stage, "AnotherCube1", (1, 1, 1))
ogts.create_cube(stage, "AnotherCube2", (1, 1, 1))
ogts.create_cube(stage, "AnotherCube3", (1, 1, 1))
controller = og.Controller()
keys = og.Controller.Keys
(graph, (find_prims,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: ("FindPrims", "omni.graph.nodes.FindPrims"),
keys.SET_VALUES: [
("FindPrims.inputs:recursive", True),
("FindPrims.inputs:pathPattern", "/Cube?"),
],
},
)
await controller.evaluate(graph)
outputs_prim_paths = find_prims.get_attribute("outputs:primPaths")
value = outputs_prim_paths.get()
self.assertEqual(len(value), 3) # Cube1, Cube2, Cube3 but not Cube44
self.assertTrue(all(item in ["/Cube1", "/Cube2", "/Cube3"] for item in value))
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: ("FindPrims.inputs:pathPattern", "/*Cube?"),
},
)
await controller.evaluate(graph)
value = outputs_prim_paths.get()
self.assertEqual(len(value), 6) # AnotherCube1,2,3 and Cube1,2,3, but not Cube44
required_cubes = ["/Cube1", "/Cube2", "/Cube3", "/AnotherCube1", "/AnotherCube2", "/AnotherCube3"]
self.assertTrue(all(item in required_cubes for item in value))
# get all /Cube?, but exclude /Cube2
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: ("FindPrims.inputs:pathPattern", "/Cube? ^/Cube2"),
},
)
await controller.evaluate(graph)
value = outputs_prim_paths.get()
self.assertEqual(len(value), 2) # Cube1,3, but not Cube2
required_cubes = ["/Cube1", "/Cube3"]
self.assertTrue(all(item in required_cubes for item in value))
# get all /Cube? but exclude /Cube1 and /Cube2
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: ("FindPrims.inputs:pathPattern", "/Cube? ^/Cube1 ^/Cube2"),
},
)
await controller.evaluate(graph)
value = outputs_prim_paths.get()
self.assertEqual(len(value), 1) # Cube3, but not Cube1,2
required_cubes = ["/Cube3"]
self.assertTrue(all(item in required_cubes for item in value))
# get all Cubes, but exclude all cubes that end with single digit
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: ("FindPrims.inputs:pathPattern", "*Cube* ^*Cube?"),
},
)
await controller.evaluate(graph)
value = outputs_prim_paths.get()
self.assertEqual(len(value), 1) # only Cube44
required_cubes = ["/Cube44"]
self.assertTrue(all(item in required_cubes for item in value))
# get all Cubes, and exclude all cubes to produce empty set
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: ("FindPrims.inputs:pathPattern", "*Cube* ^*Cube*"),
},
)
await controller.evaluate(graph)
value = outputs_prim_paths.get()
self.assertEqual(len(value), 0)
# ----------------------------------------------------------------------
async def test_getprims_path_pattern(self):
"""Test the path pattern matching feature of the GetPrims node."""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, get_prims_node), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ReadPrimsBundle", "omni.graph.nodes.ReadPrimsBundle"),
("GetPrims", "omni.graph.nodes.GetPrims"),
],
keys.CONNECT: [("ReadPrimsBundle.outputs_primsBundle", "GetPrims.inputs:bundle")],
},
)
cube_paths = {"/Cube1", "/Cube2", "/Cube3", "/Cube44", "/AnotherCube1", "/AnotherCube2", "/AnotherCube3"}
for cube_path in cube_paths:
cube_name = cube_path.split("/")[-1]
ogts.create_cube(stage, cube_name, (1, 1, 1))
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/ReadPrimsBundle.inputs:prims"),
target=cube_path,
)
await controller.evaluate(graph)
# Dictionary from each path pattern to its expected prim paths
path_pattern_dict = {
"*": cube_paths,
"": set(),
"/Cube?": {"/Cube1", "/Cube2", "/Cube3"},
"/*Cube?": {"/Cube1", "/Cube2", "/Cube3", "/AnotherCube1", "/AnotherCube2", "/AnotherCube3"},
"/* ^/Another*": {"/Cube1", "/Cube2", "/Cube3", "/Cube44"},
}
bundle_factory = og.IBundleFactory.create()
bundle = graph.get_default_graph_context().get_output_bundle(get_prims_node, "outputs_bundle")
output_bundle2 = bundle_factory.get_bundle(graph.get_default_graph_context(), bundle)
for path_pattern, expected_prim_paths in path_pattern_dict.items():
# Test path patterns with the "inverse" option off (by default)
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: [
("GetPrims.inputs:pathPattern", path_pattern),
("GetPrims.inputs:inverse", False),
]
},
)
await controller.evaluate(graph)
child_bundle_paths = set()
child_bundle_count = output_bundle2.get_child_bundle_count()
for i in range(child_bundle_count):
child_bundle = output_bundle2.get_child_bundle(i)
attr = child_bundle.get_attribute_by_name("sourcePrimPath")
child_bundle_paths.add(attr.get())
self.assertEqual(child_bundle_paths, expected_prim_paths)
# Test path patterns with the "inverse" option on
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: [
("GetPrims.inputs:inverse", True),
]
},
)
await controller.evaluate(graph)
child_bundle_paths = set()
child_bundle_count = output_bundle2.get_child_bundle_count()
for i in range(child_bundle_count):
child_bundle = output_bundle2.get_child_bundle(i)
attr = child_bundle.get_attribute_by_name("sourcePrimPath")
child_bundle_paths.add(attr.get())
self.assertEqual(child_bundle_paths, cube_paths.difference(expected_prim_paths))
# ----------------------------------------------------------------------
async def test_readtime(self):
"""Test omni.graph.nodes.ReadTime"""
app = omni.kit.app.get_app()
timeline = omni.timeline.get_timeline_interface()
time_node_name = "Time"
# setup initial timeline state and avoid possibility that running this test twice will give different results
timeline.set_fast_mode(True)
fps = 24.0
timeline.set_time_codes_per_second(fps)
timeline.set_start_time(-1.0)
timeline.set_end_time(0.0)
timeline.set_current_time(0.0)
await app.next_update_async()
keys = og.Controller.Keys
(_, (time_node,), _, _) = og.Controller.edit(
self.TEST_GRAPH_PATH, {keys.CREATE_NODES: [(time_node_name, "omni.graph.nodes.ReadTime")]}
)
await app.next_update_async()
await og.Controller.evaluate()
self.assertGreater(og.Controller(og.Controller.attribute("outputs:deltaSeconds", time_node)).get(), 0.0)
self.assertGreater(og.Controller(og.Controller.attribute("outputs:timeSinceStart", time_node)).get(), 0.0)
self.assertFalse(og.Controller(og.Controller.attribute("outputs:isPlaying", time_node)).get())
self.assertEqual(og.Controller(og.Controller.attribute("outputs:time", time_node)).get(), 0.0)
self.assertEqual(og.Controller(og.Controller.attribute("outputs:frame", time_node)).get(), 0.0)
timeline.set_start_time(1.0)
timeline.set_end_time(10.0)
timeline.play()
await app.next_update_async()
await app.next_update_async()
await og.Controller.evaluate()
# graph has been reloaded as a result of the fps change: we need re refetch the node
time_node = og.get_node_by_path(self.TEST_GRAPH_PATH + "/" + time_node_name)
self.assertTrue(og.Controller(og.Controller.attribute("outputs:isPlaying", time_node)).get())
animation_time = og.Controller(og.Controller.attribute("outputs:time", time_node)).get()
self.assertGreater(animation_time, 0.0)
self.assertAlmostEqual(
og.Controller(og.Controller.attribute("outputs:frame", time_node)).get(), fps * animation_time, places=2
)
timeline.stop()
await app.next_update_async()
# ----------------------------------------------------------------------
async def test_read_and_write_prim_material(self):
await self._read_and_write_prim_material(False)
async def test_read_and_write_prim_material_with_target(self):
await self._read_and_write_prim_material(True)
async def _read_and_write_prim_material(self, use_target_inputs):
"""
Test ReadPrimMaterial and WritePrimMaterial node. If use_target_inputs is true, use the prim target input rather
than the prim path input
"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
mat_path = "/TestMaterial"
prim_path_a = "/TestPrimA"
prim_path_b = "/TestPrimB"
(graph, (read_node, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimMaterial"),
("Write", "omni.graph.nodes.WritePrimMaterial"),
],
keys.CREATE_PRIMS: [(mat_path, "Material"), (prim_path_a, "Cube"), (prim_path_b, "Cube")],
keys.SET_VALUES: [
("Read.inputs:primPath", prim_path_a),
("Write.inputs:primPath", prim_path_b),
("Write.inputs:materialPath", mat_path),
],
},
)
await controller.evaluate(graph)
if use_target_inputs:
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prim"),
target=prim_path_a,
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prim"),
target=prim_path_b,
)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:material"),
target=mat_path,
)
await controller.evaluate(graph)
prim_a = stage.GetPrimAtPath(prim_path_a)
rel_a = prim_a.CreateRelationship("material:binding")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel_a, target=Sdf.Path(mat_path))
await controller.evaluate(graph)
read_output = og.Controller.get(controller.attribute("outputs:material", read_node))
self.assertEqual(read_output, mat_path)
prim_b = stage.GetPrimAtPath(prim_path_b)
mat_b, _ = UsdShade.MaterialBindingAPI(prim_b).ComputeBoundMaterial()
write_output = mat_b.GetPath().pathString
self.assertEqual(write_output, mat_path)
# ----------------------------------------------------------------------
async def test_read_prim_material_with_target_connections(self):
"""Test ReadPrimMaterial and WritePrimMaterial node"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
mat_path = "/TestMaterial"
prim_path_a = "/TestPrimA"
(graph, (_, _, prim_node, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimMaterial"),
("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("GetPrimPath", "omni.graph.nodes.GetPrimPath"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
],
keys.CREATE_PRIMS: [(mat_path, "Material"), (prim_path_a, "Cube")],
keys.SET_VALUES: [("ConstToken.inputs:value", prim_path_a)],
keys.CONNECT: [
("Read.outputs:materialPrim", "GetPrimPath.inputs:prim"),
("GetPrimAtPath.outputs:prims", "Read.inputs:prim"),
("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"),
],
},
)
prim_a = stage.GetPrimAtPath(prim_path_a)
rel_a = prim_a.CreateRelationship("material:binding")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel_a, target=Sdf.Path(mat_path))
await controller.evaluate(graph)
mat_output = og.Controller.get(("outputs:primPath", prim_node))
self.assertEqual(mat_output, mat_path)
# ----------------------------------------------------------------------
async def test_read_and_write_settings(self):
"""Test ReadSetting and WriteSetting node"""
controller = og.Controller()
keys = og.Controller.Keys
settings = carb.settings.get_settings()
setting_path = self.PERSISTENT_SETTINGS_PREFIX + "/omnigraph/deprecationsAreErrors"
default_value = settings.get(setting_path)
sample_value = not default_value
(graph, (read_node, _, _), _, _) = og.Controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadSetting"),
("Write", "omni.graph.nodes.WriteSetting"),
("ConstBool", "omni.graph.nodes.ConstantBool"),
],
keys.CONNECT: [("ConstBool.inputs:value", "Write.inputs:value")],
keys.SET_VALUES: [
("Read.inputs:settingPath", setting_path),
("Write.inputs:settingPath", setting_path),
("ConstBool.inputs:value", sample_value),
],
},
)
await controller.evaluate(graph)
await omni.kit.app.get_app().next_update_async()
output_value = og.Controller.get(controller.attribute("outputs:value", read_node))
self.assertEqual(output_value, sample_value)
settings.set(setting_path, default_value)
# ----------------------------------------------------------------------
async def test_get_look_at_rotation(self):
"""Test GetLookAtRotation node"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# Get the scene up-vector.
stage_up_axis = stage.GetMetadata("upAxis")
if stage_up_axis.lower() == "x":
up_vec = Gf.Vec3d.XAxis()
fwd_vec = -Gf.Vec3d.ZAxis()
right_vec = -Gf.Vec3d.YAxis()
is_y_up = False
elif stage_up_axis.lower() == "z":
up_vec = Gf.Vec3d.ZAxis()
fwd_vec = -Gf.Vec3d.XAxis()
right_vec = Gf.Vec3d.YAxis()
is_y_up = False
else:
up_vec = Gf.Vec3d.YAxis()
fwd_vec = -Gf.Vec3d.ZAxis()
right_vec = Gf.Vec3d.XAxis()
is_y_up = True
# Create a prim driven by a GetLookAtRotation node to always face its fwd_vec toward
# the origin.
distance_from_origin = 750.0
# It's important that the up component be non-zero as that creates a difference between the local and
# and world up-vectors, which is where problems can occur.
up_offset = 100.0
position = up_vec * up_offset - fwd_vec * distance_from_origin
xform_path = "/World/xform"
controller = og.Controller()
keys = og.Controller.Keys
(graph, (lookat_node, *_), (xform_prim, *_), _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("lookat", "omni.graph.nodes.GetLookAtRotation"),
("write", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: [(xform_path, "Xform")],
keys.CONNECT: [("lookat.outputs:rotateXYZ", "write.inputs:value")],
keys.SET_VALUES: [
("lookat.inputs:forward", fwd_vec),
("lookat.inputs:start", position),
("write.inputs:name", "xformOp:rotateXYZ"),
("write.inputs:primPath", xform_path),
("write.inputs:usePath", True),
],
},
)
await controller.evaluate(graph)
start_attr = lookat_node.get_attribute("inputs:start")
fwd_attr = lookat_node.get_attribute("inputs:forward")
up_attr = lookat_node.get_attribute("inputs:up")
for _ in range(2):
# Move the transform in a circle around the origin, keeping the up component constant.
for angle in range(0, 360, 45):
rad = math.radians(angle)
position = right_vec * math.sin(rad) * distance_from_origin
position -= fwd_vec * math.cos(rad) * distance_from_origin
position += up_vec * up_offset
start_attr.set(position)
await controller.evaluate(graph)
# Get the normalized vector from the current position to the origin.
pos_vec = -Gf.Vec3d(position).GetNormalized()
# The forward vector in world space should match the position vector.
cache = UsdGeom.XformCache()
xform = cache.GetLocalToWorldTransform(xform_prim)
ws_fwd = xform.TransformDir(fwd_vec).GetNormalized()
diff = Gf.Rotation(pos_vec, ws_fwd).GetAngle()
self.assertAlmostEqual(
diff, 0.0, msg=f"at {angle} degree position, forward vector does not point at origin."
)
# The local and world up-vectors should remain within 8 degrees of each other.
ws_up = xform.TransformDir(up_vec).GetNormalized()
diff = Gf.Rotation(up_vec, ws_up).GetAngle()
self.assertLess(abs(diff), 8.0, f"at {angle} degree position, up-vector has drifted too far")
# The first pass used scene-up.
# For the second pass we set an explicit up-vector, different from scene-up.
if is_y_up:
up_vec = Gf.Vec3d.ZAxis()
fwd_vec = -Gf.Vec3d.XAxis()
right_vec = Gf.Vec3d.YAxis()
else:
up_vec = Gf.Vec3d.YAxis()
fwd_vec = -Gf.Vec3d.ZAxis()
right_vec = Gf.Vec3d.XAxis()
fwd_attr.set(fwd_vec)
up_attr.set(up_vec)
async def test_selection_nodes(self):
"""Test ReadStageSelection, IsPrimSelected nodes"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
(graph, (read_node, check_node, check_target), _, _) = og.Controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadStageSelection"),
("IsSelected", "omni.graph.nodes.IsPrimSelected"),
("IsSelectedWithTarget", "omni.graph.nodes.IsPrimSelected"),
],
keys.SET_VALUES: [("IsSelected.inputs:primPath", f"{self.TEST_GRAPH_PATH}/Read")],
},
)
await controller.evaluate(graph)
rel = stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/IsSelectedWithTarget.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=f"{self.TEST_GRAPH_PATH}/Read")
selection = usd_context.get_selection()
self.assertFalse(og.Controller.get(controller.attribute("outputs:isSelected", check_node)))
self.assertFalse(og.Controller.get(controller.attribute("outputs:isSelected", check_target)))
selection.set_selected_prim_paths(
[read_node.get_prim_path()],
False,
)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
selected_paths = og.Controller.get(controller.attribute("outputs:selectedPrims", read_node))
self.assertListEqual(selected_paths, selection.get_selected_prim_paths())
self.assertTrue(og.Controller.get(controller.attribute("outputs:isSelected", check_node)))
self.assertTrue(og.Controller.get(controller.attribute("outputs:isSelected", check_target)))
selection.clear_selected_prim_paths()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
selected_paths = og.Controller.get(controller.attribute("outputs:selectedPrims", read_node))
self.assertListEqual(selected_paths, selection.get_selected_prim_paths())
self.assertFalse(og.Controller.get(controller.attribute("outputs:isSelected", check_node)))
self.assertFalse(og.Controller.get(controller.attribute("outputs:isSelected", check_target)))
# ----------------------------------------------------------------------
async def test_parallel_read_write_prim_attribute(self):
"""Attempt to read and write prim attributes in parallel"""
# ReadIndex -> Multiply
# / \
# 10 ------x--------> MakeTranslate -> WriteTranslate
# /
# ReadTranslate -> BreakTranslate -yz-
keys = og.Controller.Keys
index_name = "testIndex"
attr_name = "xformOp:translate"
scale = 10
cubes = []
for i in range(64):
graph_name = f"/graph{i}"
obj_name = f"/obj{i}"
controller = og.Controller()
(graph, _, prims, _) = controller.edit(
graph_name,
{
keys.CREATE_NODES: [
("ReadIndex", "omni.graph.nodes.ReadPrimAttribute"),
("ReadTranslate", "omni.graph.nodes.ReadPrimAttribute"),
("BreakTranslate", "omni.graph.nodes.BreakVector3"),
("Multiply", "omni.graph.nodes.Multiply"),
("MakeTranslate", "omni.graph.nodes.MakeVector3"),
("WriteTranslate", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: [
(obj_name, "Cube"),
],
},
)
# we want to test parallel execution: prevent any merging
graph.set_auto_instancing_allowed(False)
attr = prims[0].CreateAttribute(index_name, Sdf.ValueTypeNames.Double)
attr.Set(i)
cubes.append(prims[0])
controller.edit(
graph_name,
{
keys.SET_VALUES: [
("ReadIndex.inputs:name", index_name),
("ReadIndex.inputs:usePath", True),
("ReadIndex.inputs:primPath", obj_name),
("ReadTranslate.inputs:name", attr_name),
("ReadTranslate.inputs:usePath", True),
("ReadTranslate.inputs:primPath", obj_name),
("WriteTranslate.inputs:name", attr_name),
("WriteTranslate.inputs:usePath", True),
("WriteTranslate.inputs:primPath", obj_name),
("Multiply.inputs:b", scale, "double"),
],
},
)
controller.edit(
graph_name,
{
keys.CONNECT: [
("ReadIndex.outputs:value", "Multiply.inputs:a"),
("ReadTranslate.outputs:value", "BreakTranslate.inputs:tuple"),
("Multiply.outputs:product", "MakeTranslate.inputs:x"),
("BreakTranslate.outputs:y", "MakeTranslate.inputs:y"),
("BreakTranslate.outputs:z", "MakeTranslate.inputs:z"),
("MakeTranslate.outputs:tuple", "WriteTranslate.inputs:value"),
],
},
)
# cubes[0].GetStage().Export("c:/tmp/test.usda")
for cube in cubes:
translate = cube.GetAttribute(attr_name).Get()
self.assertEqual(translate[0], 0)
await og.Controller.evaluate()
for cube in cubes:
index = cube.GetAttribute(index_name).Get()
translate = cube.GetAttribute(attr_name).Get()
self.assertEqual(translate[0], index * scale)
# ----------------------------------------------------------------------
async def test_read_prim_node_default_time_code_upgrades(self):
"""
Tests that read prim node variants property upgrade their time code property
to use NAN as a default
"""
app = omni.kit.app.get_app()
nodes = [
"ReadPrim",
"ReadPrims",
"ReadPrimAttribute",
"ReadPrimAttributes",
"ReadPrimBundle",
"ReadPrimsBundle",
]
# testing under different frame rates to validate the upgrade is correctly detected
frame_rates = [12, 24, 30, 60]
for frame_rate in frame_rates:
with self.subTest(frame_rate=frame_rate):
timeline = omni.timeline.get_timeline_interface()
timeline.set_time_codes_per_second(frame_rate)
await app.next_update_async()
file_path = os.path.join(os.path.dirname(__file__), "data", "TestReadPrimNodeVariants.usda")
stage = omni.usd.get_context().get_stage()
# create a prim and add a file reference
prim = stage.DefinePrim("/Ref")
# when we make the references, there will be deprecation warnings
prim.GetReferences().AddReference(file_path)
self.assertEqual(stage.GetTimeCodesPerSecond(), frame_rate)
await omni.kit.app.get_app().next_update_async()
for node in nodes:
attr = og.Controller.attribute(f"/Ref/ActionGraph/{node}.inputs:usdTimecode")
self.assertTrue(isnan(attr.get()))
await omni.usd.get_context().new_stage_async()
# ----------------------------------------------------------------------
async def test_is_prim_active(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
contents = Usd.Stage.CreateInMemory("payload.usd")
contents.DefinePrim("/payload/A", "Xform")
payload = stage.DefinePrim("/payload", "Xform")
payload.GetPayloads().AddPayload(Sdf.Payload(contents.GetRootLayer().identifier, "/payload"))
keys = og.Controller.Keys
controller = og.Controller()
(graph, (node,), _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [("IsActive", "omni.graph.nodes.IsPrimActive")],
},
)
await controller.evaluate(graph)
rel = stage.GetRelationshipAtPath("/TestGraph/IsActive.inputs:primTarget")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/payload/A")
await controller.evaluate(graph)
out = node.get_attribute("outputs:active")
self.assertEqual(out.get(), True)
# Note: currently the node will raise an error if the prim isn't in the stage as well as set active to false
payload.Unload()
with ogts.ExpectedError():
await controller.evaluate(graph)
out = node.get_attribute("outputs:active")
self.assertEqual(out.get(), False)
# -------------------------------------------------------------------------------
async def test_get_graph_target_prim(self):
"""Test that the GetGraphTargetPrim node outputs the expected graph target prim"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_graph_target_node, path_node), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("GetGraphTargetPrim", "omni.graph.nodes.GetGraphTargetPrim"),
("GetPrimPath", "omni.graph.nodes.GetPrimPath"),
],
keys.CONNECT: [("GetGraphTargetPrim.outputs:prim", "GetPrimPath.inputs:prim")],
},
)
# no instances, it should return the graph prim
await og.Controller.evaluate(graph)
self.assertEqual(self.TEST_GRAPH_PATH, path_node.get_attribute("outputs:primPath").get())
num_instances = 5
# create instances
for i in range(0, num_instances):
prim_name = f"/World/Prim_{i}"
stage.DefinePrim(prim_name)
OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self.TEST_GRAPH_PATH)
# rerun the graph, this time evaluating instances
await og.Controller.evaluate(graph)
for i in range(0, num_instances):
self.assertEqual(f"/World/Prim_{i}", path_node.get_attribute("outputs:primPath").get(instance=i))
async def test_construct_array_invalid_array_size(self):
"""Test that setting an invalid value on OgnConstructArray.arraySize does not crash"""
# Ideally this would be done with the following test in the .ogn file, but the node parser
# applies the minimum / maximum attribute limits when parsing the tests, which means that
# we cannot define tests for invalid inputs in the .ogn file
# {
# "inputs:arraySize": -1, "inputs:arrayType": "Int64",
# "outputs:array": {"type": "int64[]", "value": []}
# }
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [("ConstructArray", "omni.graph.nodes.ConstructArray")],
keys.SET_VALUES: [
("ConstructArray.inputs:arraySize", -1),
("ConstructArray.inputs:arrayType", "int[]"),
],
},
)
# Evaluate the graph once to ensure the node has a Database created
await controller.evaluate(graph)
result = nodes[0].get_attribute("outputs:array").get()
expected: [int] = []
self.assertListEqual(expected, list(result))
async def test_get_prim_local_to_world_empty(self):
"""Regression test for GetPrimLocalToWorldTransform"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [("TestWorld", "omni.graph.nodes.GetPrimLocalToWorldTransform")],
keys.SET_VALUES: [
("TestWorld.inputs:usePath", False),
],
},
)
with ogts.ExpectedError():
await controller.evaluate(graph)
| 63,239 | Python | 43.162011 | 123 | 0.568178 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_find_prims_node.py | import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
class TestFindPrimsNode(ogts.OmniGraphTestCase):
"""Unit tests for Find Prims node in this extension"""
# ----------------------------------------------------------------------
async def test_find_prims_node_type_attribute_v1(self):
"""First version of Find Prims node did not use pattern matching. Attribute 'type' needs to be automatically
updated to support pattern matching.
"""
# load the test scene which contains a ReadPrim V1 node
(result, error) = await ogts.load_test_file("TestFindPrimsNode_v1.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
test_graph_path = "/World/TestGraph"
test_graph = og.get_graph_by_path(test_graph_path)
find_prims_empty = test_graph.get_node(test_graph_path + "/find_prims_empty")
self.assertTrue(find_prims_empty.is_valid())
find_prims_types = test_graph.get_node(test_graph_path + "/find_prims_types")
self.assertTrue(find_prims_types.is_valid())
self.assertEqual(find_prims_empty.get_attribute("inputs:type").get(), "*")
self.assertEqual(find_prims_types.get_attribute("inputs:type").get(), "Mesh")
# ----------------------------------------------------------------------
async def test_add_target_input(self):
"""
Test target input type and that path input is still used if target prim has not been selected
"""
keys = og.Controller.Keys
controller = og.Controller()
(graph, (node,), _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [("FindPrims", "omni.graph.nodes.FindPrims")],
keys.CREATE_PRIMS: [
("/World/A", "Xform"),
("/World/B", "Xform"),
("/World/A/Cone", "Cone"),
("/World/B/Cone", "Cone"),
("/World/B/Cube", "Cube"),
("/World/B/Sphere", "Sphere"),
],
keys.SET_VALUES: [("FindPrims.inputs:rootPrimPath", "/World/A")],
},
)
# If no target input is specified, fallback to path input
await controller.evaluate(graph)
out = node.get_attribute("outputs:primPaths")
self.assertEqual(out.get(), ["/World/A/Cone"])
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
rel = stage.GetRelationshipAtPath("/TestGraph/FindPrims.inputs:rootPrim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/B")
await controller.evaluate(graph)
out = node.get_attribute("outputs:primPaths")
self.assertEqual(out.get(), ["/World/B/Cone", "/World/B/Cube", "/World/B/Sphere"])
# Test with a required relationship
cone = stage.GetPrimAtPath("/World/B/Cone")
cube = stage.GetPrimAtPath("/World/B/Cube")
omni.kit.commands.execute(
"AddRelationshipTarget", relationship=cone.CreateRelationship("test_rel"), target="/World/A"
)
omni.kit.commands.execute(
"AddRelationshipTarget", relationship=cube.CreateRelationship("test_rel"), target="/World/B"
)
rel_attr = node.get_attribute("inputs:requiredRelationship")
rel_attr.set("test_rel")
rel = stage.GetRelationshipAtPath("/TestGraph/FindPrims.inputs:requiredTarget")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/B")
await controller.evaluate(graph)
self.assertEqual(out.get(), ["/World/B/Cube"])
| 3,708 | Python | 44.231707 | 116 | 0.587109 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_api.py | """Testing the stability of the API in this module"""
import omni.graph.core.tests as ogts
import omni.graph.nodes as ognd
from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents
# ======================================================================
class _TestOmniGraphNodesApi(ogts.OmniGraphTestCase):
_UNPUBLISHED = ["bindings", "ogn", "tests"]
async def test_api(self):
_check_module_api_consistency(ognd, self._UNPUBLISHED) # noqa: PLW0212
_check_module_api_consistency( # noqa: PLW0212
ognd.tests, ["create_prim_with_everything", "bundle_test_utils"], is_test_module=True
)
async def test_api_features(self):
"""Test that the known public API features continue to exist"""
_check_public_api_contents(ognd, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212
_check_public_api_contents( # noqa: PLW0212
ognd.tests,
[
"BundleInspectorResults_t",
"BundleResultKeys",
"bundle_inspector_results",
"enable_debugging",
"filter_bundle_inspector_results",
"get_bundle_with_all_results",
"prim_with_everything_definition",
"verify_bundles_are_equal",
],
[],
only_expected_allowed=False,
)
| 1,430 | Python | 39.885713 | 108 | 0.576224 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_auto_conv_on_load.py | """Test the node that inspects attribute bundles"""
import omni.graph.core as og
ogts = og.tests
# ======================================================================
class TestConversion(ogts.test_case_class()):
"""Run simple unit tests that exercises auto conversion of attribute"""
# ----------------------------------------------------------------------
async def test_auto_conv_on_load(self):
# This file contains a graph which has a chain of nodes connected through extented attributes
# The begining of this chain forces type resolution to double, but a float is required at the end of the chain
# The test makes sure that the type is correctly resolved/restored on this final attribute
(result, error) = await ogts.load_test_file("TestConversionOnLoad.usda", use_caller_subdirectory=True)
self.assertTrue(result, f"{error}")
await og.Controller.evaluate()
easing_node = og.Controller.node("/World/PushGraph/easing_function")
attr = og.Controller.attribute("inputs:alpha", easing_node)
attr_type = attr.get_resolved_type()
self.assertTrue(attr_type.base_type == og.BaseDataType.FLOAT)
| 1,195 | Python | 43.296295 | 118 | 0.620084 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_prim_relationship_nodes.py | import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.commands
import omni.kit.test
from pxr import OmniGraphSchemaTools
# ======================================================================
class TestPrimRelationshipNodes(ogts.OmniGraphTestCase):
"""Tests read and write prim relationship nodes"""
TEST_GRAPH_PATH = "/World/TestGraph"
# ----------------------------------------------------------------------
async def test_read_prim_relationships(self):
"""Test the read prim relationship nodes that use the new target input/output types"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
# For the instanced test, setup a graph like this so that each graph instance looks at the material on a
# different cube
#
# read_var -> to_token -> build_string -> find_prims -> read_prim_relationship
(graph, (read, read_test_rel, _, _, _, _), (cone,), _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimRelationship"),
("ReadTestRel", "omni.graph.nodes.ReadPrimRelationship"),
("ReadVar", "omni.graph.core.ReadVariable"),
("ToToken", "omni.graph.nodes.ToToken"),
("BuildString", "omni.graph.nodes.BuildString"),
("FindPrims", "omni.graph.nodes.FindPrims"),
],
keys.CREATE_PRIMS: [
("/World/Cone", "Cone"),
],
keys.SET_VALUES: [
("Read.inputs:name", "material:binding"),
("ReadTestRel.inputs:name", "test_rel"),
("BuildString.inputs:a", "Cube_", og.Type(og.BaseDataType.TOKEN)),
("ReadVar.inputs:variableName", "suffix"),
("FindPrims.inputs:recursive", True),
],
keys.CONNECT: [
("ReadVar.outputs:value", "ToToken.inputs:value"),
("ToToken.outputs:converted", "BuildString.inputs:b"),
("BuildString.outputs:value", "FindPrims.inputs:namePrefix"),
("FindPrims.outputs:prims", "Read.inputs:prim"),
],
},
)
await og.Controller.evaluate(graph)
var = graph.create_variable("suffix", og.Type(og.BaseDataType.INT))
# Assign materials for instanced example
num_instances = 3
for i in range(0, num_instances):
prim = stage.DefinePrim(f"/World/Cube_{i}", "Cube")
mat = stage.DefinePrim(f"/World/Material_{i}", "Material")
omni.kit.commands.execute(
"AddRelationshipTarget", relationship=prim.CreateRelationship("material:binding"), target=mat.GetPath()
)
# Setup example with more than one relationship target
rel = cone.CreateRelationship("test_rel")
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/ReadTestRel.inputs:prim"),
target=cone.GetPath(),
)
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Material_0")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube_0")
await controller.evaluate(graph)
# verify that this works without instancing
self.assertEqual(read.get_attribute("outputs:value").get(), ["/World/Material_0"])
self.assertEqual(read_test_rel.get_attribute("outputs:value").get(), ["/World/Material_0", "/World/Cube_0"])
# create instances
for i in range(0, num_instances):
prim_name = f"/World/Instance_{i}"
stage.DefinePrim(prim_name)
OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self.TEST_GRAPH_PATH)
await og.Controller.evaluate(graph)
for i in range(0, num_instances):
var.set(graph.get_default_graph_context(), value=i, instance_path=f"/World/Instance_{i}")
await og.Controller.evaluate(graph)
# rerun the graph, this time evaluating instances
for i in range(0, num_instances):
self.assertEqual(read.get_attribute("outputs:value").get(instance=i), [f"/World/Material_{i}"])
# ----------------------------------------------------------------------
async def test_basic_write_prim_relationships(self):
"""Basic test of write prim relationship node"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
# To deterministically schedule write-read operation nodes are split
# into separate graphs: write and read.
# That gives control over scheduling writing before reading.
write_graph_path = "/World/TestGraphWrite"
read_graph_path = "/World/TestGraphRead"
(write_graph, (write,), (cone, cube), _,) = controller.edit(
write_graph_path,
{
keys.CREATE_NODES: [
("Write", "omni.graph.nodes.WritePrimRelationship"),
],
keys.CREATE_PRIMS: [
("/World/Cone", "Cone"),
("/World/Cube", "Cube"),
],
keys.SET_VALUES: [
("Write.inputs:name", "test_rel"),
("Write.inputs:usdWriteBack", False),
],
},
)
(read_graph, (read,), _, _,) = controller.edit(
read_graph_path,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimRelationship"),
],
keys.SET_VALUES: [
("Read.inputs:name", "test_rel"),
],
},
)
# Setup Write
rel = stage.GetPropertyAtPath(f"{write_graph_path}/Write.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=cone.GetPath())
rel = stage.GetPropertyAtPath(f"{write_graph_path}/Write.inputs:value")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=cube.GetPath())
# Setup Read
rel = stage.GetPropertyAtPath(f"{read_graph_path}/Read.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=cone.GetPath())
# Evaluate write, then read
await og.Controller.evaluate(write_graph)
await og.Controller.evaluate(read_graph)
out = read.get_attribute("outputs:value")
self.assertEqual(out.get(), ["/World/Cube"])
# usd write back is false, so this should fail
self.assertEqual(cone.HasRelationship("test_rel"), False)
# verify usd write back
write.get_attribute("inputs:usdWriteBack").set(True)
await og.Controller.evaluate(write_graph)
await og.Controller.evaluate(read_graph)
self.assertEqual(cone.HasRelationship("test_rel"), True)
# test that relationship is cleared if value is empty
rel = stage.GetPropertyAtPath(f"{write_graph_path}/Write.inputs:value")
omni.kit.commands.execute("RemoveRelationshipTarget", relationship=rel, target=cube.GetPath())
await og.Controller.evaluate(write_graph)
await og.Controller.evaluate(read_graph)
self.assertEqual(out.get(), [])
# ----------------------------------------------------------------------
async def test_write_prim_relationships_with_instancing(self):
"""Test the write prim relationship nodes wth instancing"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
(graph, (write, read, _, _, _, _, _, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Write", "omni.graph.nodes.WritePrimRelationship"),
("Read", "omni.graph.nodes.ReadPrimRelationship"),
("ReadVar", "omni.graph.core.ReadVariable"),
("ToToken", "omni.graph.nodes.ToToken"),
("BuildStringCone", "omni.graph.nodes.BuildString"),
("BuildStringCube", "omni.graph.nodes.BuildString"),
("FindPrimsCone", "omni.graph.nodes.FindPrims"),
("FindPrimsCube", "omni.graph.nodes.FindPrims"),
],
keys.SET_VALUES: [
("Write.inputs:name", "test_rel"),
("Write.inputs:usdWriteBack", False),
("Read.inputs:name", "test_rel"),
("BuildStringCone.inputs:a", "Cone_", og.Type(og.BaseDataType.TOKEN)),
("BuildStringCube.inputs:a", "Cube_", og.Type(og.BaseDataType.TOKEN)),
("ReadVar.inputs:variableName", "suffix"),
("FindPrimsCone.inputs:recursive", True),
("FindPrimsCube.inputs:recursive", True),
],
keys.CONNECT: [
("ReadVar.outputs:value", "ToToken.inputs:value"),
("ToToken.outputs:converted", "BuildStringCone.inputs:b"),
("ToToken.outputs:converted", "BuildStringCube.inputs:b"),
("BuildStringCone.outputs:value", "FindPrimsCone.inputs:namePrefix"),
("BuildStringCube.outputs:value", "FindPrimsCube.inputs:namePrefix"),
("FindPrimsCone.outputs:prims", "Write.inputs:prim"),
("FindPrimsCube.outputs:prims", "Write.inputs:value"),
("FindPrimsCone.outputs:prims", "Read.inputs:prim"),
],
},
)
await og.Controller.evaluate(graph)
var = graph.create_variable("suffix", og.Type(og.BaseDataType.INT))
# create targets for instanced example
num_instances = 3
for i in range(0, num_instances):
stage.DefinePrim(f"/World/Cone_{i}", "Cone")
stage.DefinePrim(f"/World/Cube_{i}", "Cube")
await og.Controller.evaluate(graph)
# Setting the name input to something else and then back again is needed to trigger the prefetch of the prim
# correctly. See OM-93232 for more details. Once we get to the bottom of what's going on there, this should be
# removed. I'm not entirely sure why this workaround is also not needed in test_basic_write_prim_relationships.
# And the issue also doesn't happen when this code is run in Kit GUI via the script editor.
read.get_attribute("inputs:name").set("foo")
await og.Controller.evaluate(graph)
read.get_attribute("inputs:name").set("test_rel")
await og.Controller.evaluate(graph)
# test without instancing...
self.assertEqual(read.get_attribute("outputs:value").get(), ["/World/Cube_0"])
# usd write back is false, so this should fail
cone = stage.GetPrimAtPath("/World/Cone_0")
self.assertEqual(cone.HasRelationship("test_rel"), False)
# verify usd write back
write.get_attribute("inputs:usdWriteBack").set(True)
await og.Controller.evaluate(graph)
self.assertEqual(cone.HasRelationship("test_rel"), True)
# create instances
for i in range(0, num_instances):
prim_name = f"/World/Instance_{i}"
stage.DefinePrim(prim_name)
OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self.TEST_GRAPH_PATH)
await og.Controller.evaluate(graph)
for i in range(0, num_instances):
var.set(graph.get_default_graph_context(), value=i, instance_path=f"/World/Instance_{i}")
await og.Controller.evaluate(graph)
# Workaround. See OM-93232
read.get_attribute("inputs:name").set("foo")
await og.Controller.evaluate(graph)
read.get_attribute("inputs:name").set("test_rel")
await og.Controller.evaluate(graph)
# rerun the graph, this time evaluating instances
for i in range(0, num_instances):
self.assertEqual(read.get_attribute("outputs:value").get(instance=i), [f"/World/Cube_{i}"])
| 12,576 | Python | 44.734545 | 119 | 0.569418 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/__init__.py | """
Explicitly import the test utilities that will be part of the public interface
This way you can do things like:
import omni.graph.nodes.tests as ognt
new_prim = ognt.bundle_inspector_output()
"""
from .bundle_test_utils import (
BundleInspectorResults_t,
BundleResultKeys,
bundle_inspector_results,
enable_debugging,
filter_bundle_inspector_results,
get_bundle_with_all_results,
prim_with_everything_definition,
verify_bundles_are_equal,
)
__all__ = [
"BundleInspectorResults_t",
"BundleResultKeys",
"bundle_inspector_results",
"enable_debugging",
"filter_bundle_inspector_results",
"get_bundle_with_all_results",
"prim_with_everything_definition",
"verify_bundles_are_equal",
]
scan_for_test_modules = True
"""The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
| 900 | Python | 27.156249 | 112 | 0.716667 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_nodes_with_prim_connection.py | import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.commands
import omni.kit.stage_templates
import omni.kit.test
import omni.timeline
import omni.usd
from pxr import Gf, Sdf, UsdGeom
# ======================================================================
class TestNodesWithPrimConnection(ogts.OmniGraphTestCase):
"""Tests node using a target connection to a prim"""
TEST_GRAPH_PATH = "/World/TestGraph"
# -----------------------------------------------------------------------------------
async def setUp(self):
await super().setUp()
omni.timeline.get_timeline_interface().set_start_time(1.0)
omni.timeline.get_timeline_interface().set_end_time(100000)
omni.timeline.get_timeline_interface().set_play_every_frame(True)
# -----------------------------------------------------------------------------------
async def tearDown(self):
omni.timeline.get_timeline_interface().stop()
omni.timeline.get_timeline_interface().set_play_every_frame(False)
await super().tearDown()
# -----------------------------------------------------------------------------------
async def test_read_prim_attribute_with_connected_prims(self):
"""
Tests that ReadPrimAttributes nodes works correctly with their prim attribute is connected
using a target attribute port
"""
node = "omni.graph.nodes.ReadPrimAttribute"
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
(graph, (read_prim, _, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ReadNode", node),
("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
],
keys.CONNECT: [("ConstToken.inputs:value", "GetPrimAtPath.inputs:path")],
keys.CREATE_PRIMS: [
("/World/Cube1", {"dummy_prop": ("float", 1)}, "Cube"),
("/World/Cube2", {"dummy_prop": ("float", 2)}, "Cube"),
],
keys.SET_VALUES: [("ReadNode.inputs:name", "dummy_prop"), ("ConstToken.inputs:value", "/World/Cube2")],
},
)
rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/ReadNode.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube1")
# evaluate the unconnected graph with the first cube set directly
await og.Controller.evaluate(graph)
self.assertEquals(1, read_prim.get_attribute("outputs:value").get())
# connect the PrimPathNode, which is set to the second cube
controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: [("GetPrimAtPath.outputs:prims", "ReadNode.inputs:prim")]})
# validate the prim attribute is read from the correct attribute
await og.Controller.evaluate(graph)
self.assertEquals(2, read_prim.get_attribute("outputs:value").get())
# -----------------------------------------------------------------------------------
async def test_read_prim_attributes_with_connected_prims(self):
"""
Tests that ReadPrimAttributes nodes works correctly with their prim attribute is connected
using a target attribute port
"""
node = "omni.graph.nodes.ReadPrimAttributes"
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, to_string), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ReadNode", node),
("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
("ToString", "omni.graph.nodes.ToString"), # the output needs to be connected
],
keys.CREATE_PRIMS: [
("/World/Cube1", "Cube"),
("/World/Cube2", "Cube"),
],
keys.CONNECT: [
("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"),
],
keys.SET_VALUES: [
("ReadNode.inputs:attrNamesToImport", "**"),
("ConstToken.inputs:value", "/World/Cube2"),
],
},
)
rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/ReadNode.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube1")
# evaluate the unconnected graph with the first cube set directly
await og.Controller.evaluate(graph)
# ReadPrimAttribute only copies values on connected values
controller.edit(
self.TEST_GRAPH_PATH, {keys.CONNECT: [("ReadNode.outputs:sourcePrimPath", "ToString.inputs:value")]}
)
# run the graph again
await og.Controller.evaluate(graph)
self.assertEquals("/World/Cube1", og.Controller.get(("outputs:converted", to_string)))
# connect the PrimPathNode, which is set to the second cube
controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: [("GetPrimAtPath.outputs:prims", "ReadNode.inputs:prim")]})
await og.Controller.evaluate(graph)
# reconnect the output (a change in prims changes the outputs)
controller.edit(
self.TEST_GRAPH_PATH, {keys.CONNECT: [("ReadNode.outputs:sourcePrimPath", "ToString.inputs:value")]}
)
await og.Controller.evaluate(graph)
# validate the prim attribute is read from the correct attribute
self.assertEquals("/World/Cube2", og.Controller.get(("outputs:converted", to_string)))
# -----------------------------------------------------------------------------------
async def _test_read_prim_node_with_connected_prims(self, node):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_read_prim, _, _, extract_node, _extract_bundle, _extract_prim), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ReadNode", node),
("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
("ExtractAttr", "omni.graph.nodes.ExtractAttribute"),
("ExtractBundle", "omni.graph.nodes.ExtractBundle"),
("ExtractPrim", "omni.graph.nodes.ExtractPrim"),
],
keys.CONNECT: [
("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"),
("ReadNode.outputs_primsBundle", "ExtractPrim.inputs:prims"),
("ExtractPrim.outputs_primBundle", "ExtractBundle.inputs:bundle"),
("ExtractBundle.outputs_passThrough", "ExtractAttr.inputs:data"),
],
keys.CREATE_PRIMS: [
("/World/Cube1", {"dummy_prop": ("float", 1)}, "Cube"),
("/World/Cube2", {"dummy_prop": ("float", 2)}, "Cube"),
],
keys.SET_VALUES: [
("ReadNode.inputs:attrNamesToImport", "dummy_prop"),
("ExtractAttr.inputs:attrName", "dummy_prop"),
("ExtractPrim.inputs:primPath", "/World/Cube1"),
("ConstToken.inputs:value", "/World/Cube2"),
],
},
)
rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/ReadNode.inputs:prims")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube1")
# evaluate the unconnected graph with the first cube set directly
await og.Controller.evaluate(graph)
self.assertEquals(1, og.Controller.get(("outputs:output", extract_node)))
# connect the PrimPathNode, which is set to the second cube
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CONNECT: [("GetPrimAtPath.outputs:prims", "ReadNode.inputs:prims")],
keys.SET_VALUES: [("ExtractPrim.inputs:primPath", "/World/Cube2")],
},
)
# validate the prim attribute is read from the correct attribute
await og.Controller.evaluate(graph)
self.assertEquals(2, og.Controller.get(("outputs:output", extract_node)))
# -----------------------------------------------------------------------------------
async def test_read_prims_with_connected_prims(self):
"""Tests that ReadPrims node can be connected at the prim port"""
await self._test_read_prim_node_with_connected_prims("omni.graph.nodes.ReadPrims")
# -----------------------------------------------------------------------------------
async def test_read_prims_bundle_with_connected_prims(self):
"""Tests that ReadPrims node can be connected at the prim port"""
await self._test_read_prim_node_with_connected_prims("omni.graph.nodes.ReadPrimsBundle")
# -----------------------------------------------------------------------------------
async def test_write_prim_attribute_with_connected_prim(self):
"""Test that WritePrimAttribute can be connected at the prim port"""
node = "omni.graph.nodes.WritePrimAttribute"
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_write_prim, _, _, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("WriteNode", node),
("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
("ConstValue", "omni.graph.nodes.ConstantFloat"),
],
keys.CONNECT: [
("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"),
("ConstValue.inputs:value", "WriteNode.inputs:value"),
],
keys.CREATE_PRIMS: [
("/World/Cube1", {"dummy_prop": ("float", 1)}, "Cube"),
("/World/Cube2", {"dummy_prop": ("float", 2)}, "Cube"),
],
keys.SET_VALUES: [
("WriteNode.inputs:name", "dummy_prop"),
("ConstToken.inputs:value", "/World/Cube2"),
("ConstValue.inputs:value", 3.0),
("WriteNode.inputs:usdWriteBack", True),
],
},
)
rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/WriteNode.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube1")
# evaluate the unconnected graph with the first cube set directly
await og.Controller.evaluate(graph)
self.assertEquals(3, stage.GetAttributeAtPath("/World/Cube1.dummy_prop").Get())
# connect the PrimPathNode, which is set to the second cube
controller.edit(
self.TEST_GRAPH_PATH, {keys.CONNECT: [("GetPrimAtPath.outputs:prims", "WriteNode.inputs:prim")]}
)
# validate the prim attribute is read from the correct attribute
await og.Controller.evaluate(graph)
self.assertEquals(3, stage.GetAttributeAtPath("/World/Cube2.dummy_prop").Get())
# --------------------------------------------------------------------------------------
async def _test_generic_with_connected_prim_setup(self, node_name, prim_input="prim", use_path="usePath"):
"""Creates a graph set with the given node, two prims (cubes) and sets the path to first prim"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
(graph, (node, _, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Node", node_name),
("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
],
keys.CONNECT: [
("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"),
],
keys.CREATE_PRIMS: [
("/World/Cube1", "Cube"),
("/World/Cube2", "Cube"),
],
keys.SET_VALUES: [
(f"Node.inputs:{use_path}", False),
("ConstToken.inputs:value", "/World/Cube2"),
],
},
)
# make sure the prims have the correct transform attributes
for prim_path in ["/World/Cube1", "/World/Cube2"]:
prim = stage.GetPrimAtPath(prim_path)
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1.0, 1.0, 1.0))
prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
)
rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Node.inputs:{prim_input}")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube1")
omni.timeline.get_timeline_interface().play()
return (controller, graph, node)
def _connect_prim_path_node(self, controller):
"""
Helper to connect the prim path node from the graph created in _test_generic_with_connected_prim_setup
"""
controller.edit(
self.TEST_GRAPH_PATH,
{
og.Controller.Keys.CONNECT: [("GetPrimAtPath.outputs:prims", "Node.inputs:prim")],
},
)
# --------------------------------------------------------------------------------------
async def _advance(self, graph, delta_time=0.01):
"""
Helper routine to wait for minimum amount of time to pass
Requires the timeline to be playing
"""
timeline = omni.timeline.get_timeline_interface()
t = timeline.get_current_time() + delta_time
await og.Controller.evaluate(graph)
while timeline.get_current_time() < t:
await omni.kit.app.get_app().next_update_async()
if not timeline.is_playing():
raise og.OmniGraphError("_advance expected the timeline to be playing")
# --------------------------------------------------------------------------------------
async def test_get_prim_direction_vector_with_connected_prim(self):
"""Test GetPrimDirectorVector works with a connected prim"""
(controller, graph, node) = await self._test_generic_with_connected_prim_setup(
"omni.graph.nodes.GetPrimDirectionVector"
)
# rotate the second cube
stage = omni.usd.get_context().get_stage()
stage.GetAttributeAtPath("/World/Cube2.xformOp:rotateXYZ").Set(Gf.Vec3d(0, 180, 0))
# evaluate the unconnected graph with the first cube set directly
await og.Controller.evaluate(graph)
self.assertListEqual([0, 0, -1], list(og.Controller.get(("outputs:forwardVector", node))))
# connect the PrimPathNode, which is set to the second cube
self._connect_prim_path_node(controller)
# connect the PrimPathNode, which is set to the second cube
# validate the prim attribute is read from the correct attribute
await og.Controller.evaluate(graph)
vec = og.Controller.get(("outputs:forwardVector", node))
self.assertAlmostEqual(0, vec[0])
self.assertAlmostEqual(0, vec[1])
self.assertAlmostEqual(1, vec[2])
# --------------------------------------------------------------------------------------
async def test_get_prim_local_to_world_with_connected_prim(self):
"""Test GetPrimLocalToWorldTransform works with a connected prim"""
(controller, graph, node) = await self._test_generic_with_connected_prim_setup(
"omni.graph.nodes.GetPrimLocalToWorldTransform"
)
# rotate the second cube
stage = omni.usd.get_context().get_stage()
stage.GetAttributeAtPath("/World/Cube2.xformOp:rotateXYZ").Set(Gf.Vec3d(0, 180, 0))
# evaluate the unconnected graph with the first cube set directly
await og.Controller.evaluate(graph)
matrix = og.Controller.get(("outputs:localToWorldTransform", node))
matrix = [round(i) for i in matrix]
self.assertListEqual([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], matrix)
# connect the PrimPathNode, which is set to the second cube
self._connect_prim_path_node(controller)
# validate the prim attribute is read from the correct attribute
await og.Controller.evaluate(graph)
matrix = og.Controller.get(("outputs:localToWorldTransform", node))
matrix = [round(i) for i in matrix]
self.assertListEqual([-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1], matrix)
# --------------------------------------------------------------------------------------
async def test_get_prim_relationship_with_connected_prim(self):
"""Test GetPrimRelationship works with a connected prim"""
(controller, graph, node) = await self._test_generic_with_connected_prim_setup(
"omni.graph.nodes.GetPrimRelationship"
)
self._connect_prim_path_node(controller)
# set up a relationship from the connected to cube
stage = omni.usd.get_context().get_stage()
stage.GetPrimAtPath("/World/Cube2").CreateRelationship("dummy_rel").AddTarget("/World/Cube1")
# mark the attribute
og.Controller.set(("inputs:name", node), "dummy_rel")
await og.Controller.evaluate(graph)
self.assertEqual(["/World/Cube1"], og.Controller.get(("outputs:paths", node)))
# --------------------------------------------------------------------------------------
async def test_move_to_target_with_connected_prim(self):
"""Test MoveToTarget works with a connected prim"""
(_controller, graph, node) = await self._test_generic_with_connected_prim_setup(
"omni.graph.nodes.MoveToTarget", "sourcePrim", "useSourcePath"
)
# connect the destination
stage = omni.usd.get_context().get_stage()
rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Node.inputs:targetPrim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube2")
stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(1, 0, 0))
stage.GetAttributeAtPath("/World/Cube2.xformOp:translate").Set(Gf.Vec3d(1000, 0, 0))
og.Controller.set(("inputs:speed", node), 0.1)
# validate the source cube is moving away from the source
last_x = 0.99 # first frame is 1
for _ in range(0, 5):
await self._advance(graph)
xform_cache = UsdGeom.XformCache()
cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1"))
x = cube1.ExtractTranslation()[0]
self.assertGreater(x, last_x)
last_x = x
# --------------------------------------------------------------------------------------
async def test_move_to_transform_with_connected_prim(self):
"""Test MoveToTransform works with a connected prim"""
(_controller, graph, node) = await self._test_generic_with_connected_prim_setup(
"omni.graph.nodes.MoveToTransform"
)
# connect the destination
stage = omni.usd.get_context().get_stage()
stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(1, 0, 0))
stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set(
Gf.Quatd(0)
)
stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:orient"]
)
og.Controller.set(("inputs:speed", node), 0.1)
og.Controller.set(("inputs:target", node), Gf.Matrix4d(1).SetTranslate(Gf.Vec3d(1000, 0, 0)))
# validate the source cube is moving away from the source
last_x = 0.99 # first frame is 1
for _ in range(0, 5):
await self._advance(graph)
xform_cache = UsdGeom.XformCache()
cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1"))
x = cube1.ExtractTranslation()[0]
self.assertGreater(x, last_x)
last_x = x
# --------------------------------------------------------------------------------------
async def test_rotate_to_target_with_connected_prim(self):
"""Test RotateToTarget works with a connected prim"""
(_controller, graph, node) = await self._test_generic_with_connected_prim_setup(
"omni.graph.nodes.RotateToTarget", "sourcePrim", "useSourcePath"
)
# connect the destination
stage = omni.usd.get_context().get_stage()
rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Node.inputs:targetPrim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube2")
quat1 = Gf.Rotation().SetIdentity().GetQuat()
quat2 = Gf.Rotation().SetAxisAngle(Gf.Vec3d.YAxis(), 180).GetQuat()
stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(0, 0, 0))
stage.GetAttributeAtPath("/World/Cube2.xformOp:translate").Set(Gf.Vec3d(0, 0, 0))
stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set(
quat1
)
stage.GetPrimAtPath("/World/Cube2").CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set(
quat2
)
stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:orient", "xformOp:scale"]
)
stage.GetPrimAtPath("/World/Cube2").CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:orient", "xformOp:scale"]
)
og.Controller.set(("inputs:speed", node), 0.02) # very slow moving
last_rot = quat2
for _ in range(0, 5):
await self._advance(graph)
xform_cache = UsdGeom.XformCache()
cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1"))
rot = cube1.ExtractRotation()
self.assertNotEqual(rot, last_rot)
last_rot = rot
# --------------------------------------------------------------------------------------
async def test_rotate_to_orientation_with_connected_prim(self):
"""Test RotateToOrientation works with a connected prim"""
(_controller, graph, node) = await self._test_generic_with_connected_prim_setup(
"omni.graph.nodes.RotateToOrientation"
)
# connect the destination
stage = omni.usd.get_context().get_stage()
quat1 = Gf.Rotation().SetIdentity().GetQuat()
stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(0, 0, 0))
stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set(
quat1
)
stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:orient", "xformOp:scale"]
)
og.Controller.set(("inputs:speed", node), 0.02) # very slow moving
og.Controller.set(("inputs:target", node), (0, 180, 0))
last_rot = Gf.Rotation().SetAxisAngle(Gf.Vec3d.YAxis(), 180).GetQuat()
for _ in range(0, 5):
await self._advance(graph)
xform_cache = UsdGeom.XformCache()
cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1"))
rot = cube1.ExtractRotation()
self.assertNotEqual(rot, last_rot)
last_rot = rot
# --------------------------------------------------------------------------------------
async def test_scale_to_size_with_connected_prim(self):
"""Test ScaleToSize works with a connected prim"""
(_controller, graph, node) = await self._test_generic_with_connected_prim_setup("omni.graph.nodes.ScaleToSize")
# connect the destination
stage = omni.usd.get_context().get_stage()
stage.GetAttributeAtPath("/World/Cube1.xformOp:scale").Set(Gf.Vec3d(1, 1, 1))
og.Controller.set(("inputs:speed", node), 0.1)
og.Controller.set(("inputs:target", node), (1000, 1000, 1000))
# validate the source cube is moving away from the source
last_x = 0.99 # first frame is 1
for _ in range(0, 5):
await self._advance(graph)
xform_cache = UsdGeom.XformCache()
cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1"))
x = cube1[0][0]
self.assertGreater(x, last_x)
last_x = x
# --------------------------------------------------------------------------------------
async def test_translate_to_target_with_connected_prim(self):
"""Test TranslateToTarget works with a connected prim"""
(_controller, graph, node) = await self._test_generic_with_connected_prim_setup(
"omni.graph.nodes.TranslateToTarget", "sourcePrim", "useSourcePath"
)
# connect the destination
stage = omni.usd.get_context().get_stage()
rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Node.inputs:targetPrim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube2")
stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(1, 0, 0))
stage.GetAttributeAtPath("/World/Cube2.xformOp:translate").Set(Gf.Vec3d(1000, 0, 0))
og.Controller.set(("inputs:speed", node), 0.1)
# validate the source cube is moving away from the source
last_x = 0.99 # first frame is 1
for _ in range(0, 5):
await self._advance(graph)
xform_cache = UsdGeom.XformCache()
cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1"))
x = cube1.ExtractTranslation()[0]
self.assertGreater(x, last_x)
last_x = x
# --------------------------------------------------------------------------------------
async def test_translate_to_location_with_connected_prim(self):
"""Test TranslateToLocation works with a connected prim"""
(_controller, graph, node) = await self._test_generic_with_connected_prim_setup(
"omni.graph.nodes.TranslateToLocation"
)
# connect the destination
stage = omni.usd.get_context().get_stage()
stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(1, 0, 0))
stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set(
Gf.Quatd(0)
)
stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:orient"]
)
og.Controller.set(("inputs:speed", node), 0.1)
og.Controller.set(("inputs:target", node), Gf.Vec3d(1000, 0, 0))
# validate the source cube is moving away from the source
last_x = 0.99 # first frame is 1
for _ in range(0, 5):
await self._advance(graph)
xform_cache = UsdGeom.XformCache()
cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1"))
x = cube1.ExtractTranslation()[0]
self.assertGreater(x, last_x)
last_x = x
| 28,915 | Python | 46.637562 | 120 | 0.565416 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_omnigraph_builtins.py | """Basic tests of the compute graph"""
from unittest import skip
import numpy
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.graph.tools as ogt
import omni.kit.stage_templates
import omni.kit.test
import omni.usd
from omni.graph.core.tests.omnigraph_test_utils import create_scope_node
from pxr import Sdf
# ======================================================================
# Set of attribute types that can have default values set
ATTR_INT = Sdf.ValueTypeNames.Int
ATTR_BOOL = Sdf.ValueTypeNames.Bool
ATTR_FLOAT = Sdf.ValueTypeNames.Float
ATTR_DOUBLE = Sdf.ValueTypeNames.Double
ATTR_INT_ARRAY = Sdf.ValueTypeNames.IntArray
ATTR_FLOAT_ARRAY = Sdf.ValueTypeNames.FloatArray
ATTR_DOUBLE_ARRAY = Sdf.ValueTypeNames.DoubleArray
ATTR_FLOAT2_ARRAY = Sdf.ValueTypeNames.Float2Array
ATTR_FLOAT3_ARRAY = Sdf.ValueTypeNames.Float3Array
ATTR_STRING = Sdf.ValueTypeNames.String
ATTR_TOKEN = Sdf.ValueTypeNames.Token
ATTR_DEFAULTS = {
ATTR_INT: 0,
ATTR_BOOL: False,
ATTR_FLOAT: 0.0,
ATTR_DOUBLE: 0.0,
ATTR_INT_ARRAY: [],
ATTR_FLOAT_ARRAY: [],
ATTR_DOUBLE_ARRAY: [],
ATTR_FLOAT2_ARRAY: [],
ATTR_FLOAT3_ARRAY: [],
ATTR_STRING: "",
ATTR_TOKEN: "",
}
# ======================================================================
def initialize_attribute(prim, attribute_name, attribute_type):
"""Set up an attribute named "attribute_name" on the given prim with a default value of the specified type"""
ogt.dbg(f" Initialize {attribute_name} with value {ATTR_DEFAULTS[attribute_type]}")
prim.CreateAttribute(attribute_name, attribute_type).Set(ATTR_DEFAULTS[attribute_type])
# ======================================================================
def float3_array_of(array_order: int):
"""
Returns an array of float3 the size of the array_order, with values equal to it
e.g. array_order(1) = [[1.0, 1.0, 1.0]]
e.g. array_order(2) = [[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]
"""
return [[float(array_order)] * 3] * array_order
# ======================================================================
def generate_results(array_order1: int, array_order2: int):
"""
Returns expected test data for the concatenate node consisting of:
- an array of float3, in a sequence of "array_order1" elements with values
(array_order1, array_order1, array_order1) followed by a similar sequence for "array_order2"
e.g. values 1 and 2 would yield:
[[1.0,1.0,1.0],[2.0,2.0,2.0],[2.0,2.0,2.0]]
"""
return float3_array_of(array_order1) + float3_array_of(array_order2)
# ======================================================================
class TestOmniGraphBuiltins(ogts.OmniGraphTestCase):
"""Run a simple unit test that exercises graph functionality"""
# ----------------------------------------------------------------------
def compare_values(self, expected_value, actual_value, error_message):
"""Generic assert comparison which uses introspection to choose the correct method to compare the data values"""
ogt.dbg(f"----Comparing {actual_value} with expected {expected_value} as '{error_message}'")
if isinstance(expected_value, (list, tuple)):
# If the numpy module is not available array values cannot be tested so silently succeed
if numpy is None:
return
# Values are returned as numpy arrays so convert the expected value and use numpy to do the comparison
numpy.testing.assert_almost_equal(
actual_value, numpy.array(expected_value), decimal=3, err_msg=error_message
)
elif isinstance(expected_value, float):
self.assertAlmostEqual(actual_value, expected_value, error_message)
else:
self.assertEqual(actual_value, expected_value, error_message)
# ----------------------------------------------------------------------
@skip("TODO: Enable when gather nodes are fully supported")
async def test_concat_node(self):
"""
Run evaluation tests on the builtin math concat node. This node has its own test because it cannot be
tested in isolation, it requires a gather node to provide a meaningful input.
"""
concat_node = "ConcatFloat3Arrays"
gather_node = "GatherFloat3Arrays"
scope_node1 = "ScopeWithArrays1"
scope_node2 = "ScopeWithArrays2"
gather_output = f"/World/{gather_node}.createdOutput"
cached_prims = {}
scene_data = {
# The concatFloat3Arrays node flattens and array of arrays of float3
"omni.graph.nodes.ConcatenateFloat3Arrays": {
"name": [concat_node],
"inputs": [["inputs:inputArrays", Sdf.ValueTypeNames.Float3Array]],
"outputs": [
["outputs:outputArray", Sdf.ValueTypeNames.Float3Array, [[-1.0, -1.0, -1.0]]],
["outputs:arraySizes", Sdf.ValueTypeNames.IntArray, [-1]],
],
},
# The gather node concatenates lists of inputs together so that a node can process them on mass
"Gather": {
"name": [gather_node],
"inputs": [],
"outputs": [["createdOutput", Sdf.ValueTypeNames.Float3Array, [[-1.0, -1.0, -1.0]]]],
},
# Generic scope nodes to supply the float3 arrays to the gather node
"Scope": {
"name": [scope_node1, scope_node2],
"inputs": [],
"outputs": [["createdOutput", Sdf.ValueTypeNames.Float3Array, [[-1.0, -1.0, -1.0]]]],
},
}
# Create a stage consisting of one of each type of node to be tested with their attributes
for node_type, node_configuration in scene_data.items():
for node_name in node_configuration["name"]:
if node_type == "Scope":
prim = create_scope_node(node_name)
else:
stage = omni.usd.get_context().get_stage()
path = omni.usd.get_stage_next_free_path(stage, "/" + node_name, True)
_ = og.GraphController.create_node(path, node_type)
prim = stage.GetPrimAtPath(path)
cached_prims[node_name] = prim
for attribute_name, attribute_type in node_configuration["inputs"]:
prim.CreateAttribute(attribute_name, attribute_type)
for attribute_name, attribute_type, _ in node_configuration["outputs"]:
prim.CreateAttribute(attribute_name, attribute_type)
# Create the connections that get gathered arrays to the concat node
cached_prims[concat_node].GetAttribute("inputs:inputArrays").AddConnection(gather_output)
cached_prims[scope_node1].GetAttribute("createdOutput").Set([[1.0, 1.0, 1.0]])
cached_prims[scope_node2].GetAttribute("createdOutput").Set([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]])
# Pairs of inputs for the create nodes to generate results (extracted from generated_results())
test_data = [[1, 1], [1, 2], [1, 3], [3, 1], [3, 3]]
await omni.kit.app.get_app().next_update_async()
graph = omni.graph.core.get_current_graph()
# Get the attributes that will be used for the computations
concat_compute = graph.get_node("/World/" + concat_node)
output_attr_array = concat_compute.get_attribute("outputs:outputArray")
output_attr_counts = concat_compute.get_attribute("outputs:arraySizes")
for test_values in test_data:
# Set the test inputs
cached_prims[scope_node1].GetAttribute("createdOutput").Set(float3_array_of(test_values[0]))
cached_prims[scope_node2].GetAttribute("createdOutput").Set(float3_array_of(test_values[1]))
# Run the compute
await omni.kit.app.get_app().next_update_async()
# Check the contents of the flattened array
expected_output = generate_results(test_values[0], test_values[1])
output_array_value = og.Controller.get(output_attr_array)
self.compare_values(
expected_output, output_array_value, "ConcatNode test - outputArray attribute value error"
)
# Check the contents of the array size counts
output_counts_value = og.Controller.get(output_attr_counts)
self.compare_values(test_values, output_counts_value, "ConcatNode test - arraySizes attribute value error")
| 8,602 | Python | 46.530386 | 120 | 0.595559 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/bundle_test_utils.py | """Collection of utilities to help with testing bundled attributes on OmniGraph nodes"""
import ast
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.graph.tools.ogn as ogn
from omni.graph.core.typing import Node_t, PrimAttrs_t
__all__ = [
"bundle_inspector_results",
"BundleInspectorResults_t",
"BundleResultKeys",
"enable_debugging",
"filter_bundle_inspector_results",
"get_bundle_with_all_results",
"prim_with_everything_definition",
"verify_bundles_are_equal",
]
# ==============================================================================================================
@dataclass
class BundleResultKeys:
"""Container for the keys used in the bundle result values and the index in the return tuple that each one uses"""
COUNT = "outputs:count"
NAME = "outputs:names"
TYPE = "outputs:types"
TYPE_IDX = 0
TUPLE_COUNT = "outputs:tupleCounts"
TUPLE_COUNT_IDX = 1
ARRAY_DEPTH = "outputs:arrayDepths"
ARRAY_DEPTH_IDX = 2
ROLE = "outputs:roles"
ROLE_IDX = 3
VALUE = "outputs:values"
VALUE_IDX = 4
# ==============================================================================================================
BundleInspectorResults_t = Tuple[int, Dict[str, Tuple[str, str, int, int, Any]]]
"""Results extracted from a bundle inspector's output attributes by NAME:VALUE. The first value is the count output.
The dictionary is a mapping of name to (type, role, arrayDepth, tupleCount, value). It's stored this way to make it
easier to guarantee ordering of the lists so that they can be easily compared.
"""
# ======================================================================
# Special value used by the bundle inspector node when the output for the bundled attribute is not yet supported
_BUNDLE_INSPECTOR_UNSUPPORTED_DATA = "__unsupported__"
# ======================================================================
def enable_debugging(bundle_inspector_node_name: Union[og.Node, str]):
"""Sets the debugging input value to true on the given omnigraph.nodes.bundleInspector
Raises:
AttributeError if the node is not a bundle inspector type
"""
graph = og.get_all_graphs()[0]
if isinstance(bundle_inspector_node_name, og.Node):
bundle_node = bundle_inspector_node_name
else:
bundle_node = graph.get_node(bundle_inspector_node_name)
print_attribute = bundle_node.get_attribute("inputs:print")
og.Controller.set(print_attribute, True)
# ======================================================================
def prim_with_everything_definition(
type_names_to_filter: Optional[List[str]] = None, filter_for_inclusion: bool = True
) -> PrimAttrs_t:
"""Generates an og.Controller prim creation specification for a prim containing one of every attribute.
The name of the attribute is derived from the type.
int -> IntAttr
int[] -> IntArrayAttr
int[3] -> Int3Attr
int[3][] -> Int3ArrayAttr
Args:
type_names_to_filter: List of type names to check for inclusion. If empty no filtering happens. The type names
should be in OGN format (e.g. "int[3][]")
filter_for_inclusion: If True then the type_names_to_filter is treated as the full list of type names to
include, otherwise it is treated as a list of types to exclude from the list of all types.
Return:
A dictionary containing a prim definition that matches what is required by og.Controller.create_prim with
all of the specified attributes defined on the prim.
"""
def __type_passes_filter(type_name: str) -> bool:
"""Returns True iff the filters allow the type_name to be included"""
# The deprecated transform type always fails the filter
if type_name.startswith("transform"):
return False
if filter_for_inclusion:
return type_names_to_filter is None or type_name in type_names_to_filter
return type_names_to_filter is None or type_name not in type_names_to_filter
definition = {}
for attribute_type_name in ogn.supported_attribute_type_names():
# Skip the types that are filtered
if not __type_passes_filter(attribute_type_name):
continue
manager = ogn.get_attribute_manager_type(attribute_type_name)
sdf_type_name = manager.sdf_type_name()
# Skip the types that don't correspond to USD types
if sdf_type_name is not None:
attribute_name = f"{sdf_type_name}Attr"
values = manager.sample_values()
definition[attribute_name] = (attribute_type_name, values[0])
return definition
# ======================================================================
def get_bundle_with_all_results(
prim_source_path: Optional[str] = None,
type_names_to_filter: Optional[List[str]] = None,
filter_for_inclusion: bool = True,
prim_source_type: Optional[str] = None,
) -> BundleInspectorResults_t:
"""Generates a dictionary of expected bundle inspector contents from a bundle constructed with a filtered list
of all attribute types.
The name of the attribute is derived from the type.
int -> IntAttr
int[] -> IntArrayAttr
int[3] -> Int3Attr
int[3][] -> Int3ArrayAttr
Args:
prim_source_path: Source of the prim from which the bundle was extracted (to correctly populate the extra
attribute the ReadPrim nodes add). If None then no prim addition is required.
type_names_to_filter: List of type names to check for inclusion. If empty no filtering happens. The type names
should be in OGN format (e.g. "int[3][]")
filter_for_inclusion: If True then the type_names_to_filter is treated as the full list of type names to
include, otherwise it is treated as a list of types to exclude from the list of all types.
prim_source_type: Type of the source prim.
Return:
A dictionary containing a BundleInspector attribute name mapped onto the value of that attribute. Only the
output attributes are considered.
"""
def __type_passes_filter(type_name: str) -> bool:
"""Returns True iff the filters allow the type_name to be included"""
# The deprecated transform type always fails the filter
if type_name.startswith("transform"):
return False
if filter_for_inclusion:
return type_names_to_filter is None or type_name in type_names_to_filter
return type_names_to_filter is None or type_name not in type_names_to_filter
# This token is hardcoded into the ReadPrimBundle node and will always be present regardless of the prim contents.
# This requires either the prim path be "TestPrim", or the value be adjusted to reflect the actual prim
per_name_results = {}
for attribute_type_name in ogn.supported_attribute_type_names():
# Skip the types that are filtered
if not __type_passes_filter(attribute_type_name):
continue
manager = ogn.get_attribute_manager_type(attribute_type_name)
sdf_type_name = manager.sdf_type_name()
# Skip the types that don't correspond to USD types
if sdf_type_name is not None:
attribute_type = og.AttributeType.type_from_ogn_type_name(attribute_type_name)
attribute_name = f"{sdf_type_name}Attr"
values = manager.sample_values()
per_name_results[attribute_name] = (
attribute_type.get_base_type_name(),
attribute_type.tuple_count,
attribute_type.array_depth,
attribute_type.get_role_name(),
values[0],
)
if prim_source_path is not None:
per_name_results.update({"sourcePrimPath": ("token", 1, 0, "none", prim_source_path)})
if prim_source_type is not None:
per_name_results.update({"sourcePrimType": ("token", 1, 0, "none", prim_source_type)})
return (len(per_name_results), per_name_results)
# ======================================================================
def bundle_inspector_results(inspector_spec: Node_t) -> BundleInspectorResults_t:
"""Returns attribute values computed from a bundle inspector in the same form as inspected_bundle_values
Args:
inspector_spec: BundleInspector node from which to extract the output values
Return:
Output values of the bundle inspector, formatted for easier comparison.
Raises:
og.OmniGraphError if anything in the inspector outputs could not be interpreted
"""
inspector_node = og.Controller.node(inspector_spec)
output = {}
for inspector_attribute in inspector_node.get_attributes():
attribute_name = inspector_attribute.get_name()
if inspector_attribute.get_port_type() != og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT:
continue
if inspector_attribute.get_type_name() == "bundle":
continue
values = og.Controller.get(inspector_attribute)
if inspector_attribute.get_name().endswith("values"):
# Bundled values are formatted as strings but are actually a mixture of types
values = [
ast.literal_eval(value)
if value != _BUNDLE_INSPECTOR_UNSUPPORTED_DATA
else _BUNDLE_INSPECTOR_UNSUPPORTED_DATA
for value in values
]
output[attribute_name] = values
# Catch the case of an empty bundle separately
if not output:
return (0, {})
try:
count = output[BundleResultKeys.COUNT]
per_name_values = {
name: (v1, v2, v3, v4, v5)
for name, v1, v2, v3, v4, v5 in zip(
output[BundleResultKeys.NAME],
output[BundleResultKeys.TYPE],
output[BundleResultKeys.TUPLE_COUNT],
output[BundleResultKeys.ARRAY_DEPTH],
output[BundleResultKeys.ROLE],
output[BundleResultKeys.VALUE],
)
}
except Exception as error:
raise og.OmniGraphError(error)
return (count, per_name_values)
# ==============================================================================================================
def verify_bundles_are_equal(
actual_values: BundleInspectorResults_t, expected_values: BundleInspectorResults_t, check_values: bool = True
):
"""Check that the contents of the actual values received from a bundle inspector match the expected values.
Args:
actual_values: Bundle contents read from the graph
expected_values: Test bundle contents expected
check_values: If True then check that attribute values as well as the type information, otherwise just types
Raises:
ValueError: if the contents differ. The message in the exception explains how they differ
"""
(actual_count, actual_results) = actual_values
(expected_count, expected_results) = expected_values
def __compare_attributes(attribute_name: str):
"""Compare a single attribute's result from the bundle inspected, raising ValueError if not equal"""
actual_value = actual_results[attribute_name]
expected_value = expected_results[attribute_name]
try:
if actual_value[0] != expected_value[0]:
raise ValueError("Type mismatch")
if actual_value[1] != expected_value[1]:
raise ValueError("Tuple count mismatch")
if actual_value[2] != expected_value[2]:
raise ValueError("Array depth mismatch")
if actual_value[3] != expected_value[3]:
raise ValueError("Role mismatch")
if check_values:
ogts.verify_values(actual_value[4], expected_value[4], "Value mismatch")
except ValueError as error:
raise ValueError(
f"Actual value for '{attribute_name}' of '{actual_value}' did not match expected value"
f" of '{expected_value}'"
) from error
actual_names = set(actual_results.keys())
expected_names = set(expected_results.keys())
name_difference = actual_names.symmetric_difference(expected_names)
if name_difference:
problems = []
extra_actual_results = actual_names.difference(expected_names)
if extra_actual_results:
problems.append(f"Actual members {extra_actual_results} not expected.")
extra_expected_results = expected_names.difference(actual_names)
if extra_expected_results:
problems.append(f"Expected members {extra_expected_results} not found.")
problem = "\n".join(problems)
raise ValueError(f"Actual output attribute names differ from expected list: {problem}")
if actual_count != expected_count:
raise ValueError(f"Expected {expected_count} results, actual value was {actual_count}")
for output_attribute_name in actual_results.keys():
__compare_attributes(output_attribute_name)
# ==============================================================================================================
def filter_bundle_inspector_results(
raw_results: BundleInspectorResults_t,
names_to_filter: Optional[List[str]] = None,
filter_for_inclusion: bool = True,
) -> BundleInspectorResults_t:
"""Filter out the results retrieved from a bundle inspector by name
Args:
names_to_filter: List of attribute names to check for inclusion.
filter_for_inclusion: If True then the names_to_filter is treated as the full list of names to include,
otherwise it is treated as a list of names to exclude from the list of all names.
Return:
The raw_results with the above filtering performed
"""
def __type_passes_filter(name: str) -> bool:
"""Returns True iff the filters allow the name to be included"""
if filter_for_inclusion:
return names_to_filter is None or name in names_to_filter
return names_to_filter is None or name not in names_to_filter
(_, results) = raw_results
filtered_results = {}
for attribute_name, attribute_values in results.items():
if __type_passes_filter(attribute_name):
filtered_results[attribute_name] = attribute_values
return (len(filtered_results), filtered_results)
| 14,643 | Python | 43.108434 | 120 | 0.623096 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_bundles.py | import omni.graph.core as ogc
import omni.kit.test
class TestNodeInputAndOutputBundles(ogc.tests.OmniGraphTestCase):
"""Test to validate access to input/output bundles"""
TEST_GRAPH_PATH = "/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
self.graph = ogc.Controller.create_graph(self.TEST_GRAPH_PATH)
self.context = self.graph.get_default_graph_context()
self.prim_cube = ogc.Controller.create_prim("/cube", {}, "Cube")
(self.graph, [self.read_prim, self.extract_prim, self.extract_bundle], _, _,) = ogc.Controller.edit(
self.TEST_GRAPH_PATH,
{
ogc.Controller.Keys.CREATE_NODES: [
("read_prims", "omni.graph.nodes.ReadPrims"),
("extract_prim", "omni.graph.nodes.ExtractPrim"),
("extract_bundle", "omni.graph.nodes.ExtractBundle"),
],
ogc.Controller.Keys.CONNECT: [
("read_prims.outputs_primsBundle", "extract_prim.inputs:prims"),
("extract_prim.outputs_primBundle", "extract_bundle.inputs:bundle"),
],
ogc.Controller.Keys.SET_VALUES: [
("extract_prim.inputs:primPath", str(self.prim_cube.GetPath())),
],
},
)
stage = omni.usd.get_context().get_stage()
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(self.TEST_GRAPH_PATH + "/read_prims.inputs:prims"),
target=self.prim_cube.GetPath(),
)
async def test_pass_through_output(self):
"""Test if data from pass through output is accessible through bundles"""
await ogc.Controller.evaluate(self.graph)
factory = ogc.IBundleFactory.create()
# Accessing bundle through get_output_bundle constructs IBundle interface
output_bundle = self.context.get_output_bundle(self.extract_bundle, "outputs_passThrough")
output_bundle2 = factory.get_bundle(self.context, output_bundle)
self.assertTrue(output_bundle2.valid)
self.assertTrue(output_bundle2.get_attribute_by_name("extent").is_valid())
| 2,294 | Python | 39.982142 | 108 | 0.607236 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_read_prims_hierarchy.py | import numpy as np
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
from pxr import Gf, Sdf, Usd, UsdGeom
class TestReadPrimsHierarchy(ogts.OmniGraphTestCase):
"""Unit tests for hierarchical behavior of the ReadPrimsV2 node in this extension"""
async def test_read_prims_hierarchy_permutations(self):
# We build a hierarchy, 4 levels deep.
# Then we track each possible pair of prims in the hierarchy,
# mutate every prim in the hierarchy (scaling),
# and check if the pair USD and bundle world matrices and bounding boxes match.
# TODO: Find out why this runs so slow!
# Originally we ran 3 tests, optionally enabling matrix and/or bounds
# But since the test runs so slowly, we only have one now.
# The incremental tests will test the options anyway.
# We keep these variables to selectively disable either one for debugging.
compute_world_matrix = True
compute_bounding_box = True
usd_context = omni.usd.get_context()
stage: Usd.Stage = usd_context.get_stage()
test_graph_path = "/World/TestGraph"
# Define the compute graph
controller = og.Controller()
keys = og.Controller.Keys
(graph, [read_prims_node], _, _) = controller.edit(
test_graph_path,
{
keys.CREATE_NODES: [
("Read", "omni.graph.nodes.ReadPrimsV2"),
],
keys.SET_VALUES: [
("Read.inputs:enableChangeTracking", True),
# TODO: Re-enable when OgnReadPrimsV2 gets computeWorldMatrix
# ("Read.inputs:computeWorldMatrix", compute_world_matrix),
("Read.inputs:computeBoundingBox", compute_bounding_box),
],
},
)
debug_stamp = 0
debug_stamp_attribute = read_prims_node.get_attribute("inputs:_debugStamp")
init_scale = Gf.Vec3f(0.5, 0.5, 0.5)
test_scale = Gf.Vec3f(1.5, 1.5, 1.5)
default_time = Usd.TimeCode.Default()
# Defines 2 trees with 2 branches and 2 leaves (as spheres),
# return the prim paths of all the nodes.
# Optionally just define nodes that have the given prefix;
# this is used to restore the hierarchy after deleting a subtree
def define_hierarchies(prefix=None):
tree_prims = []
def add_prim(prim, x, y, z):
tree_prims.append(prim)
api = UsdGeom.XformCommonAPI(prim)
api.SetTranslate(Gf.Vec3d(x, y, z))
# We set the scale of each node to 0.5 instead of 1,
# so that deleting the scale attribute (which resets the scale to 1)
# is detected as a matrix and bounds change
api.SetScale(init_scale)
for tree_index in range(2):
tree_path = f"/Tree{tree_index}"
if prefix is None or Sdf.Path(tree_path).HasPrefix(prefix):
tree_prim = UsdGeom.Xform.Define(stage, tree_path)
add_prim(tree_prim, (tree_index - 0.5) * 20, 0, 0)
for branch_index in range(2):
branch_path = f"{tree_path}/Branch{branch_index}"
if prefix is None or Sdf.Path(branch_path).HasPrefix(prefix):
branch_prim = UsdGeom.Xform.Define(stage, branch_path)
add_prim(branch_prim, 0, 10, 0)
for leaf_index in range(2):
leaf_path = f"{branch_path}/Leaf{leaf_index}"
if prefix is None or Sdf.Path(leaf_path).HasPrefix(prefix):
leaf_prim = UsdGeom.Sphere.Define(stage, leaf_path)
# The leaves are positioned in a diamond shape,
# so that deleting any leaf influences that ancestor bounds
if branch_index == 0:
add_prim(leaf_prim, (leaf_index - 0.5) * 5, 10, 0)
else:
add_prim(leaf_prim, 0, 10, (leaf_index - 0.5) * 5)
return [p.GetPath() for p in tree_prims]
def get_usd_matrix_bounds_pair(prim_path):
xformable = UsdGeom.Xformable(stage.GetPrimAtPath(prim_path))
self.assertTrue(xformable is not None)
world_matrix = xformable.ComputeLocalToWorldTransform(default_time)
local_bounds = xformable.ComputeLocalBound(default_time, UsdGeom.Tokens.default_, UsdGeom.Tokens.proxy)
return (world_matrix, local_bounds)
tree_prim_paths = define_hierarchies()
# For debugging test failures, tweak the two variable below (should be lists of Sdf.Path)
track_prim_paths = tree_prim_paths
change_prim_paths = tree_prim_paths
# The original matrix and bound pairs, before changes
usd_matrix_bounds_originals = {path: get_usd_matrix_bounds_pair(path) for path in tree_prim_paths}
async def check_bundles(changed_prim, tracked_paths, debug_stamp):
changed_path = changed_prim.GetPath()
controller.set(debug_stamp_attribute, debug_stamp)
await controller.evaluate()
graph_context = graph.get_default_graph_context()
container = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle")
self.assertTrue(container.valid)
child_bundles = container.get_child_bundles()
self.assertEqual(len(child_bundles), len(tracked_paths))
for bundle in child_bundles:
stamp_attr = bundle.get_attribute_by_name("_debugStamp")
source_prim_path_attr = bundle.get_attribute_by_name("sourcePrimPath")
self.assertTrue(source_prim_path_attr.is_valid())
source_prim_path = Sdf.Path(source_prim_path_attr.get())
self.assertTrue(
source_prim_path in tracked_paths,
f"{source_prim_path} not in {tracked_paths}!",
)
source_self_changed = source_prim_path == changed_path
source_ancestor_changed = source_prim_path.HasPrefix(changed_path)
source_descendant_changed = changed_path.HasPrefix(source_prim_path)
(
usd_world_matrix_before_change,
usd_local_bounds_before_change,
) = usd_matrix_bounds_originals[source_prim_path]
(
usd_world_matrix_after_change,
usd_local_bounds_after_change,
) = get_usd_matrix_bounds_pair(source_prim_path)
usd_world_matrix_changed = usd_world_matrix_before_change != usd_world_matrix_after_change
usd_local_bounds_changed = usd_local_bounds_before_change != usd_local_bounds_after_change
# If the source is geometry (not an xform),
# then changes to the ancestors will
# NOT cause a change to the local bound
source_prim = stage.GetPrimAtPath(source_prim_path)
self.assertTrue(source_prim.IsValid())
ancestor_changed_local_bound = source_ancestor_changed and source_prim.IsA(UsdGeom.Xform)
# The logic below breaks for structural stage changes,
# which is disabled by passing 0 for debug_stamp.
if debug_stamp > 0:
# We add some tests to verify this complicated unit test itself
self.assertEqual(
usd_world_matrix_changed,
source_self_changed or source_ancestor_changed,
f"{source_prim_path} => expected world matrix change",
)
self.assertEqual(
usd_local_bounds_changed,
source_self_changed or source_descendant_changed or ancestor_changed_local_bound,
f"{source_prim_path} => expected local bounds change",
)
expected_stamp = None
world_matrix_attr = bundle.get_attribute_by_name("worldMatrix")
if compute_world_matrix:
# Compare world matrix in USD and bundle
self.assertTrue(
world_matrix_attr.is_valid(),
f"Bundle for {source_prim_path} is missing worldMatrix",
)
bundle_world_matrix = np.array(world_matrix_attr.get())
stage_world_matrix = np.array(usd_world_matrix_after_change).flatten()
np.testing.assert_array_equal(
stage_world_matrix,
bundle_world_matrix,
f"{source_prim_path} worldMatrix mismatch",
)
if debug_stamp > 0:
# Check how the world matrix was changed
if source_self_changed:
expected_stamp = debug_stamp
elif source_ancestor_changed:
expected_stamp = debug_stamp + 10000000
else:
self.assertFalse(
world_matrix_attr.is_valid(),
f"Bundle for {source_prim_path} should not contain worldMatrix",
)
bbox_transform_attr = bundle.get_attribute_by_name("bboxTransform")
bbox_min_corner_attr = bundle.get_attribute_by_name("bboxMinCorner")
bbox_max_corner_attr = bundle.get_attribute_by_name("bboxMaxCorner")
if compute_bounding_box:
# Compare local bound in USD and bundle
self.assertTrue(
bbox_transform_attr.is_valid(),
f"Bundle for {source_prim_path} is missing bboxTransform",
)
self.assertTrue(
bbox_min_corner_attr.is_valid(),
f"Bundle for {source_prim_path} is missing bboxMinCorner",
)
self.assertTrue(
bbox_max_corner_attr.is_valid(),
f"Bundle for {source_prim_path} is missing bboxMaxCorner",
)
bundle_bbox_transform = np.array(bbox_transform_attr.get())
bundle_bbox_min_corner = np.array(bbox_min_corner_attr.get())
bundle_bbox_max_corner = np.array(bbox_max_corner_attr.get())
stage_bbox = usd_local_bounds_after_change.GetBox()
stage_bbox_transform = np.array(usd_local_bounds_after_change.GetMatrix()).flatten()
stage_bbox_min_corner = np.array(stage_bbox.GetMin())
stage_bbox_max_corner = np.array(stage_bbox.GetMax())
np.testing.assert_array_equal(
stage_bbox_transform,
bundle_bbox_transform,
f"{source_prim_path} bbox_transform mismatch",
)
np.testing.assert_array_equal(
stage_bbox_min_corner,
bundle_bbox_min_corner,
f"{source_prim_path} bbox_min_corner mismatch",
)
np.testing.assert_array_equal(
stage_bbox_max_corner,
bundle_bbox_max_corner,
f"{source_prim_path} bbox_max_corner mismatch",
)
if debug_stamp > 0:
# Check how the local bounds were changed
if source_self_changed:
expected_stamp = debug_stamp
elif source_descendant_changed:
expected_stamp = debug_stamp + 1000000
elif ancestor_changed_local_bound:
expected_stamp = debug_stamp + 10000000
else:
self.assertFalse(
bbox_transform_attr.is_valid(),
f"Bundle for {source_prim_path} should not contain bboxTransform",
)
self.assertFalse(
bbox_min_corner_attr.is_valid(),
f"Bundle for {source_prim_path} should not contain bboxMinCorner",
)
self.assertFalse(
bbox_max_corner_attr.is_valid(),
f"Bundle for {source_prim_path} should not contain bboxMaxCorner",
)
if debug_stamp > 0:
# Check the debug stamp
actual_stamp = stamp_attr.get() if stamp_attr.is_valid() else 0
if expected_stamp is None:
self.assertNotEqual(
actual_stamp % 1000000,
debug_stamp,
f"{source_prim_path} shouldn't be stamped in this update!",
)
else:
self.assertEqual(
actual_stamp,
expected_stamp,
f"{source_prim_path} had a wrong stamp!",
)
async def run_sub_tests(i, j, debug_stamp):
# Track these two prims
tracked_pair_paths = [track_prim_paths[i], track_prim_paths[j]]
omni.kit.commands.execute(
"SetRelationshipTargets",
relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"),
targets=tracked_pair_paths,
)
# We expect a full evaluation here, since we changed the input prims
# We don't check that in this test that relates to hierarchy only
await controller.evaluate()
# Visit all prims in the hierarchy,
# scale them, checking the bundle against the USD data (attr change test)
# Then delete the scale attribute, and check again (attr resync remove test)
# Then re-create the scale attribute, and check again (attr resync create test)
# Then delete the prim (and subtree), and check again (prim resync remove test)
# Then re-create the subtree, and check again (prim resync create test)
for prim_path in change_prim_paths:
prim = stage.GetPrimAtPath(prim_path)
title = f"change_prim_paths={[prim_path]}, track_prim_paths={tracked_pair_paths}, debug_stamp={debug_stamp}..."
with self.subTest(f"Change scale attr, {title}"):
# Change the scale
UsdGeom.XformCommonAPI(prim).SetScale(test_scale)
# Check that the change is picked up
debug_stamp += 1
await check_bundles(prim, tracked_pair_paths, debug_stamp)
with self.subTest(f"Delete scale attr, {title}"):
# Delete the scale property.
# This should reset it back to one.
prim.RemoveProperty("xformOp:scale")
# Check that the change is picked up
debug_stamp += 1
await check_bundles(prim, tracked_pair_paths, debug_stamp)
with self.subTest(f"Create scale attr, {title}"):
# Create the scale property back, and change it.
prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3, False).Set(test_scale)
# Check that the change is picked up
debug_stamp += 1
await check_bundles(prim, tracked_pair_paths, debug_stamp)
with self.subTest(f"Delete prim, {title}"):
stage.RemovePrim(prim_path)
# The deleted prim might be a tracked one
valid_tracked_pair_paths = [
path for path in tracked_pair_paths if stage.GetPrimAtPath(path).IsValid()
]
# Check that the change is picked up
debug_stamp += 1
# NOTE: If the deleted prim was a tracked prim,
# the ReadPrimsV2 node will currently do a full update
await check_bundles(
prim,
valid_tracked_pair_paths,
debug_stamp if len(valid_tracked_pair_paths) == 2 else 0,
)
with self.subTest(f"Create prim, {title}"):
# Restore deleted sub-tree (and reset scale)
define_hierarchies(prim_path)
# Check that the change is picked up (wo stamp checking for now)
# TODO: We should also do stamp checking here, but couldn't get that working yet.
await check_bundles(prim, tracked_pair_paths, 0)
return debug_stamp
# Iterate over all possible pairs of tree prims
for i in range(len(track_prim_paths) - 1):
for j in range(i + 1, len(track_prim_paths)):
debug_stamp = await run_sub_tests(i, j, debug_stamp)
| 17,673 | Python | 46.005319 | 127 | 0.529056 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_bundle_attribute_nodes.py | """Basic tests of the bundled attribute nodes"""
import numpy
import omni.graph.core as og
import omni.graph.core.tests as ogts
# ======================================================================
class TestBundleAttributeNodes(ogts.OmniGraphTestCase):
"""Run a simple unit test that exercises graph functionality"""
# ----------------------------------------------------------------------
def compare_values(self, expected_value, actual_value, decimal, error_message):
"""Generic assert comparison which uses introspection to choose the correct method to compare the data values"""
# dbg(f"----Comparing {actual_value} with expected {expected_value}")
if isinstance(expected_value, (list, tuple)):
# If the numpy module is not available array values cannot be tested so silently succeed
if numpy is None:
return
# Values are returned as numpy arrays so convert the expected value and use numpy to do the comparison
numpy.testing.assert_almost_equal(
actual_value, numpy.array(expected_value), decimal=decimal, err_msg=error_message
)
elif isinstance(expected_value, float):
self.assertAlmostEqual(actual_value, expected_value, decimal, error_message)
else:
self.assertEqual(actual_value, expected_value, error_message)
# ----------------------------------------------------------------------
async def test_bundle_functions(self):
"""Test bundle functions"""
await ogts.load_test_file("TestBundleAttributeNodes.usda", use_caller_subdirectory=True)
# These prims are known to be in the file
bundle_prim = "/defaultPrim/inputData"
# However since we no longer spawn OgnPrim for bundle-connected prims, we don't expect it to be
# in OG. (Verified in a different test)
# self.assertEqual([], ogts.verify_node_existence([bundle_prim]))
contexts = og.get_compute_graph_contexts()
self.assertIsNotNone(contexts)
expected_values = {
"boolAttr": (1, ("bool", og.BaseDataType.BOOL, 1, 0, og.AttributeRole.NONE)),
"intAttr": (1, ("int", og.BaseDataType.INT, 1, 0, og.AttributeRole.NONE)),
"int64Attr": (1, ("int64", og.BaseDataType.INT64, 1, 0, og.AttributeRole.NONE)),
"uint64Attr": (1, ("uint64", og.BaseDataType.UINT64, 1, 0, og.AttributeRole.NONE)),
"halfAttr": (1, ("half", og.BaseDataType.HALF, 1, 0, og.AttributeRole.NONE)),
"floatAttr": (1, ("float", og.BaseDataType.FLOAT, 1, 0, og.AttributeRole.NONE)),
"doubleAttr": (1, ("double", og.BaseDataType.DOUBLE, 1, 0, og.AttributeRole.NONE)),
"tokenAttr": (1, ("token", og.BaseDataType.TOKEN, 1, 0, og.AttributeRole.NONE)),
"stringAttr": (10, ("string", og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.TEXT)),
# We don't read relationship attributes in OgnReadPrimBundle
# "relSingleAttr": (1, ("rel", og.BaseDataType.RELATIONSHIP, 1, 0, og.AttributeRole.NONE)),
"int2Attr": (1, ("int[2]", og.BaseDataType.INT, 2, 0, og.AttributeRole.NONE)),
"half2Attr": (1, ("half[2]", og.BaseDataType.HALF, 2, 0, og.AttributeRole.NONE)),
"float2Attr": (1, ("float[2]", og.BaseDataType.FLOAT, 2, 0, og.AttributeRole.NONE)),
"double2Attr": (1, ("double[2]", og.BaseDataType.DOUBLE, 2, 0, og.AttributeRole.NONE)),
"int3Attr": (1, ("int[3]", og.BaseDataType.INT, 3, 0, og.AttributeRole.NONE)),
"half3Attr": (1, ("half[3]", og.BaseDataType.HALF, 3, 0, og.AttributeRole.NONE)),
"float3Attr": (1, ("float[3]", og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.NONE)),
"double3Attr": (1, ("double[3]", og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.NONE)),
"int4Attr": (1, ("int[4]", og.BaseDataType.INT, 4, 0, og.AttributeRole.NONE)),
"half4Attr": (1, ("half[4]", og.BaseDataType.HALF, 4, 0, og.AttributeRole.NONE)),
"float4Attr": (1, ("float[4]", og.BaseDataType.FLOAT, 4, 0, og.AttributeRole.NONE)),
"double4Attr": (1, ("double[4]", og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.NONE)),
"boolArrayAttr": (65, ("bool[]", og.BaseDataType.BOOL, 1, 1, og.AttributeRole.NONE)),
"intArrayAttr": (5, ("int[]", og.BaseDataType.INT, 1, 1, og.AttributeRole.NONE)),
"floatArrayAttr": (5, ("float[]", og.BaseDataType.FLOAT, 1, 1, og.AttributeRole.NONE)),
"doubleArrayAttr": (5, ("double[]", og.BaseDataType.DOUBLE, 1, 1, og.AttributeRole.NONE)),
"tokenArrayAttr": (3, ("token[]", og.BaseDataType.TOKEN, 1, 1, og.AttributeRole.NONE)),
"int2ArrayAttr": (5, ("int[2][]", og.BaseDataType.INT, 2, 1, og.AttributeRole.NONE)),
"float2ArrayAttr": (5, ("float[2][]", og.BaseDataType.FLOAT, 2, 1, og.AttributeRole.NONE)),
"double2ArrayAttr": (5, ("double[2][]", og.BaseDataType.DOUBLE, 2, 1, og.AttributeRole.NONE)),
"point3fArrayAttr": (3, ("pointf[3][]", og.BaseDataType.FLOAT, 3, 1, og.AttributeRole.POSITION)),
"qhAttr": (1, ("quath[4]", og.BaseDataType.HALF, 4, 0, og.AttributeRole.QUATERNION)),
"qfAttr": (1, ("quatf[4]", og.BaseDataType.FLOAT, 4, 0, og.AttributeRole.QUATERNION)),
"qdAttr": (1, ("quatd[4]", og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.QUATERNION)),
"m2dAttr": (1, ("matrixd[2]", og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.MATRIX)),
"m3dAttr": (1, ("matrixd[3]", og.BaseDataType.DOUBLE, 9, 0, og.AttributeRole.MATRIX)),
"m4dAttr": (1, ("matrixd[4]", og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.MATRIX)),
}
for context in contexts:
bundle = context.get_bundle(bundle_prim)
attr_names, attr_types = bundle.get_attribute_names_and_types()
attr_count = bundle.get_attribute_data_count()
self.assertEqual(attr_count, len(expected_values))
attr_names, attr_types = bundle.get_attribute_names_and_types()
self.assertCountEqual(attr_names, list(expected_values.keys()))
# The name map has to be created because the output bundle contents are not in a defined order but the
# different array elements do correspond to each other. By creating a mapping from the name to the index
# at which it was found the other elements can be mapped exactly.
expected_types = [expected_values[name][1] for name in attr_names]
expected_counts = [expected_values[name][0] for name in attr_names]
type_name_and_properties = []
new_constructed_types = []
for attr_type in attr_types:
base_type = attr_type.base_type
tuple_count = attr_type.tuple_count
array_depth = attr_type.array_depth
role = attr_type.role
type_name_and_properties.append(
(attr_type.get_ogn_type_name(), base_type, tuple_count, array_depth, role)
)
new_constructed_types.append(og.Type(base_type, tuple_count, array_depth, role))
self.assertCountEqual(type_name_and_properties, expected_types)
self.assertEqual(new_constructed_types, attr_types)
attrs = bundle.get_attribute_data()
attr_elem_counts = []
for attr in attrs:
try:
elem_count = og.Controller.get_array_size(attr)
except AttributeError:
elem_count = 1
attr_elem_counts.append(elem_count)
self.assertEqual(attr_elem_counts, expected_counts)
| 7,784 | Python | 62.292682 | 120 | 0.594938 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_settings_removal.py | """Suite of tests to exercise the implications of the removal of various settings."""
from typing import Any, Dict, List
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from pxr import Gf, OmniGraphSchema
KEYS = og.Controller.Keys
"""Shorten keyword names"""
FILE_FORMAT_VERSION_INTRODUCING_SCHEMAS = Gf.Vec2i(1, 4)
"""File format version where the schema prims became the default"""
CURRENT_FORMAT_VERSION = Gf.Vec2i(1, 7)
"""The current version of settings"""
# ==============================================================================================================
def _verify_stage_contents(expected_contents: Dict[str, str], expected_inactive_prims: List[str] = None) -> List[str]:
"""Confirm that a stage contains the hierarchical prim type structure passed in.
Args:
expected_contents: Dictionary of primPath:primType of stage contents that were expected.
e.g. a two level prim hierarchy with an Xform and a Mesh would be passd in as
{"/MyXform": "Xform", "/MyXform/MyMesh": "Mesh"}
expected_inactive_prims: A list of keys to the above whose prims are also expected to be inactive
Returns:
A list of a description of the differences found (may not be complete), or [] if all was as expected
"""
stage = omni.usd.get_context().get_stage()
if stage is None:
return [] if not expected_contents else [f"Stage is empty but expected to find {expected_contents}"]
# Copy of the dictionary to removed found prims from that should be empty when done
inactive_list = expected_inactive_prims or []
not_found = expected_contents.copy()
errors_found = []
iterator = iter(stage.TraverseAll())
for prim in iterator:
prim_path = str(prim.GetPrimPath())
prim_type = prim.GetTypeName()
# Ignore these boilerplate prims
if prim_path.startswith("/Omniverse") or prim_path.startswith("/Render"):
continue
if prim_path not in expected_contents:
errors_found.append(
f"Prim '{prim_path}' of type '{prim_type}' was not in the expected list {expected_contents}"
)
continue
if expected_contents[prim_path] != prim_type:
errors_found.append(
f"Prim '{prim_path}' expected to be of type '{expected_contents[prim_path]}' but was '{prim_type}'"
)
continue
if prim_path in inactive_list and prim.IsActive():
errors_found.append(f"Prim '{prim_path}' of type '{prim_type}' expected to be inactive but was not")
if prim.GetTypeName() == "OmniGraphNode":
# Confirm that the expected schema attributes exist on the node as non-custom types
node_prim = OmniGraphSchema.OmniGraphNode(prim)
if not node_prim:
errors_found.append(f"Prim '{prim_path}' could not be interpreted as OmniGraphNode")
else:
type_attr = node_prim.GetNodeTypeAttr()
if not type_attr.IsValid() or type_attr.IsCustom():
errors_found.append(f"Node '{prim_path}' did not have schema attribute node:type")
version_attr = node_prim.GetNodeTypeVersionAttr()
if not version_attr.IsValid() or version_attr.IsCustom():
errors_found.append(f"Node '{prim_path}' did not have schema attribute node:typeVersion")
elif prim.GetTypeName() == "OmniGraph":
# Confirm that the expected schema attributes exist on the graph as non-custom types
graph_prim = OmniGraphSchema.OmniGraph(prim)
if not graph_prim:
errors_found.append(f"Prim '{prim_path}' could not be interpreted as OmniGraph")
else:
evaluator_attr = graph_prim.GetEvaluatorTypeAttr()
if not evaluator_attr.IsValid() or evaluator_attr.IsCustom():
errors_found.append(f"Graph '{prim_path}' did not have schema attribute evaluatorType")
version_attr = graph_prim.GetFileFormatVersionAttr()
if not version_attr.IsValid() or version_attr.IsCustom():
errors_found.append(f"Graph '{prim_path}' did not have schema attribute fileFormatVersion")
backing_attr = graph_prim.GetFabricCacheBackingAttr()
if not backing_attr.IsValid() or backing_attr.IsCustom():
errors_found.append(f"Graph '{prim_path}' did not have schema attribute fabricCacheBacking")
pipeline_attr = graph_prim.GetPipelineStageAttr()
if not pipeline_attr.IsValid() or pipeline_attr.IsCustom():
errors_found.append(f"Graph '{prim_path}' did not have schema attribute pipelineStage")
evaluation_mode_attr = graph_prim.GetEvaluationModeAttr()
if not evaluation_mode_attr.IsValid() or evaluation_mode_attr.IsCustom():
errors_found.append(f"Graph '{prim_path}' did not have schema attribute evaluationMode")
del not_found[prim_path]
for prim_path, prim_type in not_found.items():
errors_found.append(f"Prim '{prim_path}' of type '{prim_type}' was expected but not found")
return errors_found
# ==============================================================================================================
def _verify_graph_settings(graph_prim_path: str, expected_settings: Dict[str, Any]):
"""Verify that the graph prim has the expected settings (after conversion or loading of a new file)
Args:
graph_prim_path: Path to the graph's prim
expected_settings: Dictionary of attributeName:expectedValue for all of the settings
Returns:
List of descriptions of the differences found or [] if all was as expected
"""
errors_found = []
stage = omni.usd.get_context().get_stage()
graph_prim = stage.GetPrimAtPath(graph_prim_path) if stage is not None else None
if graph_prim is None:
return [f"Could not find prim `{graph_prim_path}` that is supposed to hold the settings"]
for attribute_name, expected_value in expected_settings.items():
attribute = graph_prim.GetAttribute(attribute_name)
if not attribute.IsValid():
errors_found.append(f"Could not find setting attribute '{attribute_name}' on prim '{graph_prim_path}'")
else:
actual_value = attribute.Get()
if actual_value != expected_value:
errors_found.append(
f"Expected value of setting '{attribute_name}' was '{expected_value}', got '{actual_value}'"
)
return errors_found
# ==============================================================================================================
class TestSettingsRemoval(ogts.OmniGraphTestCase):
"""Wrapper for tests to verify backward compatibility for the removal of the settings prim"""
# Settings values when nothing is specified.
DEFAULT_SETTINGS = {
"evaluator:type": "push",
"fileFormatVersion": CURRENT_FORMAT_VERSION,
"fabricCacheBacking": "Shared",
"pipelineStage": "pipelineStageSimulation",
"evaluationMode": "Automatic",
}
# ----------------------------------------------------------------------
async def test_create_graph(self):
"""Test creation of a simple graph"""
og.Controller.edit("/SimpleGraph", {KEYS.CREATE_NODES: ("NoOp", "omni.graph.nodes.Noop")})
await og.Controller.evaluate()
results = _verify_stage_contents({"/SimpleGraph": "OmniGraph", "/SimpleGraph/NoOp": "OmniGraphNode"})
self.assertEqual([], results)
results = _verify_graph_settings("/SimpleGraph", self.DEFAULT_SETTINGS)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_no_settings_1_1(self):
"""Test that a v1.1 file with a graph and no settings is converted correctly"""
(result, error) = await ogts.load_test_file("SettingsMissingFromGraph_v1_1.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/defaultGraph": "OmniGraph",
}
)
self.assertEqual([], results)
results = _verify_graph_settings("/defaultGraph", self.DEFAULT_SETTINGS)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_no_settings_post_schema(self):
"""Test that an updated file without explicit settings has the default values"""
(result, error) = await ogts.load_test_file(
"SettingsMissingFromGraph_postSchema.usda", use_caller_subdirectory=True
)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/defaultGraph": "OmniGraph",
}
)
self.assertEqual([], results)
results = _verify_graph_settings("/defaultGraph", self.DEFAULT_SETTINGS)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_no_graph_1_0(self):
"""Test that a v1.0 file that has settings data without FC and pipeline settings is converted correctly"""
(result, error) = await ogts.load_test_file("SettingsWithoutGraph_v1_0.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/__graphUsingSchemas": "OmniGraph",
"/__graphUsingSchemas/NoOp": "OmniGraphNode",
"/__graphUsingSchemas/computegraphSettings": "ComputeGraphSettings",
},
["/__graphUsingSchemas/computegraphSettings"],
)
self.assertEqual([], results)
results = _verify_graph_settings(
"/__graphUsingSchemas",
{
"evaluator:type": "push",
"fileFormatVersion": CURRENT_FORMAT_VERSION,
"fabricCacheBacking": "Shared",
"pipelineStage": "pipelineStageSimulation",
"evaluationMode": "Automatic",
},
)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_no_graph_1_1(self):
"""Test that a v1.1 file with an implicit graph is converted correctly"""
(result, error) = await ogts.load_test_file("SettingsWithoutGraph_v1_1.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/__graphUsingSchemas": "OmniGraph",
"/__graphUsingSchemas/NoOp": "OmniGraphNode",
"/__graphUsingSchemas/computegraphSettings": "ComputeGraphSettings",
},
["/__graphUsingSchemas/computegraphSettings"],
)
self.assertEqual([], results)
results = _verify_graph_settings(
"/__graphUsingSchemas",
{
"evaluator:type": "push",
"fileFormatVersion": CURRENT_FORMAT_VERSION,
"fabricCacheBacking": "StageWithHistory",
"pipelineStage": "pipelineStagePreRender",
"evaluationMode": "Automatic",
},
)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_no_graph_over_1_1(self):
"""Test that a v1.1 file with a layer in it is converted correctly.
The file has two layers of graph nodes because the layered graph nodes will not be composed unless there
is a node at the top level."""
(result, error) = await ogts.load_test_file(
"SettingsWithoutGraphWithOver_v1_1.usda", use_caller_subdirectory=True
)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/World": "World",
"/World/layeredGraph": "",
"/World/layeredGraph/innerGraph": "OmniGraph",
"/World/layeredGraph/innerGraph/NoOpOver": "OmniGraphNode",
"/World/layeredGraph/innerGraph/computegraphSettings": "ComputeGraphSettings",
"/World/__graphUsingSchemas": "OmniGraph",
"/World/__graphUsingSchemas/NoOp": "OmniGraphNode",
},
[
"/World/layeredGraph/innerGraph/computegraphSettings",
],
)
self.assertEqual([], results)
results = _verify_graph_settings(
"/World/__graphUsingSchemas",
{
"evaluator:type": "push",
"fileFormatVersion": CURRENT_FORMAT_VERSION,
"fabricCacheBacking": "Shared",
"pipelineStage": "pipelineStageSimulation",
"evaluationMode": "Automatic",
},
)
self.assertEqual([], results)
results = _verify_graph_settings(
"/World/layeredGraph/innerGraph",
{
"evaluator:type": "push",
"fileFormatVersion": FILE_FORMAT_VERSION_INTRODUCING_SCHEMAS,
"fabricCacheBacking": "StageWithHistory",
"pipelineStage": "pipelineStagePreRender",
"evaluationMode": "Automatic",
},
)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_no_graph_child_1_1(self):
"""Test that a v1.1 file with a graph underneath a World prim is converted correctly"""
(result, error) = await ogts.load_test_file("SettingsWithChildGraph_v1_1.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/World": "World",
"/World/__graphUsingSchemas": "OmniGraph",
"/World/__graphUsingSchemas/NoOp": "OmniGraphNode",
"/World/__graphUsingSchemas/computegraphSettings": "ComputeGraphSettings",
},
["/World/__graphUsingSchemas/computegraphSettings"],
)
self.assertEqual([], results)
results = _verify_graph_settings(
"/World/__graphUsingSchemas",
{
"evaluator:type": "push",
"fileFormatVersion": CURRENT_FORMAT_VERSION,
"fabricCacheBacking": "StageWithHistory",
"pipelineStage": "pipelineStagePreRender",
"evaluationMode": "Automatic",
},
)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_with_graph_1_1(self):
"""Test that a v1.1 file with an explicit graph and settings is converted correctly"""
(result, error) = await ogts.load_test_file("SettingsWithGraph_v1_1.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/pushGraph": "OmniGraph",
"/pushGraph/NoOp": "OmniGraphNode",
"/pushGraph/computegraphSettings": "ComputeGraphSettings",
},
["/pushGraph/computegraphSettings"],
)
self.assertEqual([], results)
results = _verify_graph_settings(
"/pushGraph",
{
"evaluator:type": "push",
"fileFormatVersion": CURRENT_FORMAT_VERSION,
"fabricCacheBacking": "StageWithHistory",
"pipelineStage": "pipelineStagePreRender",
"evaluationMode": "Automatic",
},
)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_with_bad_backing_name(self):
"""Test that a file using the backing name with a typo gets the correct name"""
(result, error) = await ogts.load_test_file("SettingsWithBadBackingName.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/pushGraph": "OmniGraph",
"/pushGraph/NoOp": "OmniGraphNode",
"/pushGraph/computegraphSettings": "ComputeGraphSettings",
},
["/pushGraph/computegraphSettings"],
)
self.assertEqual([], results)
results = _verify_graph_settings(
"/pushGraph",
{
"evaluator:type": "push",
"fileFormatVersion": CURRENT_FORMAT_VERSION,
"fabricCacheBacking": "StageWithHistory",
"pipelineStage": "pipelineStagePreRender",
"evaluationMode": "Automatic",
},
)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_with_graph_post_schema(self):
"""Test that an updated file with a graph and a node is read safely"""
(result, error) = await ogts.load_test_file("SettingsWithGraph_postSchema.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
results = _verify_stage_contents({"/pushGraph": "OmniGraph", "/pushGraph/NoOp": "OmniGraphNode"})
self.assertEqual([], results)
results = _verify_graph_settings(
"/pushGraph",
{
"evaluator:type": "push",
"fileFormatVersion": CURRENT_FORMAT_VERSION,
"fabricCacheBacking": "StageWithHistory",
"pipelineStage": "pipelineStagePreRender",
"evaluationMode": "Automatic",
},
)
self.assertEqual([], results)
# ==============================================================================================================
class TestSettingsPreservation(ogts.OmniGraphTestCase):
"""Wrapper for tests to confirm old files can still be safely loaded"""
# ----------------------------------------------------------------------
async def test_no_settings_1_1(self):
"""Test that a v1.1 file with a graph and no settings is read safely"""
(result, error) = await ogts.load_test_file("SettingsMissingFromGraph_v1_1.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/defaultGraph": "OmniGraph",
}
)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_no_graph_1_1(self):
"""Test that a v1.1 file with a scene with a global implicit graph is read safely"""
(result, error) = await ogts.load_test_file("SettingsWithoutGraph_v1_1.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/__graphUsingSchemas/computegraphSettings": "ComputeGraphSettings",
"/__graphUsingSchemas/NoOp": "OmniGraphNode",
"/__graphUsingSchemas": "OmniGraph",
}
)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_with_graph_1_1(self):
"""Test that a v1.1 file with a graph and settings is read safely"""
(result, error) = await ogts.load_test_file("SettingsWithGraph_v1_1.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
results = _verify_stage_contents(
{
"/pushGraph": "OmniGraph",
"/pushGraph/computegraphSettings": "ComputeGraphSettings",
"/pushGraph/NoOp": "OmniGraphNode",
}
)
self.assertEqual([], results)
# ----------------------------------------------------------------------
async def test_with_bad_connections(self):
"""Test that a file with old prims fails migration"""
(result, error) = await ogts.load_test_file("SettingsWithBadConnections.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
stage = omni.usd.get_context().get_stage()
graph_prim = stage.GetPrimAtPath("/pushGraph")
self.assertTrue(graph_prim.IsValid())
self.assertEqual("OmniGraph", graph_prim.GetTypeName())
settings_prim = stage.GetPrimAtPath("/pushGraph/computegraphSettings")
self.assertTrue(settings_prim.IsValid())
self.assertEqual("ComputeGraphSettings", settings_prim.GetTypeName())
node_prim = stage.GetPrimAtPath("/pushGraph/BundleInspector")
self.assertTrue(node_prim.IsValid())
self.assertEqual("OmniGraphNode", node_prim.GetTypeName())
| 21,073 | Python | 46.040178 | 119 | 0.560385 |
omniverse-code/kit/exts/omni.graph.nodes/docs/CHANGELOG.md | # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.48.3] - 2022-12-02
### Fixed
- Forces WriteVariable to actually write the array value to the variable location, and bypass CoW
## [1.48.2] - 2022-11-07
### Fixed
- Fix for bug in state initialization for GatherByPath, FindPrims
## [1.48.1] - 2022-11-03
### Fixed
- Fixes WritePrimAttribute not loading correctly if inputs have auto-conversion
## [1.48.0] - 2022-10-18
### Added
- ReadStageSelection, IsPrimSelected
## [1.47.0] - 2022-10-08
### Changed
- Remove omni.graph.nodes.Generate3dText
## [1.46.0] - 2022-09-30
### Changed
- `ToString` no longer adds enclosing quotes for uchar[] inputs.
## [1.45.1] - 2022-09-28
### Fixed
- Obsolete test for builtin nodes
## [1.45.0] - 2022-09-26
### Changed
- GetPrimPath returns a 'path' type as well as a token
## [1.44.0] - 2022-09-21
### Added
- New node ToUint64
## [1.43.1] - 2022-09-13
### Fixed
- Don't force FC to eject the prim every time we add another attribute.
## [1.43.0] - 2022-09-01
### Added
- EndsWith, StartsWith
## [1.42.0] - 2022-08-24
### Changed
- Added the ability to force USD read in read nodes
- Added the ability to choose whether or not write nodes should write back to USD
## [1.41.2] - 2022-08-15
### Changed
- Read Prim Into Bundle value changes of Add Target parameter did not trigger node computation
## [1.41.1] - 2022-08-11
### Changed
- Added support for tuples and arrays to Ceil & Floor nodes
## [1.41.0] - 2022-08-11
### Added
- Path inputs to transformation nodes
## [1.40.1] - 2022-08-09
### Fixed
- Applied formatting to all of the Python files
## [1.40.0] - 2022-08-09
### Changed
- Removed omni.graph.scriptnode dependency
## [1.39.0] - 2022-08-04
### Added
- Added Ceil node
## [1.38.0] - 2022-08-03
### Added
- BundleInspector returns number of child bundles.
## [1.37.4] - 2022-08-03
### Fixed
- Handling of compatible types in the Make Array node and error with saving and loading
## [1.37.3] - 2022-07-28
### Fixed
- Handling of token and string input in the Compare node
## [1.37.2] - 2022-07-27
### Changed
- WritePrimAttribute to accommodate property panel fix
## [1.37.1] - 2022-07-25
### Fixed
- All of the lint errors reported on the Python files in this extension
## [1.37.0] - 2022-07-20
### Changed
- Added requiredRelationship feature to FindPrims
## [1.36.0] - 2022-07-14
### Changed
- Added +/- icons to Make Array
## [1.35.0] - 2022-07-07
### Changed
- Refactored imports from omni.graph.tools to get the new locations
### Added
- Test for public API consistency
## [1.34.1] - 2022-07-06
### Changed
- Prevent the re-setup of the ReadPrimAttribute and WritePrimAttribute each frame, and only re-do it when necessary
## [1.34.0] - 2022-07-05
### Added
- Added dynamic version of MakeArray node replacing the previous fixed version
## [1.33.1] - 2022-06-30
### Changed
- Convert CrossProduct node to C++
## [1.33.0] - 2022-06-29
### Added
- Added OgnReadSetting and OgnWriteSetting nodes.
## [1.32.0] - 2022-06-29
### Changed
- Added several new constant nodes
## [1.31.0] - 2022-06-24
### Changed
- Moved ReadMouseState into omni.graph.ui
## [1.30.3] - 2022-06-21
### Changed
- Convert DotProduct node to C++
## [1.30.2] - 2022-06-16
### Changed
- Now using the new write-back mechanism for nodes that should write back to USD
## [1.30.1] - 2022-06-15
### Changed
- Refactored compute algorithm to find the correct type faster
## [1.28.0] - 2022-05-31
### Added
- Nodes for vertex deformation using gpu interop and pre-render evaluation
## [1.30.0] - 2022-06-13
### Added
- Added OgnReadPrimMaterial node and OgnWritePrimMaterial node
- Added UsdShade to dependencies
## [1.29.0] - 2022-06-06
### Added
- Added ReadOmniGraphValue node
## [1.28.0] - 2022-05-30
### Added
- Added logic directory for logical operators
- Added boolean operator nodes in logic which support array and bool array inputs
### Changed
- Soft deprecated (via metadata:hidden) OgnBooleanExpr in favour of the new individual logical nodes
- Moved OgnBooleanExpr to logic directory
- Moved OgnBooleanNot to logic from math and renamed it to OgnNot to match the new naming convention
- Updated OgnBooleanNot to take bool or bool array input instead of just bool, to match the new logical operator nodes
## [1.27.3] - 2022-05-27
### Removed
- Some useless dependencies/visibility to PathToAttributeMap
## [1.27.2] - 2022-05-19
- Converted ToDouble to C++
## [1.27.1] - 2022-05-18
### Changed
- Converted Array Manipulation Nodes from python to C++.
## [1.27.0] - 2022-05-18
### Added
- Added OgnNegate node that multiplies input by -1
## [1.26.2] - 2022-05-16
### Fixed
- ReadPrimBundle/Attribute not correctly export the bounding box when asked to
- Fixed and Re-activated the test that exercises this feature
## [1.26.1] - 2022-05-16
### Fixed
- ToToken no longer appends quote characters to a converted string
## [1.26.0] - 2022-05-11
### Added
- ExtractBundle node: "explode" a bundle content into individual dynamic attributes
### Changed
- ReadPrimBundle/ReadPrimAttribute/WritePrim/WritePrimAtribute now uses OG ABI instead of direct Fabric access
- ReadPrim is using functionnality of ReadPrimBundle and ExtractBundle
- RemoveAttribute is using OGN wrapper instead of direct ABI access
## [1.25.4] - 2022-05-05
### Changed
- Converted OgnArraySetIndex node from python to C++.
## [1.25.3] - 2022-05-05
### Fixed
- Fixed string input for SelectIf node
## [1.25.2] - 2022-05-05
### Fixed
- Read/WritePrimAttribute will now issue error messages when `usePath` is true and attribute is not found.
## [1.25.1] - 2022-05-03
### Changed
- Converted OgnMagnitude node from python to C++.
- Converted OgnDivide node from python to C++.
- Converted OgnRound node from python to C++.
## [1.25.0] - 2022-05-02
### Changed
- Converted OgnToString, OgnToToken, OgnToFloat, OgnClamp to cpp
- MakeVector2/3/4 will now auto-resolve inputs when at least one input is resolved
## [1.24.0] - 2022-04-29
### Removed
- Obsolete tests
### Changed
- Made tests derive from OmniGraphTestCase
## [1.23.3] - 2022-04-28
### Changed
- Converted OgnSubtract node from python to C++.
## [1.23.2] - 2022-04-27
### Fixed
- Fixed bug in Distance3D, InvertMatrix and Round nodes
## [1.23.1] - 2022-04-26
### Fixed
- Fixed bug in MakeTransform node
## [1.23.0] - 2022-04-21
### Added
- GraphTarget node that retrieves the path of instance being run
## [1.22.0] - 2022-04-14
### Added
- Changed OgnTrig node into cpp node
- Broke OgnTrig node by operation
## [1.21.4] - 2022-04-18
### Changed
- Added support for more characters to Generate3dText
## [1.21.3] - 2022-04-12
### Fixed
- Fixed a bug in GetLookAtRotation and GetLocationAtDistanceOnCurve nodes
## [1.21.2] - 2022-04-08
### Changed
- Changed Compose/Decompose Tuple to Make/Break Vector for those nodes and make them C++ nodes
## [1.21.1] - 2022-04-11
### Fixed
- Generate3dText node
## [1.21.0] - 2022-04-05
### Added
- Added Generate3dText node
## [1.20.1] - 2022-04-08
### Added
- Added absoluteSimTime output attribute to the ReadTime node
## [1.20.0] - 2022-04-05
### Added
- Noise node
## [1.19.2] - 2022-04-06
### Added
- Added Normalize node
## [1.19.1] - 2022-04-03
### Fixed
- RotateToOrientation bug, Maneuver node bugs with varying target input.
## [1.19.0] - 2022-03-30
### Added
- WriteVariable value output port
## [1.18.4] - 2022-03-31
### Fixed
- Fixed crash when copying bundle with empty points attribute
## [1.18.3] - 2022-03-23
### Added
- Tests for maneuver nodes
## [1.18.3] - 2022-03-21
-- Revive functionnality from 1.16.1 with different approach
## [1.18.2] - 2022-03-18
### Fixed
- Naming of constant nodes
## [1.18.1] - 2022-03-16
### Fixed
- Bug in MoveToTransform
## [1.18.0] - 2022-03-14
### Added
- Added MakeTransformLookAt node.
## [1.17.1] - 2022-03-11
- Revert changes of 1.16.1
## [1.17.0] - 2022-03-10
### Added
- Added _outputs::shiftOut_, _outputs::ctrlOut_, _outputs::altOut_ to _ReadKeyboardState_ node.
## [1.16.1] - 2022-03-07
### Fixed
- ReadPrimBundle/ReadPrimAttribute can now use a usd time code at which to import the prim/attribute
- ReadPrimBundle now outputs its transform and BBox
## [1.16.0] - 2022-03-01
### Added
- *bundle_test_utils.BundleResultKeys*
- *bundle_test_utils.prim_with_everything_definition*
- *bundle_test_utils.get_bundle_with_all_results*
- *bundle_test_utils.bundle_inspector_results*
- *bundle_test_utils.verify_bundles_are_equal*
- *bundle_test_utils.filter_bundle_inspector_results*
### Fixed
- Made bundle tests and utility node tests use the Controller
- GatherByPath, add checkResyncAttributes attribute
### Changed
- Deprecated old bundle test utilities that relied on USD save/read and OmniGraphHelper for functioning
- Updated some tests to use OmniGraphTestCase
## [1.15.0] - 2022-02-17
### Fixed
- added a "path"" constant node
## [1.15.0] - 2022-02-15
### Changed
- WritePrim node now uses GPU arrays for points
## [1.14.0] - 2022-02-15
### Fixed
- added a dependency on omni.graph.scriptnode
## [1.13.2] - 2022-02-14
### Fixed
- add additional extension enabled check for omni.graph.ui not enabled error
## [1.13.2] - 2022-02-14
### Fixed
- MoveToTarget, RotateToTarget etc bug with float, half precision XformOp
## [1.13.1] - 2022-02-13
### Fixed
- ReadPrimBundle, ReadPrim now support token[] attributes
## [1.13.0] - 2022-02-11
### Added
- ReadVariable and WriteVariable nodes
## [1.12.3] - 2022-02-10
### Fixed
- Fixed MoveToTarget, MoveToTransform, RotateToTarget, GetPrimDirectionVector, GetMatrix4Quaternion and GetLocationAtDistanceOnCurve nodes behaviour when rotation is scaled
## [1.12.2] - 2022-02-07
### Fixed
- Fixed ArrayRotate, Compare, and SelectIf nodes behaviour when input was a token
## [1.12.1] - 2022-02-04
### Fixed
- RotateToOrientation, MoveToTransform attrib docs
## [1.12.0] - 2022-01-31
### Added
- Added shouldWriteBack input flag to GatherByPath node
### Fixed
- Fixed duplicate path behaviour for gather nodes
## [1.11.0] - 2022-01-27
### Added
- Added IsPrimActive node
- Added BooleanNot
## [1.10.1] - 2022-01-28
### Fixed
- spurious error message when creating _ReadPrim_
- updated extension doc
## [1.10.0] - 2022-01-27
### Added
- added ReadMouseState node
## [1.9.2] - 2022-01-28
### Modified
- added three test cases for NthRoot node
## [1.9.1] - 2022-01-24
### Fixed
- categories for several nodes
## [1.9.0] - 2022-01-19
### Added
- Added constant Pi node which will output a constant Pi or its multiple
- Added Nth Root node which will calculate the nth root of inputs
## [1.8.0] - 2022-01-17
### Added
- Added sets of tryCompute (including for arrays and tuples) functions to allow one non-runtime attribute input when two inputs
- Added Increment Node
## [1.7.1] - 2022-01-11
### Changed
- Changed token names in ReadGamepadState node
- Fixed incorrect default token in ReadGamepadState node
## [1.7.0] - 2022-01-10
### Added
- Added GetPrimDirectionVector node
## [1.6.0] - 2022-01-07
### Added
- Added ReadGamepadState node
## [1.5.3] - 2022-01-06
### Changed
- Categories added to all nodes
## [1.5.2] - 2022-01-05
### Modified
- _ReadPrimBundle_ and _ReadPrim_ now have a _sourcePrimPath_ bundle attribute which contains
the path of the Prim being read.
## [1.5.1] - 2021-12-30
### Changed
- _ArrayIndex_ converted to C++, _AppendString_ now supports string inputs
## [1.5.0] - 2021-12-20
### Added
- Added _ReadTime_ and moved _GetLookAtRotation_ from _omni.graph.action_
## [1.4.0] - 2021-12-17
### Added
- Added ReadKeyboardState node
## [1.3.0] - 2021-12-02
### Added
- UI templates for Read/WritePrimAttribute nodes
### Changed
- Read/WritePrimAttribute nodes usePath attribute now defaults to False
## [1.2.2] - 2021-11-24
### Changed
- Prevented some problematic attributes from being exposed by ReadPrimAttributes and WritePrimAttributes
## [1.2.1] - 2021-11-19
### Changed
- Bug fix for ReadPrimAttributes
## [1.2.0] - 2021-11-04
### Added
- TransformVector
- RotateVector
### Changed
- Multiply: Support adding scalars to tuples
- Add: Support adding scalars to tuples
- MatrixMultiply: Support matrix * vector as well as matrix * matrix
### Moved
- OgnAdd2IntegerArray: Moved to omni.graph.test (deprecated by Add)
- OgnMultiply2IntegerArray: Moved to omni.graph.test (deprecated by Multiply)
## [1.1.0] - 2021-10-17
### Added
- PrimRead, PrimWrite
## [1.0.0] - 2021-03-01
### Initial Version
- Started changelog with initial released version of the OmniGraph core
| 12,700 | Markdown | 24.973415 | 172 | 0.703386 |
omniverse-code/kit/exts/omni.graph.nodes/docs/README.md | # OmniGraph Nodes [omni.graph.nodes]
This is a collection of simple nodes that exercise some of the functionality of the Omniverse Graph. They serve
as illustration of some features and as a common library of utility nodes.
| 225 | Markdown | 44.199991 | 111 | 0.804444 |
omniverse-code/kit/exts/omni.graph.nodes/docs/index.rst | .. _ogn_omni_graph_nodes:
OmniGraph Built-In Nodes
########################
.. tabularcolumns:: |L|R|
.. csv-table::
:width: 100%
**Extension**: omni.graph.nodes,**Documentation Generated**: |today|
.. toctree::
:maxdepth: 1
CHANGELOG
This is a collection of OmniGraph nodes that can be used in a variety of graph types.
For comprehensive examples targeted at explaining the use of OmniGraph features in detail see
:ref:`ogn_user_guide`
| 458 | reStructuredText | 18.956521 | 93 | 0.672489 |
omniverse-code/kit/exts/omni.graph.nodes/docs/Overview.md | # OmniGraph Built-In Nodes
```{csv-table}
**Extension**: omni.graph.nodes,**Documentation Generated**: {sub-ref}`today`
```
This is a collection of OmniGraph nodes that can be used in a variety of graph types.
For comprehensive examples targeted at explaining the use of OmniGraph features in detail see
{ref}`ogn_user_guide` | 328 | Markdown | 31.899997 | 93 | 0.756098 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.