file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayInsertValue.ogn
{ "ArrayInsertValue": { "version": 1, "description": [ "Inserts an element at the given index. The indexing is zero-based, so 0 adds an element to the front of the", "array and index = Length inserts at the end of the array. The index will be clamped to the range (0, Length),", "so an index of -1 will add to the front, and an index larger than the array size will append to the end." ], "uiName": "Array Insert Value", "categories": ["math:array"], "scheduling": ["threadsafe"], "inputs": { "array": { "type": ["arrays", "bool[]"], "description": "The array to be modified", "uiName": "Array" }, "value": { "type": ["array_elements", "bool"], "description": "The value to be inserted" }, "index": { "type": "int", "description": "The array index to insert the value, which is clamped to the valid range", "uiName": "Index" } }, "outputs": { "array": { "type": ["arrays", "bool[]"], "description": "The modified array", "uiName": "Array" } }, "tests": [ { "inputs:array": {"type": "int[]", "value": [41, 42]}, "inputs:index": 0, "inputs:value": {"type": "int", "value": 1}, "outputs:array": {"type": "int[]", "value": [1, 41, 42]} }, { "inputs:array": {"type": "int[]", "value": [41, 42]}, "inputs:index": 1, "inputs:value": {"type": "int", "value": 1}, "outputs:array": {"type": "int[]", "value": [41, 1, 42]} }, { "inputs:array": {"type": "int[]", "value": [41, 42]}, "inputs:index": 2, "inputs:value": {"type": "int", "value": 1}, "outputs:array": {"type": "int[]", "value": [41, 42, 1]} }, { "inputs:array": {"type": "token[]", "value": ["FOO", "BAR"]}, "inputs:index": 1, "inputs:value": {"type": "token", "value": "BAZ"}, "outputs:array": {"type": "token[]", "value": ["FOO", "BAZ", "BAR"]} }, { "inputs:array": {"type": "half[]", "value": [41, 42]}, "inputs:index": 1, "inputs:value": {"type": "half", "value": 1}, "outputs:array": {"type": "half[]", "value": [41, 1, 42]} }, { "inputs:array": {"type": "half[2][]", "value": [[41, 1], [42, 2]]}, "inputs:index": 1, "inputs:value": {"type": "half[2]", "value": [1, 2]}, "outputs:array": {"type": "half[2][]", "value": [[41, 1], [1, 2], [42, 2]]} }, { "inputs:array": {"type": "double[2][]", "value": [[41, 1], [42, 2]]}, "inputs:index": 1, "inputs:value": {"type": "double[2]", "value": [1, 2]}, "outputs:array": {"type": "double[2][]", "value": [[41, 1], [1, 2], [42, 2]]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToDouble.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 <OgnToDoubleDatabase.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(OgnToDoubleDatabase& db, size_t count) { auto functor = [](auto const& value, auto& converted) { converted = static_cast<double>(value); }; return ogn::compute::tryComputeWithArrayBroadcasting<T, double>(db.inputs.value(), db.outputs.converted(), functor, count); } template<typename T, size_t tupleSize> bool tryComputeAssumingType(OgnToDoubleDatabase& db, size_t count) { auto functor = [](auto const& value, auto& converted) { converted = static_cast<double>(value); }; return ogn::compute::tryComputeWithTupleBroadcasting<tupleSize, T, double>( db.inputs.value(), db.outputs.converted(), functor, count); } } // namespace class OgnToDouble { public: // Node to convert numeric inputs to floats static bool computeVectorized(OgnToDoubleDatabase& 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::eDouble, valueType.componentCount, valueType.arrayDepth); outAttr.iAttribute->setResolvedType(outAttr, resultType); } } }; REGISTER_OGN_NODE(); } // nodes } // graph } // omni
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBuildString.ogn
{ "BuildString": { "$comment": "Replaces the v1 AppendString node as it renames the input attributes", "version": 2, "description": [ "Creates a new token or string by concatenating the inputs.", "token[] inputs will be appended element-wise." ], "uiName": "Append String", "categories": ["function"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["token", "token[]", "string"], "description": "The string(s) to be appended to" }, "b": { "type": ["token", "token[]", "string"], "description": "The string to be appended" } }, "outputs": { "value": { "type": ["token","token[]", "string"], "description": "The new string(s)" } }, "tests": [ { "inputs:a": {"type":"token", "value": "/"}, "inputs:b": {"type":"token", "value": "foo"}, "outputs:value": {"type":"token", "value": "/foo"} }, { "inputs:a": {"type":"token[]", "value": ["/World","/World2"]}, "inputs:b": {"type":"token", "value": "/foo"}, "outputs:value": {"type":"token[]", "value": ["/World/foo","/World2/foo"]} }, { "inputs:a": {"type":"token[]", "value": ["/World","/World2"]}, "inputs:b": {"type":"token[]", "value": ["/foo", "/bar"]}, "outputs:value": {"type":"token[]", "value": ["/World/foo","/World2/bar"]} }, { "inputs:a": {"type":"string", "value": "/"}, "inputs:b": {"type":"string", "value": "foo"}, "outputs:value": {"type":"string", "value": "/foo"} } ] } }
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() } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetParentPath.ogn
{ "GetParentPath": { "version": 1, "description": ["Generates a parent path token from another path token. (ex. /World/Cube -> /World)"], "uiName": "Get Parent Path", "categories": ["sceneGraph"], "scheduling": [ "threadsafe" ], "inputs": { "path": { "type": ["token", "token[]"], "description": "One or more path tokens to compute a parent path from. (ex. /World/Cube)" } }, "outputs": { "parentPath": { "type": ["token", "token[]"], "description": "Parent path token (ex. /World)" } }, "state": { "path": { "type": "token", "description": "Snapshot of previously seen path" } }, "tests": [ { "inputs:path": { "type": "token", "value": "/" }, "outputs:parentPath": { "type": "token", "value": "" } }, { "inputs:path": { "type": "token", "value": "/World" }, "outputs:parentPath": { "type": "token", "value": "/" } }, { "inputs:path": { "type": "token", "value": "/World/foo" }, "outputs:parentPath": { "type": "token", "value": "/World" } }, { "inputs:path": { "type": "token", "value": "/World/foo/bar" }, "outputs:parentPath": { "type": "token", "value": "/World/foo" } }, { "inputs:path": { "type": "token", "value": "/World/foo/bar.attrib" }, "outputs:parentPath": { "type": "token", "value": "/World/foo/bar" } }, { "inputs:path": { "type": "token[]", "value": [ "/World1/foo", "/World2/bar" ] }, "outputs:parentPath": { "type": "token[]", "value": [ "/World1", "/World2" ] } } ] } }
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(); } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayInsertValue.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 <OgnArrayInsertValueDatabase.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 { // helper to clamp a given index to [0:arrayLength] size_t tryWrapIndex(int index, size_t arraySize) { if (index < 0) index = 0; if (index > static_cast<int>(arraySize)) index = static_cast<int>(arraySize); return static_cast<size_t>(index); } template<typename BaseType> bool tryComputeAssumingType(OgnArrayInsertValueDatabase& db) { auto const inputArray = db.inputs.array().template get<BaseType[]>(); size_t const inputArraySize = db.inputs.array().size(); size_t const index = tryWrapIndex(db.inputs.index(), inputArraySize); auto const value = db.inputs.value().template get<BaseType>(); auto outputArray = db.outputs.array().template get<BaseType[]>(); if (!value || !inputArray) return false; (*outputArray).resize(inputArraySize+1); memcpy(outputArray->data(), inputArray->data(), sizeof(BaseType) * index); memcpy(&((*outputArray)[index]), &*value, sizeof(BaseType)); memcpy(outputArray->data() + index + 1, inputArray->data() + index, sizeof(BaseType) * (inputArraySize - index)); return true; } } // namespace class OgnArrayInsertValue { public: static bool compute(OgnArrayInsertValueDatabase& 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 outputArray = node.iNode->getAttributeByToken(node, outputs::array.token()); auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray); if (inputArrayType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 3> attrs { inputArray, inputValue, outputArray }; // all should have the same tuple count std::array<uint8_t, 3> tupleCounts { inputArrayType.componentCount, inputArrayType.componentCount, inputArrayType.componentCount }; // value type can not be an array because we don't support arrays-of-arrays std::array<uint8_t, 3> arrayDepths { 1, 0, 1 }; std::array<AttributeRole, 3> rolesBuf { inputArrayType.role, AttributeRole::eUnknown, 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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeVector2.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 <OgnMakeVector2Database.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(OgnMakeVector2Database& db) { const auto x = db.inputs.x().template get<Type>(); const auto y = db.inputs.y().template get<Type>(); auto vector = db.outputs.tuple().template get<Type[2]>(); if (vector && x && y){ (*vector)[0] = *x; (*vector)[1] = *y; return true; } const auto xArray = db.inputs.x().template get<Type[]>(); const auto yArray = db.inputs.y().template get<Type[]>(); auto vectorArray = db.outputs.tuple().template get<Type[][2]>(); if (!vectorArray || !xArray || !yArray){ return false; } if (xArray->size() != yArray->size()) { throw ogn::compute::InputError("Input arrays of different lengths x:" + std::to_string(xArray->size()) + ", y:" + std::to_string(yArray->size())); } vectorArray->resize(xArray->size()); for (size_t i = 0; i < vectorArray->size(); i++) { (*vectorArray)[i][0] = (*xArray)[i]; (*vectorArray)[i][1] = (*yArray)[i]; } return true; } } // namespace // Node to merge 2 scalers together to make 2-vector class OgnMakeVector2 { public: static bool compute(OgnMakeVector2Database& 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 vector = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::tuple.token()); auto xType = vector.iAttribute->getResolvedType(x); auto yType = vector.iAttribute->getResolvedType(y); // If one of the inputs is resolved we can resolve the other because they should match std::array<AttributeObj, 2> attrs { x, y }; if (nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size())) { xType = vector.iAttribute->getResolvedType(x); yType = vector.iAttribute->getResolvedType(y); } // Require inputs to be resolved before determining outputs' type if (xType.baseType != BaseDataType::eUnknown && yType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 3> attrs{ x, y, vector }; std::array<uint8_t, 3> tuples{ 1, 1, 2 }; std::array<uint8_t, 3> arrays{ xType.arrayDepth, yType.arrayDepth, xType.arrayDepth, }; std::array<AttributeRole, 3> roles{ xType.role, yType.role, AttributeRole::eNone }; nodeObj.iNode->resolvePartiallyCoupledAttributes(nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size()); } } }; REGISTER_OGN_NODE(); } } }
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnFindPrims.ogn
{ "FindPrims": { "version": 2, "description": ["Finds Prims on the stage which match the given criteria"], "uiName": "Find Prims", "categories": ["sceneGraph"], "scheduling": ["usd-read", "threadsafe"], "inputs": { "type": { "uiName": "Prim Type Pattern", "type": "token", "default": "*", "description": [ "A list of wildcard patterns used to match the prim types that are to be imported", "", "Supported syntax of wildcard pattern:", " '*' - match an arbitrary number of any characters", " '?' - match any single character", " '^' - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['Mesh', 'Cone', 'Cube']", " '*' - match any", " '* ^Mesh' - match any, but exclude 'Mesh'", " '* ^Cone ^Cube' - match any, but exclude 'Cone' and 'Cube'" ] }, "pathPattern": { "uiName": "Prim Path Pattern", "type": "token", "description": [ "A list of wildcard patterns used to match the prim paths", "", "Supported syntax of wildcard pattern:", " '*' - match an arbitrary number of any characters", " '?' - match any single character", " '^' - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['/Cube0', '/Cube1', '/Box']", " '*' - match any", " '* ^/Box' - match any, but exclude '/Box'", " '* ^/Cube*' - match any, but exclude '/Cube0' and '/Cube1'" ] }, "rootPrimPath": { "uiName": "Root Prim Path", "type": "token", "description": "Only children of the given prim will be considered. Empty will search the whole stage.", "deprecated": "Use rootPrim input attribute instead" }, "rootPrim": { "uiName": "Root Prim", "type": "target", "description": "Only children of the given prim will be considered. If rootPrim is specified, rootPrimPath will be ignored." }, "namePrefix": { "uiName": "Prim Name Prefix", "type": "token", "description": "Only prims with a name starting with the given prefix will be returned." }, "requiredAttributes": { "uiName": "Attribute Names", "type": "string", "description": "A space-separated list of attribute names that are required to be present on matched prims" }, "requiredRelationship": { "uiName": "Relationship Name", "type": "token", "description": "The name of a relationship which must have a target specified by requiredRelationshipTarget or requiredTarget" }, "requiredRelationshipTarget": { "uiName": "Relationship Prim Path", "type": "path", "description": "The path that must be a target of the requiredRelationship", "deprecated": "Use requiredTarget instead" }, "requiredTarget": { "uiName": "Relationship Prim", "type": "target", "description": "The target of the requiredRelationship" }, "recursive": { "type": "bool", "description": "False means only consider children of the root prim, True means all prims in the hierarchy" }, "ignoreSystemPrims": { "type": "bool", "description": "Ignore system prims such as omni graph nodes that shouldn't be considered during the import.", "default": false } }, "outputs": { "prims": { "type": "target", "description": "A list of Prim paths which match the given type" }, "primPaths": { "type": "token[]", "description": "A list of Prim paths as tokens which match the given type" } }, "state": { "inputType": { "type": "token" , "description": "last corresponding input seen"}, "rootPrimPath": { "type": "token" , "description": "last corresponding input seen"}, "rootPrim": { "type": "target", "description": "last corresponding input seen"}, "namePrefix": { "type": "token" , "description": "last corresponding input seen"}, "requiredRelationship": { "type": "token" , "description": "last corresponding input seen"}, "pathPattern": { "type": "token" , "description": "last corresponding input seen"}, "requiredAttributes": { "type": "string" , "description": "last corresponding input seen"}, "requiredRelationshipTarget": { "type": "string" , "description": "last corresponding input seen"}, "requiredTarget": { "type": "target", "description": "last corresponding input seen"}, "recursive": { "type": "bool" , "description": "last corresponding input seen"}, "ignoreSystemPrims": { "type": "bool", "description": "last corresponding input seen" } }, "tests": [ { "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": { "namePrefix": "Xform" }, "outputs": { "primPaths": ["/Xform1", "/Xform2", "/XformTagged1"] } }, { "setup": {}, "inputs": { "namePrefix": "", "requiredAttributes": "foo _translate" }, "outputs": { "primPaths": ["/XformTagged1"] } } ] } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToDouble.ogn
{ "ToDouble": { "version": 1, "description": ["Converts the given input to 64 bit double. The node will attempt to convert", " array and tuple inputs to doubles of the same shape" ], "uiName": "To Double", "categories": ["math:conversion"], "scheduling": ["threadsafe"], "inputs": { "value": { "type": ["numerics", "bool", "bool[]"], "uiName": "value", "description": "The numeric value to convert to double" } }, "outputs": { "converted": { "type": ["double", "double[2]", "double[3]", "double[4]", "double[]", "double[2][]", "double[3][]", "double[4][]"], "uiName": "Double", "description": "Output double-based value" } }, "tests" : [ { "inputs:value": {"type": "float[]", "value": [] }, "outputs:converted": {"type": "double[]", "value": []} }, { "inputs:value": {"type": "double", "value": 2.1}, "outputs:converted": {"type": "double", "value": 2.1} }, { "inputs:value": {"type": "int", "value": 42}, "outputs:converted": {"type": "double", "value": 42.0} }, { "inputs:value": {"type": "bool[]", "value": [true, false]}, "outputs:converted": {"type": "double[]", "value": [1.0, 0.0]} }, { "inputs:value": {"type": "float[2]", "value": [2.1, 2.1] }, "outputs:converted": {"type": "double[2]", "value": [2.1, 2.1]} }, { "inputs:value": {"type": "half[3]", "value": [2, 3, 4] }, "outputs:converted": {"type": "double[3]", "value": [2, 3, 4] } }, { "inputs:value": {"type": "half[3][]", "value": [[2, 3, 4]] }, "outputs:converted": {"type": "double[3][]", "value": [[2, 3, 4]] } }, { "inputs:value": {"type": "int[2][]", "value": [[1, 2],[3, 4]] }, "outputs:converted": {"type": "double[2][]", "value": [[1.0, 2.0],[3.0, 4.0]] } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnSetGatheredAttribute.ogn
{ "SetGatheredAttribute": { "version": 1, "description": ["Writes a value into the given Gathered attribute. If the number elements of the value is less", "than the gathered attribute, the value will be broadcast to all prims. If the given value has", "more elements than the gathered attribute, an error will be produced.", "PROTOTYPE DO NOT USE, Requires GatherPrototype" ], "uiName": "Set Gathered Attribute (Prototype)", "categories": ["internal"], "inputs": { "gatherId": { "type": "uint64", "description": "The GatherId of the gathered prims" }, "name": { "type": "token", "description": "The name of the attribute to set in the given Gather" }, "execIn": { "type": "execution", "description": "Input execution state" }, "value": { "type": "any", "description": "The new value to be written to the gathered attributes" }, "mask": { "type": "bool[]", "optional": true, "description": "Only writes values to the indexes which are true." } }, "outputs": { "execOut": { "type": "execution", "description": "Output execution" } } } }
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnSelectIf.ogn
{ "SelectIf": { "version": 1, "description": [ "Selects an output from the given inputs based on a boolean condition.", "If the condition is an array, and the inputs are arrays of equal length, and values will be selected", "from ifTrue, ifFalse depending on the bool at the same index. If one input is an array and the other is", "a scaler of the same base type, the scaler will be extended to the length of the other input." ], "uiName": "Select If", "categories": ["flowControl"], "scheduling": ["threadsafe"], "inputs": { "ifTrue": { "type": "any", "uiName": "If True", "description": "Value if condition is True" }, "ifFalse": { "type": "any", "uiName": "If False", "description": "Value if condition is False" }, "condition": { "type": ["bool", "bool[]"], "description": "The selection variable" } }, "outputs": { "result": { "type": "any", "description": "The selected value from ifTrue and ifFalse", "uiName": "Result" } }, "tests" : [ { "inputs:ifTrue": {"type": "float", "value": 1.0}, "inputs:ifFalse": {"type": "float", "value": 3.0}, "inputs:condition": {"type":"bool", "value":true}, "outputs:result": {"type": "float", "value": 1.0} }, { "inputs:ifTrue": {"type": "float", "value": 1.0}, "inputs:ifFalse": {"type": "float", "value": 3.0}, "inputs:condition": {"type":"bool", "value":false}, "outputs:result": {"type": "float", "value": 3.0} }, { "inputs:ifTrue": {"type": "float[]", "value": [10.0, 20.0]}, "inputs:ifFalse": {"type": "float[]", "value": [1.0, 2.0]}, "inputs:condition": {"type":"bool[]", "value":[true, false]}, "outputs:result": {"type": "float[]", "value": [10.0, 2.0]} }, { "inputs:ifTrue": {"type": "float[]", "value": [10.0, 20.0]}, "inputs:ifFalse": {"type": "float", "value": 99}, "inputs:condition": {"type":"bool[]", "value":[true, false]}, "outputs:result": {"type": "float[]", "value": [10.0, 99]} }, { "inputs:ifTrue": {"type": "float", "value": 99}, "inputs:ifFalse": {"type": "float[]", "value": [1.0, 2.0]}, "inputs:condition": {"type":"bool[]", "value":[true, false]}, "outputs:result": {"type": "float[]", "value": [99, 2.0]} }, { "inputs:ifTrue": {"type": "float[2][]", "value": [[1,1], [2,2]]}, "inputs:ifFalse": {"type": "float[2][]", "value": [[3,3], [4,4]]}, "inputs:condition": {"type":"bool[]", "value":[true, false]}, "outputs:result": {"type": "float[2][]", "value": [[1,1], [4,4]]} }, { "inputs:ifTrue": {"type": "string", "value": "abc"}, "inputs:ifFalse": {"type": "string", "value": "efghi"}, "inputs:condition": {"type":"bool", "value":true}, "outputs:result": {"type": "string", "value": "abc"} }, { "inputs:ifTrue": {"type": "string", "value": "abc"}, "inputs:ifFalse": {"type": "string", "value": "efg"}, "inputs:condition": {"type":"bool", "value":false}, "outputs:result": {"type": "string", "value": "efg"} }, { "inputs:ifTrue": {"type": "uchar[]", "value": [61, 62, 63]}, "inputs:ifFalse": {"type": "uchar[]", "value": [65, 66, 67]}, "inputs:condition": {"type":"bool", "value":false}, "outputs:result": {"type": "uchar[]", "value": [65, 66, 67]} }, { "inputs:ifTrue": {"type": "uchar[]", "value": [61, 62, 63]}, "inputs:ifFalse": {"type": "uchar[]", "value": [65, 66, 67]}, "inputs:condition": {"type":"bool[]", "value":[true, false, true]}, "outputs:result": {"type": "uchar[]", "value": [61, 66, 63]} }, { "inputs:ifTrue": {"type": "token", "value": "abc"}, "inputs:ifFalse": {"type": "token", "value": "efghi"}, "inputs:condition": {"type":"bool", "value":true}, "outputs:result": {"type": "token", "value": "abc"} }, { "inputs:ifTrue": {"type": "token", "value": "abc"}, "inputs:ifFalse": {"type": "token", "value": "efghi"}, "inputs:condition": {"type":"bool", "value":false}, "outputs:result": {"type": "token", "value": "efghi"} }, { "inputs:ifTrue": {"type": "token[]", "value": ["ab", "cd"]}, "inputs:ifFalse": {"type": "token[]", "value": ["ef", "gh"]}, "inputs:condition": {"type":"bool[]", "value":[true, false]}, "outputs:result": {"type": "token[]", "value": ["ab", "gh"]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnAppendString.ogn
{ "AppendString": { "version": 1, "$comment": "This node is replaced by OgnBuildString", "description": [ "Creates a new token or string by appending the given token or string.", "token[] inputs will be appended element-wise." ], "uiName": "Append String (Deprecated)", "categories": ["function"], "scheduling": ["threadsafe"], "metadata": {"hidden": "true"}, "inputs": { "value": { "type": ["token", "token[]", "string"], "description": "The string(s) to be appended to" }, "suffix": { "type": ["token", "token[]", "string"], "description": "The string to be appended" } }, "outputs": { "value": { "type": ["token","token[]", "string"], "description": "The new string(s)" } }, "tests": [ { "inputs:value": {"type":"token", "value": "/"}, "inputs:suffix": {"type":"token", "value": "foo"}, "outputs:value": {"type":"token", "value": "/foo"} }, { "inputs:value": {"type":"token[]", "value": ["/World","/World2"]}, "inputs:suffix": {"type":"token", "value": "/foo"}, "outputs:value": {"type":"token[]", "value": ["/World/foo","/World2/foo"]} }, { "inputs:value": {"type":"token[]", "value": ["/World","/World2"]}, "inputs:suffix": {"type":"token[]", "value": ["/foo", "/bar"]}, "outputs:value": {"type":"token[]", "value": ["/World/foo","/World2/bar"]} }, { "inputs:value": {"type":"string", "value": "/"}, "inputs:suffix": {"type":"string", "value": "foo"}, "outputs:value": {"type":"string", "value": "/foo"} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToString.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 <OgnToStringDatabase.h> #include <omni/graph/core/ogn/UsdTypes.h> #include <fstream> #include <iomanip> #include <sstream> #include <string> #include "PrimCommon.h" namespace omni { namespace graph { namespace nodes { namespace { template<typename T> bool tryComputeAssumingType(OgnToStringDatabase& db) { std::string converted = tryConvertToString<T>(db, db.inputs.value()); if (converted.empty()) { return false; } db.outputs.converted() = converted.c_str(); return true; } template<> bool tryComputeAssumingType<ogn::Token>(OgnToStringDatabase& db) { std::string converted = tryConvertToString<ogn::Token>(db, db.inputs.value()); db.outputs.converted() = converted.c_str(); return true; } template<typename T, size_t tupleSize> bool tryComputeAssumingType(OgnToStringDatabase& db) { std::string converted = tryConvertToString<T, tupleSize>(db, db.inputs.value()); if (converted.empty()) { return false; } db.outputs.converted() = converted.c_str(); return true; } } // namespace class OgnToString { public: // Node to convert any input to a string static bool compute(OgnToStringDatabase& db) { NodeObj nodeObj = db.abi_node(); const AttributeObj attr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token()); const Type attrType = attr.iAttribute->getResolvedType(attr); auto value = db.inputs.value(); if (attrType.baseType == BaseDataType::eUnknown) { db.logError("Unknown input data type"); return false; } // Compute the components, if the types are all resolved. // This handles char and string case (get<ogn::string>() will return invalid result) if (attrType.baseType == BaseDataType::eUChar) { if ((attrType.arrayDepth == 1) && ((attrType.role == AttributeRole::eText) || (attrType.role == AttributeRole::ePath))) { auto val = db.inputs.value().template get<uint8_t[]>(); if (!val) { db.logError("Unable to resolve input type"); return false; } auto charData = val->data(); std::string str = std::string(charData, charData + val->size()); db.outputs.converted() = str.c_str(); return true; } else if (attrType.arrayDepth == 0) { uchar val = *db.inputs.value().template get<uchar>(); db.outputs.converted() = std::string(1, static_cast<char>(val)).c_str(); return true; } } try { auto& inputType = db.inputs.value().type(); switch (inputType.baseType) { case BaseDataType::eToken: return tryComputeAssumingType<ogn::Token>(db); case BaseDataType::eBool: return tryComputeAssumingType<bool>(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 (const std::exception& e) { db.logError("Input could not be converted to string: %s", e.what()); return false; } return true; } }; REGISTER_OGN_NODE(); } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnConstructArray.ogn
{ "ConstructArray": { "version": 1, "description": [ "Makes an output array attribute from input values, in the order of the inputs.", "If 'arraySize' is less than the number of input elements, the top 'arraySize' elements will be used.", "If 'arraySize' is greater than the number of input elements, the last input element will be repeated", "to fill the remaining space." ], "categories": ["math:array"], "uiName": "Make Array", "scheduling": ["threadsafe"], "inputs": { "input0": { "type": "any", "description": "Input array element" }, "arraySize": { "type": "int", "description": "The size of the array to create", "default": 1, "minimum": 0, "metadata": { "literalOnly": "1" } }, "arrayType": { "type": "token", "description": "The type of the array ('auto' infers the type from the first connected and resolved input)", "uiName": "Array Type", "default": "auto", "metadata": { "literalOnly": "1", "allowedTokens": { "Auto": "auto", "Bool": "bool[]", "Double": "double[]", "Float": "float[]", "Half": "half[]", "Int": "int[]", "Int64": "int64[]", "Token": "token[]", "UChar": "uchar[]", "UInt": "uint[]", "UInt64": "uint64[]", "Double_2": "double[2][]", "Double_3": "double[3][]", "Double_4": "double[4][]", "Double_9": "matrixd[3][]", "Double_16": "matrixd[4][]", "Float_2": "float[2][]", "Float_3": "float[3][]", "Float_4": "float[4][]", "Half_2": "half[2][]", "Half_3": "half[3][]", "Half_4": "half[4][]", "Int_2": "int[2][]", "Int_3": "int[3][]", "Int_4": "int[4][]" } } } }, "outputs": { "array": { "type": "any", "description": "The array of copied values of inputs in the given order" } }, "tests": [ ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBreakVector2.ogn
{ "BreakVector2": { "version": 1, "description": ["Split vector into 2 component values."], "uiName": "Break 2-Vector", "categories": ["math:conversion"], "tags": ["decompose", "separate", "isolate"], "scheduling": ["threadsafe"], "inputs": { "tuple": { "type": ["double[2]", "float[2]", "half[2]", "int[2]"], "uiName": "Vector", "description": "2-vector to be broken" } }, "outputs": { "x": { "type": ["double", "float", "half", "int"], "uiName": "X", "description": "The first component of the vector" }, "y": { "type": ["double", "float", "half", "int"], "uiName": "Y", "description": "The second component of the vector" } }, "tests" : [ { "inputs:tuple": {"type": "float[2]", "value": [42.0, 1.0]}, "outputs:x": {"type": "float", "value": 42.0}, "outputs:y": {"type": "float", "value": 1.0} }, { "inputs:tuple": {"type": "int[2]", "value": [42, -42]}, "outputs:x": {"type": "int", "value": 42}, "outputs:y": {"type": "int", "value": -42} } ] } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBundleConstructor.ogn
{ "BundleConstructor": { "version": 1, "language": "python", "description": [ "This node creates a bundle mirroring all of the dynamic input attributes that have been added to it.", "If no dynamic attributes exist then the bundle will be empty. See the 'InsertAttribute' node for", "something that can construct a bundle from existing connected attributes." ], "metadata": { "uiName": "Bundle Constructor" }, "categories": ["bundle"], "outputs": { "bundle": { "type": "bundle", "description": "The bundle consisting of copies of all of the dynamic input attributes.", "metadata": { "uiName": "Constructed Bundle" } } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimPath.ogn
{ "GetPrimPath": { "version": 3, "description": ["Generates a path from the specified relationship. This is useful when an absolute prim path may change."], "uiName": "Get Prim Path", "categories": ["sceneGraph"], "scheduling": ["threadsafe"], "inputs": { "prim": { "type": "target", "description": "The prim to determine the path of" } }, "outputs": { "primPath": { "type": "token", "description": "The absolute path of the given prim as a token" }, "path": { "type": "path", "description": "The absolute path of the given prim as a string", "deprecated": "Path is deprecated. Use primPath output instead." } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetGatheredAttribute.ogn
{ "GetGatheredAttribute": { "version": 1, "description": [ "Copies gathered scaler/vector attribute values from the Gather buckets into an array attribute", "PROTOTYPE DO NOT USE, Requires GatherPrototype" ], "uiName": "Get Gathered Attribute (Prototype)", "categories": ["internal"], "inputs": { "gatherId": { "type": "uint64", "description": "The GatherId of the Gather containing the attribute values" }, "name": { "type": "token", "description": "The name of the gathered attribute to join" } }, "outputs": { "value": { "type": "any", "description": "The gathered attribute values as an array", "unvalidated": true } }, "tests": [ { "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] ] }, "inputs": { "name": "_translate" }, "outputs": { "value": {"type": "pointd[3][]", "value": [[1,2,3],[4,5,6]]} } } ] } }
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)
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeVector3.ogn
{ "MakeVector3": { "version": 1, "description": [ "Merge 3 input values into a single output vector.", "If the inputs are arrays, the output will be an array of vectors." ], "uiName": "Make 3-Vector", "categories": ["math:conversion"], "tags": ["compose", "combine", "join"], "scheduling": ["threadsafe"], "inputs": { "x": { "type": ["double", "float", "half", "int", "double[]", "float[]", "half[]", "int[]"], "uiName": "X", "description": "The first component of the vector" }, "y": { "type": ["double", "float", "half", "int", "double[]", "float[]", "half[]", "int[]"], "uiName": "Y", "description": "The second component of the vector" }, "z": { "type": ["double", "float", "half", "int", "double[]", "float[]", "half[]", "int[]"], "uiName": "Z", "description": "The third component of the vector" } }, "outputs": { "tuple": { "type": ["double[3]", "float[3]", "half[3]", "int[3]", "double[3][]", "float[3][]", "half[3][]", "int[3][]"], "uiName": "Vector", "description": "Output 3-vector(s)" } }, "tests" : [ { "inputs:x": {"type": "float", "value": 42.0}, "inputs:y": {"type": "float", "value": 1.0}, "inputs:z": {"type": "float", "value": 0.0}, "outputs:tuple": {"type": "float[3]", "value": [42.0, 1.0, 0.0]} }, { "inputs:x": {"type": "float", "value": 42.0}, "outputs:tuple": {"type": "float[3]", "value": [42.0, 0.0, 0.0]} }, { "inputs:x": {"type": "float[]", "value": [42,1,0]}, "inputs:y": {"type": "float[]", "value": [0,1,2]}, "inputs:z": {"type": "float[]", "value": [0,2,4]}, "outputs:tuple": {"type": "float[3][]", "value": [[42,0,0],[1,1,2],[0,2,4]]} }, { "inputs:x": {"type": "int", "value": 42}, "inputs:y": {"type": "int", "value": -42}, "inputs:z": {"type": "int", "value": 5}, "outputs:tuple": {"type": "int[3]", "value": [42, -42, 5]} }, { "setup": { "create_nodes": [ ["TestNode", "omni.graph.nodes.MakeVector3"], ["ConstPoint3d", "omni.graph.nodes.ConstantPoint3d"] ], "connect": [ ["TestNode.outputs:tuple", "ConstPoint3d.inputs:value"] ] }, "inputs": { "x": {"type": "double", "value": 42.0}, "y": {"type": "double", "value": 1.0}, "z": {"type": "double", "value": 0.0} }, "outputs": { "tuple": {"type": "pointd[3]", "value": [42.0, 1.0, 0.0]} } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBundleInspector.ogn
{ "BundleInspector": { "version": 3, "description": [ "This node creates independent outputs containing information about the contents", "of a bundle attribute. It can be used for testing or debugging what is inside a", "bundle as it flows through the graph. The bundle is inspected recursively, so", "any bundles inside of the main bundle have their contents added to the output as well.", "The bundle contents can be printed when the node evaluates, and it passes the input straight", "through unchanged so you can insert this node between two nodes to inspect the data flowing", "through the graph." ], "metadata": { "uiName": "Bundle Inspector" }, "categories": ["bundle"], "inputs": { "bundle": { "type": "bundle", "description": "The attribute bundle to be inspected", "metadata": { "uiName": "Bundle To Analyze" } }, "print": { "type": "bool", "description": "Setting to true prints the contents of the bundle when the node evaluates", "metadata": { "uiName" : "Print Contents" } }, "inspectDepth": { "type": "int", "default": 1, "description": [ "The depth that the inspector is going to traverse and print.", "0 means just attributes on the input bundles. 1 means its immediate children. -1 means infinity." ], "metadata": { "uiName" : "Inspect Depth" } } }, "outputs": { "count": { "type": "uint64", "description": [ "Number of attributes present in the bundle. Every other output is an array that", "should have this number of elements in it." ], "metadata": { "uiName": "Attribute Count", "hidden": "true" } }, "attributeCount": { "type": "uint64", "description": [ "Number of attributes present in the bundle. Every other output is an array that", "should have this number of elements in it." ], "metadata": { "uiName": "Attribute Count" } }, "names": { "type": "token[]", "description": "List of the names of attributes present in the bundle", "metadata": { "uiName": "Attribute Names" } }, "types": { "type": "token[]", "description": "List of the types of attributes present in the bundle", "metadata": { "uiName": "Attribute Base Types" } }, "roles": { "type": "token[]", "description": "List of the names of the roles of attributes present in the bundle", "metadata": { "uiName": "Attribute Roles" } }, "arrayDepths": { "type": "int[]", "description": "List of the array depths of attributes present in the bundle", "metadata": { "uiName": "Array Depths" } }, "tupleCounts": { "type": "int[]", "description": "List of the tuple counts of attributes present in the bundle", "metadata": { "uiName": "Tuple Counts" } }, "values": { "type": "token[]", "description": "List of the bundled attribute values, converted to token format", "metadata": { "uiName": "Attribute Values" } }, "childCount": { "type": "uint64", "description": [ "Number of child bundles present in the bundle." ], "metadata": { "uiName": "Child Count" } }, "bundle": { "type": "bundle", "description": "The attribute bundle passed through as-is from the input bundle", "metadata": { "uiName": "Bundle Passthrough" } } }, "tests": [ { "outputs:count": 0, "outputs:names": [], "outputs:types": [], "outputs:roles": [], "outputs:arrayDepths": [], "outputs:tupleCounts": [], "outputs:values": [] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToString.ogn
{ "ToString": { "version": 1, "description": [ "Converts the given input to a string equivalent." ], "uiName": "To String", "categories": ["function"], "scheduling": ["threadsafe"], "inputs": { "value": { "type": "any", "uiName": "value", "description": [ "The value to be converted to a string.\n", "Numeric values are converted using C++'s std::ostringstream << operator. This can result in the values", "being converted to exponential form. E.g: 1.234e+06", "Arrays of numeric values are converted to Python list syntax. E.g: [1.5, -0.03]", "A uchar value is converted to a single, unquoted character.", "An array of uchar values is converted to an unquoted string. Avoid zero values (i.e. null chars) in the", "array as the behavior is undefined and may vary over time.", "A single token is converted to its unquoted string equivalent.", "An array of tokens is converted to Python list syntax with each token enclosed in double quotes. E.g. [\"first\", \"second\"]" ] } }, "outputs": { "converted": { "type": "string", "uiName": "String", "description": "Output string" } }, "tests" : [ { "inputs:value": {"type": "bool", "value": true}, "outputs:converted": "True" }, { "inputs:value": {"type": "double", "value": 2.1}, "outputs:converted": "2.1" }, { "inputs:value": {"type": "int", "value": 42}, "outputs:converted": "42" }, { "inputs:value": {"type": "double[3]", "value": [1.5, 2, 3] }, "outputs:converted": "[1.5, 2, 3]" }, { "inputs:value": {"type": "half[3]", "value": [2, 3.5, 4] }, "outputs:converted": "[2, 3.5, 4]" }, { "inputs:value": {"type": "int[2][]", "value": [[1, 2],[3, 4]] }, "outputs:converted": "[[1, 2], [3, 4]]" }, { "inputs:value": {"type": "uint64", "value": 42 }, "outputs:converted": "42" }, { "inputs:value": {"type": "uchar", "value": 65 }, "outputs:converted": "A" }, { "inputs:value": {"type": "uchar[]", "value": [ 65, 66, 67] }, "outputs:converted": "[A, B, C]" }, { "inputs:value": {"type": "string", "value": "ABC" }, "outputs:converted": "ABC" }, { "inputs:value": {"type": "token", "value": "Foo" }, "outputs:converted": "Foo" }, { "inputs:value": {"type": "token", "value": "" }, "outputs:converted": "" }, { "inputs:value": {"type": "token[]", "value": ["Foo","Bar"]}, "outputs:converted": "[\"Foo\", \"Bar\"]" } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBreakVector3.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 <OgnBreakVector3Database.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(OgnBreakVector3Database& db, size_t count = 1) { const auto vector = db.inputs.tuple().template get<Type[3]>(); const auto x = db.outputs.x().template get<Type>(); const auto y = db.outputs.y().template get<Type>(); const auto z = db.outputs.z().template get<Type>(); if (!vector || !x || !y || !z) return false; const auto pVector = vector.vectorized(count); const auto px = x.vectorized(count); const auto py = y.vectorized(count); const auto pz = z.vectorized(count); if (pVector.empty() || px.empty() || py.empty() || pz.empty()) return false; for (size_t i = 0; i < count; i++) { px[i] = pVector[i][0]; py[i] = pVector[i][1]; pz[i] = pVector[i][2]; } return true; } } // namespace // Node to break a 3-vector into it's component scalers class OgnBreakVector3 { public: static size_t computeVectorized(OgnBreakVector3Database& db, size_t count) { // Compute the components, if the types are all resolved. try { if (tryBreakVector<double>(db, count)) return count; else if (tryBreakVector<float>(db, count)) return true; else if (tryBreakVector<pxr::GfHalf>(db, count)) return count; else if (tryBreakVector<int32_t>(db, count)) return count; else { db.logWarning("Failed to resolve input types"); } } catch (const std::exception& e) { db.logError("Vector could not be broken: %s", e.what()); return 0; } return 0; } 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 z = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::z.token()); auto vectorType = vector.iAttribute->getResolvedType(vector); // Require inputs to be resolved before determining outputs' type if (vectorType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 4> attrs{ vector, x, y, z }; std::array<uint8_t, 4> tuples{ 3, 1, 1, 1}; std::array<uint8_t, 4> arrays{ 0, 0, 0, 0 }; std::array<AttributeRole, 4> roles{ vectorType.role, AttributeRole::eNone, AttributeRole::eNone, AttributeRole::eNone }; nodeObj.iNode->resolvePartiallyCoupledAttributes(nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size()); } } }; REGISTER_OGN_NODE(); } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayRemoveValue.ogn
{ "ArrayRemoveValue": { "version": 1, "description": [ "Removes the first occurrence of the given value from an array. If removeAll is true, removes all occurrences" ], "uiName": "Array Remove Value", "categories": ["math:array"], "scheduling": ["threadsafe"], "inputs": { "array": { "type": ["arrays", "bool[]"], "description": "The array to be modified", "uiName": "Array" }, "value": { "type": ["array_elements", "bool"], "description": "The value to be removed" }, "removeAll": { "type": "bool", "description": "If true, removes all occurences of the value.", "default": false } }, "outputs": { "array": { "type": ["arrays", "bool[]"], "description": "The modified array", "uiName": "Array" }, "found": { "type": "bool", "description": "true if a value was removed, false otherwise" } }, "tests": [ { "inputs:array": {"type": "int[]", "value": []}, "outputs:found": false, "inputs:removeAll": false, "inputs:value": {"type": "int", "value": 41}, "outputs:array": {"type": "int[]", "value": []} }, { "inputs:array": {"type": "int[]", "value": [41, 42, 41]}, "outputs:found": true, "inputs:removeAll": false, "inputs:value": {"type": "int", "value": 41}, "outputs:array": {"type": "int[]", "value": [42, 41]} }, { "inputs:array": {"type": "int[]", "value": [41, 42, 43, 41]}, "outputs:found": true, "inputs:removeAll": true, "inputs:value": {"type": "int", "value": 41}, "outputs:array": {"type": "int[]", "value": [42, 43]} }, { "inputs:array": {"type": "int[]", "value": [41, 41, 41, 41]}, "outputs:found": true, "inputs:removeAll": true, "inputs:value": {"type": "int", "value": 41}, "outputs:array": {"type": "int[]", "value": []} }, { "inputs:array": {"type": "token[]", "value": ["FOOD", "BARFOOD", "BAZ"]}, "outputs:found": false, "inputs:value": {"type": "token", "value":"FOO"}, "inputs:removeAll": false, "outputs:array": {"type": "token[]", "value": ["FOOD", "BARFOOD", "BAZ"]} }, { "inputs:array": {"type": "token[]", "value": ["FOOD", "BARFOOD", "BAZ"]}, "outputs:found": true, "inputs:value": {"type": "token", "value":"FOOD"}, "inputs:removeAll": false, "outputs:array": {"type": "token[]", "value": ["BARFOOD", "BAZ"]} }, { "inputs:array": {"type": "int64[]", "value": [41, 42]}, "outputs:found": true, "inputs:value": {"type": "int64", "value":41}, "inputs:removeAll": false, "outputs:array": {"type": "int64[]", "value": [42]} }, { "inputs:array": {"type": "uchar[]", "value": [41, 42]}, "outputs:found": true, "inputs:value": {"type": "uchar", "value":41}, "inputs:removeAll": false, "outputs:array": {"type": "uchar[]", "value": [42]} }, { "inputs:array": {"type": "uint[]", "value": [41, 42]}, "outputs:found": true, "inputs:value": {"type": "uint", "value":42}, "inputs:removeAll": false, "outputs:array": {"type": "uint[]", "value": [41]} }, { "inputs:array": {"type": "uint64[]", "value": [41, 42]}, "outputs:found": true, "inputs:value": {"type": "uint64", "value":42}, "inputs:removeAll": false, "outputs:array": {"type": "uint64[]", "value": [41]} }, { "inputs:array": {"type": "bool[]", "value": [false, true]}, "outputs:found": true, "inputs:value": {"type": "bool", "value":false}, "inputs:removeAll": false, "outputs:array": {"type": "bool[]", "value": [true]} }, { "inputs:array": {"type": "half[2][]", "value": [[1, 2], [3, 4]]}, "outputs:found": true, "inputs:value": {"type": "half[2]", "value":[1, 2]}, "inputs:removeAll": false, "outputs:array": {"type": "half[2][]", "value": [[3, 4]]} }, { "inputs:array": {"type": "double[2][]", "value": [[1, 2], [3, 4], [5, 6]]}, "outputs:found": true, "inputs:value": {"type": "double[2]", "value":[1, 2]}, "inputs:removeAll": false, "outputs:array": {"type": "double[2][]", "value": [[3, 4], [5, 6]]} }, { "inputs:array": {"type": "double[2][]", "value": [[1, 2], [3, 4], [5, 6], [1, 2]]}, "outputs:found": true, "inputs:value": {"type": "double[2]", "value":[1, 2]}, "inputs:removeAll": true, "outputs:array": {"type": "double[2][]", "value": [[3, 4], [5, 6]]} }, { "inputs:array": {"type": "double[3][]", "value": [[1.1, 2.1, 1.0], [3, 4, 5]]}, "outputs:found": true, "inputs:value": {"type": "double[3]", "value":[3, 4, 5]}, "inputs:removeAll": false, "outputs:array": {"type": "double[3][]", "value": [[1.1, 2.1, 1.0]]} }, { "inputs:array": {"type": "double[3][]", "value": [[1.1, 2.1, 1.0], [3, 4, 5]]}, "outputs:found": false, "inputs:value": {"type": "double[3]", "value":[3.1, 4, 5]}, "inputs:removeAll": false, "outputs:array": {"type": "double[3][]", "value": [[1.1, 2.1, 1.0], [3, 4, 5]]} }, { "inputs:array": {"type": "int[4][]", "value": [[1, 2, 3, 4], [3, 4, 5, 6]]}, "outputs:found": true, "inputs:value": {"type": "int[4]", "value":[1, 2, 3, 4]}, "inputs:removeAll": false, "outputs:array": {"type": "int[4][]", "value": [[3, 4, 5, 6]]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArraySetIndex.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 <OgnArraySetIndexDatabase.h> #include <omni/graph/core/StringUtils.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <algorithm> 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) // This will throw if the wrapped index is greater than arraySize when resizeToFit is false, // or if the wrapped index is negative. size_t tryWrapIndex(int index, size_t arraySize, bool resizeToFit) { int wrappedIndex = index; if (index < 0) wrappedIndex = static_cast<int>(arraySize) + index; if ((wrappedIndex >= static_cast<int>(arraySize) && !resizeToFit) || wrappedIndex < 0) throw ogn::compute::InputError(formatString("inputs:index %d is out of range for inputs:array of size %zu", wrappedIndex, arraySize)); return static_cast<size_t>(wrappedIndex); } template<typename BaseType> bool tryComputeAssumingType(OgnArraySetIndexDatabase& db) { auto inputArray = db.inputs.array().template get<BaseType[]>(); size_t const inputArraySize = db.inputs.array().size(); size_t const index = tryWrapIndex(db.inputs.index(), inputArraySize, db.inputs.resizeToFit()); auto const value = db.inputs.value().template get<BaseType>(); auto outputArray = db.outputs.array().template get<BaseType[]>(); if (!value || !inputArray) return false; // tryWrapIndex would have thrown already if index >= inputArraySize and resizeToFit is false size_t outputArraySize = std::max(inputArraySize, index + 1); (*outputArray).resize(outputArraySize); memcpy(outputArray->data(), inputArray->data(), sizeof(BaseType) * inputArraySize); if (outputArraySize > inputArraySize) memset(&((*outputArray)[inputArraySize]), 0, sizeof(BaseType) * (outputArraySize - inputArraySize)); memcpy(&((*outputArray)[index]), &*value, sizeof(BaseType)); return true; } } // namespace class OgnArraySetIndex { public: static bool compute(OgnArraySetIndexDatabase& 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 outputArray = node.iNode->getAttributeByToken(node, outputs::array.token()); auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray); if (inputArrayType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 3> attrs { inputArray, inputValue, outputArray }; // all should have the same tuple count std::array<uint8_t, 3> tupleCounts { inputArrayType.componentCount, inputArrayType.componentCount, inputArrayType.componentCount }; // value type can not be an array because we don't support arrays-of-arrays std::array<uint8_t, 3> arrayDepths { 1, 0, 1 }; std::array<AttributeRole, 3> rolesBuf { inputArrayType.role, AttributeRole::eUnknown, 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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetRelativePath.ogn
{ "GetRelativePath": { "version": 1, "description": ["Generates a path token relative to anchor from path.(ex. (/World, /World/Cube) -> /Cube)"], "uiName": "Get Relative Path", "categories": ["sceneGraph"], "scheduling": [ "threadsafe" ], "inputs": { "anchor": { "type": "token", "description": "Path token to compute relative to (ex. /World)" }, "path": { "type": ["token", "token[]"], "description": "Path token to convert to a relative path (ex. /World/Cube)" } }, "outputs": { "relativePath": { "type": ["token", "token[]"], "description": "Relative path token (ex. /Cube)" } }, "state": { "anchor": { "type": "token", "description": "Snapshot of previously seen rootPath" }, "path": { "type": "token", "description": "Snapshot of previously seen path" } }, "tests": [ { "inputs:anchor": "/World", "inputs:path": { "type": "token", "value": "/World" }, "outputs:relativePath": { "type": "token", "value": "." } }, { "inputs:anchor": "/World", "inputs:path": { "type": "token", "value": "/World/foo" }, "outputs:relativePath": { "type": "token", "value": "foo" } }, { "inputs:anchor": "/World", "inputs:path": { "type": "token", "value": "/World/foo/bar" }, "outputs:relativePath": { "type": "token", "value": "foo/bar" } }, { "inputs:anchor": "/World", "inputs:path": { "type": "token", "value": "/World/foo/bar.attrib" }, "outputs:relativePath": { "type": "token", "value": "foo/bar.attrib" } }, { "inputs:anchor": "/World", "inputs:path": { "type": "token[]", "value": [ "/World/foo", "/World/bar" ] }, "outputs:relativePath": { "type": "token[]", "value": [ "foo", "bar" ] } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeVector4.ogn
{ "MakeVector4": { "version": 1, "description": [ "Merge 4 input values into a single output vector.", "If the inputs are arrays, the output will be an array of vectors." ], "uiName": "Make 4-Vector", "categories": ["math:conversion"], "tags": ["compose", "combine", "join"], "scheduling": ["threadsafe"], "inputs": { "x": { "type": ["double", "float", "half", "int", "double[]", "float[]", "half[]", "int[]"], "uiName": "X", "description": "The first component of the vector" }, "y": { "type": ["double", "float", "half", "int", "double[]", "float[]", "half[]", "int[]"], "uiName": "Y", "description": "The second component of the vector" }, "z": { "type": ["double", "float", "half", "int", "double[]", "float[]", "half[]", "int[]"], "uiName": "Z", "description": "The third component of the vector" }, "w": { "type": ["double", "float", "half", "int", "double[]", "float[]", "half[]", "int[]"], "uiName": "W", "description": "The fourth component of the vector" } }, "outputs": { "tuple": { "type": ["double[4]", "float[4]", "half[4]", "int[4]", "double[4][]", "float[4][]", "half[4][]", "int[4][]"], "uiName": "Vector", "description": "Output 4-vector" } }, "tests" : [ { "inputs:x": {"type": "float", "value": 42.0}, "inputs:y": {"type": "float", "value": 1.0}, "inputs:z": {"type": "float", "value": 0}, "inputs:w": {"type": "float", "value": 0}, "outputs:tuple": {"type": "float[4]", "value": [42.0, 1.0, 0.0, 0.0]} }, { "inputs:x": {"type": "float", "value": 42.0}, "outputs:tuple": {"type": "float[4]", "value": [42.0, 0.0, 0.0, 0.0]} }, { "inputs:x": {"type": "float[]", "value": [42,1,0]}, "inputs:y": {"type": "float[]", "value": [0,1,2]}, "inputs:z": {"type": "float[]", "value": [0,2,4]}, "inputs:w": {"type": "float[]", "value": [5,6,7]}, "outputs:tuple": {"type": "float[4][]", "value": [[42,0,0,5],[1,1,2,6],[0,2,4,7]]} }, { "inputs:x": {"type": "int", "value": 42}, "inputs:y": {"type": "int", "value": -42}, "inputs:z": {"type": "int", "value": 5}, "inputs:w": {"type": "int", "value": 6}, "outputs:tuple": {"type": "int[4]", "value": [42, -42, 5, 6]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayRemoveIndex.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 <OgnArrayRemoveIndexDatabase.h> #include <omni/graph/core/StringUtils.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <algorithm> 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) // This will throw if the wrapped index is out of bounds size_t tryWrapIndex(int index, size_t arraySize) { int wrappedIndex = index; if (index < 0) wrappedIndex = static_cast<int>(arraySize) + index; if (wrappedIndex < 0 || wrappedIndex >= static_cast<int>(arraySize)) throw ogn::compute::InputError(formatString("inputs:index %d is out of range for inputs:array of size %zu", wrappedIndex, arraySize)); return static_cast<size_t>(wrappedIndex); } template<typename BaseType> bool tryComputeAssumingType(OgnArrayRemoveIndexDatabase& db) { auto const inputArray = db.inputs.array().template get<BaseType[]>(); size_t const inputArraySize = db.inputs.array().size(); size_t const index = tryWrapIndex(db.inputs.index(), inputArraySize); if (!inputArray) return false; // make sure the types match before copying input into output if (db.inputs.array().type() != db.outputs.array().type()) { auto attribute = db.abi_node().iNode->getAttributeByToken(db.abi_node(), outputs::array.m_token); auto handle = db.outputs.array().abi_handle(); attribute.iAttribute->setResolvedType(attribute, db.inputs.array().type()); db.outputs.array().reset(db.abi_context(), handle, attribute); } db.outputs.array().copyData(db.inputs.array()); auto outputArray = db.outputs.array().template get<BaseType[]>(); memcpy(outputArray->data() + index, outputArray->data() + index + 1, sizeof(BaseType) * (inputArraySize - index - 1)); (*outputArray).resize(inputArraySize - 1); return true; } } // namespace class OgnArrayRemoveIndex { public: static bool compute(OgnArrayRemoveIndexDatabase& 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); } 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); } 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); } 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); } ; 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 outputArray = node.iNode->getAttributeByToken(node, outputs::array.token()); auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray); if (inputArrayType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 2> attrs { inputArray, outputArray }; // 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, 1 }; 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
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayResize.ogn
{ "ArrayResize": { "version": 1, "description": [ "Resizes an array. If the new size is larger, zeroed values will be added to the end." ], "uiName": "Array Resize", "categories": ["math:array"], "scheduling": ["threadsafe"], "inputs": { "array": { "type": ["arrays", "bool[]"], "description": "The array to be modified", "uiName": "Array" }, "newSize": { "type": "int", "description": "The new size of the array, negative values are treated as size of 0", "minimum": 0 } }, "outputs": { "array": { "type": ["arrays", "bool[]"], "description": "The modified array", "uiName": "Array" } }, "tests": [ { "inputs:array": {"type": "int[]", "value": [41, 42]}, "inputs:newSize": 0, "outputs:array": {"type": "int[]", "value": []} }, { "inputs:array": {"type": "int64[]", "value": []}, "inputs:newSize": 1, "outputs:array": {"type": "int64[]", "value": [0]} }, { "inputs:array": {"type": "int[]", "value": [41, 42]}, "inputs:newSize": 1, "outputs:array": {"type": "int[]", "value": [41]} }, { "inputs:array": {"type": "bool[]", "value": [true, true]}, "inputs:newSize": 1, "outputs:array": {"type": "bool[]", "value": [true]} }, { "inputs:array": {"type": "half[2][]", "value": [[1, 2], [3, 4]]}, "inputs:newSize": 3, "outputs:array": {"type": "half[2][]", "value": [[1, 2], [3, 4], [0, 0]]} }, { "inputs:array": {"type": "half[2][]", "value": []}, "inputs:newSize": 1, "outputs:array": {"type": "half[2][]", "value": [[0, 0]]} }, { "inputs:array": {"type": "float[2][]", "value": [[1, 2], [3, 4]]}, "inputs:newSize": 3, "outputs:array": {"type": "float[2][]", "value": [[1, 2], [3, 4], [0, 0]]} }, { "inputs:array": {"type": "token[]", "value": ["41", "42"]}, "inputs:newSize": 1, "outputs:array": {"type": "token[]", "value": ["41"]} }, { "inputs:array": {"type": "token[]", "value": ["41", "42"]}, "inputs:newSize": 2, "outputs:array": {"type": "token[]", "value": ["41", "42"]} } ] } }
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
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(); } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayGetSize.ogn
{ "ArrayGetSize": { "version": 1, "description": [ "Returns the number of elements in an array" ], "uiName": "Array Get Size", "categories": ["math:array"], "scheduling": ["threadsafe"], "inputs": { "array": { "type": ["arrays", "bool[]"], "description": "The array in question", "uiName": "Array" } }, "outputs": { "size": { "type": "int", "description": "The size of the array" } }, "tests": [ { "inputs:array": {"type": "int[]", "value": [41, 42]}, "outputs:size": 2 }, { "inputs:array": {"type": "half[]", "value": [41, 42]}, "outputs:size": 2 }, { "inputs:array": {"type": "token[]", "value": []}, "outputs:size": 0 }, { "inputs:array": {"type": "int64[]", "value": [41]}, "outputs:size": 1 }, { "inputs:array": {"type": "uchar[]", "value": [41, 42]}, "outputs:size": 2 }, { "inputs:array": {"type": "uint[]", "value": [41, 42]}, "outputs:size": 2 }, { "inputs:array": {"type": "uint64[]", "value": [41, 42]}, "outputs:size": 2 }, { "inputs:array": {"type": "bool[]", "value": [false, true]}, "outputs:size": 2 }, { "inputs:array": {"type": "half[2][]", "value": [[41, 42], [43, 44]]}, "outputs:size": 2 }, { "inputs:array": {"type": "double[3][]", "value": [[41, 42, 43], [43, 44, 56]]}, "outputs:size": 2 }, { "inputs:array": {"type": "int[4][]", "value": [[1, 2, 3, 4], [3, 4, 5, 6]]}, "outputs:size": 2 } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimPaths.ogn
{ "GetPrimPaths": { "version": 1, "description": ["Generates a path array from the specified relationship. This is useful when absolute prim paths may change."], "uiName": "Get Prim Paths", "categories": ["sceneGraph"], "scheduling": [ "threadsafe" ], "inputs": { "prims": { "type": "target", "description": "Relationship to prims on the stage", "metadata": { "allowMultiInputs" : 1 } } }, "outputs": { "primPaths": { "type": "token[]", "description": "The absolute paths of the given prims as a token array" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayFill.ogn
{ "ArrayFill": { "version": 1, "description": [ "Creates a copy of the input array, filled with the given value" ], "uiName": "Array Fill", "categories": ["math:array"], "scheduling": ["threadsafe"], "inputs": { "array": { "type": ["arrays", "bool[]"], "description": "The array to be modified" }, "fillValue": { "type": ["array_elements", "bool"], "description": "The value to be repeated in the new array" } }, "outputs": { "array": { "type": ["arrays", "bool[]"], "description": "The modified array" } }, "tests": [ { "inputs:array": {"type": "int[]", "value": [41, 42]}, "inputs:fillValue": {"type": "int", "value": 0}, "outputs:array": {"type": "int[]", "value": [0, 0]} }, { "inputs:array": {"type": "int[2][]", "value": [[41, 42], [43,44]]}, "inputs:fillValue": {"type": "int[2]", "value": [1,2]}, "outputs:array": {"type": "int[2][]", "value": [[1, 2], [1,2]]} }, { "inputs:array": {"type": "int64[]", "value": [41, 42]}, "inputs:fillValue": {"type": "int64", "value":0}, "outputs:array": {"type": "int64[]", "value": [0, 0]} }, { "inputs:array": {"type": "uchar[]", "value": [41, 42]}, "inputs:fillValue": {"type": "uchar", "value":0}, "outputs:array": {"type": "uchar[]", "value": [0, 0]} }, { "inputs:array": {"type": "uint[]", "value": [41, 42]}, "inputs:fillValue": {"type": "uint", "value":0}, "outputs:array": {"type": "uint[]", "value": [0, 0]} }, { "inputs:array": {"type": "uint64[]", "value": [41, 42]}, "inputs:fillValue": {"type": "uint64", "value":0}, "outputs:array": {"type": "uint64[]", "value": [0, 0]} }, { "inputs:array": {"type": "bool[]", "value": [true, true]}, "inputs:fillValue": {"type": "bool", "value":false}, "outputs:array": {"type": "bool[]", "value": [false, false]} }, { "inputs:array": {"type": "token[]", "value": ["41", "42"]}, "inputs:fillValue": {"type": "token", "value":""}, "outputs:array": {"type": "token[]", "value": ["", ""]} }, { "inputs:array": {"type": "half[2][]", "value": [[1.0, 2.0], [3.0, 4.0]]}, "inputs:fillValue": {"type": "half[2]", "value":[5.0, 6.0]}, "outputs:array": {"type": "half[2][]", "value": [[5.0, 6.0], [5.0, 6.0]]} }, { "inputs:array": {"type": "double[3][]", "value": [[1.0, 2.0, 3.0], [3.0, 4.0, 5.0]]}, "inputs:fillValue": {"type": "double[3]", "value":[5.0, 6.0, 7.0]}, "outputs:array": {"type": "double[3][]", "value": [[5.0, 6.0, 7.0], [5.0, 6.0, 7.0]]} }, { "inputs:array": {"type": "int[4][]", "value": [[1, 2, 3, 4], [3, 4, 5, 6]]}, "inputs:fillValue": {"type": "int[4]", "value":[5, 6, 7, 8]}, "outputs:array": {"type": "int[4][]", "value": [[5, 6, 7, 8], [5, 6, 7, 8]]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToHalf.ogn
{ "ToHalf": { "version": 1, "description": ["Converts the given input to 16 bit float. The node will attempt to convert", " array and tuple inputs to halfs of the same shape" ], "uiName": "To Half", "categories": ["math:conversion"], "scheduling": ["threadsafe"], "inputs": { "value": { "type": ["numerics", "bool", "bool[]"], "uiName": "value", "description": "The numeric value to convert to half" } }, "outputs": { "converted": { "type": ["half", "half[2]", "half[3]", "half[4]", "half[]", "half[2][]", "half[3][]", "half[4][]"], "uiName": "Half", "description": "Output half scaler or array" } }, "tests" : [ { "inputs:value": {"type": "float[]", "value": [] }, "outputs:converted": {"type": "half[]", "value": []} }, { "inputs:value": {"type": "double", "value": 2.5}, "outputs:converted": {"type": "half", "value": 2.5} }, { "inputs:value": {"type": "int", "value": 42}, "outputs:converted": {"type": "half", "value": 42.0} }, { "inputs:value": {"type": "double[2]", "value": [2.5, 2.5] }, "outputs:converted": {"type": "half[2]", "value": [2.5, 2.5]} }, { "inputs:value": {"type": "half[3]", "value": [2, 3, 4] }, "outputs:converted": {"type": "half[3]", "value": [2, 3, 4] } }, { "inputs:value": {"type": "half[3][]", "value": [[2, 3, 4]] }, "outputs:converted": {"type": "half[3][]", "value": [[2, 3, 4]] } }, { "inputs:value": {"type": "int[2][]", "value": [[1, 2],[3, 4]] }, "outputs:converted": {"type": "half[2][]", "value": [[1.0, 2.0],[3.0, 4.0]] } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayFill.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 <OgnArrayFillDatabase.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 { // Custom implementation of std::rotate. // Using std::fill fails to build on Linux when the underlying type is a tuple (eg int[3]) template< class ForwardIt, class T > void fillArray(ForwardIt first, ForwardIt last, const T& value) { for (; first != last; ++first) { memcpy(&*first, &value, sizeof(*first)); } } template<typename BaseType> bool tryComputeAssumingType(OgnArrayFillDatabase& db) { auto const inputArray = db.inputs.array().template get<BaseType[]>(); size_t const inputArraySize = db.inputs.array().size(); auto const fillValue = db.inputs.fillValue().template get<BaseType>(); auto outputArray = db.outputs.array().template get<BaseType[]>(); if (!fillValue || !inputArray) return false; (*outputArray).resize(inputArraySize); fillArray(outputArray->begin(), outputArray->end(), *fillValue); return true; } } // namespace class OgnArrayFill { public: static bool compute(OgnArrayFillDatabase& db) { auto& inputType = db.inputs.fillValue().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 inputFillValue = node.iNode->getAttributeByToken(node, inputs::fillValue.token()); auto const outputArray = node.iNode->getAttributeByToken(node, outputs::array.token()); auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray); if (inputArrayType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 3> attrs { inputArray, inputFillValue, outputArray }; // all should have the same tuple count std::array<uint8_t, 3> tupleCounts { inputArrayType.componentCount, inputArrayType.componentCount, inputArrayType.componentCount }; // value type can not be an array because we don't support arrays-of-arrays std::array<uint8_t, 3> arrayDepths { 1, 0, 1 }; std::array<AttributeRole, 3> rolesBuf { inputArrayType.role, AttributeRole::eUnknown, 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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayRemoveValue.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 <OgnArrayRemoveValueDatabase.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 { // Custom implementation of std::remove_if. // Using std::remove_if fails to build when the underlying type is a tuple (eg int[3]) template<class ForwardIt, class UnaryPredicate> int removeArray(ForwardIt first, ForwardIt last, UnaryPredicate p) { int outputArraySize = 0; first = std::find_if(first, last, p); if (first != last) { for(ForwardIt i = first; ++i != last; ) { if (!p(*i)) { memcpy(&*first++, &*i, sizeof(*first)); outputArraySize++; } } } return outputArraySize; } template<typename BaseType> bool tryComputeAssumingType(OgnArrayRemoveValueDatabase& db) { auto const inputArray = db.inputs.array().template get<BaseType[]>(); auto const value = db.inputs.value().template get<BaseType>(); bool const removeAll = db.inputs.removeAll(); size_t const inputArraySize = db.inputs.array().size(); size_t const stride = sizeof(BaseType); db.outputs.found() = false; if (!value || !inputArray) return false; // make sure the types match before copying input into output if (db.inputs.array().type() != db.outputs.array().type()) { auto attribute = db.abi_node().iNode->getAttributeByToken(db.abi_node(), outputs::array.m_token); auto handle = db.outputs.array().abi_handle(); attribute.iAttribute->setResolvedType(attribute, db.inputs.array().type()); db.outputs.array().reset(db.abi_context(), handle, attribute); } db.outputs.array().copyData(db.inputs.array()); auto equalsValue = [&value, &stride](auto &i) { return memcmp(&i, &*value, stride) == 0; }; auto const it = std::find_if(inputArray->begin(), inputArray->end(), equalsValue); if (it == inputArray->end()){ return true; } auto outputArray = db.outputs.array().template get<BaseType[]>(); if (removeAll) { const int outputArraySize = removeArray(outputArray->begin(), outputArray->end(), equalsValue); (*outputArray).resize(outputArraySize); } else { const int index = static_cast<int>(it - inputArray->begin()); memcpy(outputArray->data() + index, outputArray->data() + index + 1, stride * (inputArraySize - index - 1)); (*outputArray).resize(inputArraySize - 1); } db.outputs.found() = true; return true; } } // namespace class OgnArrayRemoveValue { public: static bool compute(OgnArrayRemoveValueDatabase& 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 outputArray = node.iNode->getAttributeByToken(node, outputs::array.token()); auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray); if (inputArrayType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 3> attrs { inputArray, inputValue, outputArray }; // all should have the same tuple count std::array<uint8_t, 3> tupleCounts { inputArrayType.componentCount, inputArrayType.componentCount, inputArrayType.componentCount }; // value type can not be an array because we don't support arrays-of-arrays std::array<uint8_t, 3> arrayDepths { 1, 0, 1 }; std::array<AttributeRole, 3> rolesBuf { inputArrayType.role, AttributeRole::eUnknown, 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
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayRemoveIndex.ogn
{ "ArrayRemoveIndex": { "version": 1, "description": [ "Removes an element of an array by index. If the given index is negative it will be an offset from the end of the array." ], "uiName": "Array Remove Index", "categories": ["math:array"], "scheduling": ["threadsafe"], "inputs": { "array": { "type": ["arrays", "bool[]"], "description": "The array to be modified", "uiName": "Array" }, "index": { "type": "int", "description": "The index into the array, a negative value indexes from the end of the array", "uiName": "Index" } }, "outputs": { "array": { "type": ["arrays", "bool[]"], "description": "The modified array", "uiName": "Array" } }, "tests": [ { "inputs:array": {"type": "int[]", "value": [41, 42]}, "inputs:index": 0, "outputs:array": {"type": "int[]", "value": [42]} }, { "inputs:array": {"type": "bool[]", "value": [true, false]}, "inputs:index": 0, "outputs:array": {"type": "bool[]", "value": [false]} }, { "inputs:array": {"type": "half[2][]", "value": [[1, 2], [3, 4]]}, "inputs:index": 1, "outputs:array": {"type": "half[2][]", "value": [[1, 2]]} }, { "inputs:array": {"type": "token[]", "value": ["41", "42"]}, "inputs:index": -2, "outputs:array": {"type": "token[]", "value": ["42"]} }, { "inputs:array": {"type": "int[]", "value": [41, 42, 43, 41]}, "inputs:index": 1, "outputs:array": {"type": "int[]", "value": [41, 43, 41]} } ] } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToUint64.ogn
{ "ToUint64": { "version": 1, "description": [ "Converts the given input to a 64 bit unsigned integer of the same shape.", "Negative integers are converted by adding them to 2**64, decimal numbers are truncated." ], "uiName": "To Uint64", "categories": ["math:conversion"], "scheduling": ["threadsafe"], "inputs": { "value": { "type": ["bool", "int", "uint", "int64", "float", "double", "half", "uchar", "bool[]", "int[]", "uint[]", "int64[]", "float[]", "double[]", "half[]", "uchar[]"], "uiName": "value", "description": "The numeric value to convert to uint64" } }, "outputs": { "converted": { "type": ["uint64","uint64[]"], "uiName": "Uint64", "description": "Converted output" } }, "tests" : [ { "inputs:value": {"type": "float[]", "value": [] }, "outputs:converted": {"type": "uint64[]", "value": []} }, { "inputs:value": {"type": "double", "value": 2.1}, "outputs:converted": {"type": "uint64", "value": 2} }, { "inputs:value": {"type": "half", "value": 2.9}, "outputs:converted": {"type": "uint64", "value": 2} }, { "inputs:value": {"type": "int", "value": 42}, "outputs:converted": {"type": "uint64", "value": 42} }, { "inputs:value": {"type": "int64", "value": 42}, "outputs:converted": {"type": "uint64", "value": 42} }, { "inputs:value": {"type": "bool[]", "value": [true, false]}, "outputs:converted": {"type": "uint64[]", "value": [1, 0]} }, { "inputs:value": {"type": "half[]", "value": [2, 3, 4] }, "outputs:converted": {"type": "uint64[]", "value": [2, 3, 4] } }, { "inputs:value": {"type": "uint[]", "value": [2, 3, 4] }, "outputs:converted": {"type": "uint64[]", "value": [2, 3, 4] } }, { "inputs:value": {"type": "int64[]", "value": [2, 3, -4] }, "outputs:converted": {"type": "uint64[]", "value": [2, 3, 18446744073709551612] } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToFloat.ogn
{ "ToFloat": { "version": 1, "description": ["Converts the given input to 32 bit float. The node will attempt to convert", " array and tuple inputs to floats of the same shape" ], "uiName": "To Float", "categories": ["math:conversion"], "scheduling": ["threadsafe"], "inputs": { "value": { "type": ["numerics", "bool", "bool[]"], "uiName": "value", "description": "The numeric value to convert to float" } }, "outputs": { "converted": { "type": ["float", "float[2]", "float[3]", "float[4]", "float[]", "float[2][]", "float[3][]", "float[4][]"], "uiName": "Float", "description": "Output float scaler or array" } }, "tests" : [ { "inputs:value": {"type": "float[]", "value": [] }, "outputs:converted": {"type": "float[]", "value": []} }, { "inputs:value": {"type": "double", "value": 2.1}, "outputs:converted": {"type": "float", "value": 2.1} }, { "inputs:value": {"type": "int", "value": 42}, "outputs:converted": {"type": "float", "value": 42.0} }, { "inputs:value": {"type": "double[2]", "value": [2.1, 2.1] }, "outputs:converted": {"type": "float[2]", "value": [2.1, 2.1]} }, { "inputs:value": {"type": "half[3]", "value": [2, 3, 4] }, "outputs:converted": {"type": "float[3]", "value": [2, 3, 4] } }, { "inputs:value": {"type": "half[3][]", "value": [[2, 3, 4]] }, "outputs:converted": {"type": "float[3][]", "value": [[2, 3, 4]] } }, { "inputs:value": {"type": "int[2][]", "value": [[1, 2],[3, 4]] }, "outputs:converted": {"type": "float[2][]", "value": [[1.0, 2.0],[3.0, 4.0]] } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBreakVector4.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 <OgnBreakVector4Database.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(OgnBreakVector4Database& db) { const auto vector = db.inputs.tuple().template get<Type[4]>(); auto x = db.outputs.x().template get<Type>(); auto y = db.outputs.y().template get<Type>(); auto z = db.outputs.z().template get<Type>(); auto w = db.outputs.w().template get<Type>(); if (!vector || !x || !y || !z || !w){ return false; } *x = (*vector)[0]; *y = (*vector)[1]; *z = (*vector)[2]; *w = (*vector)[3]; return true; } } // namespace // Node to break a 4-vector into it's component scalers class OgnBreakVector4 { public: static bool compute(OgnBreakVector4Database& 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 z = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::z.token()); auto w = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::w.token()); auto vectorType = vector.iAttribute->getResolvedType(vector); // Require inputs to be resolved before determining outputs' type if (vectorType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 5> attrs{ vector, x, y, z, w }; std::array<uint8_t, 5> tuples{ 4, 1, 1, 1, 1}; std::array<uint8_t, 5> arrays{ 0, 0, 0, 0, 0 }; std::array<AttributeRole, 5> roles{ vectorType.role, AttributeRole::eNone, AttributeRole::eNone, AttributeRole::eNone, AttributeRole::eNone}; nodeObj.iNode->resolvePartiallyCoupledAttributes(nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size()); } } }; REGISTER_OGN_NODE(); } } }
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayResize.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 <OgnArrayResizeDatabase.h> #include <omni/graph/core/StringUtils.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <algorithm> namespace omni { namespace graph { namespace nodes { using core::ogn::array; // unnamed namespace to avoid multiple declaration when linking namespace { template<typename BaseType> bool tryComputeAssumingType(OgnArrayResizeDatabase& db) { auto const inputArray = db.inputs.array().template get<BaseType[]>(); size_t const inputArraySize = db.inputs.array().size(); size_t newSize = db.inputs.newSize(); auto outputArray = db.outputs.array().template get<BaseType[]>(); if (!inputArray) return false; if (newSize < 0) newSize = 0; (*outputArray).resize(newSize); memcpy(outputArray->data(), inputArray->data(), sizeof(BaseType) * (std::min(inputArraySize, newSize))); if (newSize > inputArraySize) memset(outputArray->data() + inputArraySize, 0, sizeof(BaseType) * (newSize - inputArraySize)); return true; } } // namespace class OgnArrayResize { public: static bool compute(OgnArrayResizeDatabase& 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 inputArray = node.iNode->getAttributeByToken(node, inputs::array.token()); auto const outputArray = node.iNode->getAttributeByToken(node, outputs::array.token()); auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray); if (inputArrayType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 2> attrs { inputArray, outputArray }; // all should have the same tuple count std::array<uint8_t, 3> 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, 1 }; 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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBreakVector4.ogn
{ "BreakVector4": { "version": 1, "description": ["Split vector into 4 component values."], "uiName": "Break 4-Vector", "categories": ["math:conversion"], "tags": ["decompose", "separate", "isolate"], "scheduling": ["threadsafe"], "inputs": { "tuple": { "type": ["double[4]", "float[4]", "half[4]", "int[4]"], "uiName": "Vector", "description": "4-vector to be broken" } }, "outputs": { "x": { "type": ["double", "float", "half", "int"], "uiName": "X", "description": "The first component of the vector" }, "y": { "type": ["double", "float", "half", "int"], "uiName": "Y", "description": "The second component of the vector" }, "z": { "type": ["double", "float", "half", "int"], "uiName": "Z", "description": "The third component of the vector" }, "w": { "type": ["double", "float", "half", "int"], "uiName": "W", "description": "The fourth component of the vector" } }, "tests" : [ { "inputs:tuple": {"type": "float[4]", "value": [42.0, 1.0, 2.0, 3.0]}, "outputs:x": {"type": "float", "value": 42.0}, "outputs:y": {"type": "float", "value": 1.0}, "outputs:z": {"type": "float", "value": 2.0}, "outputs:w": {"type": "float", "value": 3.0} }, { "inputs:tuple": {"type": "int[4]", "value": [42, -42, 5, -5]}, "outputs:x": {"type": "int", "value": 42}, "outputs:y": {"type": "int", "value": -42}, "outputs:z": {"type": "int", "value": 5}, "outputs:w": {"type": "int", "value": -5} }, { "inputs:tuple": {"type": "quatd[4]", "value": [42.0, 1.0, 2.0, 3.0]}, "outputs:x": {"type": "double", "value": 42.0}, "outputs:y": {"type": "double", "value": 1.0}, "outputs:z": {"type": "double", "value": 2.0}, "outputs:w": {"type": "double", "value": 3.0} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnConstantPrims.ogn
{ "ConstantPrims": { "version": 2, "description": ["Returns the paths of one or more targetd prims"], "uiName": "Constant Prims", "categories": ["sceneGraph"], "scheduling": [ "threadsafe" ], "inputs": { "value": { "type": "target", "description": "The input prim paths", "metadata": { "outputOnly": "1", "allowMultiInputs": "1" } } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnSetVariantSelection.ogn
{ "SetVariantSelection": { "version": 2, "categories": [ "graph:action", "sceneGraph", "variants" ], "icon": { "path": "Variant.svg" }, "scheduling": [ "usd-write" ], "description": "Set the variant selection on a prim", "uiName": "Set Variant Selection", "inputs": { "execIn": { "type": "execution", "description": "The input execution" }, "prim": { "type": "target", "description": "The prim with the variantSet" }, "variantName": { "type": "token", "description": "The variant name" }, "variantSetName": { "type": "token", "description": "The variantSet name" }, "setVariant": { "type": "bool", "default": false, "description": "Sets the variant selection when finished rather than writing to the attribute values" } }, "outputs": { "execOut": { "type": "execution", "description": "The output execution" } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantNames.ogn
{ "GetVariantNames": { "version": 2, "categories": [ "graph:action", "sceneGraph", "variants" ], "icon": { "path": "Variant.svg" }, "scheduling": [ "usd-read" ], "description": "Get variant names from a variantSet on a prim", "uiName": "Get Variant Names", "inputs": { "prim": { "type": "target", "description": "The prim with the variantSet" }, "variantSetName": { "type": "token", "description": "The variantSet name" } }, "outputs": { "variantNames": { "type": "token[]", "description": "List of variant names" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantSelection.ogn
{ "GetVariantSelection": { "version": 2, "categories": [ "graph:action", "sceneGraph", "variants" ], "icon": { "path": "Variant.svg" }, "scheduling": [ "usd-read" ], "description": "Get the variant selection on a prim", "uiName": "Get Variant Selection", "inputs": { "prim": { "type": "target", "description": "The prim with the variantSet" }, "variantSetName": { "type": "token", "description": "The variantSet name" } }, "outputs": { "variantName": { "type": "token", "description": "The variant name" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantSetNames.ogn
{ "GetVariantSetNames": { "version": 2, "categories": [ "graph:action", "sceneGraph", "variants" ], "icon": { "path": "Variant.svg" }, "scheduling": [ "usd-read" ], "description": "Get variantSet names on a prim", "uiName": "Get Variant Set Names", "inputs": { "prim": { "type": "target", "description": "The prim with the variantSet" } }, "outputs": { "variantSetNames": { "type": "token[]", "description": "List of variantSet names" } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnBlendVariants.ogn
{ "BlendVariants": { "version": 1, "categories": [ "graph:action", "sceneGraph", "variants" ], "icon": { "path": "Variant.svg" }, "scheduling": [ "usd-read" ], "description": "Add new variant by blending two variants", "uiName": "Blend Variants", "inputs": { "execIn": { "type": "execution", "description": "The input execution" }, "prim": { "type": "target", "description": "The prim with the variantSet" }, "variantSetName": { "type": "token", "description": "The variantSet name" }, "variantNameA": { "type": "token", "description": "The first variant name" }, "variantNameB": { "type": "token", "description": "The second variant name" }, "blend": { "type": "double", "description": "The blend value in [0.0, 1.0]", "default": 0.0, "minimum": 0.0, "maximum": 1.0 }, "setVariant": { "type": "bool", "default": false, "description": "Sets the variant selection when finished rather than writing to the attribute values" } }, "outputs": { "bundle": { "type": "bundle", "description": "Output bundle with blended attributes", "uiName": "Bundle" }, "execOut": { "type": "execution", "description": "The output execution" } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnSetVariantSelection.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 <OgnSetVariantSelectionDatabase.h> namespace omni::graph::nodes { class OgnSetVariantSelection { public: static bool compute(OgnSetVariantSelectionDatabase& 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 variantName = db.tokenToString(db.inputs.variantName()); if (db.inputs.setVariant()) { removeLocalOpinion(prim, variantSetName, variantName); bool success = variantSet.SetVariantSelection(variantName); if (!success) throw warning(std::string("Failed to set variant selection for variant set ") + variantSetName + " to variant " + variantName); } else { setLocalOpinion(prim, variantSetName, variantName); } 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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnClearVariantSelection.ogn
{ "ClearVariantSelection": { "version": 2, "categories": [ "graph:action", "sceneGraph", "variants" ], "icon": { "path": "Variant.svg" }, "scheduling": [ "usd-write" ], "description": "This node will clear the variant selection of the prim on the active layer. Final variant selection will be determined by layer composition below your active layer. In a single layer stage, this will be the fallback variant defined in your variantSet.", "uiName": "Clear Variant Selection", "inputs": { "execIn": { "type": "execution", "description": "The input execution" }, "prim": { "type": "target", "description": "The prim with the variantSet" }, "variantSetName": { "type": "token", "description": "The variantSet name" }, "setVariant": { "type": "bool", "default": false, "description": "Sets the variant selection when finished rather than writing to the attribute values" } }, "outputs": { "execOut": { "type": "execution", "description": "The output execution" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantSelection.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 <OgnGetVariantSelectionDatabase.h> namespace omni::graph::nodes { class OgnGetVariantSelection { public: static bool compute(OgnGetVariantSelectionDatabase& 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 variantSelection = variantSet.GetVariantSelection(); db.outputs.variantName() = db.stringToToken(variantSelection.c_str()); return true; } catch (const warning& e) { db.logWarning(e.what()); } catch (const std::exception& e) { db.logError(e.what()); } db.outputs.variantName() = db.stringToToken(""); return false; } }; REGISTER_OGN_NODE() } // namespace omni::graph::nodes
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnHasVariantSet.ogn
{ "HasVariantSet": { "version": 2, "categories": [ "graph:action", "sceneGraph", "variants" ], "icon": { "path": "Variant.svg" }, "scheduling": [ "usd-read" ], "description": "Query the existence of a variantSet on a prim", "uiName": "Has Variant Set", "inputs": { "prim": { "type": "target", "description": "The prim with the variantSet" }, "variantSetName": { "type": "token", "description": "The variantSet name" } }, "outputs": { "exists": { "type": "bool", "description": "Variant exists" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnLengthAlongCurve.ogn
{ "LengthAlongCurve": { "version": 1, "description": "Find the length along the curve of a set of points", "metadata": { "uiName": "Length Along Curve" }, "categories": ["geometry:analysis"], "scheduling": ["threadsafe"], "inputs": { "curveVertexStarts": { "type": "int[]", "description": "Vertex starting points", "metadata": { "uiName": "Curve Vertex Starts" } }, "curveVertexCounts": { "type": "int[]", "description": "Vertex counts for the curve points", "metadata": { "uiName": "Curve Vertex Counts" } }, "curvePoints": { "type": "float[3][]", "description": "Points on the curve to be framed", "metadata": { "uiName": "Curve Points" } }, "normalize": { "type": "bool", "description": "If true then normalize the curve length to a 0, 1 range", "metadata": { "uiName": "Normalize" } } }, "outputs": { "length": { "type": "float[]", "description": "List of lengths along the curve corresponding to the input points" } }, "tests": [ { "inputs:curveVertexStarts": [0], "inputs:curveVertexCounts": [4], "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]], "inputs:normalize": false, "outputs:length": [0.0, 1.0, 6.0, 21.0] }, { "inputs:curveVertexStarts": [0], "inputs:curveVertexCounts": [3], "inputs:curvePoints": [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0]], "inputs:normalize": true, "outputs:length": [0.0, 0.5, 1.0] } ] } }
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() } } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveTubeST.ogn
{ "CurveTubeST": { "version": 1, "description" : "Compute curve tube ST values", "metadata": { "uiName": "Curve Tube ST" }, "categories": ["geometry:generator"], "scheduling": ["threadsafe"], "inputs": { "curveVertexStarts": { "type": "int[]", "description": "Vertex starting points", "metadata": { "uiName": "Curve Vertex Starts" } }, "curveVertexCounts": { "type": "int[]", "description": "Vertex counts for the curve points", "metadata": { "uiName": "Curve Vertex Counts" } }, "tubeSTStarts": { "type": "int[]", "description": "Vertex index values for the tube ST starting points", "metadata": { "uiName": "Tube ST Starts" } }, "tubeQuadStarts": { "type": "int[]", "description": "Vertex index values for the tube quad starting points", "metadata": { "uiName": "Tube Quad Starts" } }, "cols": { "type": "int[]", "description": "Columns of the tubes", "metadata": { "uiName": "Columns" } }, "t": { "type": "float[]", "description": "T values of the tubes", "metadata": { "uiName": "T Values" } }, "width": { "type": "float[]", "description": "Width of tube positions, if scaling T like S", "metadata": { "uiName": "Tube Widths" } }, "scaleTLikeS": { "type": "bool", "description": "If true then scale T the same as S", "metadata": { "uiName": "Scale T Like S" } } }, "outputs": { "primvars:st": { "type": "float[2][]", "description": "Array of computed ST values", "metadata": { "uiName": "ST Values" } }, "primvars:st:indices": { "type": "int[]", "description": "Array of computed ST indices", "metadata": { "uiName": "ST Indices" } } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveFrame.ogn
{ "CurveToFrame": { "version": 1, "description": "Create a frame object based on a curve description", "metadata": { "uiName": "Crate Curve From Frame" }, "categories": ["geometry:generator"], "scheduling": ["threadsafe"], "inputs": { "curveVertexStarts": { "type": "int[]", "description": "Vertex starting points", "metadata": { "uiName": "Curve Vertex Starts" } }, "curveVertexCounts": { "type": "int[]", "description": "Vertex counts for the curve points", "metadata": { "uiName": "Curve Vertex Counts" } }, "curvePoints": { "type": "float[3][]", "description": "Points on the curve to be framed", "metadata": { "uiName": "Curve Points" } } }, "outputs": { "tangent": { "type": "float[3][]", "description": "Tangents on the curve frame", "metadata": { "uiName": "Tangents" } }, "up": { "type": "float[3][]", "description": "Up vectors on the curve frame", "metadata": { "uiName": "Up Vectors" } }, "out": { "type": "float[3][]", "description": "Out vector directions on the curve frame", "metadata": { "uiName": "Out Vectors" } } } } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCreateTubeTopology.ogn
{ "CreateTubeTopology":{ "version": 1, "description": [ "Creates the face vertex counts and indices describing a tube topology with the", "given number of rows and columns." ], "metadata": { "uiName": "Create Tube Topology" }, "categories": ["geometry:generator"], "scheduling": ["threadsafe"], "inputs": { "rows": { "type": "int[]", "description": "Array of rows in the topology to be generated", "metadata": { "uiName": "Row Array" } }, "cols": { "type": "int[]", "description": "Array of columns in the topology to be generated", "metadata": { "uiName": "Column Array" } } }, "outputs": { "faceVertexCounts": { "type": "int[]", "description": "Array of vertex counts for each face in the tube topology", "metadata": { "uiName": "Face Vertex Counts" } }, "faceVertexIndices": { "type": "int[]", "description" : "Array of vertex indices for each face in the tube topology", "metadata": { "uiName": "Face Vertex Indices" } } }, "tests": [ { "inputs:rows": [1, 2, 3], "inputs:cols": [2, 3, 4], "outputs:faceVertexCounts": [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], "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 ] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveTubePositions.ogn
{ "CurveTubePositions": { "version": 1, "description": "Generate tube positions from a curve description", "metadata": { "uiName": "Curve Tube Positions" }, "categories": ["geometry:generator"], "scheduling": ["threadsafe"], "inputs": { "curveVertexStarts": { "type": "int[]", "description": "Vertex starting points", "metadata": { "uiName": "Curve Vertex Starts" } }, "curveVertexCounts": { "type": "int[]", "description": "Vertex counts for the curve points", "metadata": { "uiName": "Curve Vertex Counts" } }, "curvePoints": { "type": "float[3][]", "description": "Points on the curve to be framed", "metadata": { "uiName": "Curve Points" } }, "tubePointStarts": { "type": "int[]", "description": "Tube starting point index values", "metadata": { "uiName": "Tube Point Starts" } }, "cols": { "type": "int[]", "description": "Columns of the tubes", "metadata": { "uiName": "Columns" } }, "up": { "type": "float[3][]", "description": "Up vectors on the tube", "metadata": { "uiName": "Up Vectors" } }, "out": { "type": "float[3][]", "description": "Out vector directions on the tube", "metadata": { "uiName": "Out Vectors" } }, "width": { "type": "float[]", "description": "Width of tube positions", "metadata": { "uiName": "Tube Widths" } } }, "outputs": { "points": { "type": "float[3][]", "description": "Points on the tube", "metadata": { "uiName": "Points" } } } } }
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() } } }
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() } } }
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() } } } }
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() } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleAllocator.ogn
{ "RpResourceExampleAllocator": { "version": 1, "description": [ "Allocate CUDA-interoperable RpResource" ], "uiName": "RpResource Example Allocator Node", "inputs": { "stream": { "type": "uint64", "description": "Pointer to the CUDA Stream", "uiName": "stream" }, "primPath": { "type": "token", "description": "Prim path input. Points and a prim path may be supplied directly as an alternative to a bundle input.", "uiName": "Prim path input" }, "points": { "type": "float[3][]", "description": "Points attribute input. Points and a prim path may be supplied directly as an alternative to a bundle input.", "uiName": "Prim Points" }, "verbose": { "type": "bool", "default": false, "description": "verbose printing", "uiName": "Verbose" }, "reload": { "type": "bool", "description": "Force RpResource reload", "default": false, "uiName": "Reload" } }, "outputs": { "resourcePointerCollection": { "type": "uint64[]", "description": [ "Pointers to RpResources ", "(two resources per prim are allocated -- one for rest positions and one for deformed positions)" ], "uiName": "Resource Pointer Collection" }, "pointCountCollection": { "type": "uint64[]", "description": [ "Point count for each prim being deformed" ], "uiName": "Point Counts" }, "primPathCollection": { "type": "token[]", "description": [ "Path for each prim being deformed" ], "uiName": "Prim Paths" }, "reload": { "type": "bool", "description": "Force RpResource reload", "default": false, "uiName": "Reload" }, "stream": { "type": "uint64", "description": "Pointer to the CUDA Stream", "uiName": "stream" } } } }
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() } } } }
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() } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnDeformedPointsToHydra.ogn
{ "DeformedPointsToHydra": { "version": 1, "description": [ "Copy deformed points into rpresource and send to hydra" ], "uiName": "Deformed Points to Hydra", "cudaPointers": "cpu", "inputs": { "stream": { "type": "uint64", "description": "Pointer to the CUDA Stream", "uiName": "stream" }, "primPath": { "type": "token", "description": "Prim path input. Points and a prim path may be supplied directly as an alternative to a bundle input.", "uiName": "Prim path input" }, "points": { "type": "float[3][]", "memoryType": "cuda", "description": "Points attribute input. Points and a prim path may be supplied directly as an alternative to a bundle input.", "uiName": "Prim Points" }, "verbose": { "type": "bool", "default": false, "description": "verbose printing", "uiName": "Verbose" }, "sendToHydra": { "type": "bool", "default": false, "description": "send to hydra", "uiName": "Send to hydra" } }, "outputs": { "reload": { "type": "bool", "description": "Force RpResource reload", "default": false, "uiName": "Reload" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleDeformer.ogn
{ "RpResourceExampleDeformer": { "version": 1, "description": [ "Allocate CUDA-interoperable RpResource" ], "uiName": "RpResource Example Deformer Node", "inputs": { "stream": { "type": "uint64", "description": "Pointer to the CUDA Stream", "uiName": "stream" }, "resourcePointerCollection": { "type": "uint64[]", "description": [ "Pointer to RpResource collection" ], "uiName": "Resource Pointer Collection" }, "pointCountCollection": { "type": "uint64[]", "description": [ "Pointer to point counts collection" ], "uiName": "Point Counts" }, "primPathCollection": { "type": "token[]", "description": [ "Pointer to prim path collection" ], "uiName": "Prim Paths" }, "verbose": { "type": "bool", "default": false, "description": "verbose printing", "uiName": "Verbose" }, "displacementAxis": { "type": "int", "default": 0, "description": "dimension in which mesh is translated", "uiName": "Displacement Axis" }, "runDeformerKernel": { "type": "bool", "default": true, "description": "Whether cuda kernel will be executed", "uiName": "Run Deformer" }, "timeScale": { "type": "float", "default": 0.01, "description": "Deformation control", "uiName": "Time Scale" }, "positionScale": { "type": "float", "default": 1.0, "description": "Deformation control", "uiName": "Position Scale" }, "deformScale": { "type": "float", "default": 1.0, "description": "Deformation control", "uiName": "Deform Scale" } }, "outputs": { "stream": { "type": "uint64", "description": "Pointer to the CUDA Stream", "uiName": "stream" }, "resourcePointerCollection": { "type": "uint64[]", "description": [ "Pointers to RpResources ", "(two resources per prim are assumed -- one for rest positions and one for deformed positions)" ], "uiName": "Resource Pointer Collection" }, "pointCountCollection": { "type": "uint64[]", "description": [ "Point count for each prim being deformed" ], "uiName": "Point Counts" }, "primPathCollection": { "type": "token[]", "description": [ "Path for each prim being deformed" ], "uiName": "Prim Paths" }, "reload": { "type": "bool", "description": "Force RpResource reload", "default": false, "uiName": "Reload" } }, "state": { "sequenceCounter": { "type": "uint64", "description": "tick counter for animation", "default": 0 } }, "tokens": { "points": "points", "transform": "transform", "rpResource": "rpResource", "pointCount": "pointCount", "primPath": "primPath", "testToken": "testToken", "uintData": "uintData" } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleHydra.ogn
{ "RpResourceExampleHydra": { "version": 1, "description": [ "Send RpResource to Hydra" ], "uiName": "RpResource to Hydra Example Node", "inputs": { "verbose": { "type": "bool", "default": false, "description": "verbose printing", "uiName": "Verbose" }, "sendToHydra": { "type": "bool", "default": false, "description": "Send rpresource pointer to hydra using the specified prim path", "uiName": "Send to Hydra" }, "resourcePointerCollection": { "type": "uint64[]", "description": [ "Pointers to RpResources ", "(two resources per prim are assumed -- one for rest positions and one for deformed positions)" ], "uiName": "Resource Pointer Collection" }, "pointCountCollection": { "type": "uint64[]", "description": [ "Point count for each prim being deformed" ], "uiName": "Point Counts" }, "primPathCollection": { "type": "token[]", "description": [ "Path for each prim being deformed" ], "uiName": "Prim Paths" } }, "outputs": { "reload": { "type": "bool", "description": "Force RpResource reload", "default": false, "uiName": "Reload" } }, "tokens": { "points": "points", "transform": "transform", "rpResource": "rpResource", "pointCount": "pointCount", "uintData": "uintData" } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineLoop.ogn
{ "LoopTimeline": { "version": 1, "description": "Controls looping playback of the main timeline", "metadata": { "uiName": "Set playback looping" }, "categories": [ "time" ], "scheduling": "compute-on-request", "inputs": { "execIn": { "type": "execution", "description": "The input that triggers the execution of this node.", "uiName": "Execute In" }, "loop": { "type": "bool", "description": "Enable or disable playback looping?", "uiName": "Loop" } }, "outputs": { "execOut": { "type": "execution", "description": "The output that is triggered when this node executed.", "uiName": "Execute Out" } } } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimer.ogn
{ "omni.graph.nodes.Timer": { "version": 2, "description": [ "Timer Node is a node that lets you create animation curve(s), plays back and samples the value(s) along its time to output values." ], "metadata": { "uiName": "Timer" }, "categories": {"animation": "Nodes dealing with Animation"}, "inputs": { "startValue": { "type": "double", "description": "Value value of the start of the duration", "uiName": "Start Value", "minimum": 0.0, "maximum": 1.0, "default": 0.0 }, "endValue": { "type": "double", "description": "Value value of the end of the duration", "uiName": "End Value", "minimum": 0.0, "maximum": 1.0, "default": 1.0 }, "duration": { "type": "double", "description": "Number of seconds to play interpolation", "uiName": "Duration", "default": 1.0 }, "play": { "type": "execution", "description": "Play the clip from current frame", "uiName": "Play" } }, "outputs": { "value": { "type": "double", "description": "Value value of the Timer node between 0.0 and 1.0", "uiName": "Value", "default": 0.0 }, "updated": { "type": "execution", "description": "The Timer node is ticked, and output value(s) resampled and updated", "uiName": "Updated" }, "finished": { "type": "execution", "description": "The Timer node has finished the playback", "uiName": "Finished" } } } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnInterpolator.ogn
{ "Interpolator": { "version": 1, "description": "Time sample interpolator", "metadata": { "uiName": "Interpolator" }, "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "param": { "type": "float", "description": "Time sample interpolation point", "metadata": { "uiName": "Interpolation Point" } }, "knots": { "type": "float[]", "description": "Array of knots on the time sample curve", "metadata": { "uiName": "Knot Array" } }, "values": { "type": "float[]", "description": "Array of time sample values", "metadata": { "uiName": "Value Array" } } }, "outputs": { "value": { "type": "float", "description": "Value in the time samples, interpolated at the given parameter location", "metadata": { "uiName": "Interpolated Value" } } }, "tests": [ { "inputs:knots": [1.0, 2.0], "inputs:values": [3.0, 4.0], "inputs:param": 1.5, "outputs:value": 3.5 }, { "inputs:knots": [1.0, 2.0], "inputs:values": [3.0, 4.0], "inputs:param": 1.0, "outputs:value": 3.0 }, { "inputs:knots": [1.0, 2.0], "inputs:values": [3.0, 4.0], "inputs:param": 2.0, "outputs:value": 4.0 }, { "inputs:knots": [1.0, 2.0], "inputs:values": [3.0, 4.0], "inputs:param": 0.5, "outputs:value": 3.0 }, { "inputs:knots": [1.0, 2.0], "inputs:values": [3.0, 4.0], "inputs:param": 2.5, "outputs:value": 4.0 } ] } }
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() }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineSet.ogn
{ "SetTimeline": { "version": 1, "description": "Set properties of the main timeline", "metadata": { "uiName": "Set main timeline" }, "categories": [ "time" ], "scheduling": "compute-on-request", "inputs": { "execIn": { "type": "execution", "description": "The input that triggers the execution of this node.", "uiName": "Execute In" }, "propValue": { "type": "double", "description": "The value of the property to set.", "uiName": "Property Value" }, "propName": { "type": "token", "description": "The name of the property to set.", "uiName": "Property Name", "default": "Frame", "metadata": { "displayGroup": "parameters", "literalOnly": "1", "allowedTokens": [ "Frame", "Time", "StartFrame", "StartTime", "EndFrame", "EndTime", "FramesPerSecond" ] } } }, "outputs": { "clamped": { "type": "bool", "description": "Was the input frame or time clamped to the playback range?", "uiName": "Clamp to range" }, "execOut": { "type": "execution", "description": "The output that is triggered when this node executed.", "uiName": "Execute Out" } } } }