file_path
stringlengths 21
202
| content
stringlengths 12
1.02M
| size
int64 12
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 10
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrims.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.
//
/*
_____ ______ _____ _____ ______ _____ _______ ______ _____
| __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \
| | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | |
| | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | |
| |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| |
|_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/
OgnWritePrims is deprecated. Use WritePrimsV2 instead.
OgnWritePrims always writes back to the original sourcePrimPath from input bundle.
The successor OgnWritePrimsV2 removed this feedback loop. Target(s) is always required to write prims to.
This old OgnWritePrims version is kept for backward compatibility.
*/
#include "OgnWritePrimsDatabase.h"
#include "WritePrimCommon.h"
#include "SpanUtils.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnWritePrims
{
static size_t getConnectedPrimCount(OgnWritePrimsDatabase& db)
{
GraphContextObj const& contextObj = db.abi_context();
NodeObj const& nodeObj = db.abi_node();
NodeContextHandle const nodeHandle = nodeObj.nodeContextHandle;
NameToken const primsToken = inputs::primsBundle.token();
return contextObj.iContext->getInputTargetCount(contextObj, nodeHandle, primsToken, db.getInstanceIndex());
}
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
ogn::OmniGraphDatabase::logWarning(nodeObj, "WritePrim node is deprecated, use WritePrimV2 instead");
}
static bool compute(OgnWritePrimsDatabase& db)
{
auto result = WritePrimResult::None;
// Since the bundle input allows multiple connections, we need to collect all of them
size_t const connectedPrimCount = getConnectedPrimCount(db);
// Even when we have no connected prims, we still return true, because the node *did* compute, and execOut
// attribute will be set.
if (connectedPrimCount > 0)
{
auto handler = [&db, &result](gsl::span<ConstBundleHandle> connectedBundleHandles)
{
GraphContextObj const& contextObj = db.abi_context();
NodeObj const& nodeObj = db.abi_node();
NodeContextHandle const nodeHandle = nodeObj.nodeContextHandle;
NameToken const primsToken = inputs::primsBundle.token();
bool const usdWriteBack = db.inputs.usdWriteBack();
ogn::const_string const attrPattern = db.inputs.attrNamesToExport();
ogn::const_string const pathPattern = db.inputs.pathPattern();
ogn::const_string const typePattern = db.inputs.typePattern();
WritePrimMatchers const matchers{ attrPattern, pathPattern, typePattern };
contextObj.iContext->getInputTargets(contextObj, nodeHandle, primsToken, (omni::fabric::PathC*)(connectedBundleHandles.data()), db.getInstanceIndex());
// Write back all bundles
WritePrimDiagnostics diagnostics;
for (ConstBundleHandle const& bundleHandle : connectedBundleHandles)
{
WritePrimResult const subResult = writeBundleHierarchyToPrims(
contextObj, nodeObj, diagnostics, bundleHandle, matchers, usdWriteBack);
mergeWritePrimResult(result, subResult);
}
// Report skipped invalid bundles
mergeWritePrimResult(result, diagnostics.report(contextObj, nodeObj));
};
withStackScopeBuffer<ConstBundleHandle>(connectedPrimCount, handler);
}
auto const ok = result != WritePrimResult::Fail;
if (ok)
{
db.outputs.execOut() = kExecutionAttributeStateEnabled;
}
return ok;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 4,470 | C++ | 37.213675 | 167 | 0.602461 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetGraphTargetPrim.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 <OgnGetGraphTargetPrimDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetGraphTargetPrim
{
public:
static size_t computeVectorized(OgnGetGraphTargetPrimDatabase& db, size_t count)
{
auto targets = db.getGraphTargets(count);
for (size_t idx = 0; idx < count; idx++)
{
auto outPrims = db.outputs.prim(idx);
outPrims.resize(1);
outPrims[0] = db.tokenToPath(targets[idx]);
}
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,038 | C++ | 23.16279 | 84 | 0.696532 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnInsertAttr.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 "OgnInsertAttrDatabase.h"
namespace omni
{
namespace graph
{
namespace core
{
class OgnInsertAttr
{
public:
// Copies all attributes from an input prim to the output prim, as well as copying an additional
// "attrToInsert" attribute from the node itself with a specified name.
static bool compute(OgnInsertAttrDatabase& db)
{
const auto& outputAttrNameToken = db.inputs.outputAttrName();
const auto& inputBundle = db.inputs.data();
auto& outputBundle = db.outputs.data();
// Start by copying the input prim into the output prim.
outputBundle = inputBundle;
if (!outputBundle.isValid())
{
db.logWarning("Failed to copy input bundle to the output");
return false;
}
const auto& inputToInsert = db.inputs.attrToInsert();
if (!inputToInsert.isValid())
{
db.logWarning("Input attribute to insert is not valid");
return false;
}
outputBundle.insertAttribute(inputToInsert, outputAttrNameToken);
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,568 | C++ | 28.603773 | 100 | 0.684311 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimBundle.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.
/*
_____ ______ _____ _____ ______ _____ _______ ______ _____
| __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \
| | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | |
| | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | |
| |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| |
|_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/
ReadPrimBundle is deprecated and should not be used.
First version of ReadPrimBundle outputs 'Single Primitive in a Bundle'(SPiB).
The successor ReadPrimsBundle outputs 'Multiple Primitives in a Bundle'(MPiB).
This operator is kept for backward compatibility.
*/
// clang-format off
#include "UsdPCH.h"
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/prim.h>
#include <omni/graph/core/PostUsdInclude.h>
// clang-format on
#include "OgnReadPrimBundleDatabase.h"
#include <omni/fabric/FabricUSD.h>
#include "PrimCommon.h"
#include "ReadPrimCommon.h"
#include <omni/usd/UsdContext.h>
using namespace omni::fabric;
namespace omni
{
namespace graph
{
namespace nodes
{
/************************************************************************/
/* */
/************************************************************************/
class OgnReadPrimBundle
{
public:
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
char const* primNodePath = nodeObj.iNode->getPrimPath(nodeObj);
CARB_LOG_WARN("ReadPrimBundle node is deprecated: %s, use ReadPrims instead", primNodePath);
// When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected.
AttributeObj inputBundleAttribObj =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimBundleAttributes::inputs::prim.m_token);
inputBundleAttribObj.iAttribute->registerValueChangedCallback(
inputBundleAttribObj, onInputBundleValueChanged, true);
}
// ----------------------------------------------------------------------------
static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData)
{
NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj);
GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj);
// If the graph is currently disabled then delay the update until the next compute.
// Arguably this should be done at the message propagation layer, then this wouldn't be necessary.
if (graphObj.iGraph->isDisabled(graphObj))
{
return;
}
// clear the output bundles
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
auto outputTokens = { OgnReadPrimBundleAttributes::outputs::primBundle.m_token };
for (auto& outputToken : outputTokens)
{
BundleHandle outBundle = context.iContext->getOutputBundle(
context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex);
context.iContext->clearBundleContents(context, outBundle);
}
}
// ----------------------------------------------------------------------------
static PathC getPath(OgnReadPrimBundleDatabase& db)
{
return readPrimBundle_getPath(db.abi_context(), db.abi_node(), OgnReadPrimBundleAttributes::inputs::prim.m_token,
db.inputs.usePath(), db.inputs.primPath(), db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static bool writeToBundle(OgnReadPrimBundleDatabase& db, PathC inputPath, bool force, pxr::UsdTimeCode const& time)
{
return readPrimBundle_writeToBundle(db.abi_context(), db.abi_node(), inputPath, db.inputs.attrNamesToImport(),
db.outputs.primBundle(), force, db.inputs.computeBoundingBox(), time, db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static void clean(OgnReadPrimBundleDatabase& db)
{
db.outputs.primBundle().clear();
}
// ----------------------------------------------------------------------------
static bool compute(OgnReadPrimBundleDatabase& db)
{
bool inputChanged = false;
if (db.state.usePath() != db.inputs.usePath())
{
db.state.usePath() = db.inputs.usePath();
inputChanged = true;
}
// bounding box changed
if (db.state.computeBoundingBox() != db.inputs.computeBoundingBox())
{
db.state.computeBoundingBox() = db.inputs.computeBoundingBox();
inputChanged = true;
}
// attribute filter changed
NameToken const attrNamesToImport = db.inputs.attrNamesToImport();
if (db.state.attrNamesToImport() != attrNamesToImport.token)
{
db.state.attrNamesToImport() = attrNamesToImport.token;
inputChanged = true;
}
return readPrimBundle_compute<OgnReadPrimBundle>(db, inputChanged);
}
static bool updateNodeVersion(GraphContextObj const& context, NodeObj const& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
bool upgraded = false;
if (oldVersion < 4)
{
// backward compatibility: `inputs:attrNamesToImport`
// Prior to this version `inputs:attrNamesToImport` attribute did not support wild cards.
// The meaning of an empty string was to include all attributes. With the introduction of the wild cards
// we need to convert an empty string to "*" in order to include all attributes.
static Token const value{ "*" };
if (nodeObj.iNode->getAttributeExists(nodeObj, "inputs:attrNamesToImport"))
{
AttributeObj attr = nodeObj.iNode->getAttribute(nodeObj, "inputs:attrNamesToImport");
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, "inputs:attrNamesToImport", Type(BaseDataType::eToken),
&value, nullptr, kAttributePortType_Input,
kExtendedAttributeType_Regular, nullptr);
}
upgraded = true;
}
if (oldVersion < 6)
{
upgraded |= upgradeUsdTimeCodeInput(context, nodeObj);
}
return upgraded;
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 7,985 | C++ | 40.164948 | 137 | 0.542142 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetAttrNames.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 "OgnGetAttrNamesDatabase.h"
#include <algorithm>
namespace omni
{
namespace graph
{
namespace core
{
class OgnGetAttrNames
{
public:
// Retrieves the names of all of the attributes contained in the input prim, optionally sorted.
static bool compute(OgnGetAttrNamesDatabase& db)
{
auto& inputBundle = db.inputs.data();
auto attributesInBundle = inputBundle.attributeCount();
auto& arrayNames = db.outputs.output();
arrayNames.resize(attributesInBundle);
// Empty bundles yield empty output arrays, which is okay
if (attributesInBundle == 0)
{
return true;
}
// Get all of the bundle member names into the output (as-is for now).
std::transform(inputBundle.begin(), inputBundle.end(), arrayNames.begin(),
[](const ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu>& attribute) -> NameToken { return attribute.name(); });
// If sorting was requested do that now
if (db.inputs.sort())
{
auto sortByNameString = [&db](const NameToken& a, const NameToken& b) -> bool {
const char* aString = db.tokenToString(a);
const char* bString = db.tokenToString(b);
return strcmp(aString, bString) < 0;
};
std::sort(arrayNames.data(), arrayNames.data() + attributesInBundle, sortByNameString);
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,927 | C++ | 31.677966 | 136 | 0.655423 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnArrayLength.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 "OgnArrayLengthDatabase.h"
namespace omni
{
namespace graph
{
namespace core
{
class OgnArrayLength
{
public:
// Outputs the length of a specified array attribute in an input prim,
// or 1 if the attribute is not an array attribute.
static bool compute(OgnArrayLengthDatabase& db)
{
auto bundledAttribute = db.inputs.data().attributeByName(db.inputs.attrName());
db.outputs.length() = bundledAttribute.isValid() ? bundledAttribute.size() : 0;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 980 | C++ | 25.513513 | 87 | 0.736735 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadOmniGraphValue.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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnReadOmniGraphValueDatabase.h>
#include <omni/graph/core/IAttributeType.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/CppWrappers.h>
#include <omni/usd/UsdContext.h>
#include "PrimCommon.h"
using namespace omni::fabric;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnReadOmniGraphValue
{
// ----------------------------------------------------------------------------
// Called by OG when our queried attrib changes. We want to catch the case of changing the queried attribute interactively
static void onValueChanged(const AttributeObj& attrObj, void const* userData)
{
onConnectionTypeResolve(attrObj.iAttribute->getNode(attrObj));
}
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
// We need to check resolution if any of our relevant inputs change
std::array<NameToken, 2> attribNames{ inputs::path.token(), inputs::name.token() };
for (auto const& attribName : attribNames)
{
AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, attribName);
attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true);
}
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
// FIXME: Be pedantic about validity checks - this can be run directly by the TfNotice so who knows
// when or where this is happening
GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) };
if (context.contextHandle == kInvalidGraphContextHandle)
return;
// reasoning on the "current" instance
const auto instIdx = kAccordingToContextIndex;
// Get the queried attribute path
ConstAttributeDataHandle constHandle =
getAttributeR(context, nodeObj.nodeContextHandle, inputs::path.token(), instIdx);
if (!constHandle.isValid())
return;
const char* pathCStr = *getDataR<const char*>(context, constHandle);
if(!pathCStr)
return;
std::string pathStr(pathCStr, getElementCount(context, constHandle));
if (pathStr == "")
return;
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
auto path = pathInterface->getHandle(std::string(pathStr).c_str());
// Get the queried attribute name
constHandle = getAttributeR(context, nodeObj.nodeContextHandle, inputs::name.token(), instIdx);
if (!constHandle.isValid())
return;
NameToken attributeName = *getDataR<NameToken>(context, constHandle);
const char* attributeNameStr = context.iToken->getText(attributeName);
if (!attributeNameStr || strlen(attributeNameStr) == 0)
return;
// Get the queried attribute
ConstAttributeDataHandle inputDataHandle;
NodeObj inputNodeObj = graphObj.iGraph->getNode(graphObj, std::string(pathStr).c_str());
if(inputNodeObj.nodeHandle != kInvalidNodeHandle)
{
// node
AttributeObj inputAttrib = inputNodeObj.iNode->getAttributeByToken(inputNodeObj, attributeName);
if(!inputAttrib.iAttribute->isValid(inputAttrib))
return;
inputDataHandle = inputAttrib.iAttribute->getConstAttributeDataHandle(inputAttrib, instIdx);
}
else
{
// bundle
ConstBundleHandle attributeHandle(path.path);
if(!attributeHandle.isValid())
return;
const Token attrName(attributeName);
inputDataHandle = getAttributeR(context, attributeHandle, attrName);
}
if(!inputDataHandle.isValid())
return;
// Try resolve output
Type attribType = context.iAttributeData->getType(context, inputDataHandle);
tryResolveOutputAttribute(nodeObj, outputs::value.token(), attribType);
}
static bool compute(OgnReadOmniGraphValueDatabase& db)
{
// Get interfaces
auto& nodeObj = db.abi_node();
const GraphContextObj context = db.abi_context();
GraphObj graph = nodeObj.iNode->getGraph(nodeObj);
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
// Get queried attribute path
auto const& pathStr = db.inputs.path();
if(pathStr.empty())
{
return false;
}
auto path = pathInterface->getHandle(std::string(pathStr).c_str());
// Get queried attribute name
NameToken attributeName = db.inputs.name();
const char* attributeNameStr = db.tokenToString(attributeName);
if(std::string(attributeNameStr) == "")
{
return false;
}
// Get queried attribute
ConstAttributeDataHandle inputDataHandle;
NodeObj inputNodeObj = graph.iGraph->getNode(graph, std::string(pathStr).c_str());
if(inputNodeObj.nodeHandle != kInvalidNodeHandle)
{
// node
AttributeObj inputAttrib = inputNodeObj.iNode->getAttributeByToken(inputNodeObj, attributeName);
if(inputAttrib.iAttribute->isValid(inputAttrib))
{
inputDataHandle = inputAttrib.iAttribute->getConstAttributeDataHandle(inputAttrib, db.getInstanceIndex());
}
}
else
{
// bundle
ConstBundleHandle attributeHandle(path.path);
if(!attributeHandle.isValid())
{
return false;
}
const Token attrName(attributeNameStr);
inputDataHandle = getAttributeR(context, attributeHandle, attrName);
}
if(!inputDataHandle.isValid())
{
db.logWarning("Attribute \"%s.%s\" can't be found in Fabric", ((std::string)pathStr).c_str(), attributeNameStr);
return false;
}
Type attribType = context.iAttributeData->getType(context, inputDataHandle);
// 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 (!attribType.compatibleRawData(outType))
{
db.logError("%s is not compatible with type %s, please disconnect to change source attrib",
attributeNameStr, getOgnTypeName(db.outputs.value().type()).c_str());
return false;
}
}
// If it's resolved, we already know that it is compatible from the above check of the USD
AttributeObj outAttrib = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::value.m_token);
if (!db.outputs.value().resolved())
{
outAttrib.iAttribute->setResolvedType(outAttrib, attribType);
db.outputs.value().reset(
context, outAttrib.iAttribute->getAttributeDataHandle(outAttrib, db.getInstanceIndex()), outAttrib);
}
// Copy queried attribute value to node's output
AttributeDataHandle outDataHandle =
outAttrib.iAttribute->getAttributeDataHandle(outAttrib, db.getInstanceIndex());
context.iAttributeData->copyData(outDataHandle, context, inputDataHandle);
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 8,149 | C++ | 37.995215 | 126 | 0.63787 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadSetting.cpp | // Copyright (c) 2022-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 <OgnReadSettingDatabase.h>
#include <carb/settings/ISettings.h>
#include <carb/settings/SettingsUtils.h>
#include <carb/dictionary/IDictionary.h>
using carb::dictionary::ItemType;
namespace omni
{
namespace graph
{
namespace nodes
{
// unnamed namespace to avoid multiple declaration when linking
namespace
{
template<typename T>
void getSetting(OgnReadSettingDatabase& db)
{
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
std::string strSettingPath = db.inputs.settingPath();
char const* settingPath = strSettingPath.c_str();
auto outputValue = db.outputs.value().template get<T>();
*outputValue = settings->get<T>(settingPath);
}
} // namespace
class OgnReadSetting
{
public:
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
AttributeObj attrObj = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::settingPath.m_token);
attrObj.iAttribute->registerValueChangedCallback(attrObj, onValueChanged, true);
onValueChanged(attrObj, nullptr);
}
// ----------------------------------------------------------------------------
// Called by OG to resolve the input type
static void onConnectionTypeResolve(NodeObj const& nodeObj)
{
auto attrObj = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::settingPath.m_token);
auto graphObj = nodeObj.iNode->getGraph(nodeObj);
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
auto context = graphObj.iGraph->getDefaultGraphContext(graphObj);
if (context.contextHandle == kInvalidGraphContextHandle)
return;
ConstAttributeDataHandle attrDataHandle =
attrObj.iAttribute->getAttributeDataHandle(attrObj, kAccordingToContextIndex);
if (!attrDataHandle.isValid())
return;
Type type(BaseDataType::eUnknown);
auto stringLen = getElementCount(context, attrDataHandle);
auto cstrPtrPtr = getDataR<char const*>(context, attrDataHandle);
if (stringLen && cstrPtrPtr && *cstrPtrPtr) {
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
std::string strSettingPath = std::string(*cstrPtrPtr, stringLen);
char const* settingPath = strSettingPath.c_str();
ItemType pathType;
if (settings->isAccessibleAsArray(settingPath))
pathType = settings->getPreferredArrayType(settingPath);
else
pathType = settings->getItemType(settingPath);
if (pathType == ItemType::eBool)
type.baseType = BaseDataType::eBool;
else if (pathType == ItemType::eInt)
type.baseType = BaseDataType::eInt;
else if (pathType == ItemType::eFloat)
type.baseType = BaseDataType::eFloat;
else if (pathType == ItemType::eString)
type.baseType = BaseDataType::eToken;
else
CARB_LOG_ERROR("Invalid Setting Path!");
if (settings->isAccessibleAsArray(settingPath)) {
size_t arrayLen = (size_t)settings->getArrayLength(settingPath);
if ((pathType == ItemType::eFloat || pathType == ItemType::eInt) && (arrayLen > 1 && arrayLen <= 4))
type.componentCount = (uint8_t)arrayLen;
else
type.arrayDepth = 1;
}
}
omni::graph::nodes::tryResolveInputAttribute(nodeObj, outputs::value.m_token, type);
}
// ----------------------------------------------------------------------------
// Called by OG when the value of the settingPath changes
static void onValueChanged(AttributeObj const& attrObj, void const* userData)
{
auto nodeObj = attrObj.iAttribute->getNode(attrObj);
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
onConnectionTypeResolve(nodeObj);
}
static bool compute(OgnReadSettingDatabase& db)
{
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
std::string strSettingPath = db.inputs.settingPath();
char const* settingPath = strSettingPath.c_str();
auto const valueType = db.outputs.value().type();
size_t arrayLen = settings->getArrayLength(settingPath);
switch (valueType.baseType)
{
case BaseDataType::eBool:
switch (valueType.arrayDepth)
{
case 0:
getSetting<bool>(db);
break;
case 1:
{
auto outputValue = db.outputs.value().template get<bool[]>();
outputValue->resize(arrayLen);
settings->getAsBoolArray(settingPath, outputValue->data(), arrayLen);
break;
}
}
break;
case BaseDataType::eInt:
switch (valueType.componentCount)
{
case 1:
switch (valueType.arrayDepth)
{
case 0:
getSetting<int32_t>(db);
break;
case 1:
{
auto outputValue = db.outputs.value().template get<int32_t[]>();
outputValue->resize(arrayLen);
settings->getAsIntArray(settingPath, outputValue->data(), arrayLen);
break;
}
}
break;
case 2:
{
auto outputValue = db.outputs.value().template get<int32_t[2]>();
settings->getAsIntArray(settingPath, *outputValue, 2);
break;
}
case 3:
{
auto outputValue = db.outputs.value().template get<int32_t[3]>();
settings->getAsIntArray(settingPath, *outputValue, 3);
break;
}
case 4:
{
auto outputValue = db.outputs.value().template get<int32_t[4]>();
settings->getAsIntArray(settingPath, *outputValue, 4);
break;
}
}
break;
case BaseDataType::eInt64:
switch (valueType.arrayDepth)
{
case 0:
getSetting<int64_t>(db);
break;
case 1:
{
auto outputValue = db.outputs.value().template get<int64_t[]>();
outputValue->resize(arrayLen);
settings->getAsInt64Array(settingPath, outputValue->data(), arrayLen);
break;
}
}
break;
case BaseDataType::eFloat:
switch (valueType.componentCount)
{
case 1:
switch (valueType.arrayDepth)
{
case 0:
getSetting<float>(db);
break;
case 1:
{
auto outputValue = db.outputs.value().template get<float[]>();
outputValue->resize(arrayLen);
settings->getAsFloatArray(settingPath, outputValue->data(), arrayLen);
break;
}
}
break;
case 2:
{
auto outputValue = db.outputs.value().template get<float[2]>();
settings->getAsFloatArray(settingPath, *outputValue, 2);
break;
}
case 3:
{
auto outputValue = db.outputs.value().template get<float[3]>();
settings->getAsFloatArray(settingPath, *outputValue, 3);
break;
}
case 4:
{
auto outputValue = db.outputs.value().template get<float[4]>();
settings->getAsFloatArray(settingPath, *outputValue, 4);
break;
}
}
break;
case BaseDataType::eDouble:
switch (valueType.componentCount)
{
case 1:
switch (valueType.arrayDepth)
{
case 0:
getSetting<double>(db);
break;
case 1:
{
auto outputValue = db.outputs.value().template get<double[]>();
outputValue->resize(arrayLen);
settings->getAsFloat64Array(settingPath, outputValue->data(), arrayLen);
break;
}
}
break;
case 2:
{
auto outputValue = db.outputs.value().template get<double[2]>();
settings->getAsFloat64Array(settingPath, *outputValue, 2);
break;
}
case 3:
{
auto outputValue = db.outputs.value().template get<double[3]>();
settings->getAsFloat64Array(settingPath, *outputValue, 3);
break;
}
case 4:
{
auto outputValue = db.outputs.value().template get<double[4]>();
settings->getAsFloat64Array(settingPath, *outputValue, 4);
break;
}
}
break;
case BaseDataType::eToken:
switch (valueType.arrayDepth)
{
case 0:
{
auto outputValue = db.outputs.value().template get<OgnToken>();
std::string stringSetting = carb::settings::getString(settings, settingPath);
*outputValue = db.stringToToken(stringSetting.c_str());
break;
}
case 1:
{
auto outputValue = db.outputs.value().template get<OgnToken[]>();
outputValue->resize(arrayLen);
std::vector<std::string> stringSetting = carb::settings::getStringArray(settings, settingPath);
for(size_t i = 0; i < arrayLen; i++)
(*outputValue)[i] = db.stringToToken(stringSetting[i].c_str());
break;
}
}
break;
default:
{
db.logError("Type %s not supported", getOgnTypeName(valueType).c_str());
return false;
}
}
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 11,297 | C++ | 34.980892 | 116 | 0.524653 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrim.cpp | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// 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.
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "OgnWritePrimDatabase.h"
#define RETURN_TRUE_EXEC \
{ \
db.outputs.execOut() = kExecutionAttributeStateEnabled;\
return true; \
}
#include <omni/fabric/FabricUSD.h>
#include <omni/graph/core/IAttributeType.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/kit/PythonInterOpHelper.h>
#include <omni/usd/UsdContext.h>
#include "PrimCommon.h"
using namespace omni::fabric;
constexpr size_t kNonDynamicAttributeCount = 2;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnWritePrim
{
public:
// ----------------------------------------------------------------------------
// Called by OG when our prim attrib changes. We want to catch the case of changing the prim attribute interactively
static void onValueChanged(const AttributeObj& attrObj, const void* userData)
{
NodeObj nodeObj = attrObj.iAttribute->getNode(attrObj);
GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj);
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
updateForPrim(context, nodeObj, true /* removeStale */, kAccordingToContextIndex, pxr::SdfPath::EmptyPath(), false);
}
// ----------------------------------------------------------------------------
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
AttributeObj attribObj =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnWritePrimAttributes::inputs::prim.m_token);
// Register for value changed - even when connected. Because it's possible that an OgnPrim
// connection will be left dangling after clearing the relationship.
attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true);
}
/** ----------------------------------------------------------------------------
* Updates the dynamic attributes for the given node.
* @param nodeObj The WritePrim node in question
* @param removeStale true means we should remove any dynamic attributes which aren't for the current inputs:prim
*/
static bool updateForPrim(GraphContextObj context, NodeObj nodeObj, bool removeStale, InstanceIndex instanceIndex,
pxr::SdfPath targetPrimPath, bool usdWriteBack)
{
const INode& iNode = *nodeObj.iNode;
const IAttribute& iAttribute = *carb::getCachedInterface<IAttribute>();
// Find our stage
auto iFabricUsd = carb::getCachedInterface<IFabricUsd>();
CARB_ASSERT(iFabricUsd);
pxr::UsdStageRefPtr stage;
omni::fabric::FabricId fabricId;
std::tie(fabricId, stage) = getFabricForNode(context, nodeObj);
if (fabricId == omni::fabric::kInvalidFabricId)
return false;
// Find the input prim via the relationship
pxr::UsdPrim targetPrim;
const char* thisPrimPathStr = iNode.getPrimPath(nodeObj);
pxr::SdfPath thisPrimPath(thisPrimPathStr);
{
// Read the path from the relationship input on this compute node
const pxr::UsdPrim thisPrim = stage->GetPrimAtPath(thisPrimPath);
if (!thisPrim.IsValid())
{
CARB_LOG_ERROR("ReadPrim requires USD backing.");
return false;
}
if (!targetPrimPath.IsEmpty())
{
targetPrim = stage->GetPrimAtPath(targetPrimPath);
if (!targetPrim)
{
CARB_LOG_ERROR_ONCE("Could not find specified prim at path %s", targetPrimPath.GetText());
return false;
}
}
else
{
// No input prim specified. This is ok, but we may have stale attributes. We rely on this function being
// called with removeStale = true to do the clean up.
if (!removeStale)
return true;
// If we have more attributes than we get by default, we know there is at least one dynamic attribute to
// be removed
size_t numAttributes = iNode.getAttributeCount(nodeObj);
if (numAttributes > kNonDynamicAttributeCount)
{
// Build a python script to disconnect and delete all dynamic attribs in one shot
static const char* cmdFmt = "import omni.graph.core as og\n"
"og.remove_attributes_if(\"%s\", lambda a: a.is_dynamic() and og.is_attribute_plain_data(a))\n";
std::string fullCmd = formatString(cmdFmt, thisPrimPathStr);
omni::kit::PythonInterOpHelper::executeCommand(fullCmd.c_str());
}
// No need to do anything more since we have no prim specified
return true;
}
}
// -----------------------------------------------------------------------------------------
// Update / Add dynamic attributes.
std::vector<AttrNameAndType> attrsOfInterest;
bool ok = addDynamicAttribs(
targetPrim, iFabricUsd, fabricId, targetPrimPath, nodeObj, thisPrimPathStr, true, attrsOfInterest);
if (!ok)
return false;
// We always have to copy our attribute data to the prim
for (auto iter = attrsOfInterest.begin(); iter != attrsOfInterest.end(); iter++)
{
TokenC primAttrName = iter->name;
// our attribute name will automatically include the "inputs:" prefix
NameToken thisAttrName = iAttribute.ensurePortTypeInName(primAttrName, AttributePortType::kAttributePortType_Input, false);
copyAttributeDataToPrim(context, asInt(targetPrimPath), primAttrName, nodeObj, thisAttrName, instanceIndex,
false, usdWriteBack);
}
return true;
}
static bool compute(OgnWritePrimDatabase& db)
{
pxr::SdfPath sdfPath;
const auto& prims = db.inputs.prim();
if(prims.size() > 0)
{
sdfPath = omni::fabric::toSdfPath(prims[0]);
}
// Update attribs, but do not make any topological changes as this could destabilize the evaluation
bool ok = updateForPrim(db.abi_context(), db.abi_node(), false /* removeStale */, db.getInstanceIndex(),
sdfPath, db.inputs.usdWriteBack());
if (ok)
RETURN_TRUE_EXEC
return false;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 7,417 | C++ | 39.758242 | 144 | 0.600512 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnCopyAttr.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 "OgnCopyAttrDatabase.h"
#include "TokenUtils.h"
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnCopyAttr
{
public:
// Copies all attributes from one input prim and specified attributes from a
// second input prim to the output prim.
static bool compute(OgnCopyAttrDatabase& db)
{
const auto& fullInputBundle = db.inputs.fullData();
auto& outputBundle = db.outputs.data();
// Set up the output, first by copying the input 'fullData' into the output if it exists, else clearing it
outputBundle = db.inputs.fullData();
if (!outputBundle.isValid())
{
db.logError("Failed to copy entire input bundle to the output");
return false;
}
// Find all of the attribute names for selection.
std::vector<NameToken> inputAttrNames;
std::vector<NameToken> outputAttrNames;
if (!TokenHelper::splitNames(db.tokenToString(db.inputs.inputAttrNames()), inputAttrNames) ||
!TokenHelper::splitNames(db.tokenToString(db.inputs.outputAttrNames()), outputAttrNames))
{
db.logError("Could not parse the attribute names");
return false;
}
// Mismatched name sizes are dealt with going with the minimum number, and reporting this warning
if (inputAttrNames.size() != outputAttrNames.size())
{
db.logWarning("Input name size %zu != output name size %zu", inputAttrNames.size(), outputAttrNames.size());
}
// Loop through the name list, adding attributes from the input
size_t nameCount = std::min(inputAttrNames.size(), outputAttrNames.size());
if (nameCount == 0)
{
return true;
}
// Figure out which bundle is to be used for renamed attributes
const auto& partialInputBundle = db.inputs.partialData();
const auto& renamingBundle = partialInputBundle.isValid() ? partialInputBundle : fullInputBundle;
auto& context = db.abi_context();
for (size_t name_index = 0; name_index < nameCount; ++name_index)
{
auto bundledAttribute = renamingBundle.attributeByName(inputAttrNames[name_index]);
if (!bundledAttribute.isValid())
{
db.logWarning("Input attribute '%s' not found in bundle", db.tokenToString(inputAttrNames[name_index]));
continue;
}
outputBundle.insertAttribute(bundledAttribute, outputAttrNames[name_index]);
}
return true;
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 3,144 | C++ | 34.738636 | 120 | 0.658397 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimAttributes.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 "OgnReadPrimAttributesDatabase.h"
#include "ReadPrimCommon.h"
#include <omni/kit/commands/ICommandBridge.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnReadPrimAttributes
{
std::unordered_set<NameToken> m_added;
public:
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
// When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected.
AttributeObj inputBundleAttribObj =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimAttributesAttributes::inputs::prim.m_token);
inputBundleAttribObj.iAttribute->registerValueChangedCallback(
inputBundleAttribObj, onInputBundleValueChanged, true);
}
// ----------------------------------------------------------------------------
static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData)
{
NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj);
GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj);
// If the graph is currently disabled then delay the update until the next compute.
// Arguably this should be done at the message propagation layer, then this wouldn't be necessary.
if (graphObj.iGraph->isDisabled(graphObj))
{
return;
}
// clear the output bundles
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
auto outputTokens = { OgnReadPrimAttributesAttributes::outputs::primBundle.m_token };
for (auto& outputToken : outputTokens)
{
BundleHandle outBundle = context.iContext->getOutputBundle(
context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex);
context.iContext->clearBundleContents(context, outBundle);
}
// Remove dynamic attributes
BundleType empty;
updateAttributes(context, nodeObj, empty, kAccordingToContextIndex);
}
// ----------------------------------------------------------------------------
static PathC getPath(OgnReadPrimAttributesDatabase& db)
{
GraphContextObj contextObj = db.abi_context();
std::string const primPathStr{ db.inputs.primPath() };
NameToken primPath = contextObj.iToken->getHandle(primPathStr.c_str());
return readPrimBundle_getPath(contextObj, db.abi_node(),
OgnReadPrimAttributesAttributes::inputs::prim.m_token, db.inputs.usePath(),
primPath, db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static bool writeToBundle(OgnReadPrimAttributesDatabase& db, PathC inputPath, bool force, pxr::UsdTimeCode const& time)
{
GraphContextObj contextObj = db.abi_context();
NodeObj nodeObj = db.abi_node();
std::string attrNamesStr{ db.inputs.attrNamesToImport() };
NameToken attrNames = contextObj.iToken->getHandle(attrNamesStr.c_str());
return readPrimBundle_writeToBundle(contextObj, nodeObj, inputPath, attrNames, db.outputs.primBundle(), force,
false, time, db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static void clean(OgnReadPrimAttributesDatabase& db)
{
db.outputs.primBundle().clear();
// remove dynamic attributes
BundleType empty;
updateAttributes(db.abi_context(), db.abi_node(), empty, db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static void updateAttributes(GraphContextObj const& contextObj,
NodeObj const& nodeObj,
BundleType const& bundle,
InstanceIndex instIdx)
{
OgnReadPrimAttributes& state = OgnReadPrimAttributesDatabase::sInternalState<OgnReadPrimAttributes>(nodeObj);
omni::kit::commands::ICommandBridge::ScopedUndoGroup scopedUndoGroup;
extractBundle_reflectBundleDynamicAttributes(nodeObj, contextObj, bundle, state.m_added, instIdx);
}
// ----------------------------------------------------------------------------
static bool compute(OgnReadPrimAttributesDatabase& db)
{
auto& context = db.abi_context();
auto& nodeObj = db.abi_node();
// import by pattern
bool inputChanged = false;
// attribute filter changed
std::string attrNamesToImport{ db.inputs.attrNamesToImport() };
if (db.state.attrNamesToImport() != attrNamesToImport)
{
db.state.attrNamesToImport() = attrNamesToImport;
inputChanged = true;
}
// compute
bool result = readPrimBundle_compute<OgnReadPrimAttributes>(db, inputChanged);
if (!result)
return false;
// update dynamic attributes
BundleType outputBundle(context, db.outputs.primBundle().abi_bundleHandle());
updateAttributes(context, nodeObj, outputBundle, db.getInstanceIndex());
return outputBundle.isValid();
}
// ----------------------------------------------------------------------------
static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
if (oldVersion < 2)
{
return upgradeUsdTimeCodeInput(context, nodeObj);
}
}
return false;
}
};
REGISTER_OGN_NODE()
}
}
}
| 6,350 | C++ | 38.203703 | 123 | 0.59685 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimsV2.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"
#include <carb/dictionary/DictionaryUtils.h>
#include <omni/fabric/FabricUSD.h>
#include <omni/kit/PythonInterOpHelper.h>
#include "FindPrimsPathTracker.h"
#include "ReadPrimCommonV2.h"
#include "DebugUtils.h"
#include "OgnReadPrimsV2Database.h"
// clang-format on
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnReadPrimsV2
{
fabric::FabricId m_fabricId;
fabric::Token m_pathTrackerId;
unstable::UsdPrimChangeTracker::Subscription m_changeTrackerSubscription;
PrimPathsState m_inputPrimPaths;
PrimPathsState m_primPaths;
// Print debug stuff to the console?
#if 0
# define debugPrintLn(nodeObj, fmt, ...) DebugHelper::printLn((nodeObj), (fmt), ##__VA_ARGS__)
#else
# define debugPrintLn(nodeObj, fmt, ...) ((void)0)
#endif
// ----------------------------------------------------------------------------
// OGN currently doesn't offer per-instance initialize/release callbacks,
// so we must create per-instance state on demand, during compute
static OgnReadPrimsV2& ensurePerInstanceState(OgnReadPrimsV2Database& db)
{
auto& internalState = db.perInstanceState<OgnReadPrimsV2>();
if (internalState.m_fabricId == fabric::kInvalidFabricId)
{
auto& context = db.abi_context();
auto& nodeObj = db.abi_node();
// Initialize per-instance internal state.
std::tie(internalState.m_fabricId, std::ignore) = getFabricForNode(context, nodeObj);
// Initialize path tracker
IToken const& iToken = *carb::getCachedInterface<omni::fabric::IToken>();
// Build a unique per-node-instance key for the path target.
std::stringstream ss;
ss << nodeObj.iNode->getPrimPath(nodeObj);
auto const graphObj = nodeObj.iNode->getGraph(nodeObj);
if (graphObj.iGraph->getInstanceCount(graphObj))
{
// For instances, append the graph target.
ss << iToken.getText(db.getGraphTarget());
}
internalState.m_pathTrackerId = iToken.getHandle(PXR_NS::TfMakeValidIdentifier(ss.str()).c_str());
unstable::UsdPrimChangeTracker::AnyTrackedPrimChangedCallback primChangedCallback = [nodeObj]()
{
// If any tracked prim changes, force this node to recompute.
debugPrintLn(nodeObj, "Any tracked prim was changed in instance '%s' => requesting re-computation",
intToToken(nodeObj.iNode->getGraphInstanceID(nodeObj.nodeHandle, {})).GetText());
nodeObj.iNode->requestCompute(nodeObj);
};
// Initialize prim change tracker
if (internalState.m_changeTrackerSubscription.initialize(context))
{
internalState.m_changeTrackerSubscription.setTrackedPrimChangedCallback(std::move(primChangedCallback));
}
else
{
OgnReadPrimsV2Database::logError(nodeObj, "Failed to initialize USD prim change tracker!");
}
}
return internalState;
}
// ----------------------------------------------------------------------------
static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData)
{
NodeObj const nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj);
GraphObj const graphObj = nodeObj.iNode->getGraph(nodeObj);
// If the graph is currently disabled then delay the update until the next compute.
// Arguably this should be done at the message propagation layer, then this wouldn't be necessary.
if (graphObj.iGraph->isDisabled(graphObj))
{
return;
}
// clear the output bundles
GraphContextObj const context = graphObj.iGraph->getDefaultGraphContext(graphObj);
auto const outputTokens = { OgnReadPrimsV2Attributes::outputs::primsBundle.m_token };
for (auto& outputToken : outputTokens)
{
BundleHandle const outBundle = context.iContext->getOutputBundle(
context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex);
context.iContext->clearBundleContents(context, outBundle);
}
}
// ----------------------------------------------------------------------------
static PathVector getMatchedPaths(OgnReadPrimsV2Database const& db, PathVector const* primPaths)
{
auto& context = db.abi_context();
auto& nodeObj = db.abi_node();
PathVector matchedPaths;
if (!db.inputs.pathPattern().empty())
{
auto [fabricId, stage] = getFabricForNode(context, nodeObj);
PXR_NS::TfToken const pathPattern{ std::string{ db.inputs.pathPattern() } };
if (pathPattern.IsEmpty())
return {};
std::string const typePatternStr{ db.inputs.typePattern() };
PXR_NS::TfToken const typePattern{ typePatternStr };
if (!primPaths || primPaths->empty())
{
PXR_NS::UsdPrim const startPrim = stage->GetPseudoRoot();
findPrims_findMatching(
matchedPaths, startPrim, true, nullptr, typePattern, {}, {}, {}, pathPattern, true, true);
}
else
{
PXR_NS::SdfPathVector consolidatedPaths;
consolidatedPaths.reserve(primPaths->size());
std::transform(primPaths->cbegin(), primPaths->cend(), std::back_inserter(consolidatedPaths),
[](fabric::PathC pathC) { return fabric::toSdfPath(pathC); });
// There's no need to find prims in /foo/bar if /foo is already one of the search paths
PXR_NS::SdfPath::RemoveDescendentPaths(&consolidatedPaths);
for (auto const& path : consolidatedPaths)
{
if (PXR_NS::UsdPrim startPrim = stage->GetPrimAtPath(path))
{
findPrims_findMatching(
matchedPaths, startPrim, true, nullptr, typePattern, {}, {}, {}, pathPattern, true, true);
}
}
}
}
else
{
matchedPaths = *primPaths;
}
return matchedPaths;
}
// ----------------------------------------------------------------------------
static bool writeToBundle(OgnReadPrimsV2Database& db,
gsl::span<PathC const> inputPaths,
bool forceFullUpdate,
bool enableChangeTracking,
pxr::UsdTimeCode const& time)
{
auto& context = db.abi_context();
auto& nodeObj = db.abi_node();
std::string const attrNamesStr{ db.inputs.attrNamesToImport() };
NameToken const attrNames = context.iToken->getHandle(attrNamesStr.c_str());
bool const computeBoundingBox = db.inputs.computeBoundingBox();
auto& containerBundle = db.outputs.primsBundle();
int const debugStamp = db.inputs._debugStamp();
bool const timeSampling = pxr::UsdTimeCode::Default() != time;
// Update or reset the USD prim change tracker.
auto& subscription = db.perInstanceState<OgnReadPrimsV2>().m_changeTrackerSubscription;
if (!subscription.isValid() || timeSampling || !enableChangeTracking)
{
debugPrintLn(nodeObj, "Doing full container bundle update (w/o change tracking)");
// We don't do any change tracking when time sampling the prims, this has overhead for nothing.
// TODO: We could detect that the prim doesn't have any time sampled attributes!
subscription.reset();
return readPrimsBundleV2_writeToBundle(context, nodeObj, inputPaths, attrNames, containerBundle,
forceFullUpdate, computeBoundingBox, time, db.getInstanceIndex(),
debugStamp);
}
// Update change tracking.
// When doing a forced output update, we need to start change tracking now,
// so we can get the changes in the next compute.
// NOTE: We assume that `force` will be true when switching from animated to non-animate compute!
unstable::UsdPrimChangeTracker::TrackOptions trackOptions;
// TODO: We should make world matrices optional
constexpr bool computeWorldMatrix = true;
// NOTE: We output local bounding boxes, and these depend on the world matrix too.
trackOptions.ancestors = computeBoundingBox || computeWorldMatrix;
// When computing bounding boxes, we need to observe descendant changes.
trackOptions.descendants = computeBoundingBox;
auto const changedPrimPaths = forceFullUpdate ? subscription.track(inputPaths, trackOptions) : subscription.update();
if (!forceFullUpdate &&
readPrimsBundleV2_updateOutputBundle(
context, nodeObj, changedPrimPaths, attrNames, containerBundle, computeBoundingBox, time, db.getInstanceIndex(), debugStamp))
{
// Incremental update succeeded.
return true;
}
// Full update
debugPrintLn(nodeObj, "Doing full container bundle update (forced)");
return readPrimsBundleV2_writeToBundle(
context, nodeObj, inputPaths, attrNames, containerBundle, true, computeBoundingBox, time, db.getInstanceIndex(), debugStamp);
}
// ----------------------------------------------------------------------------
static void clean(OgnReadPrimsV2Database& db)
{
db.outputs.primsBundle().clear();
if (db.inputs.enableBundleChangeTracking())
{
db.outputs.primsBundle.changes().activate();
}
else
{
db.outputs.primsBundle.changes().deactivate();
}
}
// ----------------------------------------------------------------------------
void updatePathTracker(bool hasPathPattern, PathVector const& rootPrimPaths) const
{
if (hasPathPattern)
{
if (rootPrimPaths.empty())
{
setFindPrimsRootPrimPaths(
m_fabricId, m_pathTrackerId, { fabric::asInt(PXR_NS::SdfPath::AbsoluteRootPath()) });
}
else
{
setFindPrimsRootPrimPaths(m_fabricId, m_pathTrackerId, rootPrimPaths);
}
}
else
{
setFindPrimsRootPrimPaths(m_fabricId, m_pathTrackerId, {});
}
}
public:
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
// When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected.
AttributeObj const inputBundleAttribObj =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimsV2Attributes::inputs::prims.m_token);
inputBundleAttribObj.iAttribute->registerValueChangedCallback(
inputBundleAttribObj, onInputBundleValueChanged, true);
}
// ----------------------------------------------------------------------------
~OgnReadPrimsV2()
{
removeFindPrimsRootPrimPathsEntry(m_fabricId, m_pathTrackerId);
}
// ----------------------------------------------------------------------------
static bool compute(OgnReadPrimsV2Database& db)
{
auto& internalState = ensurePerInstanceState(db);
auto& context = db.abi_context();
auto& nodeObj = db.abi_node();
auto const prevPathPattern = db.state.pathPattern();
auto const& pathPattern = db.inputs.pathPattern();
bool const pathPatternChanged = prevPathPattern != pathPattern;
// import by pattern
bool inputChanged = pathPatternChanged || db.state.typePattern() != db.inputs.typePattern();
db.state.pathPattern() = pathPattern;
db.state.typePattern() = db.inputs.typePattern();
// primPaths changed
// primPaths serves two different purposes.
// - if pathPattern not empty, primPaths are used as the root prims to apply pattern matching on
// - if pathPattern is empty, primPaths are the prims to be read directly from
auto primPaths = readPrimBundle_getPaths(
context, nodeObj, OgnReadPrimsV2Attributes::inputs::prims.m_token, false, {}, db.getInstanceIndex());
bool const rootPrimPathsChanged = internalState.m_inputPrimPaths.changed(primPaths);
if (rootPrimPathsChanged)
{
internalState.m_inputPrimPaths.store(primPaths);
inputChanged = true;
}
// bounding box changed
bool const computeBoundingBox = db.inputs.computeBoundingBox();
if (db.state.computeBoundingBox() != computeBoundingBox)
{
db.state.computeBoundingBox() = computeBoundingBox;
inputChanged = true;
}
// attribute filter changed
std::string const attrNamesToImport{ db.inputs.attrNamesToImport() };
if (db.state.attrNamesToImport() != attrNamesToImport)
{
db.state.attrNamesToImport() = attrNamesToImport;
inputChanged = true;
}
// applySkelBinding toggle changed
bool const applySkelBinding = db.inputs.applySkelBinding();
if (db.state.applySkelBinding() != applySkelBinding)
{
db.state.applySkelBinding() = applySkelBinding;
inputChanged = true;
}
// enableChangeTracking toggle changed
bool const enableUsdChangeTracking = db.inputs.enableChangeTracking();
if (db.state.enableChangeTracking() != enableUsdChangeTracking)
{
db.state.enableChangeTracking() = enableUsdChangeTracking;
inputChanged = true;
}
bool const enableBundleChangeTracking = db.inputs.enableBundleChangeTracking();
if (db.state.enableBundleChangeTracking() != enableBundleChangeTracking)
{
db.state.enableBundleChangeTracking() = enableBundleChangeTracking;
inputChanged = true;
}
// root prim paths changed or path pattern changed to/from empty
if (rootPrimPathsChanged || (pathPatternChanged && (pathPattern.empty() || prevPathPattern.empty())))
{
internalState.updatePathTracker(!pathPattern.empty(), primPaths);
}
// NOTE: we need to use UsdTimeCode to compare to current and previous time,
// because unlike SdfTimeCode, UsdTimeCode correctly deals with Default (NaN) time.
pxr::UsdTimeCode const time = getTime(db);
if (time != db.state.usdTimecode())
{
// time changed
inputChanged = true;
db.state.usdTimecode() = pxr::SdfTimeCode(time.GetValue());
}
// matched paths changed
PathVector const matchedPaths = getMatchedPaths(db, &primPaths);
if (internalState.m_primPaths.changed(matchedPaths))
{
internalState.m_primPaths.store(matchedPaths);
inputChanged = true;
}
// clean this node only when something changed
if (inputChanged)
{
clean(db);
}
// nothing to write
if (matchedPaths.empty())
{
return false;
}
// write the data
bool outputChanged = writeToBundle(db, matchedPaths, inputChanged, enableUsdChangeTracking, time);
if (applySkelBinding)
{
ogn::BundleContents<ogn::kOgnOutput, ogn::kCpu>& outputBundle = db.outputs.primsBundle();
if (readSkelBinding_compute(context, nodeObj, outputBundle, attrNamesToImport, inputChanged,
computeBoundingBox, getTime(db)))
{
outputChanged |= applySkelBinding_compute(context, outputBundle);
}
}
return outputChanged;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 16,839 | C++ | 38.345794 | 141 | 0.596472 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimsBundle.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"
#include <omni/graph/core/PreUsdInclude.h>
#include <omni/usd/UsdContext.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usdGeom/bboxCache.h>
#include <omni/graph/core/PostUsdInclude.h>
// clang-format on
#include "OgnReadPrimsBundleDatabase.h"
#include "PrimCommon.h"
#include "ReadPrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
/************************************************************************/
/* */
/************************************************************************/
class OgnReadPrimsBundle
{
public:
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
// When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected.
AttributeObj inputBundleAttribObj =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimsBundleAttributes::inputs::prims.m_token);
inputBundleAttribObj.iAttribute->registerValueChangedCallback(
inputBundleAttribObj, onInputBundleValueChanged, true);
}
// ----------------------------------------------------------------------------
static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData)
{
NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj);
GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj);
// If the graph is currently disabled then delay the update until the next compute.
// Arguably this should be done at the message propagation layer, then this wouldn't be necessary.
if (graphObj.iGraph->isDisabled(graphObj))
{
return;
}
// clear the output bundles
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
auto outputTokens = { OgnReadPrimsBundleAttributes::outputs::primsBundle.m_token };
for (auto& outputToken : outputTokens)
{
BundleHandle outBundle = context.iContext->getOutputBundle(
context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex);
context.iContext->clearBundleContents(context, outBundle);
}
}
// ----------------------------------------------------------------------------
static PathVector getMatchedPaths(OgnReadPrimsBundleDatabase& db, PathVector const* primPaths)
{
auto& context = db.abi_context();
auto& nodeObj = db.abi_node();
return readPrimBundle_getPaths(context, nodeObj, OgnReadPrimsBundleAttributes::inputs::prims.m_token,
db.inputs.usePaths(), db.inputs.primPaths(), db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static bool writeToBundle(OgnReadPrimsBundleDatabase& db,
gsl::span<PathC const> inputPaths,
bool force,
pxr::UsdTimeCode const& time)
{
std::string attrNamesStr{ db.inputs.attrNamesToImport() };
NameToken attrNames = db.abi_context().iToken->getHandle(attrNamesStr.c_str());
return readPrimsBundle_writeToBundle(
db.abi_context(), db.abi_node(), inputPaths, attrNames, db.outputs.primsBundle(), force, false, time, db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static void clean(OgnReadPrimsBundleDatabase& db)
{
db.outputs.primsBundle().clear();
}
// ----------------------------------------------------------------------------
static bool compute(OgnReadPrimsBundleDatabase& db)
{
bool inputChanged = false;
if (db.state.usePaths() != db.inputs.usePaths())
{
db.state.usePaths() = db.inputs.usePaths();
inputChanged = true;
}
// attribute filter changed
std::string attrNamesToImport{ db.inputs.attrNamesToImport() };
if (db.state.attrNamesToImport() != attrNamesToImport)
{
db.state.attrNamesToImport() = attrNamesToImport;
inputChanged = true;
}
return readPrimsBundle_compute<OgnReadPrimsBundle>(db, inputChanged);
}
// ----------------------------------------------------------------------------
static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
if (oldVersion < 2)
{
return upgradeUsdTimeCodeInput(context, nodeObj);
}
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 5,486 | C++ | 37.914893 | 137 | 0.570179 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrimRelationship.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 <OgnWritePrimRelationshipDatabase.h>
#include "PrimCommon.h"
namespace omni {
namespace graph {
namespace nodes {
class OgnWritePrimRelationship {
public:
// ----------------------------------------------------------------------------
// Prefetch prim to fabric
static void setup(NodeObj const& nodeObj, GraphObj const& graphObj, OgnWritePrimRelationshipDatabase& db, size_t offset)
{
db.state.correctlySetup(offset) = false;
TargetPath prim = db.inputs.prim.firstOrDefault(offset);
NameToken name = db.inputs.name(offset);
std::set<omni::fabric::TokenC> attributes = {name.token};
prefetchPrim(graphObj, nodeObj, prim, attributes);
db.state.correctlySetup(offset) = true;
db.state.prim(offset).resize(1);
db.state.prim(offset)[0] = prim;
db.state.name(offset) = name;
}
static void onValueChanged(AttributeObj const& attrObj, void const* userData)
{
NodeObj nodeObj{ attrObj.iAttribute->getNode(attrObj) };
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
GraphContextObj contextObj = graphObj.iGraph->getDefaultGraphContext(graphObj);
OgnWritePrimRelationshipDatabase db(contextObj, nodeObj);
setup(nodeObj, graphObj, db, 0);
}
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
std::array<NameToken, 2> attribNames{inputs::name.m_token, inputs::prim.m_token};
for (auto const& attribName : attribNames)
{
AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, attribName);
attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true);
}
}
// ----------------------------------------------------------------------------
static size_t computeVectorized(OgnWritePrimRelationshipDatabase& db, size_t count)
{
NodeObj nodeObj = db.abi_node();
GraphContextObj context = db.abi_context();
GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj);
auto name = db.inputs.name.vectorized(count);
auto usdWriteBack = db.inputs.usdWriteBack.vectorized(count);
auto correctlySetup = db.state.correctlySetup.vectorized(count);
auto nameState = db.state.name.vectorized(count);
auto execOut = db.outputs.execOut.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
TargetPath curPrim = db.inputs.prim.firstOrDefault(idx);
if(!correctlySetup[idx] ||
db.state.prim(idx).size() == 0 ||
db.state.prim(idx)[0] != curPrim ||
nameState[idx] != name[idx])
{
setup(nodeObj, graphObj, db, idx);
}
if(correctlySetup[idx])
{
setRelationshipTargets(context, nodeObj, curPrim, name[idx], db.inputs.value(idx), usdWriteBack[idx]);
execOut[idx] = kExecutionAttributeStateEnabled;
}
}
return count;
}
};
REGISTER_OGN_NODE()
}// namespace nodes
}// namespace graph
}// namespace omni
| 3,825 | C++ | 36.145631 | 124 | 0.614641 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadVariable.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 <OgnReadVariableDatabase.h>
#include <carb/events/EventsUtils.h>
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace core
{
class OgnReadVariable
{
public:
carb::events::ISubscriptionPtr m_EventSubscription;
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::variableName.m_token);
attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true);
onConnectionTypeResolve(nodeObj);
GraphObj graphObj{ context.iContext->getGraph(context) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
OgnReadVariableDatabase::sInternalState<OgnReadVariable>(nodeObj)
.m_EventSubscription = carb::events::createSubscriptionToPop(graphObj.iGraph->getEventStream(graphObj).get(),
[nodeObj](carb::events::IEvent* e)
{
switch (static_cast<IGraphEvent>(e->type))
{
case IGraphEvent::eCreateVariable:
case IGraphEvent::eRemoveVariable:
case IGraphEvent::eVariableTypeChange:
onConnectionTypeResolve(nodeObj);
break;
default:
break;
}
});
}
// ----------------------------------------------------------------------------
// Called by OG to resolve the output type
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
onValueChanged(nodeObj.iNode->getAttributeByToken(nodeObj, inputs::variableName.m_token), nullptr);
}
// ----------------------------------------------------------------------------
// Called by OG when the value of the variableName changes
static void onValueChanged(AttributeObj const& attrObj, void const* userData)
{
auto nodeObj = attrObj.iAttribute->getNode(attrObj);
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
auto graphObj = nodeObj.iNode->getGraph(nodeObj);
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
auto context = graphObj.iGraph->getDefaultGraphContext(graphObj);
if (context.contextHandle == kInvalidGraphContextHandle)
return;
Type type(BaseDataType::eUnknown);
const auto token = getDataR<NameToken>(
context, attrObj.iAttribute->getConstAttributeDataHandle(attrObj, kAccordingToContextIndex));
if (token)
{
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
auto variable = graphObj.iGraph->findVariable(graphObj, tokenInterface->getText(*token));
if (variable)
{
type = variable->getType();
}
}
omni::graph::nodes::tryResolveOutputAttribute(nodeObj, outputs::value.m_token, type);
}
static size_t computeVectorized(OgnReadVariableDatabase& db, size_t count)
{
auto variable = db.getVariable(db.inputs.variableName());
if (!variable.isValid())
return 0;
auto& node = db.abi_node();
// make sure the types match
if (variable.type() != db.outputs.value().type())
{
auto attribute = node.iNode->getAttributeByToken(node, outputs::value.m_token);
auto handle = db.outputs.value().abi_handle();
attribute.iAttribute->setResolvedType(attribute, variable.type());
db.outputs.value().reset(db.abi_context(), handle, attribute);
return 0;
}
//if the variable name is not a constant (ie. each instance may point to a different variable)
// or the type is an array type (may have/trigger CoW or data stealing), we cannot do a vectorized compute,
// and going through the ABI is mandatory on a per instance basis
auto varNameAttrib = node.iNode->getAttributeByToken(node, inputs::variableName.m_token);
bool const isVarNameConstant = varNameAttrib.iAttribute->isRuntimeConstant(varNameAttrib);
if (variable.type().arrayDepth || !isVarNameConstant)
{
auto varName = db.inputs.variableName();
for (size_t i = 0; i < count; ++i)
{
db.outputs.value().copyData(db.getVariable(varName));
db.moveToNextInstance();
}
}
else
{
uint8_t* dst = nullptr;
size_t sd;
db.outputs.value().rawData(dst, sd);
uint8_t* src = nullptr;
size_t ss;
variable.rawData(src, ss);
if (ss != sd)
return 0;
memcpy(dst, src, ss * count);
}
return count;
}
};
REGISTER_OGN_NODE()
} // namespace examples
} // namespace graph
} // namespace omni
| 6,311 | C++ | 40.801324 | 121 | 0.524164 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrimsV2.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 "FindPrimsPathTracker.h"
#include "LayerIdentifierResolver.h"
#include "OgnWritePrimsV2Database.h"
#include "SpanUtils.h"
#include "WritePrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnWritePrimsV2
{
// keep a set of prims that has been *created* by this node.
// If the node writes to an existing prim on the stage, it's not counted as created.
// it will be reset every time removeMissingPrims is true to track the diff
// track Usd and Fabric separately since usdWriteBack can be turned on or off
PXR_NS::SdfPathUSet createdUsdPrims;
PXR_NS::SdfPathUSet createdFabricPrims;
// keep a map of attributes that has been *created* by this node.
// If the node writes to an existing attribute on the stage, it's not counted as created.
// it will be reset every time removeMissingAttributes is true to track the diff
// track Usd and Fabric separately since usdWriteBack can be turned on or off
PXR_NS::SdfPathUSet createdUsdAttributes;
PXR_NS::SdfPathUSet createdFabricAttributes;
PathToMetadataMap createdObjectMetadata;
PrimPathsState targetPrimPaths;
static size_t getConnectedPrimCount(OgnWritePrimsV2Database& db)
{
GraphContextObj const& contextObj = db.abi_context();
NodeObj const& nodeObj = db.abi_node();
NodeContextHandle const nodeHandle = nodeObj.nodeContextHandle;
NameToken const primsToken = inputs::primsBundle.token();
return contextObj.iContext->getInputTargetCount(contextObj, nodeHandle, primsToken, db.getInstanceIndex());
}
//! Check if any of the targetPrim paths are descendants of any of the Root Prims paths in find/read prims.
//! If any of the path is an descendant, then the output prim(s) can potentially mutate the input prims' states,
//! creating a loop. This is undesirable and prohibited to prevent user errors.
//!
//! returns true if loop is detected.
static bool detectFindPrimsPathsLoop(GraphContextObj const& context,
const NodeObj& nodeObj,
PathVector const& targetPrimPaths)
{
fabric::FabricId fabricId;
std::tie(fabricId, std::ignore) = getFabricForNode(context, nodeObj);
auto const rootPrimPaths = getRootPrimPathsSet(fabricId);
if (rootPrimPaths.empty())
{
return false;
}
// AbsoluteRootPath has to be the smallest path in the set if exists
// a quick test
if (*rootPrimPaths.begin() == PXR_NS::SdfPath::AbsoluteRootPath())
{
ogn::OmniGraphDatabase::logError(
nodeObj,
"FindPrims/ReadPrims source contains absolute root path \"/\", writing to any target on the stage may mutate the input state. "
"Please choose a different source root prim path for FindPrims/ReadPrims.");
return true;
}
PXR_NS::SdfPathSet targetPrimPathsSet;
std::transform(targetPrimPaths.cbegin(), targetPrimPaths.cend(),
std::inserter(targetPrimPathsSet, targetPrimPathsSet.begin()),
[](fabric::PathC pathC) { return fabric::toSdfPath(pathC); });
for (auto const& rootPrimPath : rootPrimPaths)
{
auto const lb = targetPrimPathsSet.lower_bound(rootPrimPath);
// if a lower_bound in targetPrimPaths is a descendant of rootPrimPath, a loop could form
if (lb != targetPrimPathsSet.end() && lb->HasPrefix(rootPrimPath))
{
ogn::OmniGraphDatabase::logError(
nodeObj,
"Target prim '%s' is a descendant of FindPrims/ReadPrims source '%s', writing to the target may mutate the input state. Please choose a different target",
lb->GetText(), rootPrimPath.GetText());
return true;
}
}
return false;
}
static void handleMissingPrims(OgnWritePrimsV2Database& db,
PXR_NS::SdfPathUSet const& createdPrimPaths,
bool removeMissingPrims = true)
{
auto& internalState = OgnWritePrimsV2Database::sInternalState<OgnWritePrimsV2>(db.abi_node());
auto& prevCreatedUsdPrims = internalState.createdUsdPrims;
auto& prevCreatedFabricPrims = internalState.createdFabricPrims;
// if removeMissingPrims and usdWriteBack, find the diff of this compute's createdPrimPaths vs last
// removeMissingPrims's createdPrimPaths, and removes the ones that no longer exist in current
// createdPrimPaths
auto processMissingPrims = [&db, &createdPrimPaths, removeMissingPrims](
PXR_NS::SdfPathUSet& prevCreatedPrims, bool isUsd)
{
if (createdPrimPaths == prevCreatedPrims)
{
return;
}
if (removeMissingPrims)
{
// if removeMissingPrims is on:
// - always removes missing prims from fabric
// - if usdWriteBack is on, also remove missing prims from USD
PXR_NS::SdfPathVector primPathsToRemove;
primPathsToRemove.reserve(prevCreatedPrims.size());
for (const auto& path : prevCreatedPrims)
{
// previously created prim no longer exists
if (createdPrimPaths.find(path) == createdPrimPaths.end())
{
ogn::OmniGraphDatabase::logWarning(
db.abi_node(),
"Previously created prim %s no longer exists in upstream bundle. Removing it from %s...",
path.GetText(), isUsd ? "USD" : "Fabric");
primPathsToRemove.push_back(path);
}
}
if (!primPathsToRemove.empty())
{
removePrims(db.abi_context(), db.abi_node(), primPathsToRemove, isUsd);
}
// now the accumulated created paths should be createdPrimPaths from this execution
prevCreatedPrims = createdPrimPaths;
}
else
{
// else accumulate the written paths until next removeMissingPrims happens
prevCreatedPrims.insert(createdPrimPaths.begin(), createdPrimPaths.end());
}
};
// prims are always written to Fabric
processMissingPrims(prevCreatedFabricPrims, false);
// only when usdWriteBack is true will prims be written to USD
if (db.inputs.usdWriteBack())
{
processMissingPrims(prevCreatedUsdPrims, true);
}
}
static void handleMissingAttributes(OgnWritePrimsV2Database& db,
PXR_NS::SdfPathUSet const& createdAttributes,
bool removeMissingAttrs = true)
{
auto& internalState = OgnWritePrimsV2Database::sInternalState<OgnWritePrimsV2>(db.abi_node());
auto& prevCreatedUsdAttributes = internalState.createdUsdAttributes;
auto& prevCreatedFabricAttributes = internalState.createdFabricAttributes;
auto processMissingAttributes = [&db, &createdAttributes, removeMissingAttrs](
PXR_NS::SdfPathUSet& prevCreatedAttributes, bool isUsd)
{
if (createdAttributes == prevCreatedAttributes)
{
return;
}
if (removeMissingAttrs)
{
// if removeMissingAttrs is on:
// - always removes missing attributes from fabric
// - if usdWriteBack is on, also remove missing attributes from USD
PXR_NS::SdfPathVector attrPathsToRemove;
attrPathsToRemove.reserve(prevCreatedAttributes.size());
for (const auto& path : prevCreatedAttributes)
{
// previously created prim no longer exists
if (createdAttributes.find(path) == createdAttributes.end())
{
ogn::OmniGraphDatabase::logWarning(
db.abi_node(),
"Previously created attribute %s no longer exists in upstream bundle. Removing it from %s...",
path.GetText(), isUsd ? "USD" : "Fabric");
attrPathsToRemove.push_back(path);
}
}
if (!attrPathsToRemove.empty())
{
removeAttributes(db.abi_context(), db.abi_node(), attrPathsToRemove, isUsd);
}
// now the accumulated created paths should be createdAttributes from this execution
prevCreatedAttributes = createdAttributes;
}
else
{
// else accumulate the written attributes until next removeMissingAttrs happens
prevCreatedAttributes.insert(createdAttributes.begin(), createdAttributes.end());
}
};
// attributes are always written to Fabric
processMissingAttributes(prevCreatedFabricAttributes, false);
// only when usdWriteBack is true will attributes be written to USD
if (db.inputs.usdWriteBack())
{
processMissingAttributes(prevCreatedUsdAttributes, true);
}
}
static void handleMissingMetadata(OgnWritePrimsV2Database& db,
PathToMetadataMap const& createdObjectMetadata,
bool removeMissingMetadata = true)
{
auto& internalState = OgnWritePrimsV2Database::sInternalState<OgnWritePrimsV2>(db.abi_node());
auto& prevCreatedObjectMetadata = internalState.createdObjectMetadata;
auto processMissingMetadata = [&db, &createdObjectMetadata, removeMissingMetadata](
PathToMetadataMap& prevCreatedObjectMetadata, bool isUsd)
{
if (createdObjectMetadata == prevCreatedObjectMetadata)
{
return;
}
if (removeMissingMetadata)
{
PathToMetadataMap metadataToRemove;
for (const auto& objectMetadata : prevCreatedObjectMetadata)
{
const auto& objectPath = objectMetadata.first;
const auto& prevMetadataKeys = objectMetadata.second;
if (createdObjectMetadata.find(objectPath) == createdObjectMetadata.end())
{
ogn::OmniGraphDatabase::logWarning(
db.abi_node(),
"Previously created metadata for object %s no longer exists in upstream bundle. Removing it from %s...",
objectPath.GetText(), isUsd ? "USD" : "Fabric");
metadataToRemove[objectPath] = prevMetadataKeys;
}
else
{
const auto& metadataKeys = createdObjectMetadata.at(objectPath);
for (const auto& key : prevMetadataKeys)
{
if (metadataKeys.find(key) == metadataKeys.end())
{
ogn::OmniGraphDatabase::logWarning(
db.abi_node(),
"Previously created metadata %s for object %s no longer exists in upstream bundle. Removing it from %s...",
key.GetText(), objectPath.GetText(), isUsd ? "USD" : "Fabric");
metadataToRemove[objectPath].insert(key);
}
}
}
}
if (!metadataToRemove.empty())
{
removeMetadata(db.abi_context(), db.abi_node(), metadataToRemove, isUsd);
}
prevCreatedObjectMetadata = createdObjectMetadata;
}
else
{
for (const auto& objectMetadata : createdObjectMetadata)
{
// accumulate created metadata until this function is invoked with removeMissingAttrs
prevCreatedObjectMetadata[objectMetadata.first].insert(objectMetadata.second.begin(), objectMetadata.second.end());
}
}
};
// XXX: metadata export for fabric not yet implemented
//processMissingMetadata(prevCreatedObjectMetadata, false);
if (db.inputs.usdWriteBack())
{
processMissingMetadata(prevCreatedObjectMetadata, true);
}
}
static WritePrimResult scatterUnderTargets(GraphContextObj const& contextObj,
NodeObj const& nodeObj,
gsl::span<ConstBundleHandle> connectedBundleHandles,
PathVector const& targetPrimPaths,
bool const usdWriteBack,
NameToken const& layerIdentifier,
WritePrimMatchers const& matchers,
WrittenPrimAndAttributesTracker& primAndAttrsTracker,
WritePrimDiagnostics& diagnostics)
{
auto result = WritePrimResult::None;
// a map to contain all valid bundle prims info from ALL connected bundles and descendant bundles.
BundlePrimInfoMap bundlePrimInfoMap;
for (ConstBundleHandle const& bundleHandle : connectedBundleHandles)
{
WritePrimResult const subResult = collectPrimsFromBundleHierarchy(
contextObj, nodeObj, diagnostics, bundleHandle, matchers, bundlePrimInfoMap);
mergeWritePrimResult(result, subResult);
}
auto writeUnderTarget = [&contextObj, &nodeObj, &diagnostics, usdWriteBack, layerIdentifier, &result,
&bundlePrimInfoMap, &primAndAttrsTracker](PathC const& targetPrefix)
{
for (auto const& [_, info] : bundlePrimInfoMap)
{
WritePrimResult const subResult = writePrimAndAttributes(
contextObj, nodeObj, diagnostics, info, usdWriteBack, layerIdentifier, targetPrefix,
fabric::asInt(PXR_NS::SdfPath::AbsoluteRootPath()), primAndAttrsTracker);
mergeWritePrimResult(result, subResult);
}
};
for (auto const& target : targetPrimPaths)
{
writeUnderTarget(target);
}
return result;
}
static WritePrimResult writeToTargets(GraphContextObj const& contextObj,
NodeObj const& nodeObj,
gsl::span<ConstBundleHandle> connectedBundleHandles,
PathVector const& targetPrimPaths,
bool const usdWriteBack,
NameToken const& layerIdentifier,
WritePrimMatchers const& matchers,
WrittenPrimAndAttributesTracker& primAndAttrsTracker,
WritePrimDiagnostics& diagnostics)
{
auto result = WritePrimResult::None;
auto& internalState = OgnWritePrimsV2Database::sInternalState<OgnWritePrimsV2>(nodeObj);
size_t targetPrimIndex = 0;
for (ConstBundleHandle const& bundleHandle : connectedBundleHandles)
{
// a map to contain all valid bundle prims info from ONE connected bundle and descendant bundles.
BundlePrimInfoMap bundlePrimInfoMap;
WritePrimResult const subResult = collectPrimsFromBundleHierarchy(
contextObj, nodeObj, diagnostics, bundleHandle, matchers, bundlePrimInfoMap);
mergeWritePrimResult(result, subResult);
// remove the paths that are already prefixed by other paths.
// similar to SdfPath::RemoveDescendentPaths, but BundlePrimInfoMap is already ordered so we don't have to
// sort again
PXR_NS::SdfPathVector uniqueRootPaths;
uniqueRootPaths.reserve(bundlePrimInfoMap.size());
for (auto const& entry : bundlePrimInfoMap)
{
if (uniqueRootPaths.empty() || !entry.first.HasPrefix(uniqueRootPaths.back()))
{
uniqueRootPaths.push_back(entry.first);
}
}
// index to the currently mapped unique root prim path
size_t rootIndex = 0;
for (auto const& [sourcePrimPath, info] : bundlePrimInfoMap)
{
// when the sourcePrimPath is no longer a descendant of current unique root, move it onto the next one
if (rootIndex < uniqueRootPaths.size() && !sourcePrimPath.HasPrefix(uniqueRootPaths[rootIndex]))
{
rootIndex++;
// each root index takes up a target prim index
targetPrimIndex++;
}
if (targetPrimIndex >= targetPrimPaths.size())
{
ogn::OmniGraphDatabase::logWarning(
nodeObj,
"Not enough 'prims' targets to write out all source prims. Skipping the rest of the prims");
break;
}
WritePrimResult const subResult =
writePrimAndAttributes(contextObj, nodeObj, diagnostics, info, usdWriteBack, layerIdentifier,
targetPrimPaths[(PathVector::size_type)targetPrimIndex],
fabric::asInt(uniqueRootPaths[rootIndex]), primAndAttrsTracker);
mergeWritePrimResult(result, subResult);
}
// always increment targetPrimIndex when moving onto next bundle
targetPrimIndex++;
}
return result;
}
public:
static bool compute(OgnWritePrimsV2Database& db)
{
auto result = WritePrimResult::None;
auto& context = db.abi_context();
auto& nodeObj = db.abi_node();
auto& internalState = OgnWritePrimsV2Database::sInternalState<OgnWritePrimsV2>(nodeObj);
bool inputChanged = db.state.attrNamesToExport() != db.inputs.attrNamesToExport() ||
db.state.pathPattern() != db.inputs.pathPattern() ||
db.state.typePattern() != db.inputs.typePattern() ||
db.state.usdWriteBack() != db.inputs.usdWriteBack() ||
db.state.scatterUnderTargets() != db.inputs.scatterUnderTargets() ||
db.state.layerIdentifier() != db.inputs.layerIdentifier();
db.state.attrNamesToExport() = db.inputs.attrNamesToExport();
db.state.pathPattern() = db.inputs.pathPattern();
db.state.typePattern() = db.inputs.typePattern();
db.state.usdWriteBack() = db.inputs.usdWriteBack();
db.state.scatterUnderTargets() = db.inputs.scatterUnderTargets();
db.state.layerIdentifier() = db.inputs.layerIdentifier();
PathVector const targetPrimPaths =
getPathsFromInputRelationship(context, nodeObj, inputs::prims.token(), db.getInstanceIndex());
if (internalState.targetPrimPaths.changed(targetPrimPaths))
{
internalState.targetPrimPaths.store(targetPrimPaths);
inputChanged = true;
}
#if 0
// TODO dirty tracking of primBundle
if (!inputChanged)
{
return true;
}
#endif
long stageId = context.iContext->getStageId(context);
auto stage = PXR_NS::UsdUtilsStageCache::Get().Find(PXR_NS::UsdStageCache::Id::FromLongInt(stageId));
auto resolvedLayerIdentifier =
resolveLayerIdentifier(nodeObj, stage, inputs::layerIdentifier.m_token, db.inputs.layerIdentifier());
// Since the bundle input allows multiple connections, we need to collect all of them
size_t const connectedPrimCount = getConnectedPrimCount(db);
PXR_NS::SdfPathUSet createdPrimPaths;
PXR_NS::SdfPathUSet createdAttributes;
PathToMetadataMap createdObjectMetadata;
// Even when we have no connected prims, we still return true, because the node *did* compute, and execOut
// attribute will be set.
if (connectedPrimCount > 0)
{
auto handler = [&db, &result, &targetPrimPaths, &createdPrimPaths, &createdAttributes, &createdObjectMetadata,
&internalState, &resolvedLayerIdentifier](gsl::span<ConstBundleHandle> connectedBundleHandles)
{
GraphContextObj const& contextObj = db.abi_context();
NodeObj const& nodeObj = db.abi_node();
if (detectFindPrimsPathsLoop(contextObj, nodeObj, targetPrimPaths))
{
mergeWritePrimResult(result, WritePrimResult::Fail);
// do not proceed
return;
}
NodeContextHandle const nodeHandle = nodeObj.nodeContextHandle;
NameToken const primsToken = inputs::primsBundle.token();
bool const usdWriteBack = db.inputs.usdWriteBack();
ogn::const_string const attrPattern = db.inputs.attrNamesToExport();
ogn::const_string const pathPattern = db.inputs.pathPattern();
ogn::const_string const typePattern = db.inputs.typePattern();
WritePrimMatchers const matchers{ attrPattern, pathPattern, typePattern };
contextObj.iContext->getInputTargets(contextObj, nodeHandle, primsToken,
(omni::fabric::PathC*)(connectedBundleHandles.data()),
db.getInstanceIndex());
// Write back all bundles
WritePrimDiagnostics diagnostics;
// NOTE: writing metadata is currently only implemented for USD writeback,
// so no distinction in made for USD vs Fabric metadata collections.
WrittenPrimAndAttributesTracker tracker(
createdPrimPaths, usdWriteBack ? internalState.createdUsdPrims : internalState.createdFabricPrims,
createdAttributes,
usdWriteBack ? internalState.createdUsdAttributes : internalState.createdFabricAttributes,
createdObjectMetadata,
internalState.createdObjectMetadata);
auto writeResult = WritePrimResult::None;
if (db.inputs.scatterUnderTargets())
{
writeResult =
scatterUnderTargets(contextObj, nodeObj, connectedBundleHandles, targetPrimPaths, usdWriteBack,
resolvedLayerIdentifier, matchers, tracker, diagnostics);
}
else
{
writeResult = writeToTargets(contextObj, nodeObj, connectedBundleHandles, targetPrimPaths,
usdWriteBack, resolvedLayerIdentifier, matchers, tracker, diagnostics);
}
// Report skipped invalid bundles
mergeWritePrimResult(result, diagnostics.report(contextObj, nodeObj));
};
withStackScopeBuffer<ConstBundleHandle>(connectedPrimCount, handler);
}
{
PXR_NS::SdfChangeBlock changeblock;
// Track primBundles content changes and remove no longer existing attributes or prims
// TODO when dirtyId checking works correctly, only handle them when upstream bundle or related inputs
// changed.
handleMissingPrims(db, createdPrimPaths);
// TODO ReadPrims node will *not* remove an attribute from the bundle if it's removed due to lack of USD
// change tracking. The only way to trigger removal of missing attributes currently is to change filter
// pattern or disconnect then reconnect primBundles connection to force a re-evaluation.
handleMissingAttributes(db, createdAttributes);
handleMissingMetadata(db, createdObjectMetadata);
}
auto const ok = result != WritePrimResult::Fail;
if (ok)
{
db.outputs.execOut() = kExecutionAttributeStateEnabled;
}
return ok;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 25,845 | C++ | 43.716263 | 174 | 0.580383 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrims.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.
//
/*
_____ ______ _____ _____ ______ _____ _______ ______ _____
| __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \
| | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | |
| | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | |
| |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| |
|_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/
ReadPrims is deprecated. Use ReadPrimsV2 instead.
ReadPrimsV2 added a new inputs:prims as the root prims to perform findPrims operation (instead of always starting from
stage root "/").
It also removed inputs:useFindPrims. Instead, as long as input:pathPattern is non-empty, it acts as the on toggle in
place of useFindPrims.
*/
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <carb/dictionary/DictionaryUtils.h>
#include <omni/fabric/FabricUSD.h>
#include <omni/kit/PythonInterOpHelper.h>
#include "OgnReadPrimsDatabase.h"
#include "PrimCommon.h"
#include "ReadPrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnReadPrims
{
public:
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, const NodeObj& nodeObj)
{
ogn::OmniGraphDatabase::logWarning(nodeObj, "ReadPrims node is deprecated, use ReadPrimsV2 instead");
// When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected.
AttributeObj inputBundleAttribObj =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimsAttributes::inputs::prims.m_token);
inputBundleAttribObj.iAttribute->registerValueChangedCallback(
inputBundleAttribObj, onInputBundleValueChanged, true);
}
// ----------------------------------------------------------------------------
static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData)
{
NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj);
GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj);
// If the graph is currently disabled then delay the update until the next compute.
// Arguably this should be done at the message propagation layer, then this wouldn't be necessary.
if (graphObj.iGraph->isDisabled(graphObj))
{
return;
}
// clear the output bundles
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
auto outputTokens = { OgnReadPrimsAttributes::outputs::primsBundle.m_token };
for (auto& outputToken : outputTokens)
{
BundleHandle outBundle = context.iContext->getOutputBundle(
context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex);
context.iContext->clearBundleContents(context, outBundle);
}
}
// ----------------------------------------------------------------------------
static PathVector getMatchedPaths(OgnReadPrimsDatabase& db, PathVector const* primPaths)
{
auto& context = db.abi_context();
auto& nodeObj = db.abi_node();
if (db.inputs.useFindPrims())
{
pxr::UsdStageRefPtr stage;
omni::fabric::FabricId fabricId;
std::tie(fabricId, stage) = getFabricForNode(context, nodeObj);
pxr::UsdPrim startPrim = stage->GetPseudoRoot();
pxr::TfToken pathPattern{ std::string{ db.inputs.pathPattern() } };
if (pathPattern.IsEmpty())
return {};
std::string typePatternStr{ db.inputs.typePattern() };
pxr::TfToken typePattern{ typePatternStr };
PathVector matchedPaths;
findPrims_findMatching(matchedPaths, startPrim, true, nullptr, typePattern, {}, {}, {}, pathPattern, true);
return matchedPaths;
}
return readPrimBundle_getPaths(
context, nodeObj, OgnReadPrimsAttributes::inputs::prims.m_token, false, {}, db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static bool writeToBundle(OgnReadPrimsDatabase& db,
gsl::span<PathC const> inputPaths,
bool force,
pxr::UsdTimeCode const& time)
{
auto& context = db.abi_context();
auto& nodeObj = db.abi_node();
std::string attrNamesStr{ db.inputs.attrNamesToImport() };
NameToken attrNames = db.abi_context().iToken->getHandle(attrNamesStr.c_str());
return readPrimsBundle_writeToBundle(context, nodeObj, inputPaths, attrNames,
db.outputs.primsBundle(), force, db.inputs.computeBoundingBox(), time, db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static void clean(OgnReadPrimsDatabase& db)
{
db.outputs.primsBundle().clear();
}
// ----------------------------------------------------------------------------
static bool compute(OgnReadPrimsDatabase& db)
{
auto& context = db.abi_context();
auto& nodeObj = db.abi_node();
// import by pattern
bool inputChanged = db.state.useFindPrims() != db.inputs.useFindPrims() ||
db.state.pathPattern() != db.inputs.pathPattern() ||
db.state.typePattern() != db.inputs.typePattern();
db.state.useFindPrims() = db.inputs.useFindPrims();
db.state.pathPattern() = db.inputs.pathPattern();
db.state.typePattern() = db.inputs.typePattern();
// bounding box changed
bool const computeBoundingBox = db.inputs.computeBoundingBox();
if (db.state.computeBoundingBox() != computeBoundingBox)
{
db.state.computeBoundingBox() = computeBoundingBox;
inputChanged = true;
}
// attribute filter changed
std::string attrNamesToImport{ db.inputs.attrNamesToImport() };
if (db.state.attrNamesToImport() != attrNamesToImport)
{
db.state.attrNamesToImport() = attrNamesToImport;
inputChanged = true;
}
// applySkelBinding toggle changed
bool const applySkelBinding = db.inputs.applySkelBinding();
if (db.state.applySkelBinding() != applySkelBinding)
{
db.state.applySkelBinding() = applySkelBinding;
inputChanged = true;
}
bool result = readPrimsBundle_compute<OgnReadPrims>(db, inputChanged);
if (result && applySkelBinding)
{
ogn::BundleContents<ogn::kOgnOutput, ogn::kCpu>& outputBundle = db.outputs.primsBundle();
result = readSkelBinding_compute(context, nodeObj, outputBundle, attrNamesToImport, inputChanged,
computeBoundingBox, getTime(db)) &&
applySkelBinding_compute(context, outputBundle);
}
return result;
}
// ----------------------------------------------------------------------------
static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
if (oldVersion < 3)
{
return upgradeUsdTimeCodeInput(context, nodeObj);
}
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 8,174 | C++ | 38.302884 | 138 | 0.561292 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnRenderPostprocessEntry.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 "OgnRenderPostprocessEntryDatabase.h"
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <omni/graph/core/GpuInteropEntryUserData.h>
#include <omni/graph/core/iComputeGraph.h>
namespace omni
{
namespace graph
{
namespace core
{
// OmniGraph nodes which postprocess the RTX renderer output need to be connected downstream of a RenderPostprocessEntry
// node. The RenderPostprocessEntry outputs the R/W RgResource of the texture's final color (along with associated
// metadata such as width, height, etc.) as OmniGraph attributes which can be read by downstream nodes. Modifications to
// this RgResource will be reflected in the viewport. The format of the RgResource is an RgTexture created with CUDA
// interoperability as opposed to a buffer.
class OgnRenderPostprocessEntry
{
public:
static bool compute(OgnRenderPostprocessEntryDatabase& db)
{
GpuInteropCudaEntryUserData* userData = static_cast<GpuInteropCudaEntryUserData*>(db.abi_node().iNode->getUserData(db.abi_node()));
if (!userData)
return false;
GpuInteropCudaResourceMap& cudaRsrcMap = userData->cudaRsrcMap;
std::string sourceName = db.inputs.sourceName();
auto it = cudaRsrcMap.find(sourceName);
if (it == cudaRsrcMap.end())
{
return false;
}
GpuInteropCudaResourceData& renderVarData = it->second;
db.outputs.cudaMipmappedArray() = (uint64_t)renderVarData.cudaResource;
db.outputs.width() = renderVarData.width;
db.outputs.height() = renderVarData.height;
db.outputs.mipCount() = (uint32_t)renderVarData.mipCount;
db.outputs.format() = (uint64_t)renderVarData.format;
db.outputs.stream() = (uint64_t)userData->cudaStream;
db.outputs.simTime() = userData->simTime;
db.outputs.hydraTime() = userData->hydraTime;
return true;
}
static void initialize(const GraphContextObj&, const NodeObj&)
{
CARB_LOG_WARN_ONCE("OgnRenderPostprocessEntry is depreciated. Please use OgnGpuInteropCudaEntry");
}
static void initializeType(const NodeTypeObj& nodeTypeObj)
{
OgnRenderPostprocessEntryDatabase::initializeType(nodeTypeObj);
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,712 | C++ | 34.233766 | 139 | 0.724926 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimAttribute.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 <OgnReadPrimAttributeDatabase.h>
#include <omni/graph/core/IAttributeType.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/CppWrappers.h>
#include <omni/usd/UsdContext.h>
#include <omni/fabric/FabricUSD.h>
#include "PrimCommon.h"
#include "ReadPrimCommon.h"
using namespace omni::fabric;
namespace omni
{
namespace graph
{
namespace nodes
{
static thread_local bool recurseGuard{ false };
class OgnReadPrimAttribute
{
static bool importAtTime(omni::fabric::FabricId fabricId,
NodeObj const& nodeObj,
GraphContextObj const& context,
pxr::UsdPrim const& prim,
TokenC srcName,
pxr::SdfTimeCode const& time,
OgnReadPrimAttributeDatabase& db,
size_t offset)
{
CARB_PROFILE_ZONE(1, "ImportAtTime");
IFabricUsd* iFabricUsd = carb::getCachedInterface<IFabricUsd>();
// Handle the case where the prim is not yet available
if (! prim.IsValid())
{
CARB_LOG_WARN("Attempted to import time from invalid prim from node '%s' and source '%s'",
nodeObj.iNode->getPrimPath(nodeObj), omni::fabric::toTfToken(srcName).GetText()
);
return false;
}
pxr::SdfPath importPath = prim.GetPath();
bool force = false;
if (UsdTimeCode::Default() != time)
{
force = true;
char const* primPath = nodeObj.iNode->getPrimPath(nodeObj);
static constexpr char const kImportSubPath[] = "/Import";
std::string storingPath;
storingPath.reserve(strlen(primPath) + sizeof(kImportSubPath));
storingPath = primPath;
storingPath += kImportSubPath;
importPath = pxr::SdfPath(storingPath);
}
{
CARB_PROFILE_ZONE(1, "ImportUSDToFabric");
BucketId srcPrimBucketId =
omni::graph::nodes::addAttribToCache(prim, importPath, srcName, iFabricUsd, fabricId, time, force);
if (srcPrimBucketId == kInvalidBucketId)
{
OgnReadPrimAttributeDatabase::logError(
nodeObj, "Unable to add prim %s to fabric", prim.GetPath().GetText());
return false;
}
}
db.state.time(offset) = time.GetValue();
db.state.srcPath(offset) = asInt(prim.GetPath()).path;
db.state.srcPathAsToken(offset) = asInt(prim.GetPath().GetAsToken()).token;
db.state.importPath(offset) = asInt(importPath).path;
db.state.srcAttrib(offset) = srcName.token;
return true;
}
static void setup(NodeObj const& nodeObj,
GraphContextObj const& context,
pxr::SdfTimeCode const& time,
OgnReadPrimAttributeDatabase& db,
size_t offset,
bool isInCompute)
{
if (recurseGuard)
return;
CARB_PROFILE_ZONE(1, "setup");
recurseGuard = true;
std::shared_ptr<nullptr_t> atScopExist(nullptr, [](auto) { recurseGuard = false; });
auto typeInterface{ carb::getCachedInterface<omni::graph::core::IAttributeType>() };
InstanceIndex instanceIndex = db.getInstanceIndex() + offset;
db.state.correctlySetup(offset) = false;
pxr::UsdAttribute attrib;
try
{
attrib = omni::graph::nodes::findSelectedAttribute(context, nodeObj, instanceIndex);
}
catch (std::runtime_error const& error)
{
if (isInCompute)
OgnReadPrimAttributeDatabase::logError(nodeObj,error.what());
return;
}
if (!attrib)
{
// Couldn't get the indicated attribute for some expected reason
if (isInCompute)
OgnReadPrimAttributeDatabase::logError(nodeObj, "Prim has not been set");
return;
}
auto typeName{ attrib ? attrib.GetTypeName().GetAsToken() : pxr::TfToken() };
Type attribType{ typeInterface->typeFromSdfTypeName(typeName.GetText()) };
tryResolveOutputAttribute(nodeObj, outputs::value.m_token, attribType);
// Get interfaces
const INode& iNode = *nodeObj.iNode;
pxr::UsdPrim prim{ attrib.GetPrim() };
if (!attrib.IsAuthored())
{
if (UsdTimeCode::Default() != time)
{
CARB_LOG_ERROR("Access a non authored attrib %s:%s with a specific timestamp is not allowed",
attrib.GetName().GetText(), prim.GetPath().GetText());
return;
}
// fabric only cares about _authored_ attributes, so in order to make use of fabric mirrored arrays we
// have to contrive to have values authored, even if we just want to read them.
//
// FIXME: OM-36961 exists to work around this issue some other way.
CARB_LOG_INFO("%s: Attribute %s is not authored, authoring now", iNode.getPrimPath(nodeObj),
attrib.GetPath().GetText());
// --------------------------------------------------------------------------------------
// Get PrimVar into fabric by creating it on the prim
if (pxr::UsdGeomPrimvar::IsPrimvar(attrib))
{
try
{
addPrimvarToFabric(prim, attrib);
}
catch (std::runtime_error const& error)
{
OgnReadPrimAttributeDatabase::logError(nodeObj,error.what());
return;
}
}
else
{
// --------------------------------------------------------------------------------------
// Get non-primvar into fabric by authoring the attribute with the composed value
pxr::VtValue val;
if (!attrib.Get(&val))
{
OgnReadPrimAttributeDatabase::logError(nodeObj,"Unable to read %s of type %s", attrib.GetPath().GetText(), val.GetTypeName().c_str());
return;
}
if (!attrib.Set(val))
{
OgnReadPrimAttributeDatabase::logError(nodeObj,"Unable to author %s with value of type %s", attrib.GetPath().GetText(),
val.GetTypeName().c_str());
return;
}
}
}
// Fill Fabric with USD data
pxr::UsdStageRefPtr stage;
omni::fabric::FabricId fabricId;
std::tie(fabricId, stage) = getFabricForNode(context, nodeObj);
if (fabricId == omni::fabric::kInvalidFabricId)
return;
if (!importAtTime(fabricId, nodeObj, context, prim, asInt(attrib.GetName()), time, db, offset))
return;
// If it's resolved, we already know that it is compatible from the above check of the USD
AttributeObj outAttrib = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::value.m_token);
Type outType = outAttrib.iAttribute->getResolvedType(outAttrib);
if (outType == Type())
{
// 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.
outAttrib.iAttribute->setResolvedType(outAttrib, attribType);
}
db.state.correctlySetup(offset) = true;
}
/**
* Adds the given primvar attrib to fabric.At the moment this requires explicit authoring of the value
* @param prim: The prim which is in FC, but doesn't have the given primvar
* @param attrib: The primvar attribute for the prim, which has no value
* @throws: std::runtime_error on failure
* @
*/
static void addPrimvarToFabric(pxr::UsdPrim prim, pxr::UsdAttribute& attrib)
{
// Primvars have to go through prim var api
if (auto primVarAPI = pxr::UsdGeomPrimvarsAPI(prim))
{
if (pxr::UsdGeomPrimvar primVar = primVarAPI.FindPrimvarWithInheritance(attrib.GetName()))
{
if (auto newPrimVar = primVarAPI.CreatePrimvar(attrib.GetName(), primVar.GetTypeName()))
{
if (auto& newAttr = newPrimVar.GetAttr())
{
// Get the inherited primvar attrib value
pxr::VtValue val;
if (primVar.Get(&val))
{
if (!newAttr.Set(val))
{
throw std::runtime_error(formatString("Unable to author primvar %s with value of type %s",
newAttr.GetPath().GetText(), val.GetTypeName().c_str()));
}
}
else
{
// We don't have any value to copy, so lets use the default
auto const& defaultValue = primVar.GetTypeName().GetDefaultValue();
if (!newAttr.Set(defaultValue))
{
throw std::runtime_error(
formatString("Unable to author primvar %s with default value", newAttr.GetPath().GetText()));
}
}
}
}
}
}
}
// ----------------------------------------------------------------------------
// Called by OG when our prim attrib changes. We want to catch the case of changing the prim attribute interactively
static void onValueChanged(AttributeObj const& attrObj, void const* userData)
{
// FIXME: Be pedantic about validity checks - this can be run directly by the TfNotice so who knows
// when or where this is happening
NodeObj nodeObj{ attrObj.iAttribute->getNode(attrObj) };
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
//no setup if graph is disabled (during python edition for instance)
if (graphObj.iGraph->isDisabled(graphObj))
return;
GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) };
if (context.contextHandle == kInvalidGraphContextHandle)
return;
OgnReadPrimAttributeDatabase db(context, nodeObj);
setup(nodeObj, context, db.state.time(), db, 0, false);
}
public:
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
// We need to check resolution if any of our relevant inputs change
std::array<NameToken, 4> attribNames{ inputs::name.m_token, inputs::usePath.m_token, inputs::primPath.m_token,
inputs::prim.m_token };
for (auto const& attribName : attribNames)
{
AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, attribName);
attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true);
}
}
// ----------------------------------------------------------------------------
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) };
if (context.contextHandle == kInvalidGraphContextHandle)
return;
OgnReadPrimAttributeDatabase db(context, nodeObj);
setup(nodeObj, context, db.state.time(), db, 0, false);
}
// ----------------------------------------------------------------------------
static bool computeVectorized(OgnReadPrimAttributeDatabase& db, size_t count)
{
NodeObj nodeObj = db.abi_node();
GraphContextObj ctx = db.abi_context();
pxr::UsdStageRefPtr stage;
omni::fabric::FabricId fabricId;
std::tie(fabricId, stage) = getFabricForNode(ctx, nodeObj);
if (fabricId == omni::fabric::kInvalidFabricId)
return false;
//////////////////////////////////////////////////////////////////////////
//Gather vectorized data
auto time = db.inputs.usdTimecode.vectorized(count);
auto usePath = db.inputs.usePath.vectorized(count);
auto primPath = db.inputs.primPath.vectorized(count);
auto name = db.inputs.name.vectorized(count);
auto correctlySetup = db.state.correctlySetup.vectorized(count);
auto stateTime = db.state.time.vectorized(count);
auto importPath = db.state.importPath.vectorized(count);
auto srcPath = db.state.srcPath.vectorized(count);
auto srcPathAsToken = db.state.srcPathAsToken.vectorized(count);
auto srcAttrib = db.state.srcAttrib.vectorized(count);
//////////////////////////////////////////////////////////////////////////
// Make sure setup is correctly performed
for (size_t idx = 0; idx < count; ++idx)
{
if (!correctlySetup[idx])
{
setup(nodeObj, ctx, time[idx], db, idx, true);
}
else
{
auto pathToken = usePath[idx] ? primPath[idx] : db.pathToToken(db.inputs.prim.firstOrDefault(idx));;
if (pathToken != srcPathAsToken[idx] || name[idx] != srcAttrib[idx])
setup(nodeObj, ctx, time[idx], db, idx, true);
}
if (correctlySetup[idx] && UsdTimeCode(time[idx]) != stateTime[idx])
{
auto prim = stage->GetPrimAtPath(intToPath(srcPath[idx]));
correctlySetup[idx] = importAtTime(fabricId, nodeObj, ctx, prim, name[idx], time[idx], db, idx);
}
}
//////////////////////////////////////////////////////////////////////////
//Do the copy by the data model or by hand if possible
// for array or GPU attributes, go through the data model to properly handle the copy
Type const type = db.outputs.value().type();
bool const useDataModel = type.arrayDepth || ctx.iAttributeData->gpuValid(db.outputs.value().abi_handle(), ctx);
if (useDataModel)
{
for (size_t idx = 0; idx < count; ++idx)
{
if (correctlySetup[idx])
{
ConstAttributeDataHandle const src{ AttrKey{ importPath[idx], srcAttrib[idx] } };
db.abi_context().iAttributeData->copyData(
db.outputs.value(idx).abi_handle(), ctx, src);
}
}
}
else
{
// gather dst base pointer
uint8_t* dstData = nullptr;
size_t stride = 0;
db.outputs.value().rawData(dstData, stride);
// retrieve src pointers
std::vector<ConstAttributeDataHandle> srcHandles;
srcHandles.resize(count);
for (size_t idx = 0; idx < count; ++idx)
{
srcHandles[idx] = correctlySetup[idx] ?
ConstAttributeDataHandle(AttrKey{ importPath[idx], srcAttrib[idx] }) :
ConstAttributeDataHandle::invalidHandle();
}
std::vector<void const*> srcData;
srcData.resize(count);
{
CARB_PROFILE_ZONE(1, "Retrieve Pointers");
ctx.iAttributeData->getDataR(srcData.data(), ctx, srcHandles.data(), count);
}
for (size_t idx = 0; idx < count; ++idx)
{
if (correctlySetup[idx])
{
void* dst = dstData + idx * stride;
if (srcData[idx])
memcpy(dst, srcData[idx], stride);
else
db.logError("computeVectorized attempting to memcpy from nullptr");
}
}
}
return true;
}
// ----------------------------------------------------------------------------
static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
if (oldVersion < 2)
{
return upgradeUsdTimeCodeInput(context, nodeObj);
}
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 17,600 | C++ | 38.911565 | 154 | 0.536705 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWriteVariable.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 <OgnWriteVariableDatabase.h>
#include <carb/events/EventsUtils.h>
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace core
{
class OgnWriteVariable
{
public:
carb::events::ISubscriptionPtr m_EventSubscription;
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::variableName.m_token);
attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true);
onConnectionTypeResolve(nodeObj);
GraphObj graphObj{ context.iContext->getGraph(context) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
OgnWriteVariableDatabase::sInternalState<OgnWriteVariable>(nodeObj)
.m_EventSubscription = carb::events::createSubscriptionToPop(graphObj.iGraph->getEventStream(graphObj).get(),
[nodeObj](carb::events::IEvent* e)
{
switch (static_cast<IGraphEvent>(e->type))
{
case IGraphEvent::eCreateVariable:
case IGraphEvent::eRemoveVariable:
case IGraphEvent::eVariableTypeChange:
onConnectionTypeResolve(nodeObj);
break;
default:
break;
}
});
}
// ----------------------------------------------------------------------------
// Called by OG to resolve the input type
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
onValueChanged(nodeObj.iNode->getAttributeByToken(nodeObj, inputs::variableName.m_token), nullptr);
}
// ----------------------------------------------------------------------------
// Called by OG when the value of the variableName changes
static void onValueChanged(AttributeObj const& attrObj, void const* userData)
{
auto nodeObj = attrObj.iAttribute->getNode(attrObj);
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
auto graphObj = nodeObj.iNode->getGraph(nodeObj);
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
auto context = graphObj.iGraph->getDefaultGraphContext(graphObj);
if (context.contextHandle == kInvalidGraphContextHandle)
return;
Type type(BaseDataType::eUnknown);
const auto token = getDataR<NameToken>(
context, attrObj.iAttribute->getConstAttributeDataHandle(attrObj, kAccordingToContextIndex));
if (token)
{
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
auto variable = graphObj.iGraph->findVariable(graphObj, tokenInterface->getText(*token));
if (variable)
{
type = variable->getType();
}
}
omni::graph::nodes::tryResolveInputAttribute(nodeObj, inputs::value.m_token, type);
omni::graph::nodes::tryResolveOutputAttribute(nodeObj, outputs::value.m_token, type);
}
static bool computeVectorized(OgnWriteVariableDatabase& db, size_t count)
{
auto variable = db.getVariable(db.inputs.variableName());
if (!variable.isValid())
return false;
auto& node = db.abi_node();
if (!variable.type().compatibleRawData(db.outputs.value().type()))
{
db.logError("Variable %s with type %s is not compatible with type '%s', please disconnect",
db.tokenToString(db.inputs.variableName()),
variable.type().getTypeName().c_str(),
db.outputs.value().typeName().c_str());
return false;
}
if (variable.type().role != db.outputs.value().type().role)
{
if (variable.type().role != AttributeRole ::eNone &&
db.outputs.value().type().role != AttributeRole::eNone)
{
db.logWarning("Roles between variable %s (%s) and output (%s) differs",
db.tokenToString(db.inputs.variableName()),
getAttributeRoleName(variable.type().role).c_str(),
getAttributeRoleName(db.outputs.value().type().role).c_str());
}
}
if (variable.type() != db.inputs.value().type())
{
auto attribute = db.abi_node().iNode->getAttributeByToken(node, inputs::value.m_token);
attribute.iAttribute->setResolvedType(attribute, variable.type());
return 0;
}
// and going through the ABI is mandatory on a per instance basis
auto varNameAttrib = node.iNode->getAttributeByToken(node, inputs::variableName.m_token);
bool const isVarNameConstant = varNameAttrib.iAttribute->isRuntimeConstant(varNameAttrib);
if (variable.type().arrayDepth || !isVarNameConstant)
{
auto varName = db.inputs.variableName();
for (size_t i = 0; i < count; ++i)
{
variable = db.getVariable(varName, {i});
variable.copyData(db.inputs.value(i));
// forces an access to trigger CoW and have a real copy
if (variable.type().arrayDepth)
{
RawPtr ptr;
size_t s;
variable.rawData(ptr, s);
}
db.outputs.value(i).copyData(variable);
}
}
else
{
uint8_t* dst = nullptr;
size_t sd;
variable.rawData(dst, sd);
uint8_t const* src = nullptr;
size_t ss;
db.inputs.value().rawData(src, ss);
if (ss != sd)
return 0;
memcpy(dst, src, ss * count);
db.outputs.value().rawData(dst, sd);
if (ss != sd)
return 0;
memcpy(dst, src, ss * count);
}
auto execOut = db.outputs.execOut.vectorized(count);
std::fill(execOut.begin(), execOut.end(), kExecutionAttributeStateEnabled);
return true;
}
};
REGISTER_OGN_NODE()
} // namespace examples
} // namespace graph
} // namespace omni
| 7,662 | C++ | 39.544973 | 121 | 0.512268 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnExtractPrim.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 "OgnExtractPrimDatabase.h"
#include "ReadPrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnExtractPrim
{
public:
// Copies attributes from an input bundle to attributes directly on the node
static bool compute(OgnExtractPrimDatabase& db)
{
auto& contextObj = db.abi_context();
auto& nodeObj = db.abi_node();
auto const& inputPrims = db.inputs.prims();
// The computation should only be performed when input bundle or prim or prim path changes.
// At this moment, unfortunately, there is no way to find out if incoming bundle has changed.
// That means we have to recompute all the time.
// Extracting bundles is a O(n) operation in worse case. If the number of children in the input bundle
// is substantial, then we can get significant performance slow down.
// When Dirty IDs interface is in place, this function should be updated to recompute only
// when input bundle, or prim path is out of date.
// Suggestion: an internal cache - a map of path to child bundle handle could be sufficient.
ConstBundleHandle extractedHandle{ ConstBundleHandle::invalidValue() };
if(db.inputs.prim().size() == 0)
{
// extract child bundle using input prim path
std::string const pathStr{ db.inputs.primPath() };
if (PXR_NS::SdfPath::IsValidPathString(pathStr))
{
auto primPath = omni::fabric::asInt(PXR_NS::TfToken(pathStr.data()));
extractedHandle = extractPrimByPath(contextObj, inputPrims, primPath);
}
}
else
{
if(db.inputs.prim().size() > 1)
db.logWarning("Only one prim target is supported, the rest will be ignored");
extractedHandle = extractPrimByPath(contextObj, inputPrims, db.pathToToken(db.inputs.prim()[0]));
}
// update outputs
BundleType extractedBundle(contextObj, extractedHandle);
db.outputs.primBundle() = extractedBundle;
return extractedBundle.isValid();
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 2,684 | C++ | 35.780821 | 110 | 0.669151 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrim.cpp | // Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
/*
_____ ______ _____ _____ ______ _____ _______ ______ _____
| __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \
| | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | |
| | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | |
| |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| |
|_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/
ReadPrim is deprecated and should not be used.
First version of ReadPrim outputs 'Single Primitive in a Bundle'(SPiB) + Dynamic Attributes(DA).
The successor ReadPrims outputs 'Multiple Primitives in a Bundle'(MPiB) with no dynamic attributes.
This operator is kept for backward compatibility.
*/
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "OgnReadPrimDatabase.h"
#include "PrimCommon.h"
#include "ReadPrimCommon.h"
#include <omni/kit/commands/ICommandBridge.h>
#include <carb/dictionary/DictionaryUtils.h>
#include <omni/fabric/FabricUSD.h>
#include <omni/kit/PythonInterOpHelper.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnReadPrim
{
std::unordered_set<NameToken> m_added;
public:
// ----------------------------------------------------------------------------
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
char const* primNodePath = nodeObj.iNode->getPrimPath(nodeObj);
CARB_LOG_WARN("ReadPrim node is deprecated: %s, use ReadPrimAttributes instead", primNodePath);
// When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected.
AttributeObj inputBundleAttribObj =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimAttributes::inputs::prim.m_token);
inputBundleAttribObj.iAttribute->registerValueChangedCallback(
inputBundleAttribObj, onInputBundleValueChanged, true);
}
// ----------------------------------------------------------------------------
static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData)
{
NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj);
GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj);
// If the graph is currently disabled then delay the update until the next compute.
// Arguably this should be done at the message propagation layer, then this wouldn't be necessary.
if (graphObj.iGraph->isDisabled(graphObj))
{
return;
}
// clear the output bundles
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
auto outputTokens = { OgnReadPrimAttributes::outputs::primBundle.m_token };
for (auto& outputToken : outputTokens)
{
BundleHandle outBundle = context.iContext->getOutputBundle(
context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex);
context.iContext->clearBundleContents(context, outBundle);
}
}
// ----------------------------------------------------------------------------
static PathC getPath(OgnReadPrimDatabase& db)
{
return readPrimBundle_getPath(db.abi_context(), db.abi_node(), OgnReadPrimAttributes::inputs::prim.m_token,
false, omni::fabric::kUninitializedToken, db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static bool writeToBundle(OgnReadPrimDatabase& db, PathC inputPath, bool force, pxr::UsdTimeCode const& time)
{
return readPrimBundle_writeToBundle(db.abi_context(), db.abi_node(), inputPath, db.inputs.attrNamesToImport(),
db.outputs.primBundle(), force, db.inputs.computeBoundingBox(), time, db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static void clean(OgnReadPrimDatabase& db)
{
db.outputs.primBundle().clear();
// remove dynamic attributes
BundleType empty;
updateAttributes(db.abi_context(), db.abi_node(), empty, db.getInstanceIndex());
}
// ----------------------------------------------------------------------------
static void updateAttributes(GraphContextObj const& contextObj,
NodeObj const& nodeObj,
BundleType const& bundle,
InstanceIndex instIdx)
{
OgnReadPrim& state = OgnReadPrimDatabase::sInternalState<OgnReadPrim>(nodeObj);
omni::kit::commands::ICommandBridge::ScopedUndoGroup scopedUndoGroup;
extractBundle_reflectBundleDynamicAttributes(nodeObj, contextObj, bundle, state.m_added, instIdx);
}
// ----------------------------------------------------------------------------
static bool compute(OgnReadPrimDatabase& db)
{
// import by pattern
bool inputChanged = false;
// bounding box changed
if (db.state.computeBoundingBox() != db.inputs.computeBoundingBox())
{
db.state.computeBoundingBox() = db.inputs.computeBoundingBox();
inputChanged = true;
}
// attribute filter changed
NameToken const attrNamesToImport = db.inputs.attrNamesToImport();
if (db.state.attrNamesToImport() != attrNamesToImport.token)
{
db.state.attrNamesToImport() = attrNamesToImport.token;
inputChanged = true;
}
// compute
bool result = readPrimBundle_compute<OgnReadPrim>(db, inputChanged);
if (!result)
return false;
// update dynamic attributes
BundleType outputBundle(db.abi_context(), db.outputs.primBundle().abi_bundleHandle());
updateAttributes(db.abi_context(), db.abi_node(), outputBundle, db.getInstanceIndex());
return outputBundle.isValid();
}
static bool updateNodeVersion(GraphContextObj const& context, NodeObj const& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
bool upgraded = false;
if (oldVersion < 6)
{
// backward compatibility: `inputs:attrNamesToImport`
// Prior to this version `inputs:attrNamesToImport` attribute did not support wild cards.
// The meaning of an empty string was to include all attributes. With the introduction of the wild cards
// we need to convert an empty string to "*" in order to include all attributes.
static Token const value{ "*" };
if (nodeObj.iNode->getAttributeExists(nodeObj, "inputs:attrNamesToImport"))
{
AttributeObj attr = nodeObj.iNode->getAttribute(nodeObj, "inputs:attrNamesToImport");
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, "inputs:attrNamesToImport", Type(BaseDataType::eToken),
&value, nullptr, kAttributePortType_Input,
kExtendedAttributeType_Regular, nullptr);
}
upgraded = true;
}
if (oldVersion < 8)
{
upgraded |= upgradeUsdTimeCodeInput(context, nodeObj);
}
return upgraded;
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 8,672 | C++ | 41.101942 | 138 | 0.559502 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGpuInteropRenderProductEntry.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 "OgnGpuInteropRenderProductEntryDatabase.h"
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <omni/graph/core/GpuInteropEntryUserData.h>
#include <omni/graph/core/iComputeGraph.h>
namespace omni
{
namespace graph
{
namespace core
{
// Replaces depreciated GpuInteropRenderProductEntry
// Downstream nodes of OgnGpuInteropRenderProductEntry can write Cuda code directly and they will be scheduled on the
// Gpu Foundations Rendergraph for Device 0. GpuInteropCudaEntry passes the cuda buffer pointer and
// associated metadata for a specific named resource outputted by the Rtx Renderer (such as LdrColor for
// final color). This buffer is a read/write buffer, and changes will be passed to consumer of the renderer's
// output
class OgnGpuInteropRenderProductEntry
{
public:
static bool compute(OgnGpuInteropRenderProductEntryDatabase& db)
{
GpuInteropRpEntryUserData* userData = static_cast<GpuInteropRpEntryUserData*>(db.abi_node().iNode->getUserData(db.abi_node()));
if (!userData)
return false;
db.outputs.simTime() = userData->simTime;
db.outputs.hydraTime() = userData->hydraTime;
db.outputs.rp() = (uint64_t)userData->rp;
db.outputs.gpu() = (uint64_t)userData->gpu;
db.outputs.exec() = ExecutionAttributeState::kExecutionAttributeStateEnabled;
return true;
}
static void initializeType(const NodeTypeObj& nodeTypeObj)
{
OgnGpuInteropRenderProductEntryDatabase::initializeType(nodeTypeObj);
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,011 | C++ | 33.689655 | 135 | 0.751367 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnRenameAttr.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 "OgnRenameAttrDatabase.h"
#include "TokenUtils.h"
#include <algorithm>
#include <string>
#include <unordered_map>
#include <vector>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnRenameAttr
{
public:
// Changes the names of attributes from an input prim for the corresponding output prim.
// Attributes not renamed will be copied from the input prim to the output prim without changing the name.
static bool compute(OgnRenameAttrDatabase& db)
{
const auto& inputBundle = db.inputs.data();
auto& outputBundle = db.outputs.data();
// Find all of the attribute names for selection.
std::vector<NameToken> inputAttrNames;
std::vector<NameToken> outputAttrNames;
TokenHelper::splitNames(db.tokenToString(db.inputs.inputAttrNames()), inputAttrNames);
TokenHelper::splitNames(db.tokenToString(db.inputs.outputAttrNames()), outputAttrNames);
size_t nameCount = std::min(inputAttrNames.size(), outputAttrNames.size());
if (nameCount == 0)
{
// No renaming, so we can just copy the input data into the output.
outputBundle = inputBundle;
return true;
}
// Mismatched name sizes are dealt with going with the minimum number, and reporting this warning
if (inputAttrNames.size() != outputAttrNames.size())
{
db.logWarning("Input name size %zu != output name size %zu", inputAttrNames.size(), outputAttrNames.size());
// Reduce the size of the name arrays to make them easier to look up later
inputAttrNames.resize(nameCount);
outputAttrNames.resize(nameCount);
}
// Zip them together so that iterators can be used to find matches
std::unordered_map<NameToken, NameToken> attrNameMap;
std::transform(inputAttrNames.begin(), inputAttrNames.end(), outputAttrNames.begin(),
std::inserter(attrNameMap, attrNameMap.end()),
[](NameToken a, NameToken b) { return std::make_pair(a, b); });
// Start from an empty output prim.
outputBundle.clear();
// Loop through the attributes on the input bundle, adding them to the output and renaming if they appear
// on the list.
for (const auto& input : inputBundle)
{
CARB_ASSERT(input.isValid());
auto newName = input.name();
// If the attribute's name is in the renaming list then rename it
auto itNameFound = attrNameMap.find(input.name());
if (itNameFound != attrNameMap.end())
{
newName = itNameFound->second;
}
outputBundle.insertAttribute(input, newName);
}
return true;
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 3,297 | C++ | 35.644444 | 120 | 0.653321 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnRenderPreprocessEntry.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 "OgnRenderPreprocessEntryDatabase.h"
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <omni/graph/core/GpuInteropEntryUserData.h>
#include <omni/graph/core/iComputeGraph.h>
namespace omni
{
namespace graph
{
namespace core
{
// OmniGraph nodes executed as a render preprocess need to be connected downstream of an entry point node
// in order to be scheduled as part of the render graph.
// Scheduling of cuda interop nodes begins with one of these entry nodes, which passes data (e.g. a cuda stream
// identifier) to downstream nodes.
class OgnRenderPreprocessEntry
{
public:
static bool compute(OgnRenderPreprocessEntryDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnRenderPreprocessEntry::compute");
GpuInteropCudaEntryUserData* userData = static_cast<GpuInteropCudaEntryUserData*>(db.abi_node().iNode->getUserData(db.abi_node()));
if (!userData)
return false;
db.outputs.stream() = (uint64_t)userData->cudaStream;
db.outputs.simTime() = userData->simTime;
db.outputs.hydraTime() = userData->hydraTime;
return true;
}
static void initializeType(const NodeTypeObj& nodeTypeObj)
{
OgnRenderPreprocessEntryDatabase::initializeType(nodeTypeObj);
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,730 | C++ | 29.910714 | 139 | 0.74104 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnRemoveAttr.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 "OgnRemoveAttrDatabase.h"
#include "TokenUtils.h"
#include "PrimCommon.h"
#include <algorithm>
#include <unordered_set>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnRemoveAttr
{
public:
// Copies all attributes from an input prim to the output prim, except for any specified to be removed.
static bool compute(OgnRemoveAttrDatabase& db)
{
auto& inputBundle = db.inputs.data();
auto& outputBundle = db.outputs.data();
outputBundle = inputBundle;
// Use pattern matching to find the attribute names.
std::vector<NameToken> attributes(outputBundle.attributeCount());
outputBundle.abi_bundleInterface()->getAttributeNames(attributes.data(), attributes.size());
std::vector<NameToken> remove;
remove.reserve(outputBundle.attributeCount());
std::string const& attrNamesToRemove = intToToken(db.inputs.attrNamesToRemove()).GetString();
PatternMatcher attrNameMatcher{ attrNamesToRemove };
// allow removing primitive internal attributes
if (!db.inputs.allowRemovePrimInternal())
attrNameMatcher.addExcludeTokens(getPrimAdditionalAttrs().names);
for (auto attribute : attributes)
{
if (attrNameMatcher && attrNameMatcher.matches(attribute))
{
remove.push_back(attribute);
}
}
if (!remove.empty())
{
outputBundle.removeAttributes(remove.size(), remove.data());
}
return true;
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 2,042 | C++ | 28.185714 | 107 | 0.682174 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGpuInteropCudaEntry.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 "OgnGpuInteropCudaEntryDatabase.h"
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <omni/graph/core/GpuInteropEntryUserData.h>
#include <omni/graph/core/iComputeGraph.h>
namespace omni
{
namespace graph
{
namespace core
{
// Replaces depreciated RenderPostprocessEntry
// Downstream nodes of OgnGpuInteropCudaEntry can write Cuda code directly and they will be scheduled on the
// Gpu Foundations Rendergraph for Device 0. GpuInteropCudaEntry passes the cuda buffer pointer and
// associated metadata for a specific named resource outputted by the Rtx Renderer (such as LdrColor for
// final color). This buffer is a read/write buffer, and changes will be passed to consumer of the renderer's
// output
class OgnGpuInteropCudaEntry
{
public:
static bool compute(OgnGpuInteropCudaEntryDatabase& db)
{
GpuInteropCudaEntryUserData* userData = static_cast<GpuInteropCudaEntryUserData*>(db.abi_node().iNode->getUserData(db.abi_node()));
if (!userData)
return false;
GpuInteropCudaResourceMap& cudaRsrcMap = userData->cudaRsrcMap;
std::string sourceName = db.inputs.sourceName();
auto it = cudaRsrcMap.find(sourceName);
if (it == cudaRsrcMap.end())
{
return false;
}
GpuInteropCudaResourceData& renderVarData = it->second;
db.outputs.cudaMipmappedArray() = (uint64_t)renderVarData.cudaResource;
db.outputs.width() = renderVarData.width;
db.outputs.height() = renderVarData.height;
db.outputs.isBuffer() = renderVarData.isBuffer;
db.outputs.bufferSize() = renderVarData.depthOrArraySize;
db.outputs.mipCount() = (uint32_t)renderVarData.mipCount;
db.outputs.format() = (uint64_t)renderVarData.format;
db.outputs.stream() = (uint64_t)userData->cudaStream;
db.outputs.simTime() = userData->simTime;
db.outputs.hydraTime() = userData->hydraTime;
db.outputs.externalTimeOfSimFrame() = userData->externalTimeOfSimFrame;
db.outputs.frameId() = userData->frameId;
return true;
}
static void initializeType(const NodeTypeObj& nodeTypeObj)
{
OgnGpuInteropCudaEntryDatabase::initializeType(nodeTypeObj);
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,729 | C++ | 34 | 139 | 0.720777 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnEventUpdateTick.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 "OgnEventUpdateTickDatabase.h"
namespace omni
{
namespace graph
{
namespace core
{
class OgnEventUpdateTick
{
public:
static bool compute(OgnEventUpdateTickDatabase& db)
{
// FIXME: temporary incomplete implementation. Always output event id of 0 for now.
// This is not useful of course, but does allow the event connenction to trigger.
// In time this should become a bundle, to incorporate information about the event
// received.
db.outputs.event() = 0;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,016 | C++ | 26.486486 | 92 | 0.729331 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGraphTarget.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 <OgnGraphTargetDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGraphTarget
{
public:
static size_t computeVectorized(OgnGraphTargetDatabase& db, size_t count)
{
auto targets = db.getGraphTargets(count);
auto paths = db.outputs.primPath.vectorized(count);
memcpy(paths.data(), targets.data(), count * sizeof(NameToken));
return count;
}
};
REGISTER_OGN_NODE()
}
}
}
| 943 | C++ | 23.205128 | 77 | 0.732768 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrimMaterial.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 <omni/fabric/FabricUSD.h>
#include "OgnWritePrimMaterialDatabase.h"
using namespace omni::fabric;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnWritePrimMaterial
{
public:
static bool compute(OgnWritePrimMaterialDatabase& db)
{
// Find our stage
const GraphContextObj& context = db.abi_context();
long stageId = context.iContext->getStageId(context);
PXR_NS::UsdStagePtr stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
if (!stage)
{
db.logError("Could not find USD stage %ld", stageId);
return false;
}
PXR_NS::SdfPath sdfPath;
if(db.inputs.prim().size() == 0)
{
const auto& primPath = db.inputs.primPath();
if (!PXR_NS::SdfPath::IsValidPathString(primPath)) {
db.logError("Invalid prim path");
return false;
}
sdfPath = PXR_NS::SdfPath(primPath);
}
else
{
if(db.inputs.prim().size() > 1)
db.logWarning("Only one prim target is supported, the rest will be ignored");
sdfPath = omni::fabric::toSdfPath(db.inputs.prim()[0]);
}
PXR_NS::UsdPrim prim = stage->GetPrimAtPath(sdfPath);
if (!prim) {
db.logError("Could not find USD prim");
return false;
}
PXR_NS::SdfPath materialSdfPath;
if(db.inputs.material().size() == 0)
{
const auto& materialPath = db.inputs.materialPath();
if (!PXR_NS::SdfPath::IsValidPathString(materialPath)) {
db.logError("Invalid material path");
return false;
}
materialSdfPath = PXR_NS::SdfPath(materialPath);
}
else
{
if(db.inputs.material().size() > 1)
db.logWarning("Only one material target is supported, the rest will be ignored");
materialSdfPath = omni::fabric::toSdfPath(db.inputs.material()[0]);
}
PXR_NS::UsdPrim materialPrim = stage->GetPrimAtPath(materialSdfPath);
if (!materialPrim) {
db.logError("Could not find USD material");
return false;
}
PXR_NS::UsdShadeMaterialBindingAPI materialBinding(prim);
PXR_NS::UsdShadeMaterial material(materialPrim);
if (!materialBinding.Bind(material)) {
db.logError("Could not bind USD material to USD prim");
return false;
}
db.outputs.execOut() = kExecutionAttributeStateEnabled;
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 3,245 | C++ | 29.336448 | 118 | 0.606163 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimMaterial.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 "OgnReadPrimMaterialDatabase.h"
#include <omni/fabric/FabricUSD.h>
using namespace omni::fabric;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnReadPrimMaterial
{
public:
static bool compute(OgnReadPrimMaterialDatabase& db)
{
// Fetch from the target input by default, if it's not set,
// use the prim path
PXR_NS::SdfPath sdfPath;
if (db.inputs.prim.size() == 0)
{
const auto& primPath = db.inputs.primPath();
if (!PXR_NS::SdfPath::IsValidPathString(primPath))
{
db.logError("Invalid prim path");
return false;
}
sdfPath = PXR_NS::SdfPath(primPath);
}
else
{
sdfPath = omni::fabric::toSdfPath(db.inputs.prim()[0]);
}
// Find our stage
const GraphContextObj& context = db.abi_context();
long stageId = context.iContext->getStageId(context);
PXR_NS::UsdStagePtr stage = PXR_NS::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
if (!stage)
{
db.logError("Could not find USD stage %ld", stageId);
return false;
}
PXR_NS::UsdPrim prim = stage->GetPrimAtPath(sdfPath);
if (!prim) {
db.logError("Could not find USD prim at %s", sdfPath.GetText());
return false;
}
PXR_NS::UsdShadeMaterialBindingAPI materialBinding(prim);
PXR_NS::UsdShadeMaterial boundMat = materialBinding.ComputeBoundMaterial();
if (!boundMat) {
db.outputs.material() = "";
db.outputs.materialPrim().resize(0);
return true;
}
db.outputs.material() = boundMat.GetPath().GetString().c_str();
db.outputs.materialPrim().resize(1);
db.outputs.materialPrim()[0] = omni::fabric::asInt(boundMat.GetPath());
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 2,539 | C++ | 27.863636 | 121 | 0.620323 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrimAttribute.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 <memory>
#include "PrimCommon.h"
#include <omni/fabric/FabricUSD.h>
#include <omni/usd/UsdContext.h>
#include <OgnWritePrimAttributeDatabase.h>
using namespace omni::fabric;
namespace omni
{
namespace graph
{
namespace nodes
{
// 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.
static const pxr::TfType s_tokenTfType = pxr::SdfValueTypeNames->Token.GetType();
static const TypeC s_tokenType = TypeC(Type(BaseDataType::eToken));
static thread_local bool recursiveSetupGuard = false;
class OgnWritePrimAttribute
{
static void setup(NodeObj const& nodeObj, GraphObj const& graphObj, OgnWritePrimAttributeDatabase& db, size_t offset)
{
// Check for re-entering setup and avoid. EG When input is being resolved we may get onConnectionTypeResolve()
if (recursiveSetupGuard)
return;
CARB_PROFILE_ZONE(1, "setup");
recursiveSetupGuard = true;
std::shared_ptr<nullptr_t> atScopeExit(nullptr, [](auto) { recursiveSetupGuard = false; });
InstanceIndex instanceIndex = db.getInstanceIndex() + offset;
db.state.correctlySetup(offset) = false;
GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) };
if (context.contextHandle == kInvalidGraphContextHandle)
return;
auto typeInterface{ carb::getCachedInterface<omni::graph::core::IAttributeType>() };
pxr::UsdAttribute attrib;
try
{
attrib = omni::graph::nodes::findSelectedAttribute(context, nodeObj, instanceIndex);
}
catch (std::runtime_error const&)
{
// Ignore errors in this callback - error will be reported at the next compute
return;
}
if (!attrib)
{
// Couldn't get the indicated attribute for some expected reason
return;
}
// Since we are a sink of data, we can assume that if our inputs:value is connected, it will be resolved by
// propagation from upstream. We do not want to resolve/unresolve our inputs:value if we are connected because
// this could create a type conflict with the upstream network. So instead we will only resolve/unresolve
// when we are disconnected, and otherwise error out if we see a conflict.
auto typeName{ attrib ? attrib.GetTypeName().GetAsToken() : pxr::TfToken() };
Type usdAttribType{ typeInterface->typeFromSdfTypeName(typeName.GetText()) };
if (!tryResolveInputAttribute(nodeObj, inputs::value.m_token, usdAttribType))
return;
AttributeObj srcData = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.m_token);
Type srcDataType = srcData.iAttribute->getResolvedType(srcData);
TypeC srcDataTypeC(srcDataType);
// no need to continue if we are not resolved yet
if (srcDataType == Type(BaseDataType::eUnknown))
return;
IFabricUsd* iFabricUsd = carb::getCachedInterface<IFabricUsd>();
// Find our stage
pxr::UsdStageRefPtr stage;
omni::fabric::FabricId fabricId;
std::tie(fabricId, stage) = getFabricForNode(context, nodeObj);
if (fabricId == omni::fabric::kInvalidFabricId)
return;
pxr::UsdPrim destPrim{ attrib.GetPrim() };
NameToken destAttribName = asInt(attrib.GetName());
// Add the destination Prim to FC
BucketId destPrimBucketId = omni::graph::nodes::addAttribToCache(
destPrim, destPrim.GetPath(), destAttribName, iFabricUsd, fabricId, UsdTimeCode::Default());
if (destPrimBucketId == kInvalidBucketId)
{
OgnWritePrimAttributeDatabase::logError(nodeObj, "Unable to add prim %s to fabric", destPrim.GetPrimPath().GetText());
return;
}
PathC destPath = asInt(destPrim.GetPrimPath());
// Read the type info of the destination attribute
auto iStageReaderWriter = carb::getCachedInterface<omni::fabric::IStageReaderWriter>();
auto stageReaderWriterId = iStageReaderWriter->createOrGetFromFabricId(fabricId);
if (iStageReaderWriter->attributeExists(stageReaderWriterId,destPath, destAttribName) == 0)
{
// Failed to add the attribute - it might not be authored
// --------------------------------------------------------------------------------------
// Get PrimVar into fabric by creating it on the prim
if (pxr::UsdGeomPrimvar::IsPrimvar(attrib))
{
// Primvars have to go through prim var api. Note that we don't set the value here. That is because we
// will be subsequently writing into the attribute through Fabric.
if (auto primVarAPI = pxr::UsdGeomPrimvarsAPI(destPrim))
{
if (pxr::UsdGeomPrimvar primVar = primVarAPI.FindPrimvarWithInheritance(attrib.GetName()))
{
primVarAPI.CreatePrimvar(attrib.GetName(), primVar.GetTypeName());
}
}
}
else
{
// --------------------------------------------------------------------------------------
// Get non-primvar into fabric by authoring the attribute with the composed value
pxr::VtValue val;
if (!attrib.Get(&val))
{
OgnWritePrimAttributeDatabase::logError(
nodeObj, "Unable to read %s of type %s", attrib.GetPath().GetText(), val.GetTypeName().c_str());
return;
}
if (!attrib.Set(val))
{
OgnWritePrimAttributeDatabase::logError(nodeObj, "Unable to author %s with value of type %s",
attrib.GetPath().GetText(),
val.GetTypeName().c_str());
return;
}
}
if (omni::graph::nodes::addAttribToCache(destPrim, destPrim.GetPath(), destAttribName, iFabricUsd,
fabricId, UsdTimeCode::Default()) == kInvalidBucketId)
{
OgnWritePrimAttributeDatabase::logError(
nodeObj, "Unable to add prim %s to fabric", destPrim.GetPrimPath().GetText());
return;
}
}
TypeC destDataTypeC = TypeC(iStageReaderWriter->getType(stageReaderWriterId,destPath, destAttribName));
if (destDataTypeC == kUnknownType)
{
OgnWritePrimAttributeDatabase::logError(
nodeObj, "Unable to add prim %s to fabric", destPrim.GetPrimPath().GetText());
return;
}
Type destDataType(destDataTypeC);
if (!ogn::areTypesCompatible(srcDataType, destDataType))
{
OgnWritePrimAttributeDatabase::logError(
nodeObj, "Attribute %s.%s is not compatible with type '%s', please disconnect to change target attribute",
destPrim.GetPrimPath().GetText(), toTfToken(destAttribName).GetText(), srcDataType.getTypeName().c_str());
return;
}
db.state.destPath(offset) = destPath.path;
db.state.destPathToken(offset) = asInt(destPrim.GetPrimPath().GetToken()).token;
db.state.destAttrib(offset) = destAttribName.token;
db.state.correctlySetup(offset) = true;
}
public:
// ----------------------------------------------------------------------------
// Called by OG when our prim attrib changes. We want to catch the case of changing the prim attribute interactively
static void onValueChanged(AttributeObj const& attrObj, void const* userData)
{
// FIXME: Be pedantic about validity checks - this can be run directly by the TfNotice so who knows
// when or where this is happening
NodeObj nodeObj{ attrObj.iAttribute->getNode(attrObj) };
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
GraphContextObj contextObj = graphObj.iGraph->getDefaultGraphContext(graphObj);
OgnWritePrimAttributeDatabase db(contextObj, nodeObj);
setup(nodeObj, graphObj, db, 0);
}
// ----------------------------------------------------------------------------
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
// We need to check resolution if any of our relevant inputs change
static std::array<NameToken, 5> const attribNames{ inputs::name.m_token, inputs::usePath.m_token, inputs::primPath.m_token,
inputs::prim.m_token , inputs::value.m_token };
for (auto const& attribName : attribNames)
{
AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, attribName);
attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true);
}
}
// ----------------------------------------------------------------------------
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
GraphContextObj contextObj = graphObj.iGraph->getDefaultGraphContext(graphObj);
OgnWritePrimAttributeDatabase db(contextObj, nodeObj);
setup(nodeObj, graphObj, db, 0);
}
// ----------------------------------------------------------------------------
static bool computeVectorized(OgnWritePrimAttributeDatabase& db, size_t count)
{
if (!db.inputs.value().resolved())
return true;
NodeObj nodeObj = db.abi_node();
GraphContextObj context = db.abi_context();
GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj);
Type type = db.inputs.value().type();
bool gpuValid = context.iAttributeData->gpuValid(db.inputs.value().abi_handle(), context);
// for array or GPU attributes, go through the data model to properly handle the copy
const bool useDataModel = type.arrayDepth || gpuValid || !db.inputs.value.canVectorize();
auto usePath = db.inputs.usePath.vectorized(count);
auto primPath = db.inputs.primPath.vectorized(count);
auto name = db.inputs.name.vectorized(count);
auto execOut = db.outputs.execOut.vectorized(count);
auto usdWriteBack = db.inputs.usdWriteBack.vectorized(count);
auto correctlySetup = db.state.correctlySetup.vectorized(count);
auto destPathToken = db.state.destPathToken.vectorized(count);
auto destAttrib = db.state.destAttrib.vectorized(count);
auto destPath = db.state.destPath.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (!correctlySetup[idx])
{
setup(nodeObj, graphObj, db, idx);
}
else
{
auto path = usePath[idx] ? primPath[idx].token : db.pathToToken(db.inputs.prim.firstOrDefault(idx));
if (path != destPathToken[idx] || name[idx] != destAttrib[idx])
setup(nodeObj, graphObj, db, idx);
}
}
if (useDataModel)
{
for (size_t idx = 0; idx < count; ++idx)
{
if (correctlySetup[idx])
{
copyAttributeData(context, destPath[idx], destAttrib[idx], nodeObj,
db.inputs.value(idx).abi_handle(), usdWriteBack[idx]);
execOut[idx] = kExecutionAttributeStateEnabled;
}
}
}
else
{
// gather src base pointer
uint8_t const* srcData = nullptr;
size_t stride = 0;
db.inputs.value().rawData(srcData, stride);
// retrieve dst pointers
std::vector<AttributeDataHandle> dstHandles;
dstHandles.reserve(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (correctlySetup[idx])
dstHandles.emplace_back(AttrKey{ destPath[idx], destAttrib[idx] });
else
dstHandles.push_back(AttributeDataHandle::invalidHandle());
}
std::vector<void*> dstData;
dstData.resize(count);
{
CARB_PROFILE_ZONE(1, "Retrieve Pointers");
context.iAttributeData->getDataW(dstData.data(), context, dstHandles.data(), count);
}
size_t writeBackCount = 0;
for (size_t idx = 0; idx < count; ++idx)
{
if (correctlySetup[idx])
{
void const* const src = srcData + idx * stride;
if(dstData[idx])
{
memcpy(dstData[idx], src, stride);
if (usdWriteBack[idx])
{
if (idx != writeBackCount)
dstHandles[writeBackCount] = dstHandles[idx];
++writeBackCount;
}
execOut[idx] = kExecutionAttributeStateEnabled;
}
else
{
db.logError("Target attribute not available");
}
}
}
if (writeBackCount)
{
CARB_PROFILE_ZONE(1, "RegisterWriteBack");
context.iContext->registerForUSDWriteBacks(context, dstHandles.data(), writeBackCount);
}
}
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 14,779 | C++ | 39.828729 | 131 | 0.574464 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetGraphTargetId.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 <OgnGetGraphTargetIdDatabase.h>
namespace omni::graph::nodes
{
class OgnGetGraphTargetId
{
public:
static size_t computeVectorized(OgnGetGraphTargetIdDatabase& db, size_t count)
{
auto targets = db.getGraphTargets(count);
auto targetId = db.outputs.targetId.vectorized(count);
std::transform(targets.begin(), targets.end(), targetId.begin(), [](auto const& t) {
return omni::fabric::hash(t);
});
return count;
}
};
REGISTER_OGN_NODE()
}
| 949 | C++ | 29.64516 | 92 | 0.718651 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGatherByPath.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 <OgnGatherByPathDatabase.h>
#include <omni/graph/core/IGatherPrototype.h>
#include <carb/flatcache/IPath.h>
#include <algorithm>
#include <vector>
using namespace carb::flatcache;
namespace omni
{
namespace graph
{
namespace core
{
class OgnGatherByPath
{
// The arguments from the last compute call - we want to skip our compute if these haven't changed, and we
// haven't heard that our Gather has changed.
struct LastComputeState
{
// copies of input values
std::vector<NameToken> primPathTokens; // Used in compute to compare to input tokens
bool allAttributes{ false };
std::string attributes;
NameToken hydraFastPath{ 0 };
bool shouldWriteBack;
bool forceExportToHistory{ false };
// data use by path-changed callback
std::vector<PathC> primPaths; // Used in OG callback to compare with given paths
PathChangedCallback callback{ nullptr, nullptr };
bool checkResyncAttributes{ false }; // Set to true to be notified for resync children
bool gatherDirty{ false }; // Set to true by OG callback
const carb::flatcache::IPath * iPath = nullptr;
};
public:
LastComputeState m_state;
// Called by OG when anything changes - which indicates buckets may have been modified
static void onPathChanged(const carb::flatcache::PathC* paths, const size_t numPaths, void* userData)
{
NodeHandle nodeHandle = reinterpret_cast<NodeHandle>(userData);
auto& state =
OgnGatherByPathDatabase::sm_stateManagerOgnGatherByPath.getState<OgnGatherByPath>(nodeHandle).m_state;
// set the dirty flag if we recognize one of the changed prim paths - which will indicate a 'resync' notice
// we don't care about attribute values changing
const auto& gatheredPaths = state.primPaths;
auto iter = std::find_first_of(gatheredPaths.begin(), gatheredPaths.end(), paths, paths + numPaths);
state.gatherDirty = (iter != gatheredPaths.end());
if (!state.gatherDirty && state.checkResyncAttributes && state.iPath)
{
auto& iPath = state.iPath;
auto iter = std::find_first_of(gatheredPaths.begin(), gatheredPaths.end(), paths, paths + numPaths,
[iPath](const PathC a, const PathC b) { return a == iPath->getParent(b); });
state.gatherDirty = (iter != gatheredPaths.end());
}
}
// ----------------------------------------------------------------------------
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
auto& cppObj = OgnGatherByPathDatabase::sInternalState<OgnGatherByPath>(nodeObj);
cppObj.m_state.callback = { &onPathChanged, reinterpret_cast<void*>(nodeObj.nodeHandle) };
nodeObj.iNode->registerPathChangedCallback(nodeObj, cppObj.m_state.callback);
}
// ----------------------------------------------------------------------------
static void release(const NodeObj& nodeObj)
{
auto& cppObj = OgnGatherByPathDatabase::sInternalState<OgnGatherByPath>(nodeObj);
nodeObj.iNode->deregisterPathChangedCallback(nodeObj, cppObj.m_state.callback);
}
// ----------------------------------------------------------------------------
static bool compute(OgnGatherByPathDatabase& db)
{
const omni::graph::core::IGatherPrototype* iGatherPrototype =
carb::getCachedInterface<omni::graph::core::IGatherPrototype>();
const IGraphContext& iContext = *db.abi_context().iContext;
auto& cppObj = db.internalState<OgnGatherByPath>();
LastComputeState& state = cppObj.m_state;
const auto& primPathTokens = db.inputs.primPaths();
bool allAttributes = db.inputs.allAttributes();
const auto& attributes = db.inputs.attributes();
auto hydraFastPathToken = db.inputs.hydraFastPath();
const bool& shouldWriteBack = db.inputs.shouldWriteBack();
bool forceExportToHistory = db.inputs.forceExportToHistory();
if (primPathTokens.empty())
return true;
state.checkResyncAttributes = db.inputs.checkResyncAttributes();
state.iPath = db.abi_context().iPath;
// We can skip this compute if our state isn't dirty AND none of our inputs have changed
if (!state.gatherDirty
&& (allAttributes == state.allAttributes)
&& (attributes == state.attributes)
&& (hydraFastPathToken == state.hydraFastPath)
&& (primPathTokens.size() == state.primPathTokens.size())
&& (shouldWriteBack == state.shouldWriteBack)
&& (forceExportToHistory == state.forceExportToHistory)
&& std::equal(primPathTokens.begin(), primPathTokens.end(), state.primPathTokens.begin()))
{
return true;
}
// convert the given NameToken[] to PathC[]
std::vector<PathC> paths;
paths.resize(primPathTokens.size());
std::transform(primPathTokens.begin(), primPathTokens.end(), paths.begin(),
[&](const auto& p) { return db.abi_context().iPath->getHandle(db.tokenToString(p)); });
// Save the input args to our per-instance state
state.primPaths.resize(paths.size());
state.primPathTokens.resize(paths.size());
std::copy(paths.begin(), paths.end(), state.primPaths.begin());
std::copy(primPathTokens.begin(), primPathTokens.end(), state.primPathTokens.begin());
state.allAttributes = allAttributes;
state.attributes = attributes;
state.hydraFastPath = hydraFastPathToken;
state.shouldWriteBack = shouldWriteBack;
state.forceExportToHistory = forceExportToHistory;
// tokenize the given list of space-separated attribute names
std::vector<NameToken> gatherAttribs;
if (!attributes.empty())
{
if (allAttributes)
{
CARB_LOG_ERROR("'attributes' specified, but allAttributes is true");
return false;
}
std::istringstream iss(attributes);
std::string word;
while (std::getline(iss, word, ' '))
{
if (!word.empty())
gatherAttribs.push_back(db.stringToToken(word.c_str()));
}
}
GatherAddTransformsMode hydraTransformsMode = GatherAddTransformsMode::eNone;
if (hydraFastPathToken == db.tokens.Local)
hydraTransformsMode = GatherAddTransformsMode::eLocal;
else if (hydraFastPathToken == db.tokens.World)
hydraTransformsMode = GatherAddTransformsMode::eWorld;
// Make the Gather ABI call
GatherId gatherId = iGatherPrototype->gatherPaths(
db.abi_context(), paths.data(), paths.size(),
allAttributes, gatherAttribs.data(), gatherAttribs.size(), hydraTransformsMode, shouldWriteBack, forceExportToHistory);
db.outputs.gatherId() = gatherId;
// If the gather succeeded, copy the gathered paths into the output
if (gatherId != kInvalidGatherId)
{
size_t gatheredPathsSize{ 0 };
PathC const* gatheredPaths{ nullptr };
size_t repeatedPathsSize{ 0 };
PathBucketIndex const* repeatedPaths{ nullptr };
if (iGatherPrototype->getGatheredPaths(db.abi_context(), gatherId, gatheredPaths, gatheredPathsSize) &&
iGatherPrototype->getGatheredRepeatedPaths(db.abi_context(), gatherId, repeatedPaths, repeatedPathsSize))
{
db.outputs.gatheredPaths().resize(gatheredPathsSize + repeatedPathsSize);
std::transform(gatheredPaths, gatheredPaths + gatheredPathsSize, db.outputs.gatheredPaths().begin(),
[&db](PathC const& path) {
Path pathWrap(path);
return db.stringToToken(pathWrap.getText());
});
std::transform(repeatedPaths, repeatedPaths + repeatedPathsSize, db.outputs.gatheredPaths().begin() + gatheredPathsSize,
[&db](PathBucketIndex const& pathBucketIndex) {
Path pathWrap(std::get<0>(pathBucketIndex));
return db.stringToToken(pathWrap.getText());
});
// clear the state gather dirty flag
state.gatherDirty = false;
return true;
}
}
db.outputs.gatheredPaths().resize(0);
CARB_LOG_ERROR("Could not gather paths");
return false;
}
};
REGISTER_OGN_NODE()
} // namespace core
} // namespace graph
} // namespace omni
| 9,303 | C++ | 42.074074 | 136 | 0.617865 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/usd/OgnIsPrimSelected.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 <omni/usd/Selection.h>
#include <omni/usd/UsdContext.h>
#include <OgnIsPrimSelectedDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnIsPrimSelected
{
public:
static bool compute(OgnIsPrimSelectedDatabase& db)
{
omni::usd::UsdContext* usdContext = omni::usd::UsdContext::getContext();
NameToken primPathToken = db.inputs.primPath();
bool isSelected {false};
if (primPathToken != carb::flatcache::kUninitializedToken)
{
char const* primPath = db.abi_context().iToken->getText(primPathToken);
if (primPath)
isSelected = usdContext->getSelection()->isPrimPathSelected(primPath);
}
db.outputs.isSelected() = isSelected;
return true;
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 1,336 | C++ | 25.215686 | 86 | 0.696856 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/usd/OgnReadStageSelection.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 <omni/usd/Selection.h>
#include <omni/usd/UsdContext.h>
#include <OgnReadStageSelectionDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnReadStageSelection
{
public:
static bool compute(OgnReadStageSelectionDatabase& db)
{
omni::usd::UsdContext* usdContext = omni::usd::UsdContext::getContext();
PXR_NS::SdfPathVector selectedPaths = usdContext->getSelection()->getSelectedPrimPathsV2();
ogn::array<NameToken>& selectedPrims = db.outputs.selectedPrims();
selectedPrims.resize(selectedPaths.size());
std::transform(selectedPaths.begin(), selectedPaths.end(), selectedPrims.begin(),
[&db](PXR_NS::SdfPath const& path)
{
std::string const& s = path.GetString();
auto tokenC = db.abi_context().iToken->getHandle(s.c_str());
return tokenC;
});
return true;
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 1,554 | C++ | 28.903846 | 99 | 0.655727 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeVector3.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 <OgnMakeVector3Database.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(OgnMakeVector3Database& db, size_t count = 1)
{
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 vector = db.outputs.tuple().template get<Type[3]>();
if (x && y && z && vector)
{
const auto px = x.vectorized(count);
const auto py = y.vectorized(count);
const auto pz = z.vectorized(count);
const auto pvector = vector.vectorized(count);
if (not(pvector.empty() || px.empty() || py.empty() || pz.empty()))
{
for (size_t i = 0; i < count; i++)
{
pvector[i][0] = px[i];
pvector[i][1] = py[i];
pvector[i][2] = pz[i];
}
return true;
}
return false;
}
for(size_t i = 0; i < count ; ++i)
{
const auto xArray = db.inputs.x(i).template get<Type[]>();
const auto yArray = db.inputs.y(i).template get<Type[]>();
const auto zArray = db.inputs.z(i).template get<Type[]>();
auto vectorArray = db.outputs.tuple(i).template get<Type[][3]>();
if (!vectorArray || !xArray || !yArray || !zArray){
return false;
}
if (xArray->size() != yArray->size() || xArray->size() != zArray->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()));
}
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];
}
}
return true;
}
} // namespace
// Node to merge 3 scalers together to make 3-vector
class OgnMakeVector3
{
public:
static size_t computeVectorized(OgnMakeVector3Database& db, size_t count)
{
// Compute the components, if the types are all resolved.
try
{
if (tryMakeVector<double>(db, count))
return count;
else if (tryMakeVector<float>(db, count))
return count;
else if (tryMakeVector<pxr::GfHalf>(db, count))
return count;
else if (tryMakeVector<int32_t>(db, count))
return count;
else
{
db.logError("Failed to resolve input types");
return 0;
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be made: %s", e.what());
return 0;
}
return 0;
}
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 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);
// If one of the inputs is resolved we can resolve the other because they should match
std::array<AttributeObj, 3> attrs { x, y, z };
if (nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size()))
{
xType = vector.iAttribute->getResolvedType(x);
yType = vector.iAttribute->getResolvedType(y);
zType = vector.iAttribute->getResolvedType(z);
}
// Require inputs to be resolved before determining outputs' type
if (xType.baseType != BaseDataType::eUnknown &&
yType.baseType != BaseDataType::eUnknown &&
zType.baseType != BaseDataType::eUnknown )
{
std::array<AttributeObj, 4> attrs{ x, y, z, vector };
std::array<uint8_t, 4> tuples{ 1, 1, 1, 3 };
std::array<uint8_t, 4> arrays{
xType.arrayDepth,
yType.arrayDepth,
zType.arrayDepth,
xType.arrayDepth,
};
std::array<AttributeRole, 4> roles{ xType.role, yType.role, zType.role, AttributeRole::eNone };
nodeObj.iNode->resolvePartiallyCoupledAttributes(
nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 5,523 | C++ | 33.098765 | 116 | 0.565635 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnConstantPrims.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 <OgnConstantPrimsDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConstantPrims
{
public:
static size_t computeVectorized(OgnConstantPrimsDatabase& db, size_t count)
{
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 739 | C++ | 21.424242 | 79 | 0.749662 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnConstructArray.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 <OgnConstructArrayDatabase.h>
#include <carb/logging/Log.h>
#include <omni/graph/core/Type.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <array>
#include <unordered_map>
#include <vector>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
static constexpr size_t kMaxAttrNameLen{ 32 };
void formatAttrName(size_t n, std::array<char, kMaxAttrNameLen>& outName)
{
snprintf(outName.data(), kMaxAttrNameLen, "inputs:input%zu", n);
}
template<typename BaseType>
bool tryComputeAssumingType(OgnConstructArrayDatabase& db)
{
NodeObj nodeObj = db.abi_node();
auto iNode = nodeObj.iNode;
GraphObj graphObj = iNode->getGraph(nodeObj);
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
auto const outputArrayAttr = iNode->getAttributeByToken(nodeObj, outputs::array.token());
auto const outputArrayType = outputArrayAttr.iAttribute->getResolvedType(outputArrayAttr);
if (outputArrayType.baseType == BaseDataType::eUnknown)
{
return false;
}
auto outputArray = db.outputs.array().template get<BaseType[]>();
if (!outputArray)
return false;
size_t const arraySize = static_cast<size_t>(std::max(0, db.inputs.arraySize()));
(*outputArray).resize(arraySize);
memset(outputArray->data(), 0, sizeof(BaseType) * arraySize);
// read dynamic inputs
size_t i = 0;
std::array<char, kMaxAttrNameLen> outName;
formatAttrName(i, outName);
while (iNode->getAttributeExists(nodeObj, outName.data()) && i < arraySize) {
auto inAttrib = iNode->getAttribute(nodeObj, outName.data());
auto inputAttribType = inAttrib.iAttribute->getResolvedType(inAttrib);
if (inputAttribType.baseType != BaseDataType::eUnknown)
{
ConstAttributeDataHandle handle = inAttrib.iAttribute->getConstAttributeDataHandle(inAttrib, db.getInstanceIndex());
auto const dataPtr = getDataR<BaseType>(context, handle);
if (dataPtr)
(*outputArray)[i] = *dataPtr;
}
++i;
formatAttrName(i, outName);
}
// fill the rest of the array using the last input value if necessary
if (0 < i && i < arraySize)
{
for (size_t j = i; j < arraySize; ++j)
{
(*outputArray)[j] = (*outputArray)[i - 1];
}
}
return true;
}
template<typename BaseType, size_t TupleSize>
bool tryComputeAssumingType(OgnConstructArrayDatabase& db)
{
NodeObj nodeObj = db.abi_node();
auto iNode = nodeObj.iNode;
GraphObj graphObj = iNode->getGraph(nodeObj);
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
auto const outputArrayAttr = iNode->getAttributeByToken(nodeObj, outputs::array.token());
auto const outputArrayType = outputArrayAttr.iAttribute->getResolvedType(outputArrayAttr);
if (outputArrayType.baseType == BaseDataType::eUnknown)
{
return false;
}
auto outputArray = db.outputs.array().template get<BaseType[][TupleSize]>();
if (!outputArray)
return false;
size_t const arraySize = static_cast<size_t>(std::max(0, db.inputs.arraySize()));
(*outputArray).resize(arraySize);
memset(outputArray->data(), 0, sizeof(BaseType) * arraySize * TupleSize);
// read dynamic inputs
size_t i = 0;
std::array<char, kMaxAttrNameLen> outName;
formatAttrName(i, outName);
while (iNode->getAttributeExists(nodeObj, outName.data()) && i < arraySize) {
auto inAttrib = iNode->getAttribute(nodeObj, outName.data());
auto inputAttribType = inAttrib.iAttribute->getResolvedType(inAttrib);
if (inputAttribType.baseType != BaseDataType::eUnknown)
{
ConstAttributeDataHandle handle = inAttrib.iAttribute->getConstAttributeDataHandle(inAttrib, db.getInstanceIndex());
auto const dataPtr = getDataR<BaseType[TupleSize]>(context, handle);
if (dataPtr)
memcpy(&((*outputArray)[i]), dataPtr, sizeof(BaseType) * TupleSize);
}
++i;
formatAttrName(i, outName);
}
// fill the rest of the array using the last input value if necessary
if (0 < i && i < arraySize)
{
for (size_t j = i; j < arraySize; ++j)
{
memcpy(&((*outputArray)[j]), &((*outputArray)[i - 1]), sizeof(BaseType) * TupleSize);
}
}
return true;
}
} // namespace
class OgnConstructArray
{
static void tryResolveAttribute(omni::graph::core::NodeObj const& nodeObj,
omni::graph::core::AttributeObj attrib,
omni::graph::core::Type attribType)
{
Type valueType{ attrib.iAttribute->getResolvedType(attrib) };
bool attribIsValid = (attribType.baseType != BaseDataType::eUnknown);
if (valueType.baseType != BaseDataType::eUnknown)
{
// Resolved
// Case 1: We didn't find a valid source attribute => unresolve
// Case 2: We found an attribute but it is not compatible with our current resolution => unresolve
// Else: All good
if (!attribIsValid or (attribType != valueType))
{
// Not compatible! Request that the attribute be un-resolved. Note that this could fail if there are
// connections that result in a contradiction during type propagation
attrib.iAttribute->setResolvedType(attrib, Type(BaseDataType::eUnknown));
}
}
// If it's unresolved (and we have a valid attribute) we can request a resolution
if (attribIsValid and (attrib.iAttribute->getResolvedType(attrib).baseType == BaseDataType::eUnknown))
{
attrib.iAttribute->setResolvedType(attrib, attribType);
}
}
static void tryResolveArrayAttributes(omni::graph::core::NodeObj const& nodeObj, bool reconnectInputs)
{
auto& state = OgnConstructArrayDatabase::sInternalState<OgnConstructArray>(nodeObj);
// Get the input attributes
std::vector<AttributeObj> inputAttributes;
size_t i = 0;
std::array<char, kMaxAttrNameLen> outName;
formatAttrName(i, outName);
while (nodeObj.iNode->getAttributeExists(nodeObj, outName.data()))
{
inputAttributes.push_back(nodeObj.iNode->getAttribute(nodeObj, outName.data()));
++i;
formatAttrName(i, outName);
}
// Determine the output array type from the specified array type and connected inputs
Type outputType = state.m_inputArrayType; // Initialize to the specified array type ('eUnknown' if unspecified, i.e. 'inputs:arrayType' is set to 'auto')
for (auto const& inAttrib : inputAttributes)
{
// Check if input is an array
if (inAttrib.iAttribute->getResolvedType(inAttrib).arrayDepth != 0)
{
OgnConstructArrayDatabase::logError(nodeObj, "Nested arrays not supported: The input array element at attribute '%s' is an array",
inAttrib.iAttribute->getName(inAttrib));
// Unresolve output and return
auto outputArrayAttrib = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::array.token());
tryResolveAttribute(nodeObj, outputArrayAttrib, Type(BaseDataType::eUnknown));
return;
}
// Skip unconnected inputs
size_t upstreamConnectionCount = inAttrib.iAttribute->getUpstreamConnectionCount(inAttrib);
if (upstreamConnectionCount != 1)
continue;
// Get the type of the current input from the upstream connection
ConnectionInfo upstreamConnection;
inAttrib.iAttribute->getUpstreamConnectionsInfo(inAttrib, &upstreamConnection, 1);
Type const upstreamType = upstreamConnection.attrObj.iAttribute->getResolvedType(upstreamConnection.attrObj);
// The array type is not specified, so infer from the first connected and resolved input
if (upstreamType.baseType != BaseDataType::eUnknown)
{
if (outputType.baseType == BaseDataType::eUnknown)
{
outputType = upstreamType;
}
else
{
// Check if the specified or inferred array type matches the type of the current input
if (!outputType.compatibleRawData(upstreamType))
{
OgnConstructArrayDatabase::logError(
nodeObj, "Mismatched array element type on input attribute '%s': expected '%s', got '%s'",
inAttrib.iAttribute->getName(inAttrib), getOgnTypeName(outputType).c_str(),
getOgnTypeName(upstreamType).c_str());
outputType = Type(BaseDataType::eUnknown);
break;
}
}
}
}
// Resolve inputs
for (auto& inAttrib : inputAttributes)
{
size_t upstreamConnectionCount = inAttrib.iAttribute->getUpstreamConnectionCount(inAttrib);
if (upstreamConnectionCount == 0)
{
// Resolve unconnected inputs to the specified array type, or the inferred array type if the array type is unspecified
if (state.m_inputArrayType.baseType != BaseDataType::eUnknown)
{
if (inAttrib.iAttribute->getResolvedType(inAttrib) != state.m_inputArrayType)
{
// Case: The current input is disconnected and the array type is specified
// Action: Resolve the current input to the specified array type
tryResolveAttribute(nodeObj, inAttrib, state.m_inputArrayType);
}
}
else
{
if (inAttrib.iAttribute->getResolvedType(inAttrib) != outputType)
{
// Case: The current input is disconnected and the array type is unspecified (auto)
// Action: Resolve the current input to the inferred array type if any input is connected.
// If no inputs are connected, then outputType will be 'eUnknown', unresolving the current input.
tryResolveAttribute(nodeObj, inAttrib, outputType);
}
}
}
else if (upstreamConnectionCount == 1 && reconnectInputs) // reconnectInputs avoids an infinite loop
{
// Resolve connected inputs to the specified array type, or their upstream types if the array type is unspecified
if (state.m_inputArrayType.baseType != BaseDataType::eUnknown)
{
// Check if already resolved to the specified array type
if (inAttrib.iAttribute->getResolvedType(inAttrib) != state.m_inputArrayType)
{
// Disconnect before re-resolving
ConnectionInfo upstreamConnection;
inAttrib.iAttribute->getUpstreamConnectionsInfo(inAttrib, &upstreamConnection, 1);
inAttrib.iAttribute->disconnectAttrs(upstreamConnection.attrObj, inAttrib, true);
// Case: The current input is connected and the array type is specified
// Action: Resolve the current input to the specified array type
tryResolveAttribute(nodeObj, inAttrib, state.m_inputArrayType);
// Reconnect
ConnectionInfo destConnection {inAttrib, upstreamConnection.connectionType};
inAttrib.iAttribute->connectAttrsEx(upstreamConnection.attrObj, destConnection, true);
}
}
else
{
ConnectionInfo upstreamConnection;
inAttrib.iAttribute->getUpstreamConnectionsInfo(inAttrib, &upstreamConnection, 1);
Type const upstreamType = upstreamConnection.attrObj.iAttribute->getResolvedType(upstreamConnection.attrObj);
// Check if already resolved to the upstream type
if (inAttrib.iAttribute->getResolvedType(inAttrib) != upstreamType)
{
// Disconnect before re-resolving
inAttrib.iAttribute->disconnectAttrs(upstreamConnection.attrObj, inAttrib, true);
// Case: The current input is connected and the array type is unspecified (auto)
// Action: Resolve the current input to its upstream type (not the inferred array type 'outputType',
// which could be a different but compatible type or 'eUnknown')
tryResolveAttribute(nodeObj, inAttrib, Type(BaseDataType::eUnknown)); // Must be resolved to 'eUnknown', not 'upstreamType'
// Reconnect
ConnectionInfo destConnection {inAttrib, upstreamConnection.connectionType};
inAttrib.iAttribute->connectAttrsEx(upstreamConnection.attrObj, destConnection, true);
}
}
}
}
// Resolve the output
// If there is a type mismatch (regardless of whether the array type was specified), then 'outputType' gets set to 'eUnknown', so 'outputs:array' gets unresolved.
// If the array type is unspecified (auto) and no inputs are connected (i.e. no type is inferred), then 'outputType' gets set to 'eUnknown' as well (but the node does not error).
// Otherwise, 'outputs:array' gets resolved to the specified or inferred array type 'outputType'.
outputType.arrayDepth = 1;
auto outputArrayAttrib = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::array.token());
tryResolveAttribute(nodeObj, outputArrayAttrib, outputType);
}
static void onValueChanged(AttributeObj const& attrObj, void const* userData)
{
NodeObj nodeObj{ attrObj.iAttribute->getNode(attrObj) };
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) };
if (context.contextHandle == kInvalidGraphContextHandle)
return;
ConstAttributeDataHandle handle =
attrObj.iAttribute->getConstAttributeDataHandle(attrObj, kAccordingToContextIndex);
auto const dataPtr = getDataR<NameToken>(context, handle);
if (dataPtr)
{
auto& state = OgnConstructArrayDatabase::sInternalState<OgnConstructArray>(nodeObj);
state.m_inputArrayType = state.m_arrayTypes[*dataPtr];
}
tryResolveArrayAttributes(nodeObj, true);
}
static void onConnected(AttributeObj const& otherAttrib, AttributeObj const& inAttrib, void* userData)
{
NodeObj nodeObj{ inAttrib.iAttribute->getNode(inAttrib) };
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
NodeObj* thisNodeObj = reinterpret_cast<NodeObj*>(userData);
if (nodeObj.nodeHandle != thisNodeObj->nodeHandle)
return;
auto& state = OgnConstructArrayDatabase::sInternalState<OgnConstructArray>(nodeObj);
// Deregister onConnected callback to avoid infinite loop
struct ConnectionCallback connectedCallback = {onConnected, &state.m_nodeObj};
nodeObj.iNode->deregisterConnectedCallback(nodeObj, connectedCallback);
tryResolveArrayAttributes(nodeObj, true);
// Re-register onConnected callback
nodeObj.iNode->registerConnectedCallback(nodeObj, connectedCallback);
}
public:
omni::graph::core::NodeObj m_nodeObj;
std::unordered_map<NameToken, omni::graph::core::Type> m_arrayTypes;
omni::graph::core::Type m_inputArrayType;
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
auto& state = OgnConstructArrayDatabase::sInternalState<OgnConstructArray>(nodeObj);
state.m_nodeObj = nodeObj;
state.m_arrayTypes = {
{OgnConstructArrayDatabase::tokens.Bool, Type(BaseDataType::eBool)},
{OgnConstructArrayDatabase::tokens.Double, Type(BaseDataType::eDouble)},
{OgnConstructArrayDatabase::tokens.Float, Type(BaseDataType::eFloat)},
{OgnConstructArrayDatabase::tokens.Half, Type(BaseDataType::eHalf)},
{OgnConstructArrayDatabase::tokens.Int, Type(BaseDataType::eInt)},
{OgnConstructArrayDatabase::tokens.Int64, Type(BaseDataType::eInt64)},
{OgnConstructArrayDatabase::tokens.Token, Type(BaseDataType::eToken)},
{OgnConstructArrayDatabase::tokens.UChar, Type(BaseDataType::eUChar)},
{OgnConstructArrayDatabase::tokens.UInt, Type(BaseDataType::eUInt)},
{OgnConstructArrayDatabase::tokens.UInt64, Type(BaseDataType::eUInt64)},
{OgnConstructArrayDatabase::tokens.Double_2, Type(BaseDataType::eDouble, 2)},
{OgnConstructArrayDatabase::tokens.Double_3, Type(BaseDataType::eDouble, 3)},
{OgnConstructArrayDatabase::tokens.Double_4, Type(BaseDataType::eDouble, 4)},
{OgnConstructArrayDatabase::tokens.Double_9, Type(BaseDataType::eDouble, 9, 0, AttributeRole::eMatrix)},
{OgnConstructArrayDatabase::tokens.Double_16, Type(BaseDataType::eDouble, 16, 0, AttributeRole::eMatrix)},
{OgnConstructArrayDatabase::tokens.Float_2, Type(BaseDataType::eFloat, 2)},
{OgnConstructArrayDatabase::tokens.Float_3, Type(BaseDataType::eFloat, 3)},
{OgnConstructArrayDatabase::tokens.Float_4, Type(BaseDataType::eFloat, 4)},
{OgnConstructArrayDatabase::tokens.Half_2, Type(BaseDataType::eHalf, 2)},
{OgnConstructArrayDatabase::tokens.Half_3, Type(BaseDataType::eHalf, 3)},
{OgnConstructArrayDatabase::tokens.Half_4, Type(BaseDataType::eHalf, 4)},
{OgnConstructArrayDatabase::tokens.Int_2, Type(BaseDataType::eInt, 2)},
{OgnConstructArrayDatabase::tokens.Int_3, Type(BaseDataType::eInt, 3)},
{OgnConstructArrayDatabase::tokens.Int_4, Type(BaseDataType::eInt, 4)},
};
AttributeObj arrayTypeAttrib = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::arrayType.m_token);
arrayTypeAttrib.iAttribute->registerValueChangedCallback(arrayTypeAttrib, onValueChanged, true);
struct ConnectionCallback connectedCallback = {onConnected, &state.m_nodeObj};
nodeObj.iNode->registerConnectedCallback(nodeObj, connectedCallback);
onValueChanged(arrayTypeAttrib, nullptr);
}
static bool compute(OgnConstructArrayDatabase& db)
{
NodeObj nodeObj = db.abi_node();
auto const outputArrayAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::array.token());
auto const outputArrayType = outputArrayAttr.iAttribute->getResolvedType(outputArrayAttr);
try
{
switch (outputArrayType.baseType)
{
case BaseDataType::eBool:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<bool>(db)) return true;
break;
case BaseDataType::eDouble:
switch (outputArrayType.componentCount)
{
case 1:
if (tryComputeAssumingType<double>(db)) return true;
break;
case 2:
if (tryComputeAssumingType<double, 2>(db)) return true;
break;
case 3:
if (tryComputeAssumingType<double, 3>(db)) return true;
break;
case 4:
if (tryComputeAssumingType<double, 4>(db)) return true;
break;
case 9:
if (tryComputeAssumingType<double, 9>(db)) return true;
break;
case 16:
if (tryComputeAssumingType<double, 16>(db)) return true;
break;
}
break;
case BaseDataType::eFloat:
switch (outputArrayType.componentCount)
{
case 1:
if (tryComputeAssumingType<float>(db)) return true;
break;
case 2:
if (tryComputeAssumingType<float, 2>(db)) return true;
break;
case 3:
if (tryComputeAssumingType<float, 3>(db)) return true;
break;
case 4:
if (tryComputeAssumingType<float, 4>(db)) return true;
break;
}
break;
case BaseDataType::eHalf:
switch (outputArrayType.componentCount)
{
case 1:
if (tryComputeAssumingType<pxr::GfHalf>(db)) return true;
break;
case 2:
if (tryComputeAssumingType<pxr::GfHalf, 2>(db)) return true;
break;
case 3:
if (tryComputeAssumingType<pxr::GfHalf, 3>(db)) return true;
break;
case 4:
if (tryComputeAssumingType<pxr::GfHalf, 4>(db)) return true;
break;
}
break;
case BaseDataType::eInt:
switch (outputArrayType.componentCount)
{
case 1:
if (tryComputeAssumingType<int32_t>(db)) return true;
break;
case 2:
if (tryComputeAssumingType<int32_t, 2>(db)) return true;
break;
case 3:
if (tryComputeAssumingType<int32_t, 3>(db)) return true;
break;
case 4:
if (tryComputeAssumingType<int32_t, 4>(db)) return true;
break;
}
break;
case BaseDataType::eInt64:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<int64_t>(db)) return true;
break;
case BaseDataType::eToken:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<OgnToken>(db)) return true;
break;
case BaseDataType::eUChar:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<uint8_t>(db)) return true;
break;
case BaseDataType::eUInt:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<uint32_t>(db)) return true;
break;
case BaseDataType::eUInt64:
if (outputArrayType.componentCount == 1)
if (tryComputeAssumingType<uint64_t>(db)) return true;
break;
default:
break;
}
db.logError("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
tryResolveArrayAttributes(nodeObj, false);
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 24,641 | C++ | 44.381215 | 186 | 0.603831 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnAppendString.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 <OgnAppendStringDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnAppendString
{
public:
static bool compute(OgnAppendStringDatabase& db)
{
auto const& suffix = db.inputs.suffix();
if (suffix.type().baseType == BaseDataType::eToken)
return computeForToken(db);
return computeForString(db);
}
static bool computeForString(OgnAppendStringDatabase& db)
{
auto const inputValue = db.inputs.value();
auto const suffixIn = db.inputs.suffix();
auto const suffixData = suffixIn.get<uint8_t[]>();
auto& outValue = db.outputs.value();
// No suffix? Just copy in to out
if (suffixData->empty())
{
db.outputs.value().copyData(inputValue);
return true;
}
auto const inputValueData = inputValue.get<uint8_t[]>();
std::string outVal;
outVal.reserve(inputValueData.size() + suffixData.size());
outVal.append(reinterpret_cast<char const*>(inputValueData->data()), inputValueData.size());
outVal.append(reinterpret_cast<char const*>(suffixData->data()), suffixData.size());
auto outData = outValue.get<uint8_t[]>();
size_t outBufferSize = outVal.size();
outData->resize(outBufferSize);
memcpy(outData->data(), reinterpret_cast<uint8_t const*>(outVal.data()), outBufferSize);
return true;
}
static bool computeForToken(OgnAppendStringDatabase& db)
{
auto const& inputValue = db.inputs.value();
auto const& suffix = db.inputs.suffix();
std::vector<char const*> suffixes;
if (suffix.type().arrayDepth == 0)
{
NameToken suffixToken = *suffix.get<OgnToken>();
if (suffixToken != omni::fabric::kUninitializedToken)
suffixes.push_back(db.tokenToString(suffixToken));
}
else
{
const auto suffixTokens = *suffix.get<OgnToken[]>();
suffixes.resize(suffixTokens.size());
std::transform(suffixTokens.begin(), suffixTokens.end(), suffixes.begin(),
[&db](auto t) { return db.tokenToString(t); });
}
// No suffix? Just copy in to out
if (suffixes.empty())
{
db.outputs.value().copyData(inputValue);
return true;
}
if (inputValue.type().arrayDepth > 0)
{
const auto inputValueArray = *inputValue.get<OgnToken[]>();
auto outputPathArray = *db.outputs.value().get<OgnToken[]>();
outputPathArray.resize(inputValueArray.size());
if (suffixes.size() == 1)
{
const char* suffixStr = suffixes[0];
std::transform(inputValueArray.begin(), inputValueArray.end(), outputPathArray.begin(),
[&](const auto& p)
{
std::string s = db.tokenToString(p);
s += suffixStr;
return db.stringToToken(s.c_str());
});
}
else
{
if (inputValueArray.size() != suffixes.size())
{
CARB_LOG_ERROR("inputs:value and inputs:suffix arrays are not the same size (%zu and %zu)",
inputValueArray.size(), suffixes.size());
return false;
}
for (size_t i = 0; i < inputValueArray.size(); ++i)
{
std::string s = db.tokenToString(inputValueArray[i]);
s += suffixes[i];
outputPathArray[i] = db.stringToToken(s.c_str());
}
}
return true;
}
else
{
NameToken inValue = *inputValue.get<OgnToken>();
std::string s;
if (inValue != omni::fabric::kUninitializedToken)
{
s = db.tokenToString(inValue);
}
s += suffixes[0];
*db.outputs.value().get<OgnToken>() = db.stringToToken(s.c_str());
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto inputVal = node.iNode->getAttributeByToken(node, OgnAppendStringAttributes::inputs::value.m_token);
auto outputVal = node.iNode->getAttributeByToken(node, OgnAppendStringAttributes::outputs::value.m_token);
auto suffixVal = node.iNode->getAttributeByToken(node, OgnAppendStringAttributes::inputs::suffix.m_token);
//in type
auto type = inputVal.iAttribute->getResolvedType(inputVal);
//if input is an array of token, suffix is allowed to be either a simple or an array of token(s)
if (type.baseType == BaseDataType::eToken && type.arrayDepth != 0)
{
// both in and out needs to be the same
std::array<AttributeObj, 2> attrs{ inputVal, outputVal };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
//change suffix if necessary
auto suffixType = suffixVal.iAttribute->getResolvedType(suffixVal);
if (suffixType.baseType == BaseDataType::eUChar)//string not compatible with tokens
suffixVal.iAttribute->setResolvedType(suffixVal, type);
}
else
{
// else, the 3 needs to have the same type
std::array<AttributeObj, 3> attrs{ inputVal, suffixVal, outputVal };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 6,240 | C++ | 35.497076 | 114 | 0.567949 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToHalf.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 <OgnToHalfDatabase.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(OgnToHalfDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = pxr::GfHalf(float(value)); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, pxr::GfHalf>(db.inputs.value(), db.outputs.converted(), functor, count);
}
template<typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnToHalfDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = pxr::GfHalf(float(value)); };
return ogn::compute::tryComputeWithTupleBroadcasting<tupleSize, T, pxr::GfHalf>(
db.inputs.value(), db.outputs.converted(), functor, count);
}
} // namespace
class OgnToHalf
{
public:
// Node to convert numeric inputs to halfs
static bool computeVectorized(OgnToHalfDatabase& db, size_t count)
{
const auto& inputsValue = db.inputs.value();
auto& type = inputsValue.type();
bool result = false;
switch (type.baseType)
{
case BaseDataType::eBool:
{
result = tryComputeAssumingType<bool>(db, count);
break;
}
case BaseDataType::eDouble:
{
switch (type.componentCount)
{
case 1:
result = tryComputeAssumingType<double>(db, count);
break;
case 2:
result = tryComputeAssumingType<double, 2>(db, count);
break;
case 3:
result = tryComputeAssumingType<double, 3>(db, count);
break;
case 4:
result = tryComputeAssumingType<double, 4>(db, count);
break;
case 9:
result = tryComputeAssumingType<double, 9>(db, count);
break;
case 16:
result = tryComputeAssumingType<double, 16>(db, count);
break;
default:
result = false;
}
break;
}
case BaseDataType::eFloat:
{
switch (type.componentCount)
{
case 1:
result = tryComputeAssumingType<float>(db, count);
break;
case 2:
result = tryComputeAssumingType<float, 2>(db, count);
break;
case 3:
result = tryComputeAssumingType<float, 3>(db, count);
break;
case 4:
result = tryComputeAssumingType<float, 4>(db, count);
break;
default:
result = false;
}
break;
}
case BaseDataType::eHalf:
{
switch (type.componentCount)
{
case 1:
result = tryComputeAssumingType<pxr::GfHalf>(db, count);
break;
case 2:
result = tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
break;
case 3:
result = tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
break;
case 4:
result = tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
break;
default:
result = false;
}
break;
}
case BaseDataType::eInt:
{
switch (type.componentCount)
{
case 1:
result = tryComputeAssumingType<int32_t>(db, count);
break;
case 2:
result = tryComputeAssumingType<int32_t, 2>(db, count);
break;
case 3:
result = tryComputeAssumingType<int32_t, 3>(db, count);
break;
case 4:
result = tryComputeAssumingType<int32_t, 4>(db, count);
break;
default:
result = false;
}
break;
}
case BaseDataType::eInt64:
{
result = tryComputeAssumingType<int64_t>(db, count);
break;
}
case BaseDataType::eUChar:
{
result = tryComputeAssumingType<unsigned char>(db, count);
break;
}
case BaseDataType::eUInt:
{
result = tryComputeAssumingType<uint32_t>(db, count);
break;
}
case BaseDataType::eUInt64:
{
result = tryComputeAssumingType<uint64_t>(db, count);
break;
}
default:
{
result = false;
}
}
if (!result)
{
db.logError("Input could not be converted to half");
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::eHalf, valueType.componentCount, valueType.arrayDepth);
outAttr.iAttribute->setResolvedType(outAttr, resultType);
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 6,928 | C++ | 33.30198 | 132 | 0.487298 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnIsEmpty.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 <OgnIsEmptyDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/Types.h>
#include <string>
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnIsEmpty
{
public:
static bool compute(OgnIsEmptyDatabase& db)
{
const auto& variable = db.inputs.input();
auto& type = variable.type();
switch (type.baseType)
{
case BaseDataType::eBool:
case BaseDataType::eUChar:
case BaseDataType::eInt:
case BaseDataType::eUInt:
case BaseDataType::eInt64:
case BaseDataType::eUInt64:
case BaseDataType::eHalf:
case BaseDataType::eFloat:
case BaseDataType::eDouble:
{
db.outputs.isEmpty() = variable.size() == 0;
return true;
}
case BaseDataType::eToken:
{
std::string converted = tryConvertToString<ogn::Token>(db, variable);
db.outputs.isEmpty() = converted.length() == 0;
return true;
}
default:
{
db.logError("Type %s not supported", getOgnTypeName(type).c_str());
}
}
return false;
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 1,804 | C++ | 25.940298 | 85 | 0.601441 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToToken.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 <OgnToTokenDatabase.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
#include <sstream>
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename T>
bool tryComputeAssumingType(OgnToTokenDatabase& db)
{
std::string converted = tryConvertToString<T>(db, db.inputs.value());
if (converted.empty())
{
return false;
}
db.outputs.converted() = db.stringToToken(converted.c_str());
return true;
}
template <typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnToTokenDatabase& db)
{
std::string converted = tryConvertToString<T, tupleSize>(db, db.inputs.value());
if (converted.empty())
{
return false;
}
db.outputs.converted() = db.stringToToken(converted.c_str());
return true;
}
} // namespace
class OgnToToken
{
public:
// Node to convert any input to a token
static bool compute(OgnToTokenDatabase& 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(charData, charData + val->size());
db.outputs.converted() = db.stringToToken(str.c_str());
return true;
}
else if (attrType.arrayDepth == 0)
{
uchar val = *db.inputs.value().template get<uchar>();
db.outputs.converted() = db.stringToToken(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::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 a token: %s", e.what());
return false;
}
return true;
}
};
REGISTER_OGN_NODE();
}
}
}
| 5,950 | C++ | 33.598837 | 106 | 0.562689 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBreakVector2.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnBreakVector2Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename Type>
bool tryBreakVector(OgnBreakVector2Database& db)
{
const auto vector = db.inputs.tuple().template get<Type[2]>();
auto x = db.outputs.x().template get<Type>();
auto y = db.outputs.y().template get<Type>();
if (!vector || !x || !y){
return false;
}
*x = (*vector)[0];
*y = (*vector)[1];
return true;
}
} // namespace
// Node to break a 2-vector into it's component scalers
class OgnBreakVector2
{
public:
static bool compute(OgnBreakVector2Database& db)
{
// Compute the components, if the types are all resolved.
try
{
if (tryBreakVector<double>(db))
return true;
else if (tryBreakVector<float>(db))
return true;
else if (tryBreakVector<pxr::GfHalf>(db))
return true;
else if (tryBreakVector<int32_t>(db))
return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be broken: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto vector = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::tuple.token());
auto x = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::x.token());
auto y = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::y.token());
auto vectorType = vector.iAttribute->getResolvedType(vector);
// Require inputs to be resolved before determining outputs' type
if (vectorType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs{ vector, x, y };
std::array<uint8_t, 3> tuples{ 2, 1, 1 };
std::array<uint8_t, 3> arrays{ 0, 0, 0 };
std::array<AttributeRole, 3> roles{ vectorType.role, AttributeRole::eNone, AttributeRole::eNone };
nodeObj.iNode->resolvePartiallyCoupledAttributes(nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 2,913 | C++ | 29.041237 | 142 | 0.625815 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToFloat.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnToFloatDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnToFloatDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<float>(value); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, float>(db.inputs.value(), db.outputs.converted(), functor, count);
}
template<typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnToFloatDatabase& db, size_t count)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<float>(value); };
return ogn::compute::tryComputeWithTupleBroadcasting<tupleSize, T, float>(
db.inputs.value(), db.outputs.converted(), functor, count);
}
} // namespace
class OgnToFloat
{
public:
// Node to convert numeric inputs to floats
static bool computeVectorized(OgnToFloatDatabase& db, size_t count)
{
auto& inputType = db.inputs.value().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db, count);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (const std::exception& e)
{
db.logError("Input could not be converted to float: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto valueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token());
auto outAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::converted.token());
auto valueType = valueAttr.iAttribute->getResolvedType(valueAttr);
// The output shape must match the input shape and visa-versa, however we can't say anything
// about the input base type until it's connected
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eFloat, valueType.componentCount, valueType.arrayDepth);
outAttr.iAttribute->setResolvedType(outAttr, resultType);
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 5,427 | C++ | 38.911764 | 126 | 0.609176 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayRotate.cpp | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnArrayRotateDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
// Custom implementation of std::rotate.
// Using std::rotate fails to build on Linux when the underlying type is a tuple (eg int[3])
template<class ForwardIt>
constexpr
ForwardIt
rotateArray(ForwardIt first, ForwardIt n_first, ForwardIt last)
{
if(first == n_first) return last;
if(n_first == last) return first;
ForwardIt read = n_first;
ForwardIt write = first;
ForwardIt next_read = first; // read position for when "read" hits "last"
while(read != last) {
if(write == next_read) next_read = read; // track where "first" went
std::iter_swap(write++, read++);
}
// rotate the remaining sequence into place
(rotateArray)(write, next_read, last);
return write;
}
template<typename T>
bool tryComputeAssumingType(OgnArrayRotateDatabase& db)
{
const auto& steps = db.inputs.steps();
if (auto array = db.inputs.array().template get<T[]>())
{
if (auto result = db.outputs.array().template get<T[]>())
{
*result = *array;
if (!result->empty())
{
if (steps < 0)
{
rotateArray(result->begin(), result->begin() - steps, result->end());
}
else if (steps > 0)
{
rotateArray(result->rbegin(), result->rbegin() + steps, result->rend());
}
}
return true;
}
}
return false;
}
} // namespace
class OgnArrayRotate
{
public:
static bool compute(OgnArrayRotateDatabase& db)
{
auto& inputType = db.inputs.array().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnArrayRotate: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
std::array<AttributeObj, 2> attrs {
node.iNode->getAttributeByToken(node, inputs::array.token()),
node.iNode->getAttributeByToken(node, outputs::array.token())
};
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 5,703 | C++ | 33.780488 | 92 | 0.57198 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnSelectIf.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnSelectIfDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnSelectIfDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto const& condition, auto& result)
{
result = condition ? a : b;
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T, bool, T>(
db.inputs.ifTrue(), db.inputs.ifFalse(), db.inputs.condition(), db.outputs.result(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnSelectIfDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto const& condition, auto& result)
{
if (condition)
{
memcpy(result, a, sizeof(T) * N);
}
else
{
memcpy(result, b, sizeof(T) * N);
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], bool, T[N]>(
db.inputs.ifTrue(), db.inputs.ifFalse(), db.inputs.condition(), db.outputs.result(), functor, count);
}
} // namespace
class OgnSelectIf
{
public:
static bool computeVectorized(OgnSelectIfDatabase& db, size_t count)
{
NodeObj nodeObj = db.abi_node();
const AttributeObj ifTrueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::ifTrue.token());
const Type ifTrueType = ifTrueAttr.iAttribute->getResolvedType(ifTrueAttr);
const AttributeObj ifFalseAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::ifFalse.token());
const Type ifFalseType = ifFalseAttr.iAttribute->getResolvedType(ifFalseAttr);
const AttributeObj conditionAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::condition.token());
const Type conditionType = conditionAttr.iAttribute->getResolvedType(conditionAttr);
// This handles string case (arrays of strings are not supported)
if (ifTrueType.baseType == BaseDataType::eUChar && ifTrueType.arrayDepth == 1
&& ifFalseType.baseType == BaseDataType::eUChar && ifFalseType.arrayDepth == 1
&& conditionType.arrayDepth == 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
const bool condition = *db.inputs.condition(idx).template get<bool>();
auto ifTrue = db.inputs.ifTrue(idx).template get<uint8_t[]>();
auto ifFalse = db.inputs.ifFalse(idx).template get<uint8_t[]>();
auto result = db.outputs.result(idx).template get<uint8_t[]>();
if (condition)
{
result->resize(ifTrue->size());
memcpy(&((*result)[0]), &((*ifTrue)[0]), result->size());
}
else
{
result->resize(ifFalse->size());
memcpy(&((*result)[0]), &((*ifFalse)[0]), result->size());
}
}
return true;
}
try
{
switch (ifTrueType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db, count);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db, count);
case BaseDataType::eDouble:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (ifTrueType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto ifTrue = node.iNode->getAttributeByToken(node, inputs::ifTrue.token());
auto ifFalse = node.iNode->getAttributeByToken(node, inputs::ifFalse.token());
auto condition = node.iNode->getAttributeByToken(node, inputs::condition.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto ifTrueType = ifTrue.iAttribute->getResolvedType(ifTrue);
auto ifFalseType = ifFalse.iAttribute->getResolvedType(ifFalse);
auto conditionType = condition.iAttribute->getResolvedType(condition);
// Require ifTrue, ifFalse, and condition to be resolved before determining result's type
if (ifTrueType.baseType != BaseDataType::eUnknown && ifFalseType.baseType != BaseDataType::eUnknown
&& conditionType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { ifTrue, ifFalse, result };
std::array<uint8_t, 3> tupleCounts {
ifTrueType.componentCount,
ifFalseType.componentCount,
std::max(ifTrueType.componentCount, ifFalseType.componentCount)
};
std::array<uint8_t, 3> arrayDepths {
ifTrueType.arrayDepth,
ifFalseType.arrayDepth,
std::max(conditionType.arrayDepth, std::max(ifTrueType.arrayDepth, ifFalseType.arrayDepth))
};
const bool isStringInput = (ifTrueType.baseType == BaseDataType::eUChar
&& ifTrueType.arrayDepth == 1
&& ifFalseType.baseType == BaseDataType::eUChar
&& ifFalseType.arrayDepth == 1
&& conditionType.arrayDepth == 0
&& ifTrueType.role == AttributeRole::eText
&& ifFalseType.role == AttributeRole::eText);
std::array<AttributeRole, 3> rolesBuf {
ifTrueType.role,
ifFalseType.role,
isStringInput ? AttributeRole::eText : AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 9,218 | C++ | 43.110048 | 114 | 0.580386 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayGetSize.cpp |
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnArrayGetSizeDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
class OgnArrayGetSize
{
public:
static bool compute(OgnArrayGetSizeDatabase& db)
{
try
{
db.outputs.size() = int(db.inputs.array().size());
return true;
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 1> attrs { inputArray };
// all should have the same tuple count
std::array<uint8_t, 1> tupleCounts {
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 1> arrayDepths {
1
};
std::array<AttributeRole, 1> rolesBuf {
inputArrayType.role
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 2,153 | C++ | 31.636363 | 107 | 0.628425 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBuildString.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnBuildStringDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnBuildString
{
public:
static bool compute(OgnBuildStringDatabase& db)
{
auto const& inputValue = db.inputs.a();
auto const& suffixIn = db.inputs.b();
auto& outValue = db.outputs.value();
bool result = true;
if (inputValue.type().baseType == BaseDataType::eToken)
result = result && computeForToken(db, inputValue, suffixIn, outValue);
else
result = result && computeForString(db, inputValue, suffixIn, outValue);
auto const& dynamicInputs = db.getDynamicInputs();
if (!result || dynamicInputs.empty())
return result;
auto accumulatingValue = omni::graph::core::ogn::constructInputFromOutput(db, db.outputs.value(), outputs::value.token());
for (auto const& input : dynamicInputs)
{
if (input().type().baseType == BaseDataType::eToken)
result = result && computeForToken(db, accumulatingValue, input(), outValue);
else
result = result && computeForString(db, accumulatingValue, input(), outValue);
}
return result;
}
static bool computeForString(OgnBuildStringDatabase& db,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& inputValue,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& suffixIn,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& outValue)
{
auto const suffixData = suffixIn.get<uint8_t[]>();
// No suffix? Just copy in to out
if (suffixData->empty())
{
// the inputValue may be an alias for the outValue
if (inputValue.name() != outValue.name())
db.outputs.value().copyData(inputValue);
return true;
}
auto const inputValueData = inputValue.get<uint8_t[]>();
std::string outVal;
outVal.reserve(inputValueData.size() + suffixData.size());
outVal.append(reinterpret_cast<char const*>(inputValueData->data()), inputValueData.size());
outVal.append(reinterpret_cast<char const*>(suffixData->data()), suffixData.size());
auto outData = outValue.get<uint8_t[]>();
size_t outBufferSize = outVal.size();
outData->resize(outBufferSize);
memcpy(outData->data(), reinterpret_cast<uint8_t const*>(outVal.data()), outBufferSize);
return true;
}
static bool computeForToken(OgnBuildStringDatabase& db,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& inputValue,
ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const& suffix,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& outValue)
{
std::vector<char const*> suffixes;
if (suffix.type().arrayDepth == 0)
{
NameToken suffixToken = *suffix.get<OgnToken>();
if (suffixToken != omni::fabric::kUninitializedToken)
suffixes.push_back(db.tokenToString(suffixToken));
}
else
{
const auto suffixTokens = *suffix.get<OgnToken[]>();
suffixes.resize(suffixTokens.size());
std::transform(suffixTokens.begin(), suffixTokens.end(), suffixes.begin(),
[&db](auto t) { return db.tokenToString(t); });
}
// No suffix? Just copy in to out
if (suffixes.empty())
{
// the input value may be an alias for the output value
if (inputValue.name() != outValue.name())
db.outputs.value().copyData(inputValue);
return true;
}
if (inputValue.type().arrayDepth > 0)
{
const auto inputValueArray = *inputValue.get<OgnToken[]>();
auto outputPathArray = *db.outputs.value().get<OgnToken[]>();
outputPathArray.resize(inputValueArray.size());
if (suffixes.size() == 1)
{
const char* suffixStr = suffixes[0];
std::transform(inputValueArray.begin(), inputValueArray.end(), outputPathArray.begin(),
[&](const auto& p)
{
std::string s = db.tokenToString(p);
s += suffixStr;
return db.stringToToken(s.c_str());
});
}
else
{
if (inputValueArray.size() != suffixes.size())
{
CARB_LOG_ERROR("inputs:value and inputs:suffix arrays are not the same size (%zu and %zu)",
inputValueArray.size(), suffixes.size());
return false;
}
for (size_t i = 0; i < inputValueArray.size(); ++i)
{
std::string s = db.tokenToString(inputValueArray[i]);
s += suffixes[i];
outputPathArray[i] = db.stringToToken(s.c_str());
}
}
return true;
}
else
{
NameToken inValue = *inputValue.get<OgnToken>();
std::string s;
if (inValue != omni::fabric::kUninitializedToken)
{
s = db.tokenToString(inValue);
}
s += suffixes[0];
*db.outputs.value().get<OgnToken>() = db.stringToToken(s.c_str());
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto inputVal = node.iNode->getAttributeByToken(node, OgnBuildStringAttributes::inputs::a.m_token);
auto outputVal = node.iNode->getAttributeByToken(node, OgnBuildStringAttributes::outputs::value.m_token);
// in and out needs to be the same
std::array<AttributeObj, 2> io{ inputVal, outputVal };
node.iNode->resolveCoupledAttributes(node, io.data(), io.size());
//retrieve all other input attributes
auto totalCount = node.iNode->getAttributeCount(node);
std::vector<AttributeObj> attrs(totalCount);
node.iNode->getAttributes(node, attrs.data(), totalCount);
size_t idx = 0;
size_t count = totalCount;
while (idx != count)
{
if (attrs[idx].iAttribute->getPortType(attrs[idx]) != AttributePortType::kAttributePortType_Input ||
attrs[idx].attributeHandle == inputVal.attributeHandle)
{
count--;
std::swap(attrs[idx], attrs[count]);
}
else
{
idx++;
}
}
auto type = inputVal.iAttribute->getResolvedType(inputVal);
// if input is an array of token, suffixes are allowed to be either a simple or an array of token(s)
if (type.baseType == BaseDataType::eToken && type.arrayDepth != 0)
{
for (auto const& attr : attrs)
{
auto suffixType = attr.iAttribute->getResolvedType(attr);
if (suffixType.baseType == BaseDataType::eUChar) // string not compatible with tokens
attr.iAttribute->setResolvedType(attr, type);
}
}
else if (type.baseType != BaseDataType::eUnknown)
{
// else, they all needs to have the same type
for (auto const& attr : attrs)
attr.iAttribute->setResolvedType(attr, type);
}
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 8,071 | C++ | 36.544186 | 130 | 0.564118 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnToUint64.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnToUint64Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnToUint64Database& db)
{
auto functor = [](auto const& value, auto& converted) { converted = static_cast<uint64_t>(value); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, uint64_t>(db.inputs.value(), db.outputs.converted(), functor);
}
} // namespace
class OgnToUint64
{
public:
// Node to convert numeric inputs to floats
static bool compute(OgnToUint64Database& db)
{
auto& valueType = db.inputs.value().type();
switch (valueType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<uint8_t>(db);
case BaseDataType::eInt:
return tryComputeAssumingType<int32_t>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eHalf:
return tryComputeAssumingType<pxr::GfHalf>(db);
case BaseDataType::eFloat:
return tryComputeAssumingType<float>(db);
case BaseDataType::eDouble:
return tryComputeAssumingType<double>(db);
default:
db.logError("Failed to resolve input types");
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto valueAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.token());
auto outAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::converted.token());
auto valueType = valueAttr.iAttribute->getResolvedType(valueAttr);
// The output shape must match the input shape and visa-versa, however we can't say anything
// about the input base type until it's connected
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eUInt64, 1, valueType.arrayDepth);
outAttr.iAttribute->setResolvedType(outAttr, resultType);
}
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 2,870 | C++ | 33.178571 | 122 | 0.666899 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnStartsWith.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnStartsWithDatabase.h>
#include <algorithm>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnStartsWith
{
public:
static bool compute(OgnStartsWithDatabase& db)
{
auto const& prefix = db.inputs.prefix();
auto const& value = db.inputs.value();
auto iters = std::mismatch(prefix.begin(), prefix.end(), value.begin(), value.end());
db.outputs.isPrefix() = (iters.first == prefix.end());
return true;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 972 | C++ | 24.605263 | 93 | 0.704733 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnSetGatheredAttribute.cpp | // Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnSetGatheredAttributeDatabase.h>
#include <omni/graph/core/IGatherPrototype.h>
#include <carb/flatcache/FlatCache.h>
using namespace carb::flatcache;
namespace omni
{
namespace graph
{
namespace core
{
// WARNING!
// The following code uses low-level ABI functionality and should not be copied for other purposes when such
// low level access is not required. Please use the OGN-generated API whenever possible.
#define RETURN_TRUE_EXEC \
{\
db.outputs.execOut() = kExecutionAttributeStateEnabled;\
return true;\
}
class OgnSetGatheredAttribute
{
public:
static bool compute(OgnSetGatheredAttributeDatabase& db)
{
auto& nodeObj = db.abi_node();
const INode& iNode = *nodeObj.iNode;
const IGraphContext& iContext = *db.abi_context().iContext;
const omni::graph::core::IGatherPrototype* iGatherPrototype =
carb::getCachedInterface<omni::graph::core::IGatherPrototype>();
const auto& value = db.inputs.value();
const auto& mask = db.inputs.mask();
NameToken attributeName = db.inputs.name();
const char* attributeNameStr = db.tokenToString(attributeName);
if (!attributeNameStr || strlen(attributeNameStr) == 0)
RETURN_TRUE_EXEC
GatherId gatherId = static_cast<GatherId>(db.inputs.gatherId());
if (gatherId == kInvalidGatherId)
RETURN_TRUE_EXEC
if (!mask.empty() && value.size() > 1 && mask.size() != value.size())
{
db.logError("The length of the write mask (%zd) does not match the length of the value (%zd)",
mask.size(), value.size());
return false;
}
BucketId const* buckets{ nullptr };
size_t numBuckets{ 0 };
if (!iGatherPrototype->getGatheredBuckets(db.abi_context(), gatherId, buckets, numBuckets))
{
db.logError("Could not get gathered bucket list for Gather %zd", gatherId);
return false;
}
if (numBuckets == 0)
{
db.logError("Gathered bucket list is empty for Gather %zd", gatherId);
return false;
}
Type elementType;
size_t elementSize{ 0 };
if (!iGatherPrototype->getGatheredType(db.abi_context(), gatherId, attributeName, elementType, elementSize))
{
db.logError("Could not determine gathered type");
return false;
}
if (elementType.arrayDepth > 0)
{
db.logError("Gathering Array Type %s is not yet supported", elementType.getOgnTypeName().c_str());
return false;
}
if (elementSize == 0)
{
db.logError("The element type %s has zero size", elementType.getOgnTypeName().c_str());
return false;
}
Type srcDataType = db.inputs.value().type();
bool srcIsScaler = srcDataType.arrayDepth == 0;
if (!srcIsScaler)
{
// A scaler value will be broadcast
--srcDataType.arrayDepth;
}
if (!srcDataType.compatibleRawData(elementType))
{
db.logWarning("Attribute %s is not compatible with type '%s'", elementType.getTypeName().c_str(),
srcDataType.getTypeName().c_str());
RETURN_TRUE_EXEC
}
// determine the length of the content
size_t totalPrimCount{ 0 };
size_t inputArraySize = value.size();
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount = 0;
(void)db.abi_context().iContext->getBucketArray(db.abi_context(), bucketId, attributeName, primCount);
totalPrimCount += primCount;
}
PathBucketIndex const* repeatedPaths{ nullptr };
size_t numRepeatedPaths{ 0 };
if (!iGatherPrototype->getGatheredRepeatedPaths(db.abi_context(), gatherId, repeatedPaths, numRepeatedPaths))
{
db.logError("Could not get repeated paths list for Gather %zd", gatherId);
return false;
}
if (inputArraySize > 1 && totalPrimCount + numRepeatedPaths != inputArraySize)
{
db.logError(
"Given value of length %zd is not equal to the number of gathered attributes (%zd)", inputArraySize, totalPrimCount + numRepeatedPaths);
return false;
}
//printf("Setting %zd prims worth (%zd bytes) to %s\n", totalPrimCount, totalPrimCount * elementSize,
// attributeNameStr);
// Finally, we copy the data from the attribute to the buckets
const IAttributeData& iAttributeData = *db.abi_context().iAttributeData;
AttributeObj inputAttr =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnSetGatheredAttributeAttributes::inputs::value.m_token);
ConstAttributeDataHandle inputHandle = inputAttr.iAttribute->getConstAttributeDataHandle(inputAttr);
ConstRawPtr srcPtr{ nullptr };
{
const void** out = nullptr;
void** outPtr = reinterpret_cast<void**>(&out);
iAttributeData.getDataR((const void**)outPtr, db.abi_context(), &inputHandle, 1);
if (srcIsScaler)
srcPtr = reinterpret_cast<ConstRawPtr>(out);
else
srcPtr = reinterpret_cast<ConstRawPtr>(*out);
}
if (!srcPtr)
{
// No data to read
RETURN_TRUE_EXEC
}
size_t maskIndex = 0;
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount{ 0 };
uint8_t* destPtr = (uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !destPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
continue;
}
if (mask.empty())
{
size_t totalBytes = elementSize * primCount;
memcpy(destPtr, srcPtr, totalBytes);
if (!srcIsScaler)
srcPtr += totalBytes;
}
else
{
for (size_t j = 0; j < primCount; ++j)
{
if (mask[maskIndex++])
memcpy(destPtr, srcPtr, elementSize);
destPtr += elementSize;
if (!srcIsScaler)
srcPtr += elementSize;
}
}
}
// Set attribute for repeated paths
if (numRepeatedPaths > 0)
{
// If there are repeated paths, the set behaviour might be unexpected. Warn the user.
db.logWarning("Trying to set attribute when there are repeated prims in the gather. The first %zd values might be overwritten", totalPrimCount);
}
for (size_t i = 0; i < numRepeatedPaths; ++i)
{
PathBucketIndex pathBucketIndex = repeatedPaths[i];
BucketId bucketId = std::get<1>(pathBucketIndex);
ArrayIndex index = std::get<2>(pathBucketIndex);
size_t primCount{ 0 };
uint8_t* destPtr = (uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !destPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
continue;
}
if (index >= primCount)
{
db.logWarning("Bucket %zd has less entries than required", bucketId);
return false;
}
if (mask.empty() || mask[maskIndex++])
{
size_t byteCount = elementSize * index;
memcpy(destPtr + byteCount, srcPtr, elementSize);
if (!srcIsScaler)
srcPtr += elementSize;
}
}
RETURN_TRUE_EXEC
}
};
REGISTER_OGN_NODE()
}
}
}
| 8,672 | C++ | 32.616279 | 156 | 0.577721 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayFindValue.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnArrayFindValueDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayFindValueDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
size_t const inputArraySize = db.inputs.array().size();
auto const value = db.inputs.value().template get<BaseType>();
if (!value || !inputArray)
return false;
for (size_t i = 0; i < inputArraySize; ++i)
{
if (memcmp(&((*inputArray)[i]), &*value, sizeof(BaseType)) == 0)
{
db.outputs.index() = int(i);
return true;
}
}
db.outputs.index() = -1;
return true;
}
} // namespace
class OgnArrayFindValue
{
public:
static bool compute(OgnArrayFindValueDatabase& db)
{
auto& inputType = db.inputs.value().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const inputArray = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const inputValue = node.iNode->getAttributeByToken(node, inputs::value.token());
auto const inputArrayType = inputArray.iAttribute->getResolvedType(inputArray);
if (inputArrayType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { inputArray, inputValue };
// all should have the same tuple count
std::array<uint8_t, 2> tupleCounts {
inputArrayType.componentCount,
inputArrayType.componentCount
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 2> arrayDepths {
1,
0,
};
std::array<AttributeRole, 2> rolesBuf {
inputArrayType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni | 5,811 | C++ | 37.490066 | 107 | 0.576149 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBundleInspector.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnBundleInspectorDatabase.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
template <typename CppType>
std::string valueToString(const CppType& value)
{
return std::to_string(value);
}
template <>
std::string valueToString(const pxr::GfHalf& value)
{
return std::to_string((float) value);
}
template <>
std::string valueToString(const bool& value)
{
return value ? "True" : "False";
}
// TODO: This string conversion code is better suited to the BundledAttribute where it is accessible to all
// Since there are only three matrix dimensions a lookup is faster than a sqrt() call.
const int matrixDimensionMap[17]{ 1, 1, 1, 1, 2, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 4 };
// Helper template to output a convertible simple value as a string. Used when std::to_string works on the type.
template <typename CppType>
bool simpleValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto value = runtimeInput.get<CppType>() )
{
valueToSet = valueToString(*value);
return true;
}
return false;
}
// Helper template to output a convertible simple tuple value as a string.
// The output format is parenthesized "(X, Y, Z)"
template <typename CppType>
bool tupleValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto value = runtimeInput.get<CppType>() )
{
auto inputType = runtimeInput.type();
valueToSet = "(";
if (inputType.isMatrixType())
{
uint8_t dimension = inputType.dimension();
uint8_t index{ 0 };
for (uint8_t row=0; row<dimension; ++row)
{
if (row > 0)
{
valueToSet += ", ";
}
valueToSet += "(";
for (int col=0; col<dimension; ++col)
{
if (col > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[index++]);
}
valueToSet += ")";
}
}
else
{
for (uint8_t tupleIndex=0; tupleIndex<value.tupleSize(); ++tupleIndex )
{
if (tupleIndex > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[tupleIndex]);
}
}
valueToSet += ")";
return true;
}
return false;
}
// Helper template to output a convertible simple array value as a string.
// The output format has square brackets "[X, Y, Z]"
template <typename CppType>
bool arrayValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto arrayValue = runtimeInput.get<CppType>() )
{
auto role = runtimeInput.type().role;
auto baseType = runtimeInput.type().baseType;
const bool isString = (baseType == BaseDataType::eUChar) && ((role == AttributeRole::eText) || (role == AttributeRole::ePath));
if (isString)
{
std::string rawString(reinterpret_cast<const char*>(arrayValue->data()), arrayValue->size());
valueToSet = "'";
valueToSet += rawString;
valueToSet += "'";
}
else
{
valueToSet = "[";
size_t index{ 0 };
for (const auto& value : *arrayValue)
{
if (index++ > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value);
}
valueToSet += "]";
}
return true;
}
return false;
}
// Helper template to output a convertible tuple array value as a string.
// The output format has square brackets "[(X1, Y1), (X2, Y2), (X3, Y3))]"
template <typename CppType>
bool tupleArrayValueToString(const ogn::RuntimeAttribute<core::ogn::kOgnInput, core::ogn::kCpu>& runtimeInput, std::string& valueToSet)
{
if (const auto tupleArrayValue = runtimeInput.get<CppType>() )
{
auto inputType = runtimeInput.type();
const bool isMatrix = inputType.isMatrixType();
auto tupleSize = inputType.dimension();
valueToSet = "[";
size_t index{ 0 };
for (const auto& value : *tupleArrayValue)
{
if (index++ > 0)
{
valueToSet += ", ";
}
valueToSet += "(";
if (isMatrix)
{
int tupleIndex{ 0 };
for (int row=0; row<tupleSize; ++row)
{
if (row > 0)
{
valueToSet += ", ";
}
valueToSet += "(";
for (int col=0; col<tupleSize; ++col)
{
if (col > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[tupleIndex++]);
}
valueToSet += ")";
}
}
else
{
for (int tupleIndex=0; tupleIndex<tupleSize; ++tupleIndex )
{
if (tupleIndex > 0)
{
valueToSet += ", ";
}
valueToSet += valueToString(value[tupleIndex]);
}
}
valueToSet += ")";
}
valueToSet += "]";
return true;
}
return false;
}
// Node whose responsibility is to analyze the contents of an input bundle attribute
// and create outputs describing them.
class OgnBundleInspector
{
private:
static void inspectRecursive
(
const int currentDepth,
const int inspectDepth,
const bool printContents,
OgnBundleInspectorDatabase& db,
const ogn::BundleContents<ogn::kOgnInput, ogn::kCpu> &inputBundle,
std::ostream &output,
ogn::array<NameToken> &names,
ogn::array<NameToken> &types,
ogn::array<NameToken> &roles,
ogn::array<int> &arrayDepths,
ogn::array<int> &tupleCounts,
ogn::array<NameToken> &values
)
{
IToken const* iToken = carb::getCachedInterface<omni::fabric::IToken>();
auto bundleName = inputBundle.abi_bundleInterface()->getName();
std::string indent{" "};
auto attributeCount = inputBundle.attributeCount();
auto childCount = inputBundle.childCount();
output << "Bundle '" << iToken->getText(bundleName) << "' from " << db.abi_node().iNode->getPrimPath(db.abi_node())
<< " (attributes = " << attributeCount << " children = " << childCount << ")" << std::endl;
// Walk the contents of the input bundle, extracting the attribute information along the way
size_t index = 0;
for (const auto& bundledAttribute : inputBundle)
{
if (bundledAttribute.isValid())
{
// The attribute names and etc apply only to top level bundle passed to the BundleInspector
if (currentDepth == 0) names[index] = bundledAttribute.name();
for (int numIndent = 0; numIndent < currentDepth; numIndent++) output << indent;
output << indent << "[" << index << "] " << db.tokenToString(bundledAttribute.name());
const Type& attributeType = bundledAttribute.type();
output << "(" << attributeType << ")";
if (currentDepth == 0)
{
{
std::ostringstream nameStream;
nameStream << attributeType.baseType;
types[index] = db.stringToToken(nameStream.str().c_str());
}
{
std::ostringstream nameStream;
nameStream << getOgnRoleName(attributeType.role);
roles[index] = db.stringToToken(nameStream.str().c_str());
}
arrayDepths[index] = attributeType.arrayDepth;
tupleCounts[index] = attributeType.componentCount;
}
// Convert the value into a string, using an empty string for unknown types
std::string valueAsString{"__unsupported__"};
bool noOutput = !simpleValueToString<bool>(bundledAttribute, valueAsString)
&& !arrayValueToString<bool[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<int64_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<int64_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<uint8_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<uint8_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<uint32_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<uint32_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<uint64_t>(bundledAttribute, valueAsString)
&& !arrayValueToString<uint64_t[]>(bundledAttribute, valueAsString)
&& !simpleValueToString<double>(bundledAttribute, valueAsString)
&& !arrayValueToString<double[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][4]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[9]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][9]>(bundledAttribute, valueAsString)
&& !tupleValueToString<double[16]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<double[][16]>(bundledAttribute, valueAsString)
&& !simpleValueToString<float>(bundledAttribute, valueAsString)
&& !arrayValueToString<float[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<float[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<float[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<float[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<float[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<float[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<float[][4]>(bundledAttribute, valueAsString)
&& !simpleValueToString<int>(bundledAttribute, valueAsString)
&& !arrayValueToString<int[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<int[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<int[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<int[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<int[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<int[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<int[][4]>(bundledAttribute, valueAsString)
&& !simpleValueToString<pxr::GfHalf>(bundledAttribute, valueAsString)
&& !arrayValueToString<pxr::GfHalf[]>(bundledAttribute, valueAsString)
&& !tupleValueToString<pxr::GfHalf[2]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<pxr::GfHalf[][2]>(bundledAttribute, valueAsString)
&& !tupleValueToString<pxr::GfHalf[3]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<pxr::GfHalf[][3]>(bundledAttribute, valueAsString)
&& !tupleValueToString<pxr::GfHalf[4]>(bundledAttribute, valueAsString)
&& !tupleArrayValueToString<pxr::GfHalf[][4]>(bundledAttribute, valueAsString)
;
if (noOutput)
{
if (const auto tokenValue = bundledAttribute.get<OgnToken>() )
{
std::ostringstream tokenValueStream;
tokenValueStream << std::quoted(db.tokenToString(*tokenValue));
valueAsString = tokenValueStream.str();
noOutput = false;
}
}
if (noOutput)
{
if (const auto tokenArrayValue = bundledAttribute.get<OgnToken[]>() )
{
std::ostringstream tokenArrayValueStream;
tokenArrayValueStream << "[";
size_t index{ 0 };
for (const auto& value : *tokenArrayValue)
{
if (index++ > 0)
{
tokenArrayValueStream << ", ";
}
tokenArrayValueStream << std::quoted(db.tokenToString(value));
}
tokenArrayValueStream << "]";
valueAsString = tokenArrayValueStream.str();
noOutput = false;
}
}
output << " = " << valueAsString << std::endl;
if (currentDepth == 0) values[index] = db.stringToToken(valueAsString.c_str());
if (noOutput)
{
std::ostringstream nameStream;
nameStream << attributeType;
db.logWarning("No value output known for attribute %zu (%s), defaulting to '__unsupported__'", index, nameStream.str().c_str());
}
index++;
}
else
{
output << indent << "Bundle is invalid" << std::endl;
db.logWarning("Ignoring invalid bundle member '%s'", db.tokenToString(bundledAttribute.name()));
}
}
// Walk through its children, if any
if (printContents && childCount && ((currentDepth < inspectDepth) || (inspectDepth <= -1)))
{
IConstBundle2* inputBundleIFace = inputBundle.abi_bundleInterface();
// context is for building the child BundleContents
const auto context = inputBundleIFace->getContext();
std::vector<ConstBundleHandle> childBundleHandles(childCount);
inputBundleIFace->getConstChildBundles(childBundleHandles.data(), childCount);
for (const auto& childHandle : childBundleHandles)
{
if (childHandle.isValid())
{
ogn::BundleContents<ogn::kOgnInput, ogn::kCpu> childBundle(context, childHandle);
for (int numIndent = 0; numIndent < currentDepth + 1; numIndent++) output << indent;
output << "Has Child "; // No std::endl -> "Has Child Bundle from ..."
inspectRecursive(currentDepth+1, inspectDepth, printContents, db, childBundle, output, names, types, roles, arrayDepths, tupleCounts, values);
}
else
{
for (int numIndent = 0; numIndent < currentDepth; numIndent++) output << indent;
output << "One child is invalid." << std::endl;
}
}
}
}
public:
static bool compute(OgnBundleInspectorDatabase& db)
{
const auto& inputBundle = db.inputs.bundle();
auto attributeCount = inputBundle.attributeCount();
auto childCount = inputBundle.childCount();
db.outputs.bundle() = inputBundle;
const auto& printContents = db.inputs.print();
const auto& inspectDepth = db.inputs.inspectDepth();
// Rather than pollute the file with a bunch of "if (printContents)" setting up a file stream with a
// bad bit causes the output to be thrown away without parsing.
std::ofstream ofs;
ofs.setstate(std::ios_base::badbit);
auto& output = printContents ? std::cout : ofs;
db.outputs.count() = attributeCount;
db.outputs.attributeCount() = attributeCount;
db.outputs.childCount() = childCount;
// Extract the output interfaces to nicer names
auto& names = db.outputs.names();
auto& types = db.outputs.types();
auto& roles = db.outputs.roles();
auto& arrayDepths = db.outputs.arrayDepths();
auto& tupleCounts = db.outputs.tupleCounts();
auto& values = db.outputs.values();
// All outputs except the count are arrays of that size - preallocate them here
names.resize(attributeCount);
types.resize(attributeCount);
roles.resize(attributeCount);
arrayDepths.resize(attributeCount);
tupleCounts.resize(attributeCount);
values.resize(attributeCount);
inspectRecursive(0, inspectDepth, printContents, db, inputBundle, output, names, types, roles, arrayDepths, tupleCounts, values);
return true;
}
};
REGISTER_OGN_NODE();
}
}
}
| 18,952 | C++ | 42.872685 | 162 | 0.538518 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnArrayIndex.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnArrayIndexDatabase.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni {
namespace graph {
namespace nodes {
using core::ogn::array;
// unnamed namespace to avoid multiple declaration when linking
namespace {
// helper to wrap a given index from legal range [-arrayLength, arrayLength) to [0:arrayLength).
// values outside of the legal range with throw
size_t tryWrapIndex(int index, size_t arraySize)
{
int wrappedIndex = index;
if (index < 0)
wrappedIndex = (int)arraySize + index;
if ((wrappedIndex >= (int)arraySize) or (wrappedIndex < 0))
throw ogn::compute::InputError(formatString("inputs:index %d is out of range for inputs:array of size %zu", wrappedIndex, arraySize));
return size_t(wrappedIndex);
}
template<typename BaseType>
bool tryComputeAssumingType(OgnArrayIndexDatabase& db)
{
auto const inputArray = db.inputs.array().template get<BaseType[]>();
size_t const index = tryWrapIndex(db.inputs.index(), db.inputs.array().size());
auto outputValue = db.outputs.value().template get<BaseType>();
if (!outputValue || !inputArray)
return false;
memcpy(&*outputValue, &((*inputArray)[index]), sizeof(BaseType));
return true;
}
} // namespace
class OgnArrayIndex
{
public:
static bool compute(OgnArrayIndexDatabase& db)
{
auto& inputType = db.inputs.array().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eBool:
return tryComputeAssumingType<bool>(db);
case BaseDataType::eToken:
return tryComputeAssumingType<ogn::Token>(db);
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double[2]>(db);
case 3: return tryComputeAssumingType<double[3]>(db);
case 4: return tryComputeAssumingType<double[4]>(db);
case 9: return tryComputeAssumingType<double[9]>(db);
case 16: return tryComputeAssumingType<double[16]>(db);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float[2]>(db);
case 3: return tryComputeAssumingType<float[3]>(db);
case 4: return tryComputeAssumingType<float[4]>(db);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf[2]>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf[3]>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf[4]>(db);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t[2]>(db);
case 3: return tryComputeAssumingType<int32_t[3]>(db);
case 4: return tryComputeAssumingType<int32_t[4]>(db);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError const &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto const array = node.iNode->getAttributeByToken(node, inputs::array.token());
auto const value = node.iNode->getAttributeByToken(node, outputs::value.token());
auto const arrayType = array.iAttribute->getResolvedType(array);
auto const valueType = value.iAttribute->getResolvedType(value);
if ((arrayType.baseType == BaseDataType::eUnknown) != (valueType.baseType == BaseDataType::eUnknown))
{
std::array<AttributeObj, 2> attrs { array, value };
// array and value should have the same tuple count
std::array<uint8_t, 2> tupleCounts {
std::max(arrayType.componentCount, valueType.componentCount),
std::max(arrayType.componentCount, valueType.componentCount)
};
// value type can not be an array because we don't support arrays-of-arrays
std::array<uint8_t, 2> arrayDepths {
1,
0
};
std::array<AttributeRole, 2> rolesBuf {
arrayType.role,
// Copy the attribute role from the array type to the value type
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 6,415 | C++ | 39.352201 | 142 | 0.595168 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimPath.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnGetPrimPathDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimPath
{
public:
static size_t computeVectorized(OgnGetPrimPathDatabase& db, size_t count)
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!pathInterface || !tokenInterface)
{
CARB_LOG_ERROR("Failed to initialize path or token interface");
return 0;
}
auto primPaths = db.outputs.primPath.vectorized(count);
for (size_t i = 0; i < count; i++)
{
const auto& prims = db.inputs.prim(i);
if (prims.size() > 0)
{
auto text = pathInterface->getText(prims[0]);
db.outputs.path(i) = text;
primPaths[i] = tokenInterface->getHandle(text);
}
else
{
db.outputs.path(i) = "";
primPaths[i] = Token();
}
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 1,592 | C++ | 26.947368 | 79 | 0.607412 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetRelativePath.cpp | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnGetRelativePathDatabase.h>
#include <omni/fabric/FabricUSD.h>
using omni::fabric::asInt;
using omni::fabric::toTfToken;
static NameToken const& getRelativePath(const NameToken& pathAsToken, const pxr::SdfPath& anchor)
{
auto pathToken = toTfToken(pathAsToken);
if (pathAsToken != omni::fabric::kUninitializedToken && pxr::SdfPath::IsValidPathString(pathToken))
{
auto relPath = pxr::SdfPath(pathToken).MakeRelativePath(anchor);
return *asInt(&relPath.GetToken());
}
return pathAsToken;
}
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetRelativePath
{
public:
static size_t computeVectorized(OgnGetRelativePathDatabase& db, size_t count)
{
auto anchor = db.inputs.anchor.vectorized(count);
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
if (anchor[idx] == omni::fabric::kUninitializedToken)
{
db.outputs.relativePath(idx).copyData(db.inputs.path(idx));
}
else
{
const auto anchorPath = pxr::SdfPath(toTfToken(anchor[idx]));
const auto inputPathArray = *db.inputs.path(idx).get<OgnToken[]>();
auto outputPathArray = *db.outputs.relativePath(idx).get<OgnToken[]>();
outputPathArray.resize(inputPathArray.size());
std::transform(inputPathArray.begin(), inputPathArray.end(), outputPathArray.begin(),
[&](const auto& p) { return getRelativePath(p, anchorPath); });
}
}
}
else
{
auto ipt = db.inputs.path().get<OgnToken>();
auto inputPath = ipt.vectorized(count);
auto oldInputs = db.state.path.vectorized(count);
auto oldAnchor = db.state.anchor.vectorized(count);
auto op = db.outputs.relativePath().get<OgnToken>();
auto outputs = op.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (oldAnchor[idx] != anchor[idx] || oldInputs[idx] != inputPath[idx])
{
if (anchor[idx] == omni::fabric::kUninitializedToken)
{
outputs[idx] = inputPath[idx];
}
else
{
const auto anchorPath = pxr::SdfPath(toTfToken(anchor[idx]));
outputs[idx] = getRelativePath(inputPath[idx], anchorPath);
}
oldAnchor[idx] = anchor[idx];
oldInputs[idx] = inputPath[idx];
}
}
}
return count;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs{ node.iNode->getAttribute(node, OgnGetRelativePathAttributes::inputs::path.m_name),
node.iNode->getAttribute(node, OgnGetRelativePathAttributes::outputs::relativePath.m_name) };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 3,813 | C++ | 35.323809 | 136 | 0.577236 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnAppendPath.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/sdf/valueTypeName.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/fabric/FabricUSD.h>
#include <OgnAppendPathDatabase.h>
using omni::fabric::asInt;
using omni::fabric::toTfToken;
static NameToken const& appendPath(const NameToken& pathAsToken, const pxr::SdfPath& suffix)
{
auto pathToken = toTfToken(pathAsToken);
if (pathAsToken != omni::fabric::kUninitializedToken && pxr::SdfPath::IsValidPathString(pathToken))
{
auto newPath = pxr::SdfPath(pathToken).AppendPath(suffix);
return *asInt(&newPath.GetToken());
}
return pathAsToken;
}
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnAppendPath
{
public:
static size_t computeVectorized(OgnAppendPathDatabase& db, size_t count)
{
auto suffix = db.inputs.suffix.vectorized(count);
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
if (suffix[idx] == omni::fabric::kUninitializedToken)
{
db.outputs.path(idx).copyData(db.inputs.path(idx));
}
else
{
const auto suffixPath = pxr::SdfPath(toTfToken(suffix[idx]));
const auto inputPathArray = *db.inputs.path(idx).get<OgnToken[]>();
auto outputPathArray = *db.outputs.path(idx).get<OgnToken[]>();
outputPathArray.resize(inputPathArray.size());
std::transform(inputPathArray.begin(), inputPathArray.end(), outputPathArray.begin(),
[&](const auto& p) { return appendPath(p, suffixPath); });
}
}
}
else
{
auto ipt = db.inputs.path().get<OgnToken>();
auto inputPath = ipt.vectorized(count);
auto oldInputs = db.state.path.vectorized(count);
auto oldSuffix = db.state.suffix.vectorized(count);
auto op = db.outputs.path().get<OgnToken>();
auto outputs = op.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (oldSuffix[idx] != suffix[idx] || oldInputs[idx] != inputPath[idx])
{
if (suffix[idx] == omni::fabric::kUninitializedToken)
{
outputs[idx] = inputPath[idx];
}
else
{
const auto suffixPath = pxr::SdfPath(toTfToken(suffix[idx]));
outputs[idx] = appendPath(inputPath[idx], suffixPath);
}
oldSuffix[idx] = suffix[idx];
oldInputs[idx] = inputPath[idx];
}
}
}
return count;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs{ node.iNode->getAttribute(node, OgnAppendPathAttributes::inputs::path.m_name),
node.iNode->getAttribute(node, OgnAppendPathAttributes::outputs::path.m_name) };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 3,897 | C++ | 33.495575 | 123 | 0.576084 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnFindPrims.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnFindPrimsDatabase.h>
#include <omni/fabric/FabricUSD.h>
#include "ReadPrimCommon.h"
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnFindPrims
{
struct Listener
{
UsdStageChangeListenerRefPtr changeListener; // Lets us know when the USD stage changes
};
public:
// ----------------------------------------------------------------------------
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
auto& ls = OgnFindPrimsDatabase::sSharedState<Listener>(nodeObj);
ls.changeListener = UsdStageChangeListener::New(context, UsdStageChangeListener::ListenMode::eResync);
}
// ----------------------------------------------------------------------------
static void release(const NodeObj& nodeObj)
{
auto& ls = OgnFindPrimsDatabase::sSharedState<Listener>(nodeObj);
ls.changeListener.Reset();
}
// ----------------------------------------------------------------------------
static bool compute(OgnFindPrimsDatabase& db)
{
auto& ls = db.sharedState<Listener>();
auto inputType = db.inputs.type();
auto rootPrimPath = db.inputs.rootPrimPath();
auto rootPrim = db.inputs.rootPrim();
auto recursive = db.inputs.recursive();
auto namePrefix = db.inputs.namePrefix();
auto requiredAttributesStr = db.inputs.requiredAttributes();
auto requiredRelationship = db.inputs.requiredRelationship();
auto requiredRelationshipTargetStr = db.inputs.requiredRelationshipTarget();
auto requiredTarget = db.inputs.requiredTarget();
auto pathPattern = db.inputs.pathPattern();
auto ignoreSystemPrims = db.inputs.ignoreSystemPrims();
// We can skip compute if our state isn't dirty, and our inputs haven't changed
if (not ls.changeListener->checkDirty())
{
if (db.state.inputType() == inputType &&
db.state.rootPrim().size() == rootPrim.size() &&
(db.state.rootPrim().size() == 0 ? db.state.rootPrimPath() == rootPrimPath
: db.state.rootPrim()[0] == rootPrim[0]) &&
db.state.recursive() == recursive &&
db.state.namePrefix() == namePrefix &&
requiredAttributesStr == db.state.requiredAttributes() &&
db.state.requiredRelationship() == requiredRelationship &&
(db.state.requiredTarget.size() == 0 ? requiredRelationshipTargetStr == db.state.requiredRelationshipTarget()
: db.state.requiredTarget()[0] == requiredTarget[0]) &&
pathPattern == db.state.pathPattern() &&
ignoreSystemPrims == db.state.ignoreSystemPrims())
{
// Not dirty and inputs didn't change
return true;
}
}
db.state.inputType() = inputType;
db.state.rootPrimPath() = rootPrimPath;
db.state.rootPrim() = rootPrim;
db.state.recursive() = recursive;
db.state.namePrefix() = namePrefix;
db.state.requiredAttributes() = requiredAttributesStr;
db.state.requiredRelationship() = requiredRelationship;
db.state.requiredRelationshipTarget() = requiredRelationshipTargetStr;
db.state.requiredTarget() = requiredTarget;
db.state.pathPattern() = pathPattern;
db.state.ignoreSystemPrims() = ignoreSystemPrims;
long stageId = db.abi_context().iContext->getStageId(db.abi_context());
auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
if (!stage)
{
db.logError("Could not find USD stage %ld", stageId);
return false;
}
pxr::UsdPrim startPrim;
if(rootPrim.size() == 0)
{
if (rootPrimPath == omni::fabric::kUninitializedToken)
startPrim = stage->GetPseudoRoot();
else
{
if (const char* primPathStr = db.tokenToString(rootPrimPath))
{
startPrim = stage->GetPrimAtPath(pxr::SdfPath(primPathStr));
if (!startPrim)
{
db.logError("Could not find rootPrim \"%s\"", primPathStr);
return false;
}
}
}
}
else
{
if(rootPrim.size() > 1)
db.logWarning("Only one rootPrim target is supported, the rest will be ignored");
startPrim = stage->GetPrimAtPath(omni::fabric::toSdfPath(rootPrim[0]));
if (!startPrim)
{
db.logError("Could not find rootPrim \"%s\"", db.pathToString(rootPrim[0]));
return false;
}
}
// Figure out the required type if any
pxr::TfToken requiredTypeName;
if (inputType != omni::fabric::kUninitializedToken)
{
if (char const* typeStr = db.tokenToString(inputType))
requiredTypeName = pxr::TfToken(typeStr);
}
char const* requiredNamePrefix{ db.tokenToString(namePrefix) };
// Figure out require relationship target if any
pxr::SdfPath requiredRelationshipTarget;
pxr::TfToken requiredRelName;
if (requiredRelationship != omni::fabric::kUninitializedToken)
{
requiredRelName = pxr::TfToken(db.tokenToString(requiredRelationship));
if (!requiredRelName.IsEmpty())
{
bool validTarget = (requiredTarget.size() == 0 && !requiredRelationshipTargetStr.empty());
if(requiredTarget.size() == 0)
{
if(!requiredRelationshipTargetStr.empty())
requiredRelationshipTarget = pxr::SdfPath{ requiredRelationshipTargetStr };
}
else
{
if(requiredTarget.size() > 1)
db.logWarning("Only one requiredTarget is supported, the rest will be ignored");
requiredRelationshipTarget = omni::fabric::toSdfPath(requiredTarget[0]);
}
if (validTarget && !requiredRelationshipTarget.IsPrimPath())
{
db.logError("Required relationship target \"%s\" is not valid", requiredRelationshipTarget.GetText());
}
}
}
// now find matching prims
pxr::TfToken requiredAttribs{ std::string{ requiredAttributesStr.data(), requiredAttributesStr.size() } };
PathVector matchedPaths;
findPrims_findMatching(matchedPaths, startPrim, recursive, requiredNamePrefix, requiredTypeName,
requiredAttribs, requiredRelName, requiredRelationshipTarget,
omni::fabric::intToToken(pathPattern), ignoreSystemPrims);
// output PathC
auto outputPrims = db.outputs.prims();
outputPrims.resize(matchedPaths.size());
std::transform(matchedPaths.begin(), matchedPaths.end(), outputPrims.begin(),
[&db](auto path) {return path;});
// convert PathC to TokenC
auto outputPaths = db.outputs.primPaths();
outputPaths.resize(matchedPaths.size());
std::transform(matchedPaths.begin(), matchedPaths.end(), outputPaths.begin(),
[&db](auto path)
{
const char* pathStr = omni::fabric::intToPath(path).GetText();
return db.stringToToken(pathStr);
});
return true;
}
static bool updateNodeVersion(GraphContextObj const& context, NodeObj const& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
if (oldVersion < 2)
{
// backward compatibility: `inputs:type`
// Prior to this version `inputs:type` attribute did not support wild cards.
// The meaning of an empty string was to include all types. With the introduction of the wild cards
// we need to convert an empty string to "*" in order to include all types.
static Token const value{ "*" };
if (nodeObj.iNode->getAttributeExists(nodeObj, OgnFindPrimsAttributes::inputs::type.m_name))
{
AttributeObj attr = nodeObj.iNode->getAttribute(nodeObj, OgnFindPrimsAttributes::inputs::type.m_name);
auto roHandle = attr.iAttribute->getAttributeDataHandle(attr, kAccordingToContextIndex);
Token const* roValue = getDataR<Token const>(context, roHandle);
if (roValue && roValue->getString().empty())
{
Token* rwValue = getDataW<Token>(
context, attr.iAttribute->getAttributeDataHandle(attr, kAccordingToContextIndex));
*rwValue = value;
}
}
else
{
nodeObj.iNode->createAttribute(nodeObj, OgnFindPrimsAttributes::inputs::type.m_name, Type(BaseDataType::eToken), &value, nullptr,
kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr);
}
return true;
}
}
return false;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 10,203 | C++ | 40.819672 | 149 | 0.565814 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetGatheredAttribute.cpp | // Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnGetGatheredAttributeDatabase.h>
#include <omni/graph/core/IGatherPrototype.h>
#include <carb/flatcache/FlatCache.h>
using namespace carb::flatcache;
namespace omni
{
namespace graph
{
namespace core
{
class OgnGetGatheredAttribute
{
public:
static bool compute(OgnGetGatheredAttributeDatabase& db)
{
auto& nodeObj = db.abi_node();
const INode& iNode = *nodeObj.iNode;
const IGraphContext& iContext = *db.abi_context().iContext;
const omni::graph::core::IGatherPrototype* iGatherPrototype =
carb::getCachedInterface<omni::graph::core::IGatherPrototype>();
NameToken attributeName = db.inputs.name();
const char* attributeNameStr = db.tokenToString(attributeName);
if (!attributeNameStr || strlen(attributeNameStr) == 0)
return true;
GatherId gatherId = static_cast<GatherId>(db.inputs.gatherId());
BucketId const* buckets{ nullptr };
size_t numBuckets{ 0 };
if (!iGatherPrototype->getGatheredBuckets(db.abi_context(), gatherId, buckets, numBuckets))
{
db.logError("Could not get gathered bucket list for Gather %zd", gatherId);
return false;
}
if (numBuckets == 0)
{
db.logError("Gathered bucket list is empty for Gather %zd", gatherId);
return false;
}
Type elementType;
size_t elementSize{ 0 };
if (!iGatherPrototype->getGatheredType(db.abi_context(), gatherId, attributeName, elementType, elementSize))
{
db.logError("Could not determine gathered type");
return false;
}
if (elementType.arrayDepth > 0)
{
db.logError("Gathering Array Type %s is not yet supported", elementType.getOgnTypeName().c_str());
return false;
}
Type outputType(elementType);
++outputType.arrayDepth;
// Determine if the output attribute has already been resolved to an incompatible type
if (db.outputs.value().resolved())
{
Type outType = db.outputs.value().type();
if (!outputType.compatibleRawData(outType))
{
db.logWarning("Resolved type %s of outputs:value is not compatible with type %s",
outType.getOgnTypeName().c_str(), db.outputs.value().type().getOgnTypeName().c_str());
return false;
}
}
// If it's resolved, we already know that it is compatible from the above check
if (!db.outputs.value().resolved())
{
// Not resolved, so we have to resolve it now. This node is strange in that the resolved output type
// depends on external state instead of other attributes.
AttributeObj out = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::value.m_token);
out.iAttribute->setResolvedType(out, outputType);
db.outputs.value().reset(db.abi_context(), out.iAttribute->getAttributeDataHandle(out), out);
}
AttributeObj outputAttr = nodeObj.iNode->getAttributeByToken(
nodeObj, OgnGetGatheredAttributeAttributes::outputs::value.m_token);
AttributeDataHandle outputHandle = outputAttr.iAttribute->getAttributeDataHandle(outputAttr);
// determine the length of the output
size_t totalPrimCount{ 0 };
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount = 0;
void* ptr = db.abi_context().iContext->getBucketArray(db.abi_context(), bucketId, attributeName, primCount);
if (!ptr)
{
CARB_LOG_WARN("Attribute %s not found in Gather %zd, bucket %zd", attributeNameStr, gatherId, size_t(bucketId));
return true;
}
totalPrimCount += primCount;
}
PathBucketIndex const* repeatedPaths{ nullptr };
size_t numRepeatedPaths{ 0 };
if (!iGatherPrototype->getGatheredRepeatedPaths(db.abi_context(), gatherId, repeatedPaths, numRepeatedPaths))
{
db.logError("Could not get repeated paths list for Gather %zd", gatherId);
return false;
}
//printf("Getting %zd prims worth of %s\n", totalPrimCount, attributeNameStr);
// Set the required length of output array
db.abi_context().iAttributeData->setElementCount(db.abi_context(), outputHandle, totalPrimCount + numRepeatedPaths);
// Get pointer to target data
uint8_t* destPtr = nullptr;
{
void** out = nullptr;
void** outPtr = reinterpret_cast<void**>(&out);
db.abi_context().iAttributeData->getDataW(outPtr, db.abi_context(), &outputHandle, 1);
destPtr = (uint8_t*)(*out);
}
CARB_ASSERT(destPtr);
// Finally, we copy the data into the output, bucket by bucket
for (size_t i = 0; i < numBuckets; ++i)
{
BucketId bucketId = buckets[i];
size_t primCount{ 0 };
const uint8_t* srcPtr = (const uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !srcPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
return false;
}
size_t byteCount = elementSize * primCount;
{
// Copy the data
memcpy(destPtr, srcPtr, byteCount);
// Move the write pointer
destPtr += byteCount;
}
}
// Copy the data for repeated paths
for (size_t i = 0; i < numRepeatedPaths; ++i)
{
BucketId bucketId = std::get<1>(repeatedPaths[i]);
size_t primCount{ 0 };
const uint8_t* srcPtr = (const uint8_t*)db.abi_context().iContext->getBucketArray(
db.abi_context(), bucketId, attributeName, primCount);
if (primCount == 0 || !srcPtr)
{
db.logWarning("Bucket %zd has no entries for the given attribute", bucketId);
return false;
}
ArrayIndex index = std::get<2>(repeatedPaths[i]);
if (index >= primCount)
{
db.logWarning("Bucket %zd has less entries than required", bucketId);
return false;
}
size_t byteCount = elementSize * index;
{
// Copy the data
memcpy(destPtr, srcPtr + byteCount, elementSize);
// Move the write pointer
destPtr += elementSize;
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 7,383 | C++ | 34.84466 | 128 | 0.592713 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeArray.py | """
This is the implementation of the OGN node defined in OgnMakeArrayDouble3.ogn
"""
import omni.graph.core as og
class OgnMakeArray:
"""
Makes an output array attribute from input values
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
if db.inputs.a.type.base_type == og.BaseDataType.UNKNOWN:
return False
array_size = db.inputs.arraySize
out_array = []
if array_size > 0:
out_array.append(db.inputs.a.value)
if array_size > 1:
out_array.append(db.inputs.b.value)
if array_size > 2:
out_array.append(db.inputs.c.value)
if array_size > 3:
out_array.append(db.inputs.d.value)
if array_size > 4:
out_array.append(db.inputs.e.value)
out_array.extend([db.inputs.e.value] * (array_size - 5))
db.outputs.array.value = out_array
return True
@staticmethod
def on_connection_type_resolve(node) -> None:
attribs = [(node.get_attribute("inputs:" + a), None, 0, None) for a in ("a", "b", "c", "d", "e")]
attribs.append((node.get_attribute("outputs:array"), None, 1, None))
og.resolve_base_coupled(attribs)
| 1,266 | Python | 29.902438 | 105 | 0.591627 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetParentPath.cpp | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnGetParentPathDatabase.h>
#include <omni/fabric/FabricUSD.h>
using omni::fabric::asInt;
using omni::fabric::toTfToken;
static NameToken const& getParentPath(const NameToken& pathAsToken)
{
auto pathToken = toTfToken(pathAsToken);
if (pathAsToken != omni::fabric::kUninitializedToken && pxr::SdfPath::IsValidPathString(pathToken))
{
auto parentPath = pxr::SdfPath(pathToken).GetParentPath();
return *asInt(&parentPath.GetToken());
}
return pathAsToken;
}
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetParentPath
{
public:
static bool computeVectorized(OgnGetParentPathDatabase& db, size_t count)
{
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
const auto inputPathArray = *db.inputs.path(idx).get<OgnToken[]>();
auto outputPathArray = *db.outputs.parentPath(idx).get<OgnToken[]>();
outputPathArray.resize(inputPathArray.size());
std::transform(inputPathArray.begin(), inputPathArray.end(), outputPathArray.begin(),
[&](const auto& p) { return getParentPath(p); });
}
}
else
{
auto ipt = db.inputs.path().get<OgnToken>();
auto inputPath = ipt.vectorized(count);
auto oldInputs = db.state.path.vectorized(count);
auto op = db.outputs.parentPath().get<OgnToken>();
auto outputs = op.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
if (oldInputs[idx] != inputPath[idx])
{
outputs[idx] = getParentPath(inputPath[idx]);
oldInputs[idx] = inputPath[idx];
}
}
}
return count;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs{ node.iNode->getAttribute(node, OgnGetParentPathAttributes::inputs::path.m_name),
node.iNode->getAttribute(node, OgnGetParentPathAttributes::outputs::parentPath.m_name) };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 2,841 | C++ | 32.046511 | 132 | 0.619852 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimRelationship.cpp | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "OgnGetPrimRelationshipDatabase.h"
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/relationship.h>
#include <pxr/usd/usdUtils/stageCache.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <algorithm>
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimRelationship
{
public:
// Queries relationship data on a prim
static bool compute(OgnGetPrimRelationshipDatabase& db)
{
auto& nodeObj = db.abi_node();
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
try {
auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::path.token(),
inputs::usePath.token(), db.getInstanceIndex());
const char* relName = db.tokenToString(db.inputs.name());
if (!relName)
return false;
long int stageId = iContext->getStageId(contextObj);
pxr::UsdStageRefPtr stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
pxr::UsdPrim prim = stage->GetPrimAtPath(primPath);
if (!prim)
return false;
pxr::UsdRelationship relationship = prim.GetRelationship(pxr::TfToken(relName));
pxr::SdfPathVector targets;
if (relationship.GetTargets(&targets))
{
auto& outputPaths = db.outputs.paths();
outputPaths.resize(targets.size());
std::transform(targets.begin(), targets.end(), outputPaths.begin(),
[&db](const pxr::SdfPath& path) { return db.stringToToken(path.GetText()); });
}
return true;
}
catch(const std::exception& e)
{
db.logError(e.what());
return false;
}
}
static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
if (oldVersion < 2)
{
// for older nodes, inputs:usePath must equal true so the prim path method is on by default
const bool val{ true };
nodeObj.iNode->createAttribute(nodeObj, "inputs:usePath", Type(BaseDataType::eBool), &val, nullptr,
kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr);
}
return true;
}
return false;
}
};
REGISTER_OGN_NODE()
}
}
}
| 3,133 | C++ | 31.309278 | 122 | 0.618896 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimsAtPath.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnGetPrimsAtPathDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimsAtPath
{
public:
static bool computeVectorized(OgnGetPrimsAtPathDatabase& db, size_t count)
{
if (db.inputs.path().type().arrayDepth > 0)
{
for (size_t idx = 0; idx < count; ++idx)
{
auto& outPrims = db.outputs.prims(idx);
const auto paths = *db.inputs.path(idx).template get<OgnToken[]>();
outPrims.resize(paths.size());
std::transform(paths.begin(), paths.end(), outPrims.begin(),
[&](const auto& p) {
return (p != omni::fabric::kUninitializedToken) ? db.tokenToPath(p) : omni::fabric::kUninitializedPath;
});
}
}
else
{
const auto pathPtr = db.inputs.path().template get<OgnToken>();
if (pathPtr)
{
auto path = pathPtr.vectorized(count);
auto oldPath = db.state.path.vectorized(count);
for (size_t idx = 0; idx < count; ++idx)
{
auto outPrims = db.outputs.prims(idx);
if (oldPath[idx] != path[idx])
{
if (path[idx] != omni::fabric::kUninitializedToken)
{
outPrims.resize(1);
outPrims[0] = db.tokenToPath(path[idx]);
}
else
{
outPrims.resize(0);
}
}
}
}
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 2,255 | C++ | 30.333333 | 127 | 0.504656 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeVector4.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnMakeVector4Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <fstream>
#include <iomanip>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename Type>
bool tryMakeVector(OgnMakeVector4Database& db)
{
const auto x = db.inputs.x().template get<Type>();
const auto y = db.inputs.y().template get<Type>();
const auto z = db.inputs.z().template get<Type>();
const auto w = db.inputs.w().template get<Type>();
auto vector = db.outputs.tuple().template get<Type[4]>();
if (vector && x && y && z && w)
{
(*vector)[0] = *x;
(*vector)[1] = *y;
(*vector)[2] = *z;
(*vector)[3] = *w;
return true;
}
const auto xArray = db.inputs.x().template get<Type[]>();
const auto yArray = db.inputs.y().template get<Type[]>();
const auto zArray = db.inputs.z().template get<Type[]>();
const auto wArray = db.inputs.w().template get<Type[]>();
auto vectorArray = db.outputs.tuple().template get<Type[][4]>();
if (!vectorArray || !xArray || !yArray || !zArray || !wArray)
{
return false;
}
if (xArray->size() != yArray->size() || xArray->size() != zArray->size() || xArray->size() != wArray->size())
{
throw ogn::compute::InputError("Input arrays of different lengths x:" +
std::to_string(xArray->size()) + ", y:" +
std::to_string(yArray->size()) + ", z:" +
std::to_string(zArray->size()) + ", w:" +
std::to_string(wArray->size()));
}
vectorArray->resize(xArray->size());
for (size_t i = 0; i < vectorArray->size(); i++)
{
(*vectorArray)[i][0] = (*xArray)[i];
(*vectorArray)[i][1] = (*yArray)[i];
(*vectorArray)[i][2] = (*zArray)[i];
(*vectorArray)[i][3] = (*wArray)[i];
}
return true;
}
} // namespace
// Node to merge 4 scalers together to make 4-vector
class OgnMakeVector4
{
public:
static bool compute(OgnMakeVector4Database& db)
{
// Compute the components, if the types are all resolved.
try
{
if (tryMakeVector<double>(db))
return true;
else if (tryMakeVector<float>(db))
return true;
else if (tryMakeVector<pxr::GfHalf>(db))
return true;
else if (tryMakeVector<int32_t>(db))
return true;
else
{
db.logError("Failed to resolve input types");
return false;
}
}
catch (const std::exception& e)
{
db.logError("Vector could not be made: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto x = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::x.token());
auto y = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::y.token());
auto z = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::z.token());
auto w = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::w.token());
auto vector = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::tuple.token());
auto xType = vector.iAttribute->getResolvedType(x);
auto yType = vector.iAttribute->getResolvedType(y);
auto zType = vector.iAttribute->getResolvedType(z);
auto wType = vector.iAttribute->getResolvedType(w);
std::array<AttributeObj, 4> attrs{ x, y, z, w };
if (nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size()))
{
xType = vector.iAttribute->getResolvedType(x);
yType = vector.iAttribute->getResolvedType(y);
zType = vector.iAttribute->getResolvedType(z);
wType = vector.iAttribute->getResolvedType(w);
}
// Require inputs to be resolved before determining outputs' type
if (xType.baseType != BaseDataType::eUnknown && yType.baseType != BaseDataType::eUnknown &&
zType.baseType != BaseDataType::eUnknown && wType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 5> attrs{ x, y, z, w, vector };
std::array<uint8_t, 5> tuples{ 1, 1, 1, 1, 4 };
std::array<uint8_t, 5> arrays{
xType.arrayDepth,
yType.arrayDepth,
zType.arrayDepth,
wType.arrayDepth,
xType.arrayDepth
};
std::array<AttributeRole, 5> roles{ xType.role, yType.role, zType.role, wType.role, AttributeRole::eNone };
nodeObj.iNode->resolvePartiallyCoupledAttributes(
nodeObj, attrs.data(), tuples.data(), arrays.data(), roles.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 5,369 | C++ | 33.645161 | 119 | 0.583349 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnCompare.cpp | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnCompareDatabase.h>
#include <functional>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/graph/core/ogn/Types.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
std::function<bool(const T&, const T&)> getOperation(OgnCompareDatabase& db, NameToken operation)
{
// Find the desired comparison
std::function<bool(const T&, const T&)> fn;
if (operation == db.tokens.gt) fn = [](const T& a, const T& b){ return a > b; };
else if (operation == db.tokens.lt) fn =[](const T& a, const T& b){ return a < b; };
else if (operation == db.tokens.ge) fn = [](const T& a, const T& b){ return a >= b; };
else if (operation == db.tokens.le) fn = [](const T& a, const T& b){ return a <= b; };
else if (operation == db.tokens.eq) fn = [](const T& a, const T& b){ return a == b; };
else if (operation == db.tokens.ne) fn = [](const T& a, const T& b){ return a != b; };
else
{
throw ogn::compute::InputError("Failed to resolve token " + std::string(db.tokenToString(operation)) +
", expected one of (>,<,>=,<=,==,!=)");
}
return fn;
}
template<>
std::function<bool(const OgnToken&, const OgnToken&)> getOperation(OgnCompareDatabase& db, NameToken operation)
{
std::function<bool(const OgnToken&, const OgnToken&)> fn;
if (operation == db.tokens.eq)
fn = [](const OgnToken& a, const OgnToken& b) { return a == b; };
else if (operation == db.tokens.ne)
fn = [](const OgnToken& a, const OgnToken& b) { return a != b; };
else if (operation == db.tokens.gt || operation == db.tokens.lt || operation == db.tokens.ge || operation == db.tokens.le)
throw ogn::compute::InputError("Operation " + std::string(db.tokenToString(operation)) +
" not supported for Tokens, expected one of (==,!=)");
else
throw ogn::compute::InputError("Failed to resolve token " + std::string(db.tokenToString(operation)) +
", expected one of (>,<,>=,<=,==,!=)");
return fn;
}
template<typename T>
bool tryComputeAssumingType(OgnCompareDatabase& db, NameToken operation, size_t count)
{
auto op = getOperation<T>(db, operation);
auto functor = [&](auto const& a, auto const& b, auto& result)
{
result = op(a, b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T, bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnCompareDatabase& db, NameToken operation, size_t count)
{
auto op = getOperation<T>(db, operation);
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Lexicographical comparison of tuples
result = true;
for (size_t i = 0; i < N; i++)
{
if (i < (N - 1) && (a[i] == b[i]))
continue;
else if (op(a[i], b[i]))
{
result = true;
break;
}
else
{
result = false;
break;
}
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor, count);
}
bool tryComputeAssumingString(OgnCompareDatabase& db, NameToken operation, size_t count)
{
auto op = getOperation<ogn::const_string>(db, operation);
for (size_t idx = 0; idx < count; ++idx)
{
auto stringA = db.inputs.a(idx).get<const char[]>();
auto stringB = db.inputs.b(idx).get<const char[]>();
*(db.outputs.result(idx).get<bool>()) = op(stringA(), stringB());
}
return true;
}
} // namespace
class OgnCompare
{
public:
static bool computeVectorized(OgnCompareDatabase& db, size_t count)
{
try
{
auto& aType = db.inputs.a().type();
auto& bType = db.inputs.b().type();
if (aType.baseType != bType.baseType || aType.componentCount != bType.componentCount)
throw ogn::compute::InputError("Failed to resolve input types");
const auto& operation = db.inputs.operation();
if ((operation != db.tokens.gt) and (operation != db.tokens.lt) and (operation != db.tokens.ge) and
(operation != db.tokens.le) and (operation != db.tokens.eq) and (operation != db.tokens.ne))
{
std::string op{ "Unknown" };
char const* opStr = db.tokenToString(operation);
if (opStr)
op = opStr;
throw ogn::compute::InputError("Unrecognized operation '" + op + std::string("'"));
}
auto node = db.abi_node();
auto opAttrib = node.iNode->getAttributeByToken(node, inputs::operation.m_token);
bool isOpConstant = opAttrib.iAttribute->isRuntimeConstant(opAttrib);
using FUNC_SIG = bool (*)(OgnCompareDatabase& db, NameToken operation, size_t count);
auto repeatWork = [&](FUNC_SIG const& func)
{
if (isOpConstant)
{
return func(db, operation, count);
}
bool ret = true;
while (count)
{
ret = func(db, operation, 1) && ret;
db.moveToNextInstance();
--count;
}
return ret;
};
switch (aType.baseType)
{
case BaseDataType::eBool:
return repeatWork(tryComputeAssumingType<bool>);
case BaseDataType::eDouble:
switch (aType.componentCount)
{
case 1: return repeatWork(tryComputeAssumingType<double>);
case 2: return repeatWork(tryComputeAssumingType<double, 2>);
case 3: return repeatWork(tryComputeAssumingType<double, 3>);
case 4: return repeatWork(tryComputeAssumingType<double, 4>);
case 9: return repeatWork(tryComputeAssumingType<double, 9>);
case 16: return repeatWork(tryComputeAssumingType<double, 16>);
}
case BaseDataType::eFloat:
switch (aType.componentCount)
{
case 1: return repeatWork(tryComputeAssumingType<float>);
case 2: return repeatWork(tryComputeAssumingType<float, 2>);
case 3: return repeatWork(tryComputeAssumingType<float, 3>);
case 4: return repeatWork(tryComputeAssumingType<float, 4>);
}
case BaseDataType::eInt:
switch (aType.componentCount)
{
case 1: return repeatWork(tryComputeAssumingType<int32_t>);
case 2: return repeatWork(tryComputeAssumingType<int32_t, 2>);
case 3: return repeatWork(tryComputeAssumingType<int32_t, 3>);
case 4: return repeatWork(tryComputeAssumingType<int32_t, 4>);
}
case BaseDataType::eHalf:
return repeatWork(tryComputeAssumingType<pxr::GfHalf>);
case BaseDataType::eInt64:
return repeatWork(tryComputeAssumingType<int64_t>);
case BaseDataType::eUChar:
if (aType.role == AttributeRole::eText && bType.role == AttributeRole::eText &&
aType.arrayDepth == 1 && bType.arrayDepth == 1 && aType.componentCount == 1 &&
bType.componentCount == 1)
{
return repeatWork(tryComputeAssumingString);
}
return repeatWork(tryComputeAssumingType<unsigned char>);
case BaseDataType::eUInt:
return repeatWork(tryComputeAssumingType<uint32_t>);
case BaseDataType::eToken:
return repeatWork(tryComputeAssumingType<OgnToken>);
case BaseDataType::eUInt64:
return repeatWork(tryComputeAssumingType<uint64_t>);
default:
break;
}
throw ogn::compute::InputError("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto b = node.iNode->getAttributeByToken(node, inputs::b.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto aType = a.iAttribute->getResolvedType(a);
auto bType = b.iAttribute->getResolvedType(b);
// Require inputs to be resolved before determining result's type
if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown)
{
const bool isStringInput = (aType.baseType == BaseDataType::eUChar && bType.baseType == BaseDataType::eUChar
&& aType.role == AttributeRole::eText && bType.role == AttributeRole::eText
&& aType.arrayDepth == 1 && bType.arrayDepth == 1
&& aType.componentCount == 1 && bType.componentCount == 1);
const uint8_t resultArrayDepth = isStringInput ? 0 : std::max(aType.arrayDepth, bType.arrayDepth);
Type resultType(BaseDataType::eBool, 1, resultArrayDepth);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 10,275 | C++ | 40.772358 | 142 | 0.57635 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBundleConstructor.py | """
Module contains the OmniGraph node implementation of BundleConstructor
"""
import omni.graph.core as og
class OgnBundleConstructor:
"""Node to create a bundle out of dynamic attributes"""
@staticmethod
def compute(db) -> bool:
"""Compute the bundle from the dynamic input attributes"""
# Start with an empty output bundle.
output_bundle = db.outputs.bundle
output_bundle.clear()
# Walk the list of node attribute, looking for dynamic inputs
for attribute in db.abi_node.get_attributes():
if attribute.is_dynamic():
if attribute.get_port_type() != og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT:
continue
if attribute.get_extended_type() != og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR:
db.log_warn(f"Cannot add extended attribute types like '{attribute.get_name()}' to a bundle")
continue
if attribute.get_resolved_type().base_type in [og.BaseDataType.RELATIONSHIP]:
db.log_warn(f"Cannot add bundle attribute types like '{attribute.get_name()}' to a bundle")
continue
# The bundled name does not need the port namespace
new_name = attribute.get_name().replace("inputs:", "")
output_bundle.insert((attribute.get_resolved_type(), new_name))
return True
| 1,448 | Python | 37.131578 | 113 | 0.619475 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetPrimPaths.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnGetPrimPathsDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimPaths
{
public:
static size_t computeVectorized(OgnGetPrimPathsDatabase& db, size_t count)
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!pathInterface || !tokenInterface)
{
CARB_LOG_ERROR("Failed to initialize path or token interface");
return 0;
}
for (size_t p = 0; p < count; p++)
{
const auto& prims = db.inputs.prims(p);
auto& primPaths = db.outputs.primPaths(p);
primPaths.resize(prims.size());
for (size_t i = 0; i < prims.size(); i++)
{
primPaths[i] = tokenInterface->getHandle(pathInterface->getText(prims[i]));
}
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 1,448 | C++ | 27.411764 | 91 | 0.640884 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnGetParentPrims.cpp | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnGetParentPrimsDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetParentPrims
{
public:
static size_t computeVectorized(OgnGetParentPrimsDatabase& db, size_t count)
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
if (!pathInterface)
{
CARB_LOG_ERROR("Failed to initialize path or token interface");
return 0;
}
for (size_t i = 0; i < count; i++)
{
const auto& prims = db.inputs.prims(i);
auto& parentPaths = db.outputs.parentPrims(i);
parentPaths.resize(prims.size());
std::transform(prims.begin(), prims.end(), parentPaths.begin(),
[&](const auto& p) { return pathInterface->getParent(p); });
}
return count;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 1,351 | C++ | 27.166666 | 87 | 0.647668 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnEndsWith.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnEndsWithDatabase.h>
#include <algorithm>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnEndsWith
{
public:
static bool compute(OgnEndsWithDatabase& db)
{
auto const& suffix = db.inputs.suffix();
auto const& value = db.inputs.value();
auto iters = std::mismatch(suffix.rbegin(), suffix.rend(), value.rbegin(), value.rend());
db.outputs.isSuffix() = (iters.first == suffix.rend());
return true;
}
};
REGISTER_OGN_NODE();
} // nodes
} // graph
} // omni
| 971 | C++ | 24.578947 | 97 | 0.704428 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantNames.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <carb/logging/Log.h>
#include <OgnGetVariantNamesDatabase.h>
namespace omni::graph::nodes
{
class OgnGetVariantNames
{
public:
static bool compute(OgnGetVariantNamesDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetName = db.tokenToString(db.inputs.variantSetName());
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
auto variantNames = variantSet.GetVariantNames();
db.outputs.variantNames().resize(variantNames.size());
for (size_t i = 0; i < variantNames.size(); i++)
{
db.outputs.variantNames()[i] = db.stringToToken(variantNames[i].c_str());
}
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
db.outputs.variantNames().resize(0);
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,721 | C++ | 28.18644 | 89 | 0.639163 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnClearVariantSelection.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include "VariantCommon.h"
#include <carb/logging/Log.h>
#include <OgnClearVariantSelectionDatabase.h>
namespace omni::graph::nodes
{
class OgnClearVariantSelection
{
public:
static bool compute(OgnClearVariantSelectionDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetName = db.tokenToString(db.inputs.variantSetName());
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
if (db.inputs.setVariant())
{
bool success = variantSet.SetVariantSelection("");
if (!success)
throw warning(std::string("Failed to clear variant selection for variant set ") + variantSetName);
}
else
{
removeLocalOpinion(prim, variantSetName);
}
db.outputs.execOut() = kExecutionAttributeStateEnabled;
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,868 | C++ | 28.203125 | 118 | 0.630621 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnHasVariantSet.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <carb/logging/Log.h>
#include <omni/usd/UsdContext.h>
#include <OgnHasVariantSetDatabase.h>
namespace omni::graph::nodes
{
class OgnHasVariantSet
{
public:
static bool compute(OgnHasVariantSetDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
db.outputs.exists() = variantSets.HasVariantSet(db.tokenToString(db.inputs.variantSetName()));
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
db.outputs.exists() = false;
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,373 | C++ | 24.444444 | 106 | 0.656956 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnGetVariantSetNames.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <carb/logging/Log.h>
#include <OgnGetVariantSetNamesDatabase.h>
namespace omni::graph::nodes
{
class OgnGetVariantSetNames
{
public:
static bool compute(OgnGetVariantSetNamesDatabase& db)
{
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
auto variantSetNames = variantSets.GetNames();
db.outputs.variantSetNames().resize(variantSetNames.size());
for (size_t i = 0; i < variantSetNames.size(); i++)
{
db.outputs.variantSetNames()[i] = db.stringToToken(variantSetNames[i].c_str());
}
return true;
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
db.outputs.variantSetNames().resize(0);
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 1,578 | C++ | 26.701754 | 95 | 0.636882 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/variant/OgnBlendVariants.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include "VariantCommon.h"
#include <carb/logging/Log.h>
#include <omni/fabric/Enums.h>
#include <omni/graph/core/ogn/Types.h>
#include <omni/math/linalg/SafeCast.h>
#include <omni/usd/UsdContext.h>
#include <pxr/usd/sdf/variantSetSpec.h>
#include <pxr/usd/sdf/variantSpec.h>
#include <OgnBlendVariantsDatabase.h>
using omni::graph::core::ogn::eAttributeType::kOgnOutput;
using omni::graph::core::ogn::eMemoryType::kCpu;
using omni::math::linalg::vec3f;
using DB = OgnBlendVariantsDatabase;
namespace omni::graph::nodes
{
namespace
{
using LerpFunction = void (*)(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
pxr::UsdAttribute attribute);
template <typename T>
void floatLerp(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
pxr::UsdAttribute attribute)
{
T a = propertyA->GetDefaultValue().Get<T>();
T b = propertyB->GetDefaultValue().Get<T>();
T c = pxr::GfLerp(alpha, a, b);
if (attribute.IsValid())
attribute.Set<T>(c);
}
template <typename T>
void discreteLerp(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
pxr::UsdAttribute attribute)
{
T a = propertyA->GetDefaultValue().Get<T>();
T b = propertyB->GetDefaultValue().Get<T>();
if (attribute.IsValid())
{
if (alpha < 0.5)
attribute.Set<T>(a);
else
attribute.Set<T>(b);
}
}
void lerpAttribute(const double alpha,
const pxr::SdfPropertySpecHandle& propertyA,
const pxr::SdfPropertySpecHandle& propertyB,
const pxr::UsdAttribute& attribute)
{
if (propertyA->GetSpecType() != propertyB->GetSpecType())
throw warning("Property spec types do not match (attribute " + attribute.GetPath().GetString() + ")");
if (propertyA->GetTypeName() != attribute.GetTypeName())
throw warning("Attribute types do not match (attribute " + attribute.GetPath().GetString() + ")");
if (propertyA->GetValueType() != propertyB->GetValueType())
throw warning("Property value types do not match");
auto typeName = propertyA->GetValueType().GetTypeName();
auto handleType = [alpha, &propertyA, &propertyB, &attribute, &typeName](const char* type, LerpFunction lerpFunction) -> bool
{
if (typeName == type)
{
lerpFunction(alpha, propertyA, propertyB, attribute);
return true;
}
return false;
};
if (!handleType("bool", discreteLerp<bool>)
&& !handleType("double", floatLerp<double>)
&& !handleType("float", floatLerp<float>)
&& !handleType("pxr_half::half", floatLerp<pxr::GfHalf>)
&& !handleType("int", discreteLerp<int>)
&& !handleType("__int64", discreteLerp<int64_t>) // Windows
&& !handleType("long", discreteLerp<int64_t>) // Linux
&& !handleType("unsigned char", discreteLerp<uint8_t>)
&& !handleType("unsigned int", discreteLerp<uint32_t>)
&& !handleType("unsigned __int64", discreteLerp<uint64_t>) // Windows
&& !handleType("unsigned long", discreteLerp<uint64_t>) // Linux
&& !handleType("TfToken", discreteLerp<pxr::TfToken>)
&& !handleType("SdfTimeCode", floatLerp<pxr::SdfTimeCode>)
&& !handleType("GfVec2d", floatLerp<pxr::GfVec2d>)
&& !handleType("GfVec2f", floatLerp<pxr::GfVec2f>)
&& !handleType("GfVec2h", floatLerp<pxr::GfVec2h>)
&& !handleType("GfVec2i", discreteLerp<pxr::GfVec2i>)
&& !handleType("GfVec3d", floatLerp<pxr::GfVec3d>)
&& !handleType("GfVec3f", floatLerp<pxr::GfVec3f>)
&& !handleType("GfVec3h", floatLerp<pxr::GfVec3h>)
&& !handleType("GfVec3i", discreteLerp<pxr::GfVec3i>)
&& !handleType("GfVec4d", floatLerp<pxr::GfVec4d>)
&& !handleType("GfVec4f", floatLerp<pxr::GfVec4f>)
&& !handleType("GfVec4h", floatLerp<pxr::GfVec4h>)
&& !handleType("GfVec4i", discreteLerp<pxr::GfVec4i>)
&& !handleType("GfQuatd", floatLerp<pxr::GfQuatd>)
&& !handleType("GfQuatf", floatLerp<pxr::GfQuatf>)
&& !handleType("GfQuath", floatLerp<pxr::GfQuath>)
&& !handleType("GfMatrix2d", floatLerp<pxr::GfMatrix2d>)
&& !handleType("GfMatrix3d", floatLerp<pxr::GfMatrix3d>)
&& !handleType("GfMatrix4d", floatLerp<pxr::GfMatrix4d>))
throw warning("Unsupported property type " + typeName);
}
}
class OgnBlendVariants
{
public:
static bool compute(OgnBlendVariantsDatabase& db)
{
auto ok = [&db]()
{
db.outputs.execOut() = kExecutionAttributeStateEnabled;
return true;
};
try
{
pxr::UsdPrim prim = tryGetTargetPrim(db, db.inputs.prim(), "prim");
std::string variantSetName = db.tokenToString(db.inputs.variantSetName());
std::string variantNameA = db.tokenToString(db.inputs.variantNameA());
std::string variantNameB = db.tokenToString(db.inputs.variantNameB());
double blend = std::max(std::min(db.inputs.blend(), 1.0), 0.0);
pxr::UsdVariantSets variantSets = prim.GetVariantSets();
pxr::UsdVariantSet variantSet = variantSets.GetVariantSet(variantSetName);
if (!variantSet.IsValid())
throw warning("Invalid variant set " + variantSetName);
bool finishing = (1.0 - blend) < 1e-6;
if (finishing && db.inputs.setVariant())
variantSet.SetVariantSelection(variantNameB);
VariantData a = getVariantData(prim, variantSetName, variantNameA);
VariantData b = getVariantData(prim, variantSetName, variantNameB);
for (const auto& [path, propertyA] : a)
{
if (b.find(path) == b.end())
continue;
auto propertyB = b[path];
auto attribute = prim.GetStage()->GetAttributeAtPath(path);
if (!attribute.IsValid())
throw warning("Invalid attribute " + path.GetString());
if (finishing && db.inputs.setVariant())
attribute.Clear();
else
lerpAttribute(blend, propertyA, propertyB, attribute);
}
return ok();
}
catch (const warning& e)
{
db.logWarning(e.what());
}
catch (const std::exception& e)
{
db.logError(e.what());
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace omni::graph::nodes
| 7,396 | C++ | 35.800995 | 129 | 0.611682 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveFrame.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnCurveFrameDatabase.h>
#include "omni/math/linalg/vec.h"
#include <carb/Framework.h>
#include <carb/Types.h>
#include <math.h>
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace nodes
{
static vec3f perpendicular(vec3f v)
{
vec3f av(abs(v[0]), abs(v[1]), abs(v[2]));
// Find the smallest coordinate of v.
int axis = (av[0] < av[1] && av[0] < av[2]) ? 0 : ((av[1] < av[2]) ? 1 : 2);
// Start with that coordinate.
vec3f p(0.0f);
p[axis] = 1.0f;
// Subtract the portion parallel to v.
p -= (GfDot(p, v) / GfDot(v, v)) * v;
// Normalize
return p.GetNormalized();
}
static vec3f rotateLike(vec3f v, vec3f a, vec3f aPlusb)
{
// To apply to another vector v, the rotation that brings tangent a to tangent b:
// - reflect v through the line in direction of unit vector a
// - reflect that through the line in direction of a+b
vec3f temp = (2 * GfDot(a, v)) * a - v;
return (2 * GfDot(aPlusb, temp) / GfDot(aPlusb, aPlusb)) * aPlusb - temp;
}
class OgnCurveFrame
{
public:
static bool compute(OgnCurveFrameDatabase& db)
{
const auto& vertexStartIndices = db.inputs.curveVertexStarts();
const auto& vertexCounts = db.inputs.curveVertexCounts();
const auto& curvePoints = db.inputs.curvePoints();
auto& tangentArray = db.outputs.tangent();
auto& upArray = db.outputs.up();
auto &outArray = db.outputs.out();
size_t curveCount = vertexStartIndices.size();
if (vertexCounts.size() < curveCount)
curveCount = vertexCounts.size();
const size_t pointCount = curvePoints.size();
if (curveCount == 0)
{
tangentArray.resize(0);
upArray.resize(0);
outArray.resize(0);
return true;
}
tangentArray.resize(pointCount);
upArray.resize(pointCount);
outArray.resize(pointCount);
for (size_t curve = 0; curve < curveCount; ++curve)
{
if (vertexCounts[curve] <= 0)
continue;
const size_t vertex = vertexStartIndices[curve];
if (vertex >= pointCount)
break;
size_t vertexCount = size_t(vertexCounts[curve]);
// Limit the vertex count on this curve if it goes past the end of the points array.
if (vertexCount > pointCount - vertex)
{
vertexCount = pointCount - vertex;
}
if (vertexCount == 1)
{
// Only one vertex: predetermined frame.
tangentArray[vertex] = vec3f( 0.0f, 0.0f, 1.0f );
upArray[vertex] = vec3f( 0.0f, 1.0f, 0.0f );
outArray[vertex] = vec3f( 1.0f, 0.0f, 0.0f );
continue;
}
// First, compute all tangents.
// The first tangent is the first edge direction.
// TODO: Skip zero-length edges to get the first real edge direction.
vec3f prev = curvePoints[vertex];
vec3f current = curvePoints[vertex + 1];
vec3f prevDir = (current - prev).GetNormalized();
tangentArray[vertex] = prevDir;
for (size_t i = 1; i < vertexCount - 1; ++i)
{
vec3f next = curvePoints[vertex + i + 1];
vec3f nextDir = (next - current).GetNormalized();
// Middle tangents are averages of previous and next directions.
vec3f dir = (prevDir + nextDir).GetNormalized();
tangentArray[vertex + i] = dir;
prev = current;
current = next;
prevDir = nextDir;
}
// The last tangent is the last edge direction.
tangentArray[vertex + vertexCount - 1] = prevDir;
// Choose the first up vector as anything that's perpendicular to the first tangent.
// TODO: Use a curve "normal" for more consistency.
vec3f prevTangent = tangentArray[vertex];
vec3f prevUpVector = perpendicular(prevTangent);
// x = cross(y, z)
vec3f prevOutVector = GfCross(prevUpVector, prevTangent);
upArray[vertex] = prevUpVector;
outArray[vertex] = prevOutVector;
for (size_t i = 1; i < vertexCount; ++i)
{
vec3f nextTangent = tangentArray[vertex + i];
vec3f midTangent = prevTangent + nextTangent;
vec3f nextUpVector = rotateLike(prevUpVector, prevTangent, midTangent);
vec3f nextOutVector = rotateLike(prevOutVector, prevTangent, midTangent);
upArray[vertex + i] = nextUpVector;
outArray[vertex + i] = nextOutVector;
prevTangent = nextTangent;
prevUpVector = nextUpVector;
prevOutVector = nextOutVector;
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 5,465 | C++ | 32.533742 | 96 | 0.579323 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnLengthAlongCurve.cpp | // Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnLengthAlongCurveDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnLengthAlongCurve
{
public:
static bool compute(OgnLengthAlongCurveDatabase& db)
{
const auto& vertexStartIndices = db.inputs.curveVertexStarts();
const auto& vertexCounts = db.inputs.curveVertexCounts();
const auto& curvePoints = db.inputs.curvePoints();
const auto& normalize = db.inputs.normalize();
auto& lengthArray = db.outputs.length();
size_t curveCount = std::min(vertexStartIndices.size(), vertexCounts.size());
const size_t pointCount = curvePoints.size();
if (curveCount == 0)
{
lengthArray.resize(0);
return true;
}
lengthArray.resize(pointCount);
for (size_t curve = 0; curve < curveCount; ++curve)
{
if (vertexCounts[curve] <= 0)
continue;
const size_t vertex = vertexStartIndices[curve];
if (vertex >= pointCount)
break;
size_t vertexCount = size_t(vertexCounts[curve]);
// Limit the vertex count on this curve if it goes past the end of the points array.
if (vertexCount > pointCount - vertex)
{
vertexCount = pointCount - vertex;
}
if (vertexCount == 1)
{
// Only one vertex: predetermined frame.
lengthArray[vertex] = 0.0f;
continue;
}
// First, compute all lengths along the curve.
auto prev = curvePoints[vertex];
lengthArray[vertex] = 0.0f;
// Sum in double precision to avoid catastrophic roundoff error.
double lengthSum = 0.0;
for (size_t i = 1; i < vertexCount; ++i)
{
auto& current = curvePoints[vertex + i];
auto edge = (current - prev);
lengthSum += edge.GetLength();
lengthArray[vertex + i] = float(lengthSum);
prev = current;
}
// Don't normalize if lengthSum is zero.
if (normalize && float(lengthSum) != 0)
{
for (size_t i = 0; i < vertexCount; ++i)
{
lengthArray[vertex + i] /= float(lengthSum);
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,908 | C++ | 28.98969 | 96 | 0.563274 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCreateTubeTopology.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnCreateTubeTopologyDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnCreateTubeTopology
{
public:
static bool compute(OgnCreateTubeTopologyDatabase& db)
{
const auto& inputRows = db.inputs.rows();
const auto& inputColumns = db.inputs.cols();
auto& faceVertexCounts = db.outputs.faceVertexCounts();
auto& faceVertexIndices = db.outputs.faceVertexIndices();
const size_t rowValueCount = inputRows.size();
const size_t colValueCount = inputColumns.size();
size_t inputTubeCount;
if (colValueCount == 1 || colValueCount == rowValueCount)
{
inputTubeCount = rowValueCount;
}
else if (rowValueCount == 1)
{
inputTubeCount = colValueCount;
}
else
{
faceVertexCounts.resize(0);
faceVertexIndices.resize(0);
return true;
}
size_t validTubeCount = 0;
size_t quadCount = 0;
for (size_t inputTube = 0; inputTube < inputTubeCount; ++inputTube)
{
auto rows = inputRows[(rowValueCount == 1) ? 0 : inputTube];
auto cols = inputColumns[(colValueCount == 1) ? 0 : inputTube];
if (rows <= 0 || cols <= 1)
{
continue;
}
const size_t currentQuadCount = size_t(rows) * cols;
quadCount += currentQuadCount;
++validTubeCount;
}
// Generate a faceVertexCounts array with all 4, for all quads.
faceVertexCounts.resize(quadCount);
for (auto& faceVertex : faceVertexCounts)
{
faceVertex = 4;
}
faceVertexIndices.resize(4 * quadCount);
size_t faceVertexIndex{ 0 };
int pointIndex = 0;
for (size_t inputTube = 0; inputTube < inputTubeCount; ++inputTube)
{
auto rows = inputRows[(rowValueCount == 1) ? 0 : inputTube];
auto cols = inputColumns[(colValueCount == 1) ? 0 : inputTube];
if (rows <= 0 || cols <= 1)
{
continue;
}
for (auto row = 0; row < rows; ++row)
{
// Main quads of the row
for (auto col = 0; col < cols - 1; ++col)
{
faceVertexIndices[faceVertexIndex++] = pointIndex;
faceVertexIndices[faceVertexIndex++] = pointIndex + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + cols + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + cols;
++pointIndex;
}
// Wrap around
faceVertexIndices[faceVertexIndex++] = pointIndex;
faceVertexIndices[faceVertexIndex++] = pointIndex - cols + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + 1;
faceVertexIndices[faceVertexIndex++] = pointIndex + cols;
++pointIndex;
}
pointIndex += cols;
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 3,600 | C++ | 30.867256 | 81 | 0.565 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveTubeST.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnCurveTubeSTDatabase.h>
#include "omni/math/linalg/vec.h"
#include <carb/Framework.h>
#include <carb/Types.h>
#include <omni/graph/core/ArrayWrapper.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <omni/graph/core/iComputeGraph.h>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
using omni::math::linalg::vec2f;
namespace omni
{
namespace graph
{
namespace nodes
{
static void computeNewSs(std::vector<float>& sValues, size_t edgeCount)
{
if (sValues.size() == edgeCount + 1)
return;
sValues.resize(edgeCount + 1);
sValues[0] = 0.0f;
if (edgeCount == 0)
return;
for (size_t i = 1; i < edgeCount; ++i)
{
sValues[i] = float(double(i) / double(edgeCount));
}
sValues[edgeCount] = 1.0f;
}
class OgnCurveTubeST
{
public:
static bool compute(OgnCurveTubeSTDatabase& db)
{
const auto& curveStartIndices = db.inputs.curveVertexStarts();
const auto& tubeVertexCounts = db.inputs.curveVertexCounts();
const auto& tubeSTStartArray = db.inputs.tubeSTStarts();
const auto& tubeQuadStartArray = db.inputs.tubeQuadStarts();
const auto& columnsArray = db.inputs.cols();
const auto& widthArray = db.inputs.width();
const auto& tArray = db.inputs.t();
auto scaleTLikeS = db.inputs.scaleTLikeS(); // Might change, so get a copy
auto& stArray = db.outputs.primvars_st();
auto& stIndicesArray = db.outputs.primvars_st_indices();
size_t curveCount = curveStartIndices.size();
if (tubeVertexCounts.size() < curveCount)
curveCount = tubeVertexCounts.size();
size_t tubeCount = tubeSTStartArray.size();
if (tubeQuadStartArray.size() < tubeCount)
{
tubeCount = tubeQuadStartArray.size();
}
const size_t colValueCount = columnsArray.size();
const int32_t tubeSTsCount = (tubeCount == 0) ? 0 : tubeSTStartArray[tubeCount - 1];
const int32_t tubeQuadsCount = (tubeCount == 0) ? 0 : tubeQuadStartArray[tubeCount - 1];
if (tubeCount != 0)
--tubeCount;
const size_t tCount = tArray.size();
size_t widthCount = 0;
if (scaleTLikeS)
{
widthCount = widthArray.size();
if (widthCount == 0 || (widthCount != 1 && widthCount != tCount && widthCount != tubeCount))
{
scaleTLikeS = false;
}
}
if (tubeSTsCount <= 0 || tubeCount == 0 || (colValueCount != 1 && colValueCount != tubeCount) ||
(colValueCount == 1 && columnsArray[0] <= 0) || (tubeCount != curveCount))
{
stArray.resize(0);
stIndicesArray.resize(0);
return true;
}
if (tCount == 0)
{
stArray.resize(0);
stIndicesArray.resize(0);
return true;
}
std::vector<float> sValues;
size_t circleN = 0;
float perimeterScale = 0.0f;
if (colValueCount == 1)
{
circleN = columnsArray[0];
computeNewSs(sValues, circleN);
perimeterScale = float(circleN * sin(M_PI / circleN));
}
stArray.resize(tubeSTsCount);
stIndicesArray.resize(4 * tubeQuadsCount);
float width = (scaleTLikeS ? widthArray[0] : 0.0f);
for (size_t tube = 0; tube < tubeCount; ++tube)
{
if (tubeSTStartArray[tube] < 0 || curveStartIndices[tube] < 0 || tubeQuadStartArray[tube] < 0 ||
tubeVertexCounts[tube] < 0)
continue;
size_t tubeSTStartIndex = tubeSTStartArray[tube];
size_t tubeSTEndIndex = tubeSTStartArray[tube + 1];
size_t tubeQuadStartIndex = 4 * tubeQuadStartArray[tube];
size_t tubeQuadEndIndex = 4 * tubeQuadStartArray[tube + 1];
size_t curveStartIndex = curveStartIndices[tube];
size_t curveEndIndex = curveStartIndex + tubeVertexCounts[tube];
if (colValueCount != 1)
{
circleN = columnsArray[tube];
if (circleN <= 0)
continue;
computeNewSs(sValues, circleN);
perimeterScale = float(circleN * sin(M_PI / circleN));
}
if ((int32_t)tubeSTEndIndex > tubeSTsCount || tubeSTEndIndex < tubeSTStartIndex)
break;
if (tubeSTEndIndex == tubeSTStartIndex)
continue;
size_t curveTCount = curveEndIndex - curveStartIndex;
size_t tubeSTCount = tubeSTEndIndex - tubeSTStartIndex;
if (curveTCount * (circleN + 1) != tubeSTCount)
{
continue;
}
if (scaleTLikeS)
{
if (widthCount == tubeCount)
{
width = widthArray[tube];
}
else if (widthCount == tCount)
{
// Use the max width along the curve for the whole curve's
// t scaling, just for stability for now.
// Some situations need varying scale, but that's more complicated,
// and not what's needed for the current use cases.
width = widthArray[curveStartIndex];
for (size_t i = curveStartIndex + 1; i < curveEndIndex; ++i)
{
if (widthArray[i] > width)
{
width = widthArray[i];
}
}
}
}
// First, compute the st values.
size_t circleIndex = 0;
float tScale = 1.0f;
if (scaleTLikeS)
{
// Scale t by 1/(2nr*sin(2pi/2n)), where 2r*sin(2pi/2n) is the side length,
// and the full denominator is the perimeter of the tube's circle.
// This is, in a sense, scaling t by the same factor that s was "scaled"
// by, to make it go from 0 to 1, instead of 0 to the perimeter.
// This way, t will change proportionally to s moving along the surface in 3D space.
tScale = 1.0f / (width * perimeterScale);
}
float tValue = tScale * tArray[curveStartIndex];
for (size_t sti = tubeSTStartIndex; sti < tubeSTEndIndex; ++sti)
{
vec2f st( sValues[circleIndex], tValue );
stArray[sti] = st;
++circleIndex;
if (circleIndex >= circleN + 1)
{
circleIndex = 0;
++curveStartIndex;
if (curveStartIndex < curveEndIndex)
{
tValue = tScale * tArray[curveStartIndex];
}
}
}
// Second, compute indices into the st values.
circleIndex = 0;
for (size_t indexi = tubeQuadStartIndex, sti = tubeSTStartIndex; indexi < tubeQuadEndIndex; indexi += 4, ++sti)
{
stIndicesArray[indexi] = int32_t(sti);
stIndicesArray[indexi + 1] = int32_t(sti + 1);
stIndicesArray[indexi + 2] = int32_t(sti + circleN + 1 + 1);
stIndicesArray[indexi + 3] = int32_t(sti + circleN + 1);
++circleIndex;
if (circleIndex >= circleN)
{
circleIndex = 0;
++sti;
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 8,158 | C++ | 32.995833 | 123 | 0.537509 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/geo/OgnCurveTubePositions.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnCurveTubePositionsDatabase.h>
#include <carb/Framework.h>
#include <carb/Types.h>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
using carb::Float2;
using carb::Float3;
namespace omni
{
namespace graph
{
namespace nodes
{
static void computeNewCircle(std::vector<Float2>& circle, size_t edgeCount)
{
if (circle.size() == edgeCount)
return;
circle.resize(edgeCount);
circle[0] = Float2{ 1.0f, 0.0f };
for (size_t i = 1; i < edgeCount; ++i)
{
double theta = ((2 * M_PI) / double(edgeCount)) * double(i);
float c = float(cos(theta));
float s = float(sin(theta));
circle[i] = Float2{ c, s };
}
}
class OgnCurveTubePositions
{
public:
static bool compute(OgnCurveTubePositionsDatabase& db)
{
const auto& curveStartIndices = db.inputs.curveVertexStarts();
const auto& tubeVertexCounts = db.inputs.curveVertexCounts();
const auto& curvePointsArray = db.inputs.curvePoints();
const auto& tubeStartIndices = db.inputs.tubePointStarts();
const auto& columnsArray = db.inputs.cols();
const auto& widthArray = db.inputs.width();
const auto& upArray = db.inputs.up();
const auto& outArray = db.inputs.out();
auto& pointsArray = db.outputs.points();
size_t curveCount = curveStartIndices.size();
if (tubeVertexCounts.size() < curveCount)
curveCount = tubeVertexCounts.size();
size_t tubeCount = tubeStartIndices.size();
const size_t colValueCount = columnsArray.size();
const int32_t tubePointsCount = (tubeCount == 0) ? 0 : tubeStartIndices[tubeCount - 1];
if (tubeCount != 0)
--tubeCount;
const size_t curvePointCount = curvePointsArray.size();
const size_t upCount = upArray.size();
const size_t outCount = outArray.size();
const size_t widthCount = widthArray.size();
size_t curvePointsCount = curvePointCount;
if (upCount != 1 && upCount < curvePointsCount)
curvePointsCount = upCount;
if (outCount != 1 && outCount < curvePointsCount)
curvePointsCount = outCount;
if (widthCount != 1 && widthCount < curvePointsCount)
curvePointsCount = widthCount;
if (tubePointsCount <= 0 || tubeCount == 0 || (colValueCount != 1 && colValueCount != tubeCount) ||
(colValueCount == 1 && columnsArray[0] <= 0) || (tubeCount != curveCount))
{
pointsArray.resize(0);
return true;
}
if (curvePointsCount == 0)
{
pointsArray.resize(0);
return true;
}
std::vector<Float2> circle;
size_t circleN = 0;
if (colValueCount == 1)
{
circleN = columnsArray[0];
computeNewCircle(circle, circleN);
}
pointsArray.resize(tubePointsCount);
for (size_t tube = 0; tube < tubeCount; ++tube)
{
if (tubeStartIndices[tube] < 0 || curveStartIndices[tube] < 0 || tubeVertexCounts[tube] < 0)
continue;
size_t tubeStartIndex = tubeStartIndices[tube];
size_t tubeEndIndex = tubeStartIndices[tube + 1];
size_t curveStartIndex = curveStartIndices[tube];
size_t curveEndIndex = curveStartIndex + tubeVertexCounts[tube];
if (colValueCount != 1)
{
circleN = columnsArray[tube];
if (circleN <= 0)
continue;
computeNewCircle(circle, circleN);
}
if ((int32_t)tubeEndIndex > tubePointsCount || tubeEndIndex < tubeStartIndex)
break;
if (tubeEndIndex == tubeStartIndex)
continue;
size_t curvePointCount = curveEndIndex - curveStartIndex;
size_t tubePointCount = tubeEndIndex - tubeStartIndex;
if (curvePointCount * circleN != tubePointCount)
{
continue;
}
size_t circleIndex = 0;
// Do bounds check on up and out arrays.
auto center = curvePointsArray[curveStartIndex];
auto up = upArray[(upCount == 1) ? 0 : curveStartIndex];
auto out = outArray[(outCount == 1) ? 0 : curveStartIndex];
float width = 0.5f * widthArray[(widthCount == 1) ? 0 : curveStartIndex];
for (size_t point = tubeStartIndex; point < tubeEndIndex; ++point)
{
float x = width * circle[circleIndex].x;
float y = width * circle[circleIndex].y;
auto newPoint = (center + (x * out + y * up));
pointsArray[point] = newPoint;
++circleIndex;
if (circleIndex >= circleN)
{
circleIndex = 0;
++curveStartIndex;
if (curveStartIndex < curveEndIndex)
{
center = curvePointsArray[curveStartIndex];
up = upArray[(upCount == 1) ? 0 : curveStartIndex];
out = outArray[(outCount == 1) ? 0 : curveStartIndex];
width = 0.5f * widthArray[(widthCount == 1) ? 0 : curveStartIndex];
}
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 5,884 | C++ | 33.415204 | 107 | 0.57155 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleAllocator.cpp | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "OgnRpResourceExampleAllocatorDatabase.h"
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/graph/core/BundlePrims.h>
#include <omni/math/linalg/vec.h>
using omni::math::linalg::vec3f;
using omni::graph::core::BundleAttributeInfo;
using omni::graph::core::BundlePrim;
using omni::graph::core::BundlePrims;
using omni::graph::core::ConstBundlePrim;
using omni::graph::core::ConstBundlePrims;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
class OgnRpResourceExampleAllocator
{
// NOTE: this node is meant only as an early example of gpu interop on a prerender graph.
// Storing a pointer to an RpResource is a temporary measure that will not work in a
// multi-node setting.
bool previousSuccess;
bool previousReload;
std::vector<rtx::resourcemanager::RpResource*> resourcePointerCollection;
std::vector<uint64_t> pointCountCollection;
std::vector<NameToken> primPathCollection;
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleAllocator::initialize" << std::endl;
}
static void release(const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleAllocator::release" << std::endl;
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
rtx::resourcemanager::ResourceManager* resourceManager = gpuFoundation->getResourceManager();
rtx::resourcemanager::Context* resourceManagerContext = gpuFoundation->getResourceManagerContext();
auto& internalState = OgnRpResourceExampleAllocatorDatabase::sInternalState<OgnRpResourceExampleAllocator>(nodeObj);
auto& resourcePointerCollection = internalState.resourcePointerCollection;
const size_t resourceCount = resourcePointerCollection.size();
for (size_t i = 0; i < resourceCount; i++)
{
resourceManager->releaseResource(*resourcePointerCollection[i]);
}
}
}
}
static bool compute(OgnRpResourceExampleAllocatorDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleAllocator::compute");
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
auto& internalState = db.internalState<OgnRpResourceExampleAllocator>();
const bool previousSuccess = internalState.previousSuccess;
const bool previousReload = internalState.previousReload;
internalState.previousSuccess = false;
internalState.previousReload= false;
const bool verbose = db.inputs.verbose();
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
cudaStream_t stream = (cudaStream_t)db.inputs.stream();
if (verbose)
{
std::cout<<"OgnRpResourceExampleAllocator::compute -- cudaStream: "<<stream<<std::endl;
}
if (!stream)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
auto& resourcePointerCollection = internalState.resourcePointerCollection;
auto& pointCountCollection = internalState.pointCountCollection;
auto& primPathCollection = internalState.primPathCollection;
const bool reloadAttr = db.inputs.reload();
if ((reloadAttr && !previousReload) || !previousSuccess)
{
internalState.previousReload = true;
if (resourcePointerCollection.size() != 0)
{
if (verbose)
{
std::cout << "freeing RpResource." << std::endl;
}
const size_t resourceCount = resourcePointerCollection.size();
for (size_t i = 0; i < resourceCount; i++)
{
resourceManager->releaseResource(*resourcePointerCollection[i]);
}
resourcePointerCollection.resize(0);
pointCountCollection.resize(0);
primPathCollection.resize(0);
}
}
if (resourcePointerCollection.size() == 0)
{
const auto& pointsAttr = db.inputs.points();
const size_t pointsCount = pointsAttr.size();
const vec3f* points = pointsAttr.data();
const NameToken primPath = db.inputs.primPath();
if (pointsCount == 0)
return false;
if (points == nullptr)
return false;
//const uint64_t dimension = 4;
const uint64_t dimension = 3;
const uint64_t size = pointsCount * dimension * sizeof(float);
const uint32_t deviceIndex = 0;
carb::graphics::BufferUsageFlags usageFlags = carb::graphics::kBufferUsageFlagNone;
usageFlags |= carb::graphics::kBufferUsageFlagShaderResourceStorage;
usageFlags |= carb::graphics::kBufferUsageFlagVertexBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRawOrStructuredBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRaytracingBuffer;
carb::graphics::BufferDesc bufferDesc = rtx::RtxBufferDesc(size, "Mesh Buffer", usageFlags);
rtx::resourcemanager::ResourceDesc resourceDesc;
resourceDesc.mode = rtx::resourcemanager::ResourceMode::eDefault;
resourceDesc.memoryLocation = carb::graphics::MemoryLocation::eDevice;
resourceDesc.category = rtx::resourcemanager::ResourceCategory::eVertexBuffer;
resourceDesc.usageFlags = rtx::resourcemanager::kResourceUsageFlagCudaShared;
resourceDesc.deviceMask = OMNI_ALL_DEVICES_MASK;
resourceDesc.creationDeviceIndex = deviceIndex;
for (size_t i = 0; i < 2; i++)
{
rtx::resourcemanager::RpResource* rpResource = resourceManager->getResourceFromBufferDesc(*resourceManagerContext, bufferDesc, resourceDesc);
float* cpuPtr = new float[pointsCount * dimension];
for (size_t j = 0; j < pointsCount; j++)
{
cpuPtr[dimension * j] = points[j][0];
cpuPtr[dimension * j + 1] = points[j][1];
cpuPtr[dimension * j + 2] = points[j][2];
if (dimension == 4)
cpuPtr[dimension * j + 3] = 1.f;
}
void* cudaPtr = resourceManager->getCudaDevicePointer(*rpResource, deviceIndex);
cudaError_t err = cudaMemcpy(cudaPtr, cpuPtr, pointsCount * dimension * sizeof(float), cudaMemcpyHostToDevice);
delete [] cpuPtr;
if (verbose)
{
std::cout << "prim: " << db.tokenToString(primPath) << std::endl;
std::cout << "cudaMemcpy to device error code: " << err << std::endl;
std::cout << "errorName: " << cudaGetErrorName(err) << std::endl;
std::cout << "errorDesc: " << cudaGetErrorString(err) << std::endl;
std::cout << std::endl;
}
resourcePointerCollection.push_back(rpResource);
}
pointCountCollection.push_back((uint64_t)pointsCount);
primPathCollection.push_back(primPath);
db.outputs.resourcePointerCollection.resize(resourcePointerCollection.size());
memcpy(db.outputs.resourcePointerCollection().data(),
resourcePointerCollection.data(),
resourcePointerCollection.size() * sizeof(uint64_t));
db.outputs.pointCountCollection.resize(pointCountCollection.size());
memcpy(db.outputs.pointCountCollection().data(),
pointCountCollection.data(),
pointCountCollection.size() * sizeof(uint64_t));
db.outputs.primPathCollection.resize(primPathCollection.size());
memcpy(db.outputs.primPathCollection().data(),
primPathCollection.data(),
primPathCollection.size() * sizeof(NameToken));
}
if (resourcePointerCollection.size() == 0)
{
return false;
}
db.outputs.stream() = (uint64_t)stream;
internalState.previousSuccess = true;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 10,107 | C++ | 38.027027 | 157 | 0.624617 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleHydra.cpp | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <omni/hydra/IOmniHydra.h>
#include <omni/usd/UsdContextIncludes.h>
#include <omni/usd/UsdContext.h>
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <omni/graph/core/iComputeGraph.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/math/linalg/vec.h>
#include "OgnRpResourceExampleHydraDatabase.h"
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
class OgnRpResourceExampleHydra
{
public:
static bool compute(OgnRpResourceExampleHydraDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleHydra::compute");
const bool sendToHydra = db.inputs.sendToHydra();
const bool verbose = db.inputs.verbose();
//const size_t dimension = 4;
const size_t dimension = 3;
const uint32_t deviceIndex = 0;
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
if (verbose)
{
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
return false;
}
}
auto& resourcePointerCollection = db.inputs.resourcePointerCollection();
auto& pointCountCollection = db.inputs.pointCountCollection();
auto& primPathCollection = db.inputs.primPathCollection();
const size_t primCount = primPathCollection.size();
if (primCount == 0 ||
pointCountCollection.size() != primPathCollection.size() ||
2 * pointCountCollection.size() != resourcePointerCollection.size())
{
return false;
}
rtx::resourcemanager::RpResource** rpResources = (rtx::resourcemanager::RpResource**)resourcePointerCollection.data();
const uint64_t* pointCounts = pointCountCollection.data();
const NameToken* primPaths = primPathCollection.data();
omni::usd::hydra::IOmniHydra* omniHydra = sendToHydra ?
carb::getFramework()->acquireInterface<omni::usd::hydra::IOmniHydra>() :
nullptr;
for (size_t primIndex = 0; primIndex < primCount; primIndex++)
{
rtx::resourcemanager::RpResource* rpResource = rpResources[2 * primIndex + 1]; //only want deformed positions
const uint64_t& pointsCount = pointCounts[primIndex];
const NameToken& primPath = primPaths[primIndex];
if (verbose)
{
carb::graphics::AccessFlags accessFlags = resourceManager->getResourceAccessFlags(*rpResource, deviceIndex);
std::cout << "Sending to Hydra..." << std::endl;
std::cout << "prim path: " << db.tokenToString(primPath) << std::endl;
std::cout << "\trpResource: " << rpResource << std::endl;
std::cout << "\taccessFlags: " << accessFlags << std::endl;
if (accessFlags & carb::graphics::kAccessFlagUnknown)
std::cout << "\t\tkAccessFlagUnknown" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagVertexBuffer)
std::cout << "\t\tkAccessFlagVertexBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagIndexBuffer)
std::cout << "\t\tkAccessFlagIndexBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagConstantBuffer)
std::cout << "\t\tkAccessFlagConstantBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagArgumentBuffer)
std::cout << "\t\tkAccessFlagArgumentBuffer" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagTextureRead)
std::cout << "\t\tkAccessFlagTextureRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagStorageRead)
std::cout << "\t\tkAccessFlagStorageRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagStorageWrite)
std::cout << "\t\tkAccessFlagStorageWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagColorAttachmentWrite)
std::cout << "\t\tkAccessFlagColorAttachmentWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagDepthStencilAttachmentWrite)
std::cout << "\t\tkAccessFlagDepthStencilAttachmentWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagDepthStencilAttachmentRead)
std::cout << "\t\tkAccessFlagDepthStencilAttachmentRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagCopySource)
std::cout << "\t\tkAccessFlagCopySource" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagCopyDestination)
std::cout << "\t\tkAccessFlagCopyDestination" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagAccelStructRead)
std::cout << "\t\tkAccessFlagAccelStructRead" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagAccelStructWrite)
std::cout << "\t\tkAccessFlagAccelStructWrite" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagResolveSource)
std::cout << "\t\tkAccessFlagResolveSource" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagResolveDestination)
std::cout << "\t\tkAccessFlagResolveDestination" << std::endl;
if (accessFlags & carb::graphics::kAccessFlagStorageClear)
std::cout << "\t\tkAccessFlagStorageClear" << std::endl;
const carb::graphics::BufferDesc* bufferDesc = resourceManager->getBufferDesc(rpResource);
std::cout << "\tbufferDesc: " << bufferDesc << std::endl;
if (bufferDesc != nullptr)
{
std::cout << "\tbuffer usage flags: " << bufferDesc->usageFlags << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagNone)
std::cout << "\t\tkBufferUsageFlagNone" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagShaderResource)
std::cout << "\t\tkBufferUsageFlagShaderResource" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagShaderResourceStorage)
std::cout << "\t\tkBufferUsageFlagShaderResourceStorage" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagVertexBuffer)
std::cout << "\t\tkBufferUsageFlagVertexBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagIndexBuffer)
std::cout << "\t\tkBufferUsageFlagIndexBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagConstantBuffer)
std::cout << "\t\tkBufferUsageFlagConstantBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRawOrStructuredBuffer)
std::cout << "\t\tkBufferUsageFlagRawOrStructuredBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagArgumentBuffer)
std::cout << "\t\tkBufferUsageFlagArgumentBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingAccelStruct)
std::cout << "\t\tkBufferUsageFlagRaytracingAccelStruct" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingBuffer)
std::cout << "\t\tkBufferUsageFlagRaytracingBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingScratchBuffer)
std::cout << "\t\tkBufferUsageFlagRaytracingScratchBuffer" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagExportShared)
std::cout << "\t\tkBufferUsageFlagExportShared" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagImportShared)
std::cout << "\t\tkBufferUsageFlagImportShared" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagSharedCrossAdapter)
std::cout << "\t\tkBufferUsageFlagSharedCrossAdapter" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagHostMappedForeignMemory)
std::cout << "\t\tkBufferUsageFlagHostMappedForeignMemory" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagConcurrentAccess)
std::cout << "\t\tkBufferUsageFlagConcurrentAccess" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagVisibleCrossAdapter)
std::cout << "\t\tkBufferUsageFlagVisibleCrossAdapter" << std::endl;
if (bufferDesc->usageFlags & carb::graphics::kBufferUsageFlagRaytracingShaderBindingTable)
std::cout << "\t\tkBufferUsageFlagRaytracingShaderBindingTable" << std::endl;
std::cout << "\tbuffer size: " << bufferDesc->size << std::endl;
std::cout << "\tbuffer debug name: " << bufferDesc->debugName << std::endl;
std::cout << "\tbuffer ext: " << bufferDesc->ext << std::endl;
}
}
if (sendToHydra)
{
omni::usd::hydra::BufferDesc desc;
desc.data = (void*)rpResource;
desc.elementSize = dimension * sizeof(float);
desc.elementStride = dimension * sizeof(float);
desc.count = pointsCount;
desc.isGPUBuffer = true;
desc.isDataRpResource = true;
pxr::SdfPath path = pxr::SdfPath(db.tokenToString(primPath));
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleHydra, sending to hydra");
omniHydra->SetPointsBuffer(pxr::SdfPath(db.tokenToString(primPath)), desc);
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 11,707 | C++ | 50.80531 | 126 | 0.606987 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnRpResourceExampleDeformer.cpp | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "OgnRpResourceExampleDeformerDatabase.h"
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/math/linalg/vec.h>
#include <stdlib.h>
#include <iostream>
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
extern "C" void modifyPositions(float3* points, size_t numPoints, unsigned sequenceCounter, int displacementAxis, bool verbose, cudaStream_t stream);
extern "C" void modifyPositionsSinusoidal(const float3* pointsRest, float3* pointsDeformed, size_t numPoints, unsigned sequenceCounter, float positionScale, float timeScale, float deformScale, bool verbose, cudaStream_t stream);
class OgnRpResourceExampleDeformer
{
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleDeformer::initialize" << std::endl;
}
static void release(const NodeObj& nodeObj)
{
// std::cout << "OgnRpResourceExampleDeformer::release" << std::endl;
}
static bool compute(OgnRpResourceExampleDeformerDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleDeformer::compute");
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
const bool verbose = db.inputs.verbose();
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
cudaStream_t stream = (cudaStream_t)db.inputs.stream();
if (verbose)
{
std::cout<<"OgnRpResourceExampleDeformer::compute -- cudaStream: "<<stream<<std::endl;
}
if (!stream)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
auto& resourcePointerCollection = db.inputs.resourcePointerCollection();
auto& pointCountCollection = db.inputs.pointCountCollection();
auto& primPathCollection = db.inputs.primPathCollection();
const size_t primCount = primPathCollection.size();
if (primCount == 0 ||
pointCountCollection.size() != primPathCollection.size() ||
2 * pointCountCollection.size() != resourcePointerCollection.size())
{
db.outputs.resourcePointerCollection().resize(0);
db.outputs.pointCountCollection().resize(0);
db.outputs.primPathCollection().resize(0);
return false;
}
bool& reloadAttr = db.outputs.reload();
auto& sequenceCounter = db.state.sequenceCounter();
if (reloadAttr)
{
reloadAttr = false;
sequenceCounter = 0;
}
//const uint64_t dimension = 4;
const uint64_t dimension = 3;
const uint32_t deviceIndex = 0;
rtx::resourcemanager::RpResource** rpResources = (rtx::resourcemanager::RpResource**)resourcePointerCollection.data();
const uint64_t* pointCounts = pointCountCollection.data();
const NameToken* primPaths = primPathCollection.data();
for (size_t primIndex = 0; primIndex < primCount; primIndex++)
{
rtx::resourcemanager::RpResource* rpResourceRest = rpResources[2 * primIndex];
rtx::resourcemanager::RpResource* rpResourceDeformed = rpResources[2 * primIndex + 1];
const uint64_t& pointsCount = pointCounts[primIndex];
//const NameToken& path = primPaths[primIndex];
// run some simple kernel
if (verbose)
{
std::cout
<< "OgnRpResourceExampleDeformer: Modifying " << pointsCount
<< " positions at sequence point " << sequenceCounter
<< std::endl;
}
if (db.inputs.runDeformerKernel())
{
void* cudaPtrRest = resourceManager->getCudaDevicePointer(*rpResourceRest, deviceIndex);
void* cudaPtrDeformed = resourceManager->getCudaDevicePointer(*rpResourceDeformed, deviceIndex);
{
CARB_PROFILE_ZONE(1, "OgnRpResourceExampleDeformer::modifyPositions kernel");
modifyPositionsSinusoidal((float3*)cudaPtrRest, (float3*)cudaPtrDeformed, pointsCount, (unsigned)sequenceCounter, db.inputs.positionScale(), db.inputs.timeScale(), db.inputs.deformScale(), verbose, stream);
}
}
}
if (db.inputs.runDeformerKernel())
{
sequenceCounter++;
}
db.outputs.resourcePointerCollection.resize(resourcePointerCollection.size());
memcpy(db.outputs.resourcePointerCollection().data(),
resourcePointerCollection.data(),
resourcePointerCollection.size() * sizeof(uint64_t));
db.outputs.pointCountCollection.resize(pointCountCollection.size());
memcpy(db.outputs.pointCountCollection().data(),
pointCountCollection.data(),
pointCountCollection.size() * sizeof(uint64_t));
db.outputs.primPathCollection.resize(primPathCollection.size());
memcpy(db.outputs.primPathCollection().data(),
primPathCollection.data(),
primPathCollection.size() * sizeof(NameToken));
db.outputs.stream() = (uint64_t)stream;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 6,875 | C++ | 35.189473 | 228 | 0.651055 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/gpu_interop/OgnDeformedPointsToHydra.cpp | // Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "OgnDeformedPointsToHydraDatabase.h"
#include <carb/graphics/GraphicsTypes.h>
#include <carb/logging/Log.h>
#include <cuda/include/cuda_runtime_api.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/NodeTypeRegistrar.h>
#include <rtx/utils/GraphicsDescUtils.h>
#include <rtx/resourcemanager/ResourceManager.h>
#include <omni/kit/KitUtils.h>
#include <omni/kit/renderer/IRenderer.h>
#include <gpu/foundation/FoundationTypes.h>
#include <omni/hydra/IOmniHydra.h>
#include <omni/graph/core/BundlePrims.h>
#include <omni/math/linalg/vec.h>
using omni::math::linalg::vec3f;
using omni::graph::core::BundleAttributeInfo;
using omni::graph::core::BundlePrim;
using omni::graph::core::BundlePrims;
using omni::graph::core::ConstBundlePrim;
using omni::graph::core::ConstBundlePrims;
namespace omni
{
namespace graph
{
namespace core
{
namespace examples
{
class OgnDeformedPointsToHydra
{
// NOTE: this node is meant only for early usage of gpu interop on a prerender graph.
// Storing a pointer to an RpResource is a temporary measure that will not work in a
// multi-node setting.
bool previousSuccess;
rtx::resourcemanager::RpResource* resourcePointer;
uint64_t pointCount;
NameToken primPath;
public:
static void initialize(const GraphContextObj& context, const NodeObj& nodeObj)
{
OgnDeformedPointsToHydraDatabase db(context, nodeObj);
auto& internalState = db.internalState<OgnDeformedPointsToHydra>();
internalState.resourcePointer = nullptr;
internalState.pointCount = 0;
internalState.primPath = db.stringToToken("");
internalState.previousSuccess = false;
}
static void release(const NodeObj& nodeObj)
{
}
static bool compute(OgnDeformedPointsToHydraDatabase& db)
{
CARB_PROFILE_ZONE(1, "OgnDeformedPointsToHydra::compute");
rtx::resourcemanager::Context* resourceManagerContext = nullptr;
rtx::resourcemanager::ResourceManager* resourceManager = nullptr;
auto& internalState = db.internalState<OgnDeformedPointsToHydra>();
const bool previousSuccess = internalState.previousSuccess;
internalState.previousSuccess = false;
const bool verbose = db.inputs.verbose();
if (db.inputs.primPath() == db.stringToToken("") || db.inputs.points.size() == 0)
{
return false;
}
bool reload = false;
if (internalState.resourcePointer == nullptr ||
internalState.primPath != db.inputs.primPath() ||
internalState.pointCount != db.inputs.points.size() ||
!internalState.previousSuccess)
{
reload = true;
}
if (auto renderer = carb::getCachedInterface<omni::kit::renderer::IRenderer>())
{
if (auto gpuFoundation = renderer->getGpuFoundation())
{
resourceManager = gpuFoundation->getResourceManager();
resourceManagerContext = gpuFoundation->getResourceManagerContext();
}
}
cudaStream_t stream = (cudaStream_t)db.inputs.stream();
if (verbose)
{
std::cout<<"OgnDeformedPointsToHydra::compute -- cudaStream: "<<stream<<std::endl;
}
if (resourceManager == nullptr || resourceManagerContext == nullptr)
{
return false;
}
const uint32_t deviceIndex = 0;
const size_t pointsCount = db.inputs.points.size();
const uint64_t dimension = 3;
const uint64_t size = pointsCount * dimension * sizeof(float);
if (reload)
{
if (internalState.resourcePointer != nullptr)
{
if (verbose)
{
std::cout << "freeing RpResource." << std::endl;
}
resourceManager->releaseResource(*internalState.resourcePointer);
internalState.resourcePointer = nullptr;
}
carb::graphics::BufferUsageFlags usageFlags = carb::graphics::kBufferUsageFlagNone;
usageFlags |= carb::graphics::kBufferUsageFlagShaderResourceStorage;
usageFlags |= carb::graphics::kBufferUsageFlagVertexBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRawOrStructuredBuffer;
usageFlags |= carb::graphics::kBufferUsageFlagRaytracingBuffer;
carb::graphics::BufferDesc bufferDesc = rtx::RtxBufferDesc(size, "Mesh Buffer", usageFlags);
rtx::resourcemanager::ResourceDesc resourceDesc;
resourceDesc.mode = rtx::resourcemanager::ResourceMode::eDefault;
resourceDesc.memoryLocation = carb::graphics::MemoryLocation::eDevice;
resourceDesc.category = rtx::resourcemanager::ResourceCategory::eVertexBuffer;
resourceDesc.usageFlags = rtx::resourcemanager::kResourceUsageFlagCudaShared;
resourceDesc.deviceMask = OMNI_ALL_DEVICES_MASK;
resourceDesc.creationDeviceIndex = deviceIndex;
internalState.resourcePointer = resourceManager->getResourceFromBufferDesc(*resourceManagerContext, bufferDesc, resourceDesc);
internalState.pointCount = pointsCount;
internalState.primPath = db.inputs.primPath();
}
const float3* cudaSrc = (const float3*)(*db.inputs.points.gpu());
void* cudaDst = resourceManager->getCudaDevicePointer(*internalState.resourcePointer, deviceIndex);
cudaMemcpy(cudaDst, (const void*)cudaSrc, size, cudaMemcpyDeviceToDevice);
if (db.inputs.sendToHydra())
{
omni::usd::hydra::IOmniHydra* omniHydra = carb::getFramework()->acquireInterface<omni::usd::hydra::IOmniHydra>();
omni::usd::hydra::BufferDesc desc;
desc.data = (void*)internalState.resourcePointer;
desc.elementSize = dimension * sizeof(float);
desc.elementStride = dimension * sizeof(float);
desc.count = pointsCount;
desc.isGPUBuffer = true;
desc.isDataRpResource = true;
pxr::SdfPath path = pxr::SdfPath(db.tokenToString(internalState.primPath));
CARB_PROFILE_ZONE(1, "OgnRpResourceToHydra_Arrays, sending to hydra");
omniHydra->SetPointsBuffer(pxr::SdfPath(db.tokenToString(internalState.primPath)), desc);
}
internalState.previousSuccess = true;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
}
| 6,928 | C++ | 34.172589 | 138 | 0.667292 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineStart.cpp | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineStartDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineStart
{
public:
static bool compute(OgnTimelineStartDatabase& db)
{
auto handler = [](timeline::TimelinePtr const& timeline)
{
timeline->play();
return true;
};
return timelineNodeExecute(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 915 | C++ | 21.341463 | 77 | 0.714754 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineGet.cpp | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineGetDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineGet
{
public:
static bool compute(OgnTimelineGetDatabase& db)
{
auto handler = [&db](timeline::TimelinePtr const& timeline)
{
db.outputs.isLooping() = timeline->isLooping();
db.outputs.isPlaying() = timeline->isPlaying();
double const currentTime = timeline->getCurrentTime();
double const startTime = timeline->getStartTime();
double const endTime = timeline->getEndTime();
db.outputs.time() = currentTime;
db.outputs.startTime() = startTime;
db.outputs.endTime() = endTime;
db.outputs.frame() = timeline->timeToTimeCode(currentTime);
db.outputs.startFrame() = timeline->timeToTimeCode(startTime);
db.outputs.endFrame() = timeline->timeToTimeCode(endTime);
db.outputs.framesPerSecond() = timeline->getTimeCodesPerSecond();
// TODO: Should we return false when the outputs didn't change?
return true;
};
return timelineNodeEvaluate(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,706 | C++ | 28.431034 | 77 | 0.672333 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimer.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "PrimCommon.h"
#include <OgnTimerDatabase.h>
using namespace pxr;
using DB = OgnTimerDatabase;
namespace omni::graph::nodes
{
namespace
{
constexpr double kUninitializedStartTime = -1.;
}
enum TimeState : uint32_t
{
kTimeStateInit,
kTimeStateStart,
kTimeStatePlay,
kTimeStateLast,
kTimeStateFinish
};
class OgnTimer
{
double m_startTime{ kUninitializedStartTime }; // The value of the context time when we started latent state
TimeState m_timeState{ kTimeStateInit };
public:
static bool compute(DB& db)
{
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
double now = iContext->getTimeSinceStart(contextObj);
auto& state = db.internalState<OgnTimer>();
auto& timeState = state.m_timeState;
auto& startTime = state.m_startTime;
const double duration = std::max(db.inputs.duration(), 1.0e-6);
const double startValue = db.inputs.startValue();
const double endValue = db.inputs.endValue();
switch (timeState)
{
case kTimeStateInit:
{
timeState = kTimeStateStart;
db.outputs.finished() = kExecutionAttributeStateLatentPush;
break;
}
case kTimeStateStart:
{
startTime = now;
timeState = kTimeStatePlay;
// Do not break here, we want to fall through to the next case
}
case kTimeStatePlay:
{
double deltaTime = now - startTime;
double value = startValue + (endValue - startValue) * deltaTime / duration;
value = std::min(value, 1.0);
db.outputs.value() = value;
if (deltaTime >= duration)
{
timeState = kTimeStateLast;
}
else
{
db.outputs.updated() = kExecutionAttributeStateEnabled;
}
break;
}
case kTimeStateLast:
{
timeState = kTimeStateFinish;
db.outputs.value() = endValue;
db.outputs.updated() = kExecutionAttributeStateEnabled;
break;
}
case kTimeStateFinish:
{
startTime = kUninitializedStartTime;
timeState = kTimeStateInit;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
break;
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
| 2,923 | C++ | 26.847619 | 112 | 0.6117 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnInterpolator.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnInterpolatorDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
inline float computeInterpolation(size_t numSamples, const float* knots, const float* values, const float& param)
{
// do really simple search for now
for (size_t i = 0; i < numSamples - 1; i++)
{
float knot = knots[i];
float knotNext = knots[i + 1];
float value = values[i];
float valueNext = values[i + 1];
if (param < knot)
return value;
if (param <= knotNext)
{
float interpolant = (param - knot) / (knotNext - knot);
float interpolatedValue = interpolant * valueNext + (1.0f - interpolant) * value;
return interpolatedValue;
}
}
return values[numSamples - 1];
}
class OgnInterpolator
{
public:
static bool compute(OgnInterpolatorDatabase& db)
{
const auto& inputKnots = db.inputs.knots();
const auto& inputValues = db.inputs.values();
size_t numSamples = inputValues.size();
if (inputKnots.size() != numSamples)
{
db.logWarning("Knots size %zu does not match value size %zu, skipping evaluation", inputKnots.size(), numSamples);
return false;
}
if (numSamples > 0)
{
db.outputs.value() = computeInterpolation(numSamples, inputKnots.data(), inputValues.data(), db.inputs.param());
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,933 | C++ | 25.861111 | 126 | 0.636834 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineStop.cpp | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineStopDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineStop
{
public:
static bool compute(OgnTimelineStopDatabase& db)
{
auto handler = [](timeline::TimelinePtr const& timeline)
{
// Pause stops at the current frame, stop resets time
timeline->pause();
return true;
};
return timelineNodeExecute(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 979 | C++ | 22.333333 | 77 | 0.707865 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineSet.cpp | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineSetDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineSet
{
public:
static bool compute(OgnTimelineSetDatabase& db)
{
auto handler = [&db](timeline::TimelinePtr const& timeline)
{
auto const value = db.inputs.propValue();
bool clamped = false;
auto setTime = [&timeline](double desiredTime) -> bool
{
auto const startTime = timeline->getStartTime();
auto const endTime = timeline->getEndTime();
auto const clampedTime = std::clamp(desiredTime, startTime, endTime);
timeline->setCurrentTime(clampedTime);
return clampedTime != desiredTime; // NOLINT(clang-diagnostic-float-equal)
};
auto const propName = db.inputs.propName();
if (propName == OgnTimelineSetDatabase::tokens.Time)
clamped = setTime(value);
else if (propName == OgnTimelineSetDatabase::tokens.StartTime)
timeline->setStartTime(value);
else if (propName == OgnTimelineSetDatabase::tokens.EndTime)
timeline->setEndTime(value);
else if (propName == OgnTimelineSetDatabase::tokens.FramesPerSecond)
timeline->setTimeCodesPerSecond(value);
else
{
// The property to set is frame-based, convert to time in seconds.
auto const time = timeline->timeCodeToTime(value);
if (propName == OgnTimelineSetDatabase::tokens.Frame)
clamped = setTime(time);
else if (propName == OgnTimelineSetDatabase::tokens.StartFrame)
timeline->setStartTime(time);
else if (propName == OgnTimelineSetDatabase::tokens.EndFrame)
timeline->setEndTime(time);
}
db.outputs.clamped() = clamped;
return true;
};
return timelineNodeExecute(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,579 | C++ | 32.947368 | 90 | 0.621559 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/animation/OgnTimelineLoop.cpp | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "TimelineCommon.h"
#include <omni/timeline/ITimeline.h>
#include <OgnTimelineLoopDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnTimelineLoop
{
public:
static bool compute(OgnTimelineLoopDatabase& db)
{
auto handler = [&db](timeline::TimelinePtr const& timeline)
{
auto const loop = db.inputs.loop();
timeline->setLooping(loop);
return true;
};
return timelineNodeExecute(db, handler);
}
};
REGISTER_OGN_NODE()
}
}
}
| 973 | C++ | 22.190476 | 77 | 0.707091 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnNthRoot.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:value', {'type': 'float', 'value': 36.0}, False],
],
'outputs': [
['outputs:result', {'type': 'float', 'value': 6.0}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'double', 'value': 27.0}, False],
['inputs:nthRoot', 3, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 3.0}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'float[2]', 'value': [0.25, 4.0]}, False],
],
'outputs': [
['outputs:result', {'type': 'float[2]', 'value': [0.5, 2.0]}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'float[]', 'value': [1.331, 8.0]}, False],
['inputs:nthRoot', 3, False],
],
'outputs': [
['outputs:result', {'type': 'float[]', 'value': [1.1, 2.0]}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'float[2][]', 'value': [[4.0, 16.0], [2.25, 64.0]]}, False],
],
'outputs': [
['outputs:result', {'type': 'float[2][]', 'value': [[2.0, 4.0], [1.5, 8.0]]}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'int64', 'value': 9223372036854775807}, False],
['inputs:nthRoot', 1, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 9.223372036854776e+18}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'int', 'value': 256}, False],
['inputs:nthRoot', 4, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 4.0}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'uint64', 'value': 8}, False],
['inputs:nthRoot', 3, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 2.0}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'half[2]', 'value': [0.125, 1.0]}, False],
['inputs:nthRoot', 3, False],
],
'outputs': [
['outputs:result', {'type': 'half[2]', 'value': [0.5, 1.0]}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'uchar', 'value': 25}, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 5.0}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'int64', 'value': 16}, False],
['inputs:nthRoot', -2, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 0.25}, False],
],
},
{
'inputs': [
['inputs:value', {'type': 'double', 'value': 0.125}, False],
['inputs:nthRoot', -3, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 2}, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_NthRoot", "omni.graph.nodes.NthRoot", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.NthRoot User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_NthRoot","omni.graph.nodes.NthRoot", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.NthRoot User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_NthRoot", "omni.graph.nodes.NthRoot", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.NthRoot User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnNthRootDatabase import OgnNthRootDatabase
test_file_name = "OgnNthRootTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_NthRoot")
database = OgnNthRootDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:nthRoot"))
attribute = test_node.get_attribute("inputs:nthRoot")
db_value = database.inputs.nthRoot
expected_value = 2
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
| 7,684 | Python | 40.54054 | 187 | 0.520432 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnATan2.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:a', {'type': 'float', 'value': 5.0}, False],
['inputs:b', {'type': 'float', 'value': 3.0}, False],
],
'outputs': [
['outputs:result', {'type': 'float', 'value': 59.0362434679}, False],
],
},
{
'inputs': [
['inputs:a', {'type': 'double', 'value': 70.0}, False],
['inputs:b', {'type': 'double', 'value': 10.0}, False],
],
'outputs': [
['outputs:result', {'type': 'double', 'value': 81.8698976458}, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_ATan2", "omni.graph.nodes.ATan2", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.ATan2 User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_ATan2","omni.graph.nodes.ATan2", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.ATan2 User test case #{i+1}", 16)
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnATan2Database import OgnATan2Database
test_file_name = "OgnATan2Template.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_ATan2")
database = OgnATan2Database(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
| 3,279 | Python | 45.857142 | 164 | 0.609332 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnBooleanExpr.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:a', True, False],
['inputs:b', True, False],
['inputs:operator', "XOR", False],
],
'outputs': [
['outputs:result', False, False],
],
},
{
'inputs': [
['inputs:a', True, False],
['inputs:b', True, False],
['inputs:operator', "XNOR", False],
],
'outputs': [
['outputs:result', True, False],
],
},
{
'inputs': [
['inputs:a', True, False],
['inputs:b', False, False],
['inputs:operator', "OR", False],
],
'outputs': [
['outputs:result', True, False],
],
},
{
'inputs': [
['inputs:a', True, False],
['inputs:b', False, False],
['inputs:operator', "AND", False],
],
'outputs': [
['outputs:result', False, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanExpr", "omni.graph.nodes.BooleanExpr", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.BooleanExpr User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanExpr","omni.graph.nodes.BooleanExpr", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.BooleanExpr User test case #{i+1}", 16)
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnBooleanExprDatabase import OgnBooleanExprDatabase
test_file_name = "OgnBooleanExprTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_BooleanExpr")
database = OgnBooleanExprDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:a"))
attribute = test_node.get_attribute("inputs:a")
db_value = database.inputs.a
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:b"))
attribute = test_node.get_attribute("inputs:b")
db_value = database.inputs.b
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:operator"))
attribute = test_node.get_attribute("inputs:operator")
db_value = database.inputs.operator
expected_value = "AND"
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:result"))
attribute = test_node.get_attribute("outputs:result")
db_value = database.outputs.result
| 5,285 | Python | 43.05 | 176 | 0.600189 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnFindPrims.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:namePrefix', "Xform", False],
],
'outputs': [
['outputs:primPaths', ["/Xform1", "/Xform2", "/XformTagged1"], False],
],
'setup': {'create_nodes': [['TestNode', 'omni.graph.nodes.FindPrims']], 'create_prims': [['Empty', {}], ['Xform1', {'_translate': ['pointd[3][]', [[1, 2, 3]]]}], ['Xform2', {'_translate': ['pointd[3][]', [[4, 5, 6]]]}], ['XformTagged1', {'foo': ['token', ''], '_translate': ['pointd[3][]', [[1, 2, 3]]]}], ['Tagged1', {'foo': ['token', '']}]]} },
{
'inputs': [
['inputs:namePrefix', "", False],
['inputs:requiredAttributes', "foo _translate", False],
],
'outputs': [
['outputs:primPaths', ["/XformTagged1"], False],
],
'setup': {} },
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_FindPrims", "omni.graph.nodes.FindPrims", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.FindPrims User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_FindPrims","omni.graph.nodes.FindPrims", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.FindPrims User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_FindPrims", "omni.graph.nodes.FindPrims", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.FindPrims User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnFindPrimsDatabase import OgnFindPrimsDatabase
test_file_name = "OgnFindPrimsTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_FindPrims")
database = OgnFindPrimsDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 2)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:ignoreSystemPrims"))
attribute = test_node.get_attribute("inputs:ignoreSystemPrims")
db_value = database.inputs.ignoreSystemPrims
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:namePrefix"))
attribute = test_node.get_attribute("inputs:namePrefix")
db_value = database.inputs.namePrefix
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pathPattern"))
attribute = test_node.get_attribute("inputs:pathPattern")
db_value = database.inputs.pathPattern
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:recursive"))
attribute = test_node.get_attribute("inputs:recursive")
db_value = database.inputs.recursive
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:requiredAttributes"))
attribute = test_node.get_attribute("inputs:requiredAttributes")
db_value = database.inputs.requiredAttributes
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:requiredRelationship"))
attribute = test_node.get_attribute("inputs:requiredRelationship")
db_value = database.inputs.requiredRelationship
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:requiredRelationshipTarget"))
attribute = test_node.get_attribute("inputs:requiredRelationshipTarget")
db_value = database.inputs.requiredRelationshipTarget
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:requiredTarget"))
attribute = test_node.get_attribute("inputs:requiredTarget")
db_value = database.inputs.requiredTarget
self.assertTrue(test_node.get_attribute_exists("inputs:rootPrim"))
attribute = test_node.get_attribute("inputs:rootPrim")
db_value = database.inputs.rootPrim
self.assertTrue(test_node.get_attribute_exists("inputs:rootPrimPath"))
attribute = test_node.get_attribute("inputs:rootPrimPath")
db_value = database.inputs.rootPrimPath
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:type"))
attribute = test_node.get_attribute("inputs:type")
db_value = database.inputs.type
expected_value = "*"
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:primPaths"))
attribute = test_node.get_attribute("outputs:primPaths")
db_value = database.outputs.primPaths
self.assertTrue(test_node.get_attribute_exists("outputs:prims"))
attribute = test_node.get_attribute("outputs:prims")
db_value = database.outputs.prims
self.assertTrue(test_node.get_attribute_exists("state:ignoreSystemPrims"))
attribute = test_node.get_attribute("state:ignoreSystemPrims")
db_value = database.state.ignoreSystemPrims
self.assertTrue(test_node.get_attribute_exists("state:inputType"))
attribute = test_node.get_attribute("state:inputType")
db_value = database.state.inputType
self.assertTrue(test_node.get_attribute_exists("state:namePrefix"))
attribute = test_node.get_attribute("state:namePrefix")
db_value = database.state.namePrefix
self.assertTrue(test_node.get_attribute_exists("state:pathPattern"))
attribute = test_node.get_attribute("state:pathPattern")
db_value = database.state.pathPattern
self.assertTrue(test_node.get_attribute_exists("state:recursive"))
attribute = test_node.get_attribute("state:recursive")
db_value = database.state.recursive
self.assertTrue(test_node.get_attribute_exists("state:requiredAttributes"))
attribute = test_node.get_attribute("state:requiredAttributes")
db_value = database.state.requiredAttributes
self.assertTrue(test_node.get_attribute_exists("state:requiredRelationship"))
attribute = test_node.get_attribute("state:requiredRelationship")
db_value = database.state.requiredRelationship
self.assertTrue(test_node.get_attribute_exists("state:requiredRelationshipTarget"))
attribute = test_node.get_attribute("state:requiredRelationshipTarget")
db_value = database.state.requiredRelationshipTarget
self.assertTrue(test_node.get_attribute_exists("state:requiredTarget"))
attribute = test_node.get_attribute("state:requiredTarget")
db_value = database.state.requiredTarget
self.assertTrue(test_node.get_attribute_exists("state:rootPrim"))
attribute = test_node.get_attribute("state:rootPrim")
db_value = database.state.rootPrim
self.assertTrue(test_node.get_attribute_exists("state:rootPrimPath"))
attribute = test_node.get_attribute("state:rootPrimPath")
db_value = database.state.rootPrimPath
| 11,264 | Python | 49.743243 | 365 | 0.694158 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnCurveTubeST.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnCurveTubeSTDatabase import OgnCurveTubeSTDatabase
test_file_name = "OgnCurveTubeSTTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_CurveTubeST")
database = OgnCurveTubeSTDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:cols"))
attribute = test_node.get_attribute("inputs:cols")
db_value = database.inputs.cols
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexCounts"))
attribute = test_node.get_attribute("inputs:curveVertexCounts")
db_value = database.inputs.curveVertexCounts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexStarts"))
attribute = test_node.get_attribute("inputs:curveVertexStarts")
db_value = database.inputs.curveVertexStarts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:scaleTLikeS"))
attribute = test_node.get_attribute("inputs:scaleTLikeS")
db_value = database.inputs.scaleTLikeS
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:t"))
attribute = test_node.get_attribute("inputs:t")
db_value = database.inputs.t
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:tubeQuadStarts"))
attribute = test_node.get_attribute("inputs:tubeQuadStarts")
db_value = database.inputs.tubeQuadStarts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:tubeSTStarts"))
attribute = test_node.get_attribute("inputs:tubeSTStarts")
db_value = database.inputs.tubeSTStarts
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:width"))
attribute = test_node.get_attribute("inputs:width")
db_value = database.inputs.width
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:primvars:st"))
attribute = test_node.get_attribute("outputs:primvars:st")
db_value = database.outputs.primvars_st
self.assertTrue(test_node.get_attribute_exists("outputs:primvars:st:indices"))
attribute = test_node.get_attribute("outputs:primvars:st:indices")
db_value = database.outputs.primvars_st_indices
| 5,437 | Python | 51.796116 | 92 | 0.691926 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnTimelineGet.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnTimelineGetDatabase import OgnTimelineGetDatabase
test_file_name = "OgnTimelineGetTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_GetTimeline")
database = OgnTimelineGetDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("outputs:endFrame"))
attribute = test_node.get_attribute("outputs:endFrame")
db_value = database.outputs.endFrame
self.assertTrue(test_node.get_attribute_exists("outputs:endTime"))
attribute = test_node.get_attribute("outputs:endTime")
db_value = database.outputs.endTime
self.assertTrue(test_node.get_attribute_exists("outputs:frame"))
attribute = test_node.get_attribute("outputs:frame")
db_value = database.outputs.frame
self.assertTrue(test_node.get_attribute_exists("outputs:framesPerSecond"))
attribute = test_node.get_attribute("outputs:framesPerSecond")
db_value = database.outputs.framesPerSecond
self.assertTrue(test_node.get_attribute_exists("outputs:isLooping"))
attribute = test_node.get_attribute("outputs:isLooping")
db_value = database.outputs.isLooping
self.assertTrue(test_node.get_attribute_exists("outputs:isPlaying"))
attribute = test_node.get_attribute("outputs:isPlaying")
db_value = database.outputs.isPlaying
self.assertTrue(test_node.get_attribute_exists("outputs:startFrame"))
attribute = test_node.get_attribute("outputs:startFrame")
db_value = database.outputs.startFrame
self.assertTrue(test_node.get_attribute_exists("outputs:startTime"))
attribute = test_node.get_attribute("outputs:startTime")
db_value = database.outputs.startTime
self.assertTrue(test_node.get_attribute_exists("outputs:time"))
attribute = test_node.get_attribute("outputs:time")
db_value = database.outputs.time
| 3,183 | Python | 46.522387 | 92 | 0.699969 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnCreateTubeTopology.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:rows', [1, 2, 3], False],
['inputs:cols', [2, 3, 4], False],
],
'outputs': [
['outputs:faceVertexCounts', [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], False],
['outputs:faceVertexIndices', [0, 1, 3, 2, 1, 0, 2, 3, 4, 5, 8, 7, 5, 6, 9, 8, 6, 4, 7, 9, 7, 8, 11, 10, 8, 9, 12, 11, 9, 7, 10, 12, 13, 14, 18, 17, 14, 15, 19, 18, 15, 16, 20, 19, 16, 13, 17, 20, 17, 18, 22, 21, 18, 19, 23, 22, 19, 20, 24, 23, 20, 17, 21, 24, 21, 22, 26, 25, 22, 23, 27, 26, 23, 24, 28, 27, 24, 21, 25, 28], False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_CreateTubeTopology", "omni.graph.nodes.CreateTubeTopology", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.CreateTubeTopology User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_CreateTubeTopology","omni.graph.nodes.CreateTubeTopology", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.CreateTubeTopology User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_CreateTubeTopology", "omni.graph.nodes.CreateTubeTopology", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.CreateTubeTopology User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnCreateTubeTopologyDatabase import OgnCreateTubeTopologyDatabase
test_file_name = "OgnCreateTubeTopologyTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_CreateTubeTopology")
database = OgnCreateTubeTopologyDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:cols"))
attribute = test_node.get_attribute("inputs:cols")
db_value = database.inputs.cols
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:rows"))
attribute = test_node.get_attribute("inputs:rows")
db_value = database.inputs.rows
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts"))
attribute = test_node.get_attribute("outputs:faceVertexCounts")
db_value = database.outputs.faceVertexCounts
self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices"))
attribute = test_node.get_attribute("outputs:faceVertexIndices")
db_value = database.outputs.faceVertexIndices
| 5,763 | Python | 52.869158 | 349 | 0.661635 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnRandomNumeric.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 6649909271, False],
['inputs:min', {'type': 'uint', 'value': 0}, False],
['inputs:max', {'type': 'uint', 'value': 4294967295}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint', 'value': 0}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 6159018942, False],
['inputs:min', {'type': 'uint[]', 'value': [0, 100]}, False],
['inputs:max', {'type': 'uint', 'value': 4294967295}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint[]', 'value': [2147483648, 2160101208]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 3280530163, False],
['inputs:min', {'type': 'uint', 'value': 0}, False],
['inputs:max', {'type': 'uint[]', 'value': [4294967295, 199]}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint[]', 'value': [4294967295, 19]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 6159018942, False],
['inputs:min', {'type': 'int', 'value': -2147483648}, False],
['inputs:max', {'type': 'int', 'value': 2147483647}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'int', 'value': 0}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 6649909271, False],
['inputs:min', {'type': 'int[2]', 'value': [-2147483648, -100]}, False],
['inputs:max', {'type': 'int', 'value': 2147483647}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'int[2]', 'value': [-2147483648, 1629773655]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 3280530163, False],
['inputs:min', {'type': 'int', 'value': -2147483648}, False],
['inputs:max', {'type': 'int[2]', 'value': [2147483647, 99]}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'int[2]', 'value': [2147483647, -2146948710]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 8280086, False],
['inputs:min', {'type': 'float', 'value': 0}, False],
['inputs:max', {'type': 'float', 'value': 1}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'float', 'value': 0}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 17972581, False],
['inputs:min', {'type': 'float[]', 'value': [0, -10]}, False],
['inputs:max', {'type': 'float', 'value': 1}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'float[]', 'value': [0.5, -6.7663326]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 15115159, False],
['inputs:min', {'type': 'float', 'value': 0}, False],
['inputs:max', {'type': 'float[]', 'value': [1, 10]}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'float[]', 'value': [0.9999999403953552, 4.0452986]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 14092058508772706262, False],
['inputs:min', {'type': 'uint64', 'value': 0}, False],
['inputs:max', {'type': 'uint64', 'value': 18446744073709551615}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint64', 'value': 0}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 9302349107990861236, False],
['inputs:min', {'type': 'uint64', 'value': 0}, False],
['inputs:max', {'type': 'uint64', 'value': 18446744073709551615}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint64', 'value': 9223372036854775808}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 1955209015103813879, False],
['inputs:min', {'type': 'uint64', 'value': 0}, False],
['inputs:max', {'type': 'uint64', 'value': 18446744073709551615}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint64', 'value': 18446744073709551615}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 123456789, False],
['inputs:min', {'type': 'uint64', 'value': 1099511627776}, False],
['inputs:max', {'type': 'uint64', 'value': 1125899906842624}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uint64', 'value': 923489197424953}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 1955209015103813879, False],
['inputs:min', {'type': 'double[2][]', 'value': [[0, -10], [10, 0]]}, False],
['inputs:max', {'type': 'double', 'value': 1}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'double[2][]', 'value': [[0, 0.28955788], [7.98645811, 0.09353537]]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 123456789, False],
['inputs:min', {'type': 'half[]', 'value': [0, -100]}, False],
['inputs:max', {'type': 'half[]', 'value': [1, 100]}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'half[]', 'value': [0.17993164, -76.375]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 0, False],
['inputs:min', {'type': 'uchar[]', 'value': [0, 100]}, False],
['inputs:max', {'type': 'uchar[]', 'value': [255, 200]}, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'uchar[]', 'value': [153, 175]}, False],
['outputs:execOut', 1, False],
],
},
{
'inputs': [
['inputs:useSeed', True, False],
['inputs:seed', 9302349107990861236, False],
['inputs:execIn', 1, False],
['inputs:isNoise', True, False],
],
'outputs': [
['outputs:random', {'type': 'double', 'value': 0.5}, False],
['outputs:execOut', 1, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_RandomNumeric", "omni.graph.nodes.RandomNumeric", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.RandomNumeric User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_RandomNumeric","omni.graph.nodes.RandomNumeric", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.RandomNumeric User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_RandomNumeric", "omni.graph.nodes.RandomNumeric", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.RandomNumeric User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnRandomNumericDatabase import OgnRandomNumericDatabase
test_file_name = "OgnRandomNumericTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_RandomNumeric")
database = OgnRandomNumericDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:isNoise"))
attribute = test_node.get_attribute("inputs:isNoise")
db_value = database.inputs.isNoise
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:useSeed"))
attribute = test_node.get_attribute("inputs:useSeed")
db_value = database.inputs.useSeed
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
self.assertTrue(test_node.get_attribute_exists("state:gen"))
attribute = test_node.get_attribute("state:gen")
db_value = database.state.gen
| 15,030 | Python | 43.602374 | 199 | 0.499135 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnGatherByPath.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
import os
class TestOgn(ogts.OmniGraphTestCase):
async def test_generated(self):
test_data = [{'inputs': [['inputs:primPaths', ['/Xform1', '/Xform2'], False], ['inputs:attributes', '_translate', False], ['inputs:allAttributes', False, False]], 'outputs': [['outputs:gatheredPaths', ['/Xform1', '/Xform2'], False], ['outputs:gatherId', 1, False]], 'setup': {'create_nodes': [['TestNode', 'omni.graph.nodes.GatherByPath']], 'create_prims': [['Empty', {}], ['Xform1', {'_translate': ['pointd[3]', [1, 2, 3]]}], ['Xform2', {'_translate': ['pointd[3]', [4, 5, 6]]}], ['XformTagged1', {'foo': ['token', ''], '_translate': ['pointd[3]', [1, 2, 3]]}], ['Tagged1', {'foo': ['token', '']}]]}}, {'inputs': [['inputs:primPaths', ['/XformTagged1', '/Xform2', '/Xform1'], False], ['inputs:attributes', '_translate', False], ['inputs:allAttributes', False, False]], 'outputs': [['outputs:gatheredPaths', ['/XformTagged1', '/Xform1', '/Xform2'], False]], 'setup': {}}]
test_node = None
test_graph = None
for i, test_run in enumerate(test_data):
inputs = test_run.get('inputs', [])
outputs = test_run.get('outputs', [])
state_set = test_run.get('state_set', [])
state_get = test_run.get('state_get', [])
setup = test_run.get('setup', None)
if setup is None or setup:
await omni.usd.get_context().new_stage_async()
test_graph = None
elif not setup:
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test")
if setup:
(test_graph, test_nodes, _, _) = og.Controller.edit("/TestGraph", setup)
self.assertTrue(test_nodes)
test_node = test_nodes[0]
elif setup is None:
if test_graph is None:
test_graph = og.Controller.create_graph("/TestGraph")
self.assertTrue(test_graph is not None and test_graph.is_valid())
test_node = og.Controller.create_node(
("TestNode_omni_graph_nodes_GatherByPath", test_graph), "omni.graph.nodes.GatherByPath"
)
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test graph invalid")
self.assertTrue(test_node is not None and test_node.is_valid(), "Test node invalid")
await og.Controller.evaluate(test_graph)
values_to_set = inputs + state_set
if values_to_set:
for attribute_name, attribute_value, _ in inputs + state_set:
og.Controller((attribute_name, test_node)).set(attribute_value)
await og.Controller.evaluate(test_graph)
for attribute_name, expected_value, _ in outputs + state_get:
attribute = og.Controller.attribute(attribute_name, test_node)
actual_output = og.Controller.get(attribute)
expected_type = None
if isinstance(expected_value, dict):
expected_type = expected_value["type"]
expected_value = expected_value["value"]
ogts.verify_values(expected_value, actual_output, f"omni.graph.nodes.GatherByPath User test case #{i+1}: {attribute_name} attribute value error")
if expected_type:
tp = og.AttributeType.type_from_ogn_type_name(expected_type)
actual_type = attribute.get_resolved_type()
if tp != actual_type:
raise ValueError(f"omni.graph.nodes.GatherByPath User tests - {attribute_name}: Expected {expected_type}, saw {actual_type.get_ogn_type_name()}")
async def test_data_access(self):
from omni.graph.nodes.ogn.OgnGatherByPathDatabase import OgnGatherByPathDatabase
test_file_name = "OgnGatherByPathTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_GatherByPath")
database = OgnGatherByPathDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:allAttributes"))
attribute = test_node.get_attribute("inputs:allAttributes")
db_value = database.inputs.allAttributes
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:attributes"))
attribute = test_node.get_attribute("inputs:attributes")
db_value = database.inputs.attributes
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:checkResyncAttributes"))
attribute = test_node.get_attribute("inputs:checkResyncAttributes")
db_value = database.inputs.checkResyncAttributes
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:forceExportToHistory"))
attribute = test_node.get_attribute("inputs:forceExportToHistory")
db_value = database.inputs.forceExportToHistory
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:hydraFastPath"))
attribute = test_node.get_attribute("inputs:hydraFastPath")
db_value = database.inputs.hydraFastPath
expected_value = "Disabled"
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:primPaths"))
attribute = test_node.get_attribute("inputs:primPaths")
db_value = database.inputs.primPaths
expected_value = []
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:shouldWriteBack"))
attribute = test_node.get_attribute("inputs:shouldWriteBack")
db_value = database.inputs.shouldWriteBack
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:gatherId"))
attribute = test_node.get_attribute("outputs:gatherId")
db_value = database.outputs.gatherId
self.assertTrue(test_node.get_attribute_exists("outputs:gatheredPaths"))
attribute = test_node.get_attribute("outputs:gatheredPaths")
db_value = database.outputs.gatheredPaths
| 8,500 | Python | 60.158273 | 879 | 0.639529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.