file_path
stringlengths
21
224
content
stringlengths
0
80.8M
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateToTarget.ogn
{ "RotateToTarget": { "version": 2, "description": [ "This node smoothly rotates a prim object to match a target prim object given a speed and easing factor. ", "At the end of the maneuver, the source prim will have the rotation as the target prim.\n", "Note: The Prim must have xform:orient in transform stack in order to interpolate rotations" ], "uiName": "Rotate To Target", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "sourcePrim": { "type": "target", "description": "The source prim to be transformed", "optional": true }, "useSourcePath": { "type": "bool", "default": false, "description": "When true, the 'sourcePrimPath' attribute is used, otherwise it will read the connection at the 'sourcePrim' attribute" }, "sourcePrimPath": { "type": "path", "description": "The source prim to be transformed, used when 'useSourcePath' is true", "optional": true }, "targetPrim": { "type": "target", "description": "The destination prim. The target's rotation will be matched by the sourcePrim", "optional": true }, "useTargetPath": { "type": "bool", "default": false, "description": "When true, the 'targetPrimPath' attribute is used, otherwise it will read the connection at the 'targetPrim' attribute" }, "targetPrimPath": { "type": "path", "description": "The destination prim. The target's rotation will be matched by the sourcePrim, used when 'useTargetPath' is true", "optional": true }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateToOrientation.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. // #include <OgnRotateToOrientationDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> #include "PrimCommon.h" #include "XformUtils.h" using namespace omni::math::linalg; namespace omni { namespace graph { namespace nodes { struct RotateMoveState: public XformUtils::MoveState { vec3d targetEuler; }; class OgnRotateToOrientation { public: RotateMoveState m_moveState; static bool compute(OgnRotateToOrientationDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnRotateToOrientation>(); double& startTime = state.m_moveState.startTime; pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName; quatd& startOrientation = state.m_moveState.startOrientation; vec3d& startEuler = state.m_moveState.startEuler; vec3d& targetEuler = state.m_moveState.targetEuler; XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = XformUtils::kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::primPath.token(), inputs::usePath.token(), db.getInstanceIndex()); if (primPath.IsEmpty()) return true; // First frame of the maneuver. if (startTime <= XformUtils::kUninitializedStartTime || now < startTime) { try { std::tie(startOrientation, targetAttribName) = XformUtils::extractPrimOrientOp(contextObj, primPath); if (not targetAttribName.IsEmpty()) rotationMode = XformUtils::RotationMode::eQuat; else { std::tie(startEuler, targetAttribName) = XformUtils::extractPrimEulerOp(contextObj, primPath); if (not targetAttribName.IsEmpty()) rotationMode = XformUtils::RotationMode::eEuler; } if (targetAttribName.IsEmpty()) throw std::runtime_error( formatString("Could not find suitable XformOp on %s, please add", primPath.GetText())); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } // Copy the target in case it changes during the movement targetEuler = db.inputs.target(); startTime = now; // Start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); try { if (rotationMode == XformUtils::RotationMode::eQuat) { quatd const& targetOrientation = eulerAnglesToQuaternion(GfDegreesToRadians(targetEuler), EulerRotationOrder::XYZ); auto const quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized(); // Write back to the prim trySetPrimAttribute( contextObj, nodeObj, primPath, targetAttribName.GetText(), quat); } else if (rotationMode == XformUtils::RotationMode::eEuler) { vec3d rot = lerp(startEuler, targetEuler, alpha2); // Write back to the prim trySetPrimAttribute( contextObj, nodeObj, primPath, targetAttribName.GetText(), rot); } } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } if (alpha2 < 1) { // still waiting, output is disabled db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = XformUtils::kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return true; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMoveToTransform.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. // #include <OgnMoveToTransformDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/math.h> #include <omni/math/linalg/SafeCast.h> #include <cmath> #include "PrimCommon.h" #include "XformUtils.h" using namespace omni::math::linalg; namespace omni { namespace graph { namespace nodes { namespace { constexpr double kUninitializedStartTime = -1.; } struct MoveMoveState : public XformUtils::MoveState { matrix4d targetTransform; }; class OgnMoveToTransform { public: MoveMoveState m_moveState; static bool compute(OgnMoveToTransformDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnMoveToTransform>(); double& startTime = state.m_moveState.startTime; pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName; quatd& startOrientation = state.m_moveState.startOrientation; vec3d& startTranslation = state.m_moveState.startTranslation; matrix4d& targetTransform = state.m_moveState.targetTransform; vec3d& startScale = state.m_moveState.startScale; XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::primPath.token(), inputs::usePath.token(), db.getInstanceIndex()); if (primPath.IsEmpty()) return true; // First frame of the maneuver. if (startTime <= kUninitializedStartTime || now < startTime) { try { std::tie(startOrientation, targetAttribName) = XformUtils::extractPrimOrientOp(contextObj, primPath); if (targetAttribName.IsEmpty()) throw std::runtime_error("MoveToTransform requires the source Prim to have xformOp:orient, please add"); rotationMode = XformUtils::RotationMode::eQuat; startTranslation = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr); startScale = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::ScaleAttrStr); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } startTime = now; targetTransform = db.inputs.target(); // Start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); try { if (rotationMode == XformUtils::RotationMode::eQuat) { quatd targetOrientation = extractRotationQuatd(targetTransform).GetNormalized(); quatd quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized(); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, primPath, targetAttribName.GetText(), quat); } vec3d targetTranslation = targetTransform.ExtractTranslation(); vec3d targetScale{ targetTransform.GetRow(0).GetLength(), targetTransform.GetRow(1).GetLength(), targetTransform.GetRow(2).GetLength() }; vec3d translation = GfLerp(alpha2, startTranslation, targetTranslation); vec3d scale = GfLerp(alpha2, startScale, targetScale); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr, translation); trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::ScaleAttrStr, scale); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } if (alpha2 < 1) { // still waiting, output is disabled db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return false; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Rotation.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. // #include <OgnSetMatrix4RotationDatabase.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <cmath> using omni::math::linalg::matrix4d; using omni::math::linalg::quatd; using omni::math::linalg::vec3d; namespace omni { namespace graph { namespace nodes { namespace { void updateMatrix(const double input[16], double result[16], vec3d axis, double angle) { matrix4d& resultMat = *reinterpret_cast<matrix4d*>(result); memcpy(resultMat.data(), input, sizeof(double) * 16); axis.Normalize(); // 0.5 is because quaternions cover the space of rotations twice angle = 0.5f * omni::math::linalg::GfDegreesToRadians(angle); double c = std::cos(angle); double s = std::sin(angle); resultMat.SetRotateOnly(quatd(c, s * axis)); } } class OgnSetMatrix4Rotation { public: static bool compute(OgnSetMatrix4RotationDatabase& db) { vec3d axis(0); const auto& fixedRotationAxis = db.inputs.fixedRotationAxis(); if (fixedRotationAxis == db.tokens.X) { axis[0] = 1; } else if (fixedRotationAxis == db.tokens.Z) { axis[2] = 1; } else if (fixedRotationAxis == db.tokens.Y || fixedRotationAxis == omni::fabric::kUninitializedToken) { axis[1] = 1; } else { db.logError("fixedRotationAxis must be one of X,Y,Z"); return false; } const auto& matrixInput = db.inputs.matrix(); const auto& rotationAngleInput = db.inputs.rotationAngle(); auto matrixOutput = db.outputs.matrix(); bool failed = true; // Singular case if (auto matrix = matrixInput.get<double[16]>()) { if (auto rotationAngle = rotationAngleInput.get<double>()) { if (auto output = matrixOutput.get<double[16]>()) { updateMatrix(*matrix, *output, axis, *rotationAngle); failed = false; } } } // Array case else if (auto matrices = matrixInput.get<double[][16]>()) { if (auto rotationAngles = rotationAngleInput.get<double[]>()) { if (auto output = matrixOutput.get<double[][16]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { updateMatrix((*matrices)[i], (*output)[i], axis, (*rotationAngles)[i]); } failed = false; } } } else { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, rotation angles input with depth %s, and output with depth %s", matrixInput.type().arrayDepth, rotationAngleInput.type().arrayDepth, matrixOutput.type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node){ // Resolve fully-coupled types for the 2 attributes std::array<AttributeObj, 2> attrs { node.iNode->getAttribute(node, OgnSetMatrix4RotationAttributes::inputs::matrix.m_name), node.iNode->getAttribute(node, OgnSetMatrix4RotationAttributes::outputs::matrix.m_name) }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Quaternion.ogn
{ "GetMatrix4Quaternion": { "version": 1, "description": [ "Gets the rotation of the given matrix4d value which represents a linear transformation.", "Returns a quaternion" ], "uiName": "Get Rotation Quaternion", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The transformation matrix" } }, "outputs": { "quaternion": { "type": ["quatd[4]", "quatd[4][]"], "description": "quaternion representing the orientation of the matrix transformation" } }, "tests" : [ { "inputs:matrix": {"type":"matrixd[4]", "value":[1,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1]}, "outputs:quaternion": {"type":"quatd[4]", "value": [0.38268481, 0, 0, 0.9238804]} }, { "inputs:matrix": {"type":"matrixd[4][]", "value": [[1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1], [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 100,0,0,1]] }, "outputs:quaternion": {"type":"quatd[4][]", "value": [[0.38268481, 0, 0, 0.9238804], [0.38268481, 0, 0, 0.9238804]] } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Translation.ogn
{ "SetMatrix4Translation": { "version": 1, "description": [ "Sets the translation of the given matrix4d value which represents a linear transformation.", "Does not modify the orientation (row 0-2) of the matrix." ], "uiName": "Set Translation", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The matrix to be modified" }, "translation": { "type": ["vectord[3]", "vectord[3][]"], "uiName": "Translation", "description": [ "The translation that the matrix will apply" ] } }, "outputs": { "matrix": { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The updated matrix" } }, "tests" : [ { "inputs": { "matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]}, "translation": {"type": "vectord[3]", "value":[1, 2, 3]}}, "outputs:matrix": {"type":"matrixd[4]", "value":[1,0,0,0, 0,1,0,0, 10,10,1,0, 1,2,3,1]} }, { "inputs": { "matrix": {"type":"matrixd[4][]", "value":[ [1.0,10,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1], [1.0,15,0,0, 0,1,0,0, 0,0,1,0, 100,0,0,1]] }, "translation": {"type": "vectord[3][]", "value": [[45, 10, 10], [3, 2, 1]]}}, "outputs:matrix": {"type":"matrixd[4][]", "value" : [ [1.0,10,0,0, 0,1,0,0, 0,0,1,0, 45,10,10,1], [1.0,15,0,0, 0,1,0,0, 0,0,1,0, 3,2,1,1]]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetPrimDirectionVector.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 <OgnGetPrimDirectionVectorDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/SafeCast.h> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/usdGeom/xformCache.h> #include <omni/graph/core/PostUsdInclude.h> #include "PrimCommon.h" #include "XformUtils.h" using namespace omni::math::linalg; namespace omni { namespace graph { namespace nodes { class OgnGetPrimDirectionVector { public: static bool compute(OgnGetPrimDirectionVectorDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; try { // Retrieve the prim path string in one of two ways bool usePath = db.inputs.usePath(); std::string primPathStr; if (usePath) { // Use the absolute path NameToken primPath = db.inputs.primPath(); primPathStr = db.tokenToString(primPath); if (primPathStr.empty()) { db.logWarning("No prim path specified"); return false; } } else { // Read the path from the relationship input on this compute node auto primPath = getRelationshipPrimPath( contextObj, nodeObj, OgnGetPrimDirectionVectorAttributes::inputs::prim.m_token, db.getInstanceIndex()); primPathStr = primPath.GetText(); } // Retrieve a reference to the prim pxr::UsdPrim prim = getPrim(contextObj, pxr::SdfPath(primPathStr)); // Extract the rotation from the local to world transformation matrix pxr::UsdGeomXformCache xformCache; matrix4d localWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(prim)); quatd rotation = extractRotationQuatd(localWorldTransform).GetNormalized(); // Apply the rotation to (0,1,0) to get the up vector vec3<double> upVector = rotation.Transform(vec3<double>::YAxis()); db.outputs.upVector() = upVector; db.outputs.downVector() = -upVector; // Apply the rotation to (0,0,-1) to get the forward vector vec3<double> forwardVector = rotation.Transform(-vec3<double>::ZAxis()); db.outputs.forwardVector() = forwardVector; db.outputs.backwardVector() = -forwardVector; // Apply the rotation to (1,0,0) to get the right vector vec3<double> rightVector = rotation.Transform(vec3<double>::XAxis()); db.outputs.rightVector() = rightVector; db.outputs.leftVector() = -rightVector; return true; } catch(const std::exception& e) { db.logError(e.what()); return false; } } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMakeTransform.ogn
{ "MakeTransform": { "version": 1, "description": "Make a transformation matrix that performs a translation, rotation (in euler angles), and scale in that order", "uiName": "Make Transformation Matrix from TRS", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "translation": { "type": "vectord[3]", "description": "the desired translation as a vector", "default": [0, 0, 0] }, "rotationXYZ": { "type": "vectord[3]", "description": "The desired orientation in euler angles (XYZ)", "default": [0, 0, 0] }, "scale": { "type": "vectord[3]", "description": "The desired scaling factor about the X, Y, and Z axis respectively", "default": [1, 1, 1] } }, "outputs": { "transform": { "type": "matrixd[4]", "description": "the resulting transformation matrix" } }, "tests": [ { "inputs:rotationXYZ": [0, 0, 0], "inputs:translation": [0, 0, 0], "outputs:transform": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] }, { "inputs:rotationXYZ": [0, 0, 0], "inputs:translation": [1, 2, 3], "outputs:transform": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1] }, { "inputs:rotationXYZ": [20, 0, 30], "inputs:translation": [1, -2, 3], "outputs:transform": [ 8.66025404e-01, 5.00000000e-01, 4.16333634e-17, 0.00000000e+00, -4.69846310e-01, 8.13797681e-01, 3.42020143e-01, 0.00000000e+00, 1.71010072e-01,-2.96198133e-01, 9.39692621e-01, 0.00000000e+00, 1.00000000e+00,-2.00000000e+00, 3.00000000e+00, 1.00000000e+00] }, { "inputs:scale": [10, 5, 2], "outputs:transform": [10, 0, 0, 0, 0, 5, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1] }, { "inputs:translation": [1, -2, 3], "inputs:rotationXYZ": [20, 0, 30], "inputs:scale": [10, 5, 2], "outputs:transform": [ 8.66025404e+00, 5.00000000e+00, 0.00000000e+00, 0.00000000e+00, -2.34923155e+00, 4.06898841e+00, 1.71010072e+00, 0.00000000e+00, 3.42020140e-01,-5.92396270e-01, 1.87938524e+00, 0.00000000e+00, 1.00000000e+00,-2.00000000e+00, 3.00000000e+00, 1.00000000e+00] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Translation.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. // #include <OgnGetMatrix4TranslationDatabase.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> using omni::math::linalg::matrix4d; using omni::math::linalg::vec3d; namespace omni { namespace graph { namespace nodes { namespace { void getTranslation(const double input[16], double result[4]) { vec3d translation = reinterpret_cast<const matrix4d*>(input)->ExtractTranslation(); memcpy(result, translation.data(), sizeof(double) * 3); } } class OgnGetMatrix4Translation { public: static bool computeVectorized(OgnGetMatrix4TranslationDatabase& db, size_t count) { const auto& matrixInput = db.inputs.matrix(); bool inOk = false; bool failed = true; // Singular case if (matrixInput.type().arrayDepth == 0) { if (auto matrix = matrixInput.get<double[16]>()) { inOk = true; auto translationOutput = db.outputs.translation(); if (auto output = translationOutput.get<double[3]>()) { auto matrices = matrix.vectorized(count); auto outputs = output.vectorized(count); for (size_t i = 0; i < count; ++i) getTranslation(matrices[i], outputs[i]); failed = false; } } } // Array case else { for (size_t inst = 0; inst < count; ++inst) { if (auto matrices = db.inputs.matrix(inst).get<double[][16]>()) { inOk = true; if (auto output = db.outputs.translation(inst).get<double[][3]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { getTranslation((*matrices)[i], (*output)[i]); } failed = false; } } } } if (!inOk) { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, output with depth %s", matrixInput.type().arrayDepth, db.outputs.translation().type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node) { auto start = node.iNode->getAttribute(node, OgnGetMatrix4TranslationAttributes::inputs::matrix.m_name); auto result = node.iNode->getAttribute(node, OgnGetMatrix4TranslationAttributes::outputs::translation.m_name); auto startType = start.iAttribute->getResolvedType(start); std::array<AttributeObj, 2> attrs { start, result }; std::array<uint8_t, 2> tupleCounts { 16, 3 }; std::array<uint8_t, 2> arrayDepths { startType.arrayDepth, startType.arrayDepth }; std::array<AttributeRole, 2> rolesBuf { AttributeRole::eNone, AttributeRole::eVector }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Rotation.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. // #include <OgnGetMatrix4RotationDatabase.h> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/base/gf/rotation.h> #include <omni/graph/core/PostUsdInclude.h> namespace omni { namespace graph { namespace nodes { namespace { void getRotation(const double input[16], double result[3]) { pxr::GfVec3d rotation = reinterpret_cast<const pxr::GfMatrix4d*>(input)->DecomposeRotation(pxr::GfVec3d::XAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::ZAxis()); memcpy(result, rotation.data(), sizeof(double) * 3); } } class OgnGetMatrix4Rotation { public: static bool compute(OgnGetMatrix4RotationDatabase& db) { const auto& matrixInput = db.inputs.matrix(); auto rotationOutput = db.outputs.rotation(); bool failed = true; // Singular case if (auto matrix = matrixInput.get<double[16]>()) { if (auto output = rotationOutput.get<double[3]>()) { getRotation(*matrix, *output); failed = false; } } // Array case else if (auto matrices = matrixInput.get<double[][16]>()) { if (auto output = rotationOutput.get<double[][3]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { getRotation((*matrices)[i], (*output)[i]); } failed = false; } } else { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, output with depth %s", matrixInput.type().arrayDepth, rotationOutput.type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node) { auto start = node.iNode->getAttribute(node, OgnGetMatrix4RotationAttributes::inputs::matrix.m_name); auto result = node.iNode->getAttribute(node, OgnGetMatrix4RotationAttributes::outputs::rotation.m_name); auto startType = start.iAttribute->getResolvedType(start); std::array<AttributeObj, 2> attrs { start, result }; std::array<uint8_t, 2> tupleCounts { 16, 3 }; std::array<uint8_t, 2> arrayDepths { startType.arrayDepth, startType.arrayDepth }; std::array<AttributeRole, 2> rolesBuf { AttributeRole::eNone, AttributeRole::eVector }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMakeTransform.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. // #include <OgnMakeTransformDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/matrix.h> using omni::math::linalg::quatd; using omni::math::linalg::matrix4d; namespace omni { namespace graph { namespace nodes { class OgnMakeTransform { public: static bool compute(OgnMakeTransformDatabase& db) { auto& translation = db.inputs.translation(); auto& orientation = db.inputs.rotationXYZ(); auto& scale = db.inputs.scale(); const quatd q = omni::math::linalg::eulerAnglesToQuaternion(GfDegreesToRadians(orientation), omni::math::linalg::EulerRotationOrder::XYZ).GetNormalized(); db.outputs.transform() = matrix4d().SetScale(scale) * matrix4d().SetRotate(q) * matrix4d().SetTranslate(translation); return true; } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Rotation.ogn
{ "GetMatrix4Rotation": { "version": 1, "description": [ "Gets the rotation of the given matrix4d value which represents a linear transformation.", "Returns euler angles (XYZ)" ], "uiName": "Get Rotation", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The transformation matrix" } }, "outputs": { "rotation": { "type": ["vectord[3]", "vectord[3][]"], "description": "vector representing the rotation component of the transformation (XYZ)" } }, "tests" : [ { "inputs:matrix": {"type":"matrixd[4]", "value":[1,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1]}, "outputs:rotation": {"type":"vectord[3]", "value": [45, 0, 0]} }, { "inputs:matrix": {"type":"matrixd[4][]", "value": [[1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1], [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 100,0,0,1]] }, "outputs:rotation": {"type":"vectord[3][]", "value": [[45, 0, 0], [45, 0, 0]] } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateVector.ogn
{ "RotateVector": { "version": 1, "description": [ "Rotates a 3d direction vector by a specified rotation.", "Accepts 3x3 matrices, 4x4 matrices, euler angles (XYZ), or quaternions", "For 4x4 matrices, the transformation information in the matrix is ignored and the vector is treated as ", "a 4-component vector where the fourth component is zero. The result is then projected back to a 3-vector. ", "Supports mixed array inputs, eg a single quaternion and an array of vectors." ], "uiName": "Rotate Vector", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "rotation" : { "type": ["matrixd[4]", "matrixd[4][]", "matrixd[3]", "matrixd[3][]", "vectord[3]", "vectord[3][]", "vectorf[3]", "vectorf[3][]", "vectorh[3]", "vectorh[3][]", "quatd[4]", "quatd[4][]", "quatf[4]", "quatf[4][]", "quath[4]", "quath[4][]"], "uiName": "Rotation", "description": "The rotation to be applied" }, "vector": { "type": ["vectord[3]", "vectord[3][]", "vectorf[3]", "vectorf[3][]", "vectorh[3]", "vectorh[3][]"], "uiName": "Vector", "description": "The row vector(s) to be rotated" } }, "outputs": { "result": { "type": ["vectord[3]", "vectord[3][]", "vectorf[3]", "vectorf[3][]", "vectorh[3]", "vectorh[3][]"], "uiName": "Result", "description": "The transformed row vector(s)" } }, "tests" : [ { "inputs": { "rotation": {"type":"matrixd[4]", "value":[1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]}, "vector": {"type": "vectord[3]", "value":[1, 2, 3]}}, "outputs:result": {"type":"vectord[3]", "value":[31, 32, 3]} }, { "inputs": { "rotation": {"type":"matrixd[3]", "value":[1,0,0, 0,0,1, 0,-1,0]}, "vector": {"type": "vectorf[3]", "value":[0, 0, 1]}}, "outputs:result": {"type":"vectorf[3]", "value":[0, -1, 0]} }, { "inputs": { "rotation": {"type":"vectord[3]", "value":[90, 0, 0]}, "vector": {"type": "vectord[3]", "value":[0, 0, 1]}}, "outputs:result": {"type":"vectord[3]", "value":[0, -1, 0]} }, { "inputs": { "rotation": {"type":"quatf[4]", "value":[0.7071068, 0, 0, 0.7071068]}, "vector": {"type": "vectorf[3]", "value":[0, 0, 1]}}, "outputs:result": {"type":"vectorf[3]", "value":[0, -1, 0]} }, { "inputs": { "rotation": {"type":"vectorf[3][]", "value":[[0, 90, 0], [90, 0, 0], [90, 90, 0]]}, "vector": {"type": "vectorf[3]", "value": [0, 0, 1]}}, "outputs:result": {"type":"vectorf[3][]", "value" : [[1, 0, 0], [0, -1, 0], [0, -1, 0]]} }, { "inputs": { "rotation": {"type":"vectord[3]", "value":[90, 90, 0]}, "vector": {"type": "vectord[3][]", "value": [[0, 0, 1], [0, 1, 0], [1, 0, 0]]}}, "outputs:result": {"type":"vectord[3][]", "value" : [[0, -1, 0], [1, 0, 0], [0, 0, -1]]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTranslateToTarget.ogn
{ "TranslateToTarget": { "version": 2, "description": [ "This node smoothly translates a prim object to a target prim object given a speed and easing factor. ", "At the end of the maneuver, the source prim will have the same translation as the target prim" ], "uiName": "Translate To Target", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "sourcePrim": { "type": "target", "description": "The source prim to be transformed", "optional": true }, "useSourcePath": { "type": "bool", "default": false, "description": "When true, the 'sourcePrimPath' attribute is used, otherwise it will read the connection at the 'sourcePrim' attribute" }, "sourcePrimPath": { "type": "path", "description": "The source prim to be transformed, used when 'useSourcePath' is true", "optional": true }, "targetPrim": { "type": "bundle", "description": "The destination prim. The target's translation will be matched by the sourcePrim", "optional": true }, "useTargetPath": { "type": "bool", "default": false, "description": "When true, the 'targetPrimPath' attribute is used, otherwise it will read the connection at the 'targetPrim' attribute" }, "targetPrimPath": { "type": "path", "description": "The destination prim. The target's translation will be matched by the sourcePrim, used when 'useTargetPath' is true", "optional": true }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Translation.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. // #include <OgnSetMatrix4TranslationDatabase.h> #include <omni/math/linalg/matrix.h> using omni::math::linalg::matrix4d; namespace omni { namespace graph { namespace nodes { namespace { void updateMatrix(const double input[16], double result[16], const double translation[3]) { matrix4d& resultMat = *reinterpret_cast<matrix4d*>(result); memcpy(resultMat.data(), input, sizeof(double) * 16); resultMat.SetTranslateOnly({translation[0], translation[1], translation[2]}); } } class OgnSetMatrix4Translation { public: static bool compute(OgnSetMatrix4TranslationDatabase& db) { const auto& matrixInput = db.inputs.matrix(); const auto& translationInput = db.inputs.translation(); auto matrixOutput = db.outputs.matrix(); bool failed = true; // Singular case if (auto matrix = matrixInput.get<double[16]>()) { if (auto translation = translationInput.get<double[3]>()) { if (auto output = matrixOutput.get<double[16]>()) { updateMatrix(*matrix, *output, *translation); failed = false; } } } // Array case else if (auto matrices = matrixInput.get<double[][16]>()) { if (auto translations = translationInput.get<double[][3]>()) { if (auto output = matrixOutput.get<double[][16]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { updateMatrix((*matrices)[i], (*output)[i], (*translations)[i]); } failed = false; } } } else { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, translation input with depth %s, and output with depth %s", matrixInput.type().arrayDepth, translationInput.type().arrayDepth, matrixOutput.type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node){ // Resolve fully-coupled types for the 2 attributes std::array<AttributeObj, 2> attrs { node.iNode->getAttribute(node, OgnSetMatrix4TranslationAttributes::inputs::matrix.m_name), node.iNode->getAttribute(node, OgnSetMatrix4TranslationAttributes::outputs::matrix.m_name) }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Quaternion.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. // #include <OgnGetMatrix4QuaternionDatabase.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/quat.h> #include "XformUtils.h" using omni::math::linalg::matrix4d; using omni::math::linalg::quatd; namespace omni { namespace graph { namespace nodes { namespace { void getQuaternion(const double input[16], double result[4]) { quatd quat = extractRotationQuatd(*reinterpret_cast<const matrix4d*>(input)); // In fabric, quaternions are stored as (XYZW). Note the quatd constructor uses (WXYZ)s memcpy(&result[0], quat.GetImaginary().data(), sizeof(double) * 3); result[3] = quat.GetReal(); } } class OgnGetMatrix4Quaternion { public: static bool compute(OgnGetMatrix4QuaternionDatabase& db) { const auto& matrixInput = db.inputs.matrix(); auto quaternionOutput = db.outputs.quaternion(); bool failed = true; // Singular case if (auto matrix = matrixInput.get<double[16]>()) { if (auto output = quaternionOutput.get<double[4]>()) { getQuaternion(*matrix, *output); failed = false; } } // Array case else if (auto matrices = matrixInput.get<double[][16]>()) { if (auto output = quaternionOutput.get<double[][4]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { getQuaternion((*matrices)[i], (*output)[i]); } failed = false; } } else { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, output with depth %s", matrixInput.type().arrayDepth, quaternionOutput.type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node) { auto start = node.iNode->getAttribute(node, OgnGetMatrix4QuaternionAttributes::inputs::matrix.m_name); auto result = node.iNode->getAttribute(node, OgnGetMatrix4QuaternionAttributes::outputs::quaternion.m_name); auto startType = start.iAttribute->getResolvedType(start); std::array<AttributeObj, 2> attrs { start, result }; std::array<uint8_t, 2> tupleCounts { 16, 4 }; std::array<uint8_t, 2> arrayDepths { startType.arrayDepth, startType.arrayDepth }; std::array<AttributeRole, 2> rolesBuf { AttributeRole::eNone, AttributeRole::eQuaternion }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Rotation.ogn
{ "SetMatrix4Rotation": { "version": 1, "description": [ "Sets the rotation of the given matrix4d value which represents a linear transformation.", "Does not modify the translation (row 3) of the matrix." ], "uiName": "Set Rotation", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The matrix to be modified" }, "fixedRotationAxis": { "type": "token", "description": ["The axis of the given rotation"], "default": "Y", "metadata": { "allowedTokens": ["X", "Y", "Z"] } }, "rotationAngle": { "type": ["double", "double[]"], "uiName": "Rotation", "description": [ "The rotation in degrees that the matrix will apply about the given rotationAxis." ] } }, "outputs": { "matrix": { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The updated matrix" } }, "tests" : [ { "inputs": { "matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1]}, "fixedRotationAxis": "X", "rotationAngle": {"type": "double", "value":45}}, "outputs:matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1]} }, { "inputs": { "matrix": {"type":"matrixd[4][]", "value":[ [1.0,0,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1], [1.0,0,0,0, 0,1,0,0, 0,0,1,0, 100,0,0,1]] }, "fixedRotationAxis": "X", "rotationAngle": {"type": "double[]", "value": [45, 45]}}, "outputs:matrix": {"type":"matrixd[4][]", "value":[ [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1], [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 100,0,0,1] ]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateVector.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. // #include <OgnRotateVectorDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/quat.h> using omni::math::linalg::matrix4d; using omni::math::linalg::matrix3d; using omni::math::linalg::vec3; using omni::math::linalg::quat; using ogn::compute::tryComputeWithArrayBroadcasting; namespace omni { namespace graph { namespace nodes { namespace { template<typename T> bool tryComputeWithMatrix3(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto& matrix = *reinterpret_cast<const matrix3d*>(rotation); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<T>*>(result); // left multiplication by row vector resultVec = vec3<T>(sourceVec * matrix); }; return tryComputeWithArrayBroadcasting<double[9], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } template<typename T> bool tryComputeWithMatrix4(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto& matrix = *reinterpret_cast<const matrix4d*>(rotation); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<T>*>(result); resultVec = vec3<T>(matrix.TransformDir(sourceVec)); }; return tryComputeWithArrayBroadcasting<double[16], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } template<typename T> bool tryComputeWithQuat(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto& quaternion = *reinterpret_cast<const quat<T>*>(rotation); auto& sourceVec = *reinterpret_cast<const vec3<T>*>(vector); auto& resultVec = *reinterpret_cast<vec3<T>*>(result); resultVec = quaternion.Transform(sourceVec); }; return tryComputeWithArrayBroadcasting<T[4], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } template<typename T> bool tryComputeWithEulerAngles(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto eulerAngles = vec3<double>(*reinterpret_cast<const vec3<T>*>(rotation)); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<T>*>(result); auto quaternion = omni::math::linalg::eulerAnglesToQuaternion(GfDegreesToRadians(eulerAngles), omni::math::linalg::EulerRotationOrder::XYZ); resultVec = vec3<T>(quaternion.Transform(sourceVec)); }; return tryComputeWithArrayBroadcasting<T[3], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } /* FIXME: GfHalf has no explicit conversion from double to half, so we need to convert to a float first */ template<> bool tryComputeWithMatrix3<pxr::GfHalf>(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto& matrix = *reinterpret_cast<const matrix3d*>(rotation); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result); // left multiplication by row vector resultVec = vec3<pxr::GfHalf>(vec3<float>(sourceVec * matrix)); }; return tryComputeWithArrayBroadcasting<double[9], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } template<> bool tryComputeWithMatrix4<pxr::GfHalf>(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto& matrix = *reinterpret_cast<const matrix4d*>(rotation); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result); resultVec = vec3<pxr::GfHalf>(vec3<float>(matrix.TransformDir(sourceVec))); }; return tryComputeWithArrayBroadcasting<double[16], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } template<> bool tryComputeWithEulerAngles<pxr::GfHalf>(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto eulerAngles = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(rotation)); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result); auto quaternion = omni::math::linalg::eulerAnglesToQuaternion(GfDegreesToRadians(eulerAngles), omni::math::linalg::EulerRotationOrder::XYZ); resultVec = vec3<pxr::GfHalf>(vec3<float>(quaternion.Transform(sourceVec))); }; return tryComputeWithArrayBroadcasting<pxr::GfHalf[3], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } } // namespace class OgnRotateVector { public: static bool compute(OgnRotateVectorDatabase& db) { try { // matrix3 if (tryComputeWithMatrix3<double>(db)) return true; else if (tryComputeWithMatrix3<float>(db)) return true; else if (tryComputeWithMatrix3<pxr::GfHalf>(db)) return true; // matrix4 else if (tryComputeWithMatrix4<double>(db)) return true; else if (tryComputeWithMatrix4<float>(db)) return true; else if (tryComputeWithMatrix4<pxr::GfHalf>(db)) return true; // quat else if (tryComputeWithQuat<double>(db)) return true; else if (tryComputeWithQuat<float>(db)) return true; else if (tryComputeWithQuat<pxr::GfHalf>(db)) return true; // euler angles else if (tryComputeWithEulerAngles<double>(db)) return true; else if (tryComputeWithEulerAngles<float>(db)) return true; else if (tryComputeWithEulerAngles<pxr::GfHalf>(db)) return true; else { db.logWarning("OgnRotateVector: Failed to resolve input types"); } } catch (ogn::compute::InputError &error) { db.logWarning("OgnRotateVector: %s", error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node) { auto vector = node.iNode->getAttributeByToken(node, inputs::vector.token()); auto rotation = node.iNode->getAttributeByToken(node, inputs::rotation.token()); auto result = node.iNode->getAttributeByToken(node, outputs::result.token()); auto vectorType = vector.iAttribute->getResolvedType(vector); auto rotationType = rotation.iAttribute->getResolvedType(rotation); // Require vector, rotation to be resolved before determining result's type if (vectorType.baseType != BaseDataType::eUnknown && rotationType.baseType != BaseDataType::eUnknown) { Type resultType(vectorType.baseType, vectorType.componentCount, std::max(vectorType.arrayDepth, rotationType.arrayDepth), vectorType.role); result.iAttribute->setResolvedType(result, resultType); } } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMakeTransformLookAt.ogn
{ "MakeTransformLookAt": { "version": 1, "description": [ "Make a transformation matrix from eye, center world-space position and an up vector.", "Forward vector is negative Z direction computed from eye-center and normalized.", "Up is positive Y direction. Right is the positive X direction." ], "uiName": "Make Transformation Matrix Look At", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "eye": { "type": "vectord[3]", "description": "The desired look at position in world-space", "default": [1, 0, 0] }, "center": { "type": "vectord[3]", "description": "The desired center position in world-space", "default": [0, 0, 0] }, "up": { "type": "vectord[3]", "description": "The desired up vector", "default": [0, 1, 0] } }, "outputs": { "transform": { "type": "matrixd[4]", "description": "The resulting transformation matrix" } }, "tests": [ { "inputs:eye": [1, 0, 0], "inputs:center": [0, 0, 1], "inputs:up": [0, 1, 0], "outputs:transform": [ 0.70710678, 0, -0.70710678, 0, 0, 1, 0, 0, 0.70710678, 0, 0.70710678, 0, -0.70710678, 0, -0.70710678, 1 ] }, { "inputs:eye": [1, 0, 0], "inputs:center": [0, 0, 0], "inputs:up": [0, 1, 0], "outputs:transform": [ 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 ] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMoveToTarget.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. // #include <OgnMoveToTargetDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/math.h> #include <omni/math/linalg/SafeCast.h> #include <cmath> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/usdGeom/xformCache.h> #include <omni/graph/core/PostUsdInclude.h> #include "PrimCommon.h" #include "XformUtils.h" using namespace omni::math::linalg; namespace omni { namespace graph { namespace nodes { class OgnMoveToTarget { XformUtils::MoveState m_moveState; public: static bool compute(OgnMoveToTargetDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnMoveToTarget>(); double& startTime = state.m_moveState.startTime; pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName; vec3d& startTranslation = state.m_moveState.startTranslation; quatd& startOrientation = state.m_moveState.startOrientation; vec3d& startEuler = state.m_moveState.startEuler; vec3d& startScale = state.m_moveState.startScale; XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = XformUtils::kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto sourcePrimPath = getPrimOrPath(contextObj, nodeObj, inputs::sourcePrim.token(), inputs::sourcePrimPath.token(), inputs::useSourcePath.token(), db.getInstanceIndex()); auto destPrimPath = getPrimOrPath(contextObj, nodeObj, inputs::targetPrim.token(), inputs::targetPrimPath.token(), inputs::useTargetPath.token(), db.getInstanceIndex()); if (sourcePrimPath.IsEmpty() || destPrimPath.IsEmpty()) return true; pxr::UsdPrim sourcePrim = getPrim(contextObj, sourcePrimPath); pxr::UsdPrim targetPrim = getPrim(contextObj, destPrimPath); pxr::UsdGeomXformCache xformCache; if (not sourcePrim or not targetPrim) { throw std::runtime_error("Could not find source or target prim"); } matrix4d destWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(targetPrim)); matrix4d sourceParentTransform = safeCastToOmni(xformCache.GetParentToWorldTransform(sourcePrim)); quatd destWorldOrient = extractRotationQuatd(destWorldTransform).GetNormalized(); quatd sourceParentWorldOrient = extractRotationQuatd(sourceParentTransform).GetNormalized(); bool hasRotations = (destWorldOrient != quatd::GetIdentity()) or (sourceParentWorldOrient != quatd::GetIdentity()); // First frame of the maneuver. if (startTime <= XformUtils::kUninitializedStartTime || now < startTime) { std::tie(startOrientation, targetAttribName) = XformUtils::extractPrimOrientOp(contextObj, sourcePrimPath); if (targetAttribName.IsEmpty()) { if (hasRotations) throw std::runtime_error("MoveToTarget requires the source Prim to have xformOp:orient" " when the destination Prim or source Prim parent has rotation, please Add"); std::tie(startEuler, targetAttribName) = XformUtils::extractPrimEulerOp(contextObj, sourcePrimPath); if (not targetAttribName.IsEmpty()) rotationMode = XformUtils::RotationMode::eEuler; } else rotationMode = XformUtils::RotationMode::eQuat; if (targetAttribName.IsEmpty()) throw std::runtime_error( formatString("Could not find suitable XformOp on %s, please add", sourcePrimPath.GetText())); startTranslation = tryGetPrimVec3dAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr); startScale = tryGetPrimVec3dAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::ScaleAttrStr); startTime = now; // Start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); // Convert dest prim transform to the source's parent frame matrix4d destLocalTransform = destWorldTransform / sourceParentTransform; if (rotationMode == XformUtils::RotationMode::eQuat) { quatd targetOrientation = extractRotationQuatd(destLocalTransform).GetNormalized(); auto quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized(); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, targetAttribName.GetText(), quat); } else if (rotationMode == XformUtils::RotationMode::eEuler) { // FIXME: We previously checked that there is no rotation on the target, so we just have to interpolate // to identity. vec3d const targetRot{}; auto rot = GfLerp(alpha2, startEuler, targetRot); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, targetAttribName.GetText(), rot); } vec3d targetTranslation = destLocalTransform.ExtractTranslation(); vec3d targetScale{destLocalTransform.GetRow(0).GetLength(), destLocalTransform.GetRow(1).GetLength(), destLocalTransform.GetRow(2).GetLength()}; vec3d translation = GfLerp(alpha2, startTranslation, targetTranslation); vec3d scale = GfLerp(alpha2, startScale, targetScale); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr, translation); trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::ScaleAttrStr, scale); if (alpha2 < 1) { // still waiting, output is disabled db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = XformUtils::kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return false; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnScaleToSize.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. // #include <OgnScaleToSizeDatabase.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/math.h> #include "PrimCommon.h" #include "XformUtils.h" using omni::math::linalg::vec3d; using omni::math::linalg::GfLerp; namespace omni { namespace graph { namespace nodes { namespace { constexpr double kUninitializedStartTime = -1.; } struct ScaleMoveState : public XformUtils::MoveState { vec3d targetScale; }; class OgnScaleToSize { ScaleMoveState m_moveState; public: static bool compute(OgnScaleToSizeDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnScaleToSize>(); double& startTime = state.m_moveState.startTime; vec3d& startScale = state.m_moveState.startScale; vec3d& targetScale = state.m_moveState.targetScale; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::primPath.token(), inputs::usePath.token(), db.getInstanceIndex()); if (primPath.IsEmpty()) return true; if (startTime <= kUninitializedStartTime || now < startTime) { // Set state variables try { startScale = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::ScaleAttrStr); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } startTime = now; targetScale = db.inputs.target(); // This is the first entry, start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); vec3d scale = GfLerp(alpha2, startScale, targetScale); // Write back to the prim try { trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::ScaleAttrStr, scale); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } if (alpha2 < 1) { // still waiting db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return true; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Quaternion.ogn
{ "SetMatrix4Quaternion": { "version": 1, "description": [ "Sets the rotation of the given matrix4d value which represents a linear transformation.", "Does not modify the translation (row 3) of the matrix." ], "uiName": "Set Rotation Quaternion", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The matrix to be modified" }, "quaternion": { "type": ["quatd[4]", "quatd[4][]"], "uiName": "Quaternion", "description": [ "The quaternion the matrix will apply about the given rotationAxis." ] } }, "outputs": { "matrix": { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The updated matrix" } }, "tests" : [ { "inputs": { "matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1]}, "quaternion": {"type": "quatd[4]", "value": [0.3826834, 0, 0, 0.9238795]}}, "outputs:matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1]} }, { "inputs": { "matrix": {"type":"matrixd[4][]", "value":[ [1.0,0,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1], [1.0,0,0,0, 0,1,0,0, 0,0,1,0, 100,0,0,1]] }, "quaternion": {"type": "quatd[4][]", "value": [[0.3826834, 0, 0, 0.9238795], [0.3826834, 0, 0, 0.9238795]]}}, "outputs:matrix": {"type":"matrixd[4][]", "value":[ [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1], [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 100,0,0,1] ]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetPrimLocalToWorldTransform.ogn
{ "GetPrimLocalToWorldTransform": { "version": 2, "description": ["Given a path to a prim on the current USD stage, return the the transformation matrix.", " that transforms a vector from the local frame to the global frame " ], "uiName": "Get Prim Local to World Transform", "scheduling": ["usd-read", "threadsafe"], "categories": ["sceneGraph"], "inputs": { "primPath": { "type": "token", "description": "The path of the prim used as the local coordinate system when 'usePath' is true" }, "usePath": { "type": "bool", "default": true, "description": "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "prim": { "type": "target", "description": "The prim used as the local coordinate system when 'usePath' is false", "optional": true, "deprecated": "Use prim input with a GetPrimsAtPath node instead" } }, "outputs": { "localToWorldTransform": { "type": "matrixd[4]", "description": "the local to world transformation matrix for the prim" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnScaleToSize.ogn
{ "ScaleToSize": { "version": 2, "description": [ "Perform a smooth scaling maneuver, scaling a prim to a desired size tuple given a speed and easing factor" ], "uiName": "Scale To Size", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "prim": { "type": "target", "description": "The prim to be scaled", "optional": true }, "usePath": { "type": "bool", "default": false, "description": "When true, the 'primPath' attribute is used, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "primPath": { "type": "path", "description": "The source prim to be transformed, used when 'usePath' is true", "optional": true, "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "target": { "type": "vectord[3]", "description": "The desired local scale" }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetPrimLocalToWorldTransform.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. // #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/usdGeom/xformCache.h> #include <pxr/usd/usdUtils/stageCache.h> #include <omni/graph/core/PostUsdInclude.h> #include <omni/fabric/FabricUSD.h> #include <OgnGetPrimLocalToWorldTransformDatabase.h> #include <omni/math/linalg/SafeCast.h> #include "PrimCommon.h" using namespace omni::fabric; namespace omni { namespace graph { namespace nodes { class OgnGetPrimLocalToWorldTransform { public: static bool compute(OgnGetPrimLocalToWorldTransformDatabase& db) { // Get interfaces auto& nodeObj = db.abi_node(); const IPath& iPath = *db.abi_context().iPath; const IToken& iToken = *db.abi_context().iToken; const INode& iNode = *nodeObj.iNode; bool usePath = db.inputs.usePath(); long stageId = db.abi_context().iContext->getStageId(db.abi_context()); auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId)); if (!stage) { db.logWarning("Could not find USD stage %ld", stageId); return true; } // Find the target prim path one of 2 ways std::string destPrimPathStr; if (usePath) { // Use the absolute path NameToken primPath = db.inputs.primPath(); destPrimPathStr = db.tokenToString(primPath); if (destPrimPathStr.empty()) { db.logWarning("No target prim path specified"); return true; } } else { // Read the path from the relationship input on this compute node const char* thisPrimPathStr = iNode.getPrimPath(nodeObj); // Find our stage long stageId = db.abi_context().iContext->getStageId(db.abi_context()); auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId)); if (!stage) { db.logWarning("Could not find USD stage %ld", stageId); return true; } // Find this prim const pxr::UsdPrim thisPrim = stage->GetPrimAtPath(pxr::SdfPath(thisPrimPathStr)); if (!thisPrim.IsValid()) { db.logError("GetPrimAttribute requires USD backing when 'usePath' is false."); return false; } try { // Find the relationship const pxr::SdfPath primPath = getRelationshipPrimPath( db.abi_context(), nodeObj, OgnGetPrimLocalToWorldTransformAttributes::inputs::prim.m_token, db.getInstanceIndex()); destPrimPathStr = primPath.GetString(); } catch (const std::exception& e) { db.logError(e.what()); return false; } } // Retrieve a reference to the prim PathC destPath = iPath.getHandle(destPrimPathStr.c_str()); pxr::UsdPrim prim = stage->GetPrimAtPath(pxr::SdfPath(toSdfPath(destPath))); if (!prim.IsValid()) { return true; } pxr::UsdGeomXformCache xformCache; pxr::GfMatrix4d usdTransform = xformCache.GetLocalToWorldTransform(prim); db.outputs.localToWorldTransform() = omni::math::linalg::safeCastToOmni(usdTransform); return true; } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMoveToTarget.ogn
{ "MoveToTarget": { "version": 2, "description": [ "This node smoothly translates, rotates, and scales a prim object to a target prim object given a speed and easing factor. ", "At the end of the maneuver, the source prim will have the translation, rotation, and scale of the target prim.\n", "Note: The Prim must have xform:orient in transform stack in order to interpolate rotations" ], "uiName": "Move To Target", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "sourcePrim": { "type": "target", "description": "The source prim to be transformed", "optional": true }, "useSourcePath": { "type": "bool", "default": false, "description": "When true, the 'sourcePrimPath' attribute is used, otherwise it will read the connection at the 'sourcePrim' attribute" }, "sourcePrimPath": { "type": "path", "description": "The source prim to be transformed, used when 'useSourcePath' is true", "optional": true }, "targetPrim": { "type": "target", "description": "The destination prim. The target's translation, rotation, and scale will be matched by the sourcePrim", "optional": true }, "useTargetPath": { "type": "bool", "default": false, "description": "When true, the 'targetPrimPath' attribute is used, otherwise it will read the connection at the 'targetPrim' attribute" }, "targetPrimPath": { "type": "path", "description": "The destination prim. The target's translation, rotation, and scale will be matched by the sourcePrim, used when 'useTargetPath' is true", "optional": true }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMakeTransformLookAt.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. // #include <OgnMakeTransformLookAtDatabase.h> #include <omni/math/linalg/matrix.h> using omni::math::linalg::matrix4d; namespace omni { namespace graph { namespace nodes { class OgnMakeTransformLookAt { public: static bool compute(OgnMakeTransformLookAtDatabase& db) { const auto& eyeInput = db.inputs.eye(); const auto& centerInput = db.inputs.center(); const auto& upInput = db.inputs.up(); matrix4d matrix; matrix.SetLookAt(centerInput,eyeInput,upInput); db.outputs.transform() = matrix; return true; } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNor.ogn
{ "BooleanNor": { "version": 2, "description": [ "Boolean NOR on two or more inputs.", "If the inputs are arrays, NOR operations will be performed pair-wise. The input sizes must match.", "If only one input is an array, the other input will be broadcast to the size of the array.", "Returns an array of booleans if either input is an array, otherwise returning a boolean." ], "uiName": "Boolean NOR", "categories": ["math:condition"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["bool", "bool[]"], "description": "Input A: bool or bool array." }, "b": { "type": ["bool", "bool[]"], "description": "Input B: bool or bool array." } }, "outputs": { "result": { "type": ["bool", "bool[]"], "description": "The result of the boolean NOR - an array of booleans if either input is an array, otherwise a boolean.", "uiName": "Result" } }, "tests": [ { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool", "value": true}, "outputs:result": false }, { "inputs:a": {"type": "bool[]", "value": [false, false, true, true]}, "inputs:b": {"type": "bool[]", "value": [false, true, false, true]}, "outputs:result": [true, false, false, false] }, { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool[]", "value": [false, true]}, "outputs:result": [true, false] }, { "inputs:a": {"type": "bool[]", "value": [false, true]}, "inputs:b": {"type": "bool", "value": false}, "outputs:result": [true, false] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnAnd.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 <OgnAndDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include "OperatorComputeWrapper.h" #include "ResolveBooleanOpAttributes.h" namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Boolean AND on two inputs. * If a and b are arrays, AND operations will be performed pair-wise. Sizes of a and b must match. * If only one input is an array, the other input will be broadcast to the size of the array. * Returns an array of booleans if either input is an array, otherwise returning a boolean. * * @param db: database object * @return True if we can get a result properly, false if not */ bool tryCompute(OgnAndDatabase& db) { auto const& dynamicInputs = db.getDynamicInputs(); if (dynamicInputs.empty()) { auto functor = [](bool const& a, bool const& b, bool& result) { result = static_cast<bool>(a && b); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor); } else { std::vector<ogn::InputAttribute> inputs{ db.inputs.a(), db.inputs.b() }; inputs.reserve(dynamicInputs.size() + 2); for (auto const& input : dynamicInputs) inputs.emplace_back(input()); auto functor = [](bool const& a, bool& result) { result = static_cast<bool>(result && a); }; return ogn::compute::tryComputeInputsWithArrayBroadcasting<bool>(inputs, db.outputs.result(), functor); } } } // namespace class OgnAnd { public: static bool compute(OgnAndDatabase& db) { return tryComputeOperator<OgnAndDatabase>(tryCompute, db); } static void onConnectionTypeResolve(const NodeObj& node) { resolveBooleanOpDynamicAttributes(node, outputs::result.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNot.ogn
{ "BooleanNot": { "description": "Inverts a bool or bool array", "version": 1, "categories": ["math:condition"], "scheduling": ["threadsafe"], "uiName": "Boolean Not", "inputs": { "valueIn": { "type": ["bool", "bool[]"], "description": "bool or bool array to invert" } }, "outputs": { "valueOut": { "type": ["bool", "bool[]"], "description": "inverted bool or bool array" } }, "tests": [ { "inputs:valueIn": {"type": "bool", "value": true}, "outputs:valueOut": false }, { "inputs:valueIn": {"type": "bool", "value": false}, "outputs:valueOut": true }, { "inputs:valueIn": {"type": "bool[]", "value": [true, false, true, false]}, "outputs:valueOut": [false, true, false, true] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNot.cpp
// Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnNotDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> namespace omni { namespace graph { namespace nodes { class OgnNot { public: static bool compute(OgnNotDatabase& db) { auto functor = [](bool const& valueIn, bool& valueOut) { valueOut = static_cast<bool>(!valueIn); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool>(db.inputs.valueIn(), db.outputs.valueOut(), functor); } static void onConnectionTypeResolve(const NodeObj& node) { auto valueIn = node.iNode->getAttributeByToken(node, inputs::valueIn.token()); auto valueOut = node.iNode->getAttributeByToken(node, outputs::valueOut.token()); auto valueInType = valueIn.iAttribute->getResolvedType(valueIn); // Require inputs to be resolved before determining result type if (valueInType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 2> attrs { valueIn, valueOut }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnXor.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 <OgnXorDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include "ResolveBooleanOpAttributes.h" #include "OperatorComputeWrapper.h" namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Boolean XOR on two inputs. * If a and b are arrays, XOR operations will be performed pair-wise. Sizes of a and b must match. * If only one input is an array, the other input will be broadcast to the size of the array. * Returns an array of booleans if either input is an array, otherwise returning a boolean. * * @param db: database object * @return True if we can get a result properly, false if not */ bool tryCompute(OgnXorDatabase& db) { auto functor = [](bool const& a, bool const& b, bool& result) { result = static_cast<bool>(a != b); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor); } } // namespace class OgnXor { public: static bool compute(OgnXorDatabase& db) { return tryComputeOperator<OgnXorDatabase>(tryCompute, db); } static void onConnectionTypeResolve(const NodeObj& node) { resolveBooleanOpAttributes(node, inputs::a.token(), inputs::b.token(), outputs::result.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNand.ogn
{ "BooleanNand": { "version": 2, "description": [ "Boolean NAND on two or more inputs.", "If the inputs are arrays, NAND operations will be performed pair-wise. The input sizes must match.", "If only one input is an array, the other input will be broadcast to the size of the array.", "Returns an array of booleans if either input is an array, otherwise returning a boolean." ], "uiName": "Boolean NAND", "categories": ["math:condition"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["bool", "bool[]"], "description": "Input A: bool or bool array." }, "b": { "type": ["bool", "bool[]"], "description": "Input B: bool or bool array." } }, "outputs": { "result": { "type": ["bool", "bool[]"], "description": "The result of the boolean NAND - an array of booleans if either input is an array, otherwise a boolean.", "uiName": "Result" } }, "tests": [ { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool", "value": true}, "outputs:result": true }, { "inputs:a": {"type": "bool[]", "value": [false, false, true, true]}, "inputs:b": {"type": "bool[]", "value": [false, true, false, true]}, "outputs:result": [true, true, true, false] }, { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool[]", "value": [false, true]}, "outputs:result": [true, true] }, { "inputs:a": {"type": "bool[]", "value": [false, true]}, "inputs:b": {"type": "bool", "value": false}, "outputs:result": [true, true] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNand.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 <OgnNandDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include "ResolveBooleanOpAttributes.h" #include "OperatorComputeWrapper.h" namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Boolean NAND on two inputs. * If a and b are arrays, NAND operations will be performed pair-wise. Sizes of a and b must match. * If only one input is an array, the other input will be broadcast to the size of the array. * Returns an array of booleans if either input is an array, otherwise returning a boolean. * * @param db: database object * @return True if we can get a result properly, false if not */ bool tryCompute(OgnNandDatabase& db) { auto const& dynamicInputs = db.getDynamicInputs(); if (dynamicInputs.empty()) { // if there are no dynamic inputs, compute the result in one call auto functor = [](bool const& a, bool const& b, bool& result) { result = static_cast<bool>(!(a && b)); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool, bool, bool>( db.inputs.a(), db.inputs.b(), db.outputs.result(), functor); } // The NAND operator is not associative. // If we have dynamic inputs, we must compute the result in two steps std::vector<ogn::InputAttribute> inputs{ db.inputs.a(), db.inputs.b() }; inputs.reserve(dynamicInputs.size() + 2); for (auto const& input : dynamicInputs) inputs.emplace_back(input()); // 1. apply the OR operator for all inputs auto andFunctor = [](bool const& a, bool& result) { result = static_cast<bool>(a && result); }; bool result = ogn::compute::tryComputeInputsWithArrayBroadcasting<bool>(inputs, db.outputs.result(), andFunctor); // the output attribute has to be cast to an input so that we can write the final value on it auto resultInput = omni::graph::core::ogn::constructInputFromOutput(db, db.outputs.result(), outputs::result.token()); // 2. negate the result auto negateFunctor = [](bool const& a, bool& result) { result = static_cast<bool>(!a); }; result = result && ogn::compute::tryComputeWithArrayBroadcasting<bool, bool>(resultInput, db.outputs.result(), negateFunctor); return result; } } // namespace class OgnNand { public: static bool compute(OgnNandDatabase& db) { return tryComputeOperator<OgnNandDatabase>(tryCompute, db); } static void onConnectionTypeResolve(const NodeObj& node) { resolveBooleanOpDynamicAttributes(node, outputs::result.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNor.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 <OgnNorDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include "ResolveBooleanOpAttributes.h" #include "OperatorComputeWrapper.h" namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Boolean NOR on two inputs. * If a and b are arrays, NOR operations will be performed pair-wise. Sizes of a and b must match. * If only one input is an array, the other input will be broadcast to the size of the array. * Returns an array of booleans if either input is an array, otherwise returning a boolean. * * @param db: database object * @return True if we can get a result properly, false if not */ bool tryCompute(OgnNorDatabase& db) { auto const& dynamicInputs = db.getDynamicInputs(); if (dynamicInputs.empty()) { auto functor = [](bool const& a, bool const& b, bool& result) { result = static_cast<bool>(!(a || b)); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor); } // The NOR operator is not associative. // If we have dynamic inputs, we must compute the result in two steps std::vector<ogn::InputAttribute> inputs{ db.inputs.a(), db.inputs.b() }; inputs.reserve(dynamicInputs.size() + 2); for (auto const& input : dynamicInputs) inputs.emplace_back(input()); // 1. apply the OR operator for all inputs auto orFunctor = [](bool const& a, bool& result) { result = static_cast<bool>(a || result); }; bool result = ogn::compute::tryComputeInputsWithArrayBroadcasting<bool>(inputs, db.outputs.result(), orFunctor); // the output attribute has to be cast to an input so that we can write the final value on it auto resultInput = omni::graph::core::ogn::constructInputFromOutput(db, db.outputs.result(), outputs::result.token()); // 2. negate the result auto negateFunctor = [](bool const& a, bool& result) { result = static_cast<bool>(!a); }; result = result && ogn::compute::tryComputeWithArrayBroadcasting<bool, bool>(resultInput, db.outputs.result(), negateFunctor); return result; } } // namespace class OgnNor { public: static bool compute(OgnNorDatabase& db) { return tryComputeOperator<OgnNorDatabase>(tryCompute, db); } static void onConnectionTypeResolve(const NodeObj& node) { resolveBooleanOpDynamicAttributes(node, outputs::result.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnOr.ogn
{ "BooleanOr": { "version": 2, "description": [ "Boolean OR on two or more inputs.", "If the inputs are arrays, OR operations will be performed pair-wise. The input sizes must match.", "If only one input is an array, the other input will be broadcast to the size of the array.", "Returns an array of booleans if either input is an array, otherwise returning a boolean." ], "uiName": "Boolean OR", "categories": ["math:condition"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["bool", "bool[]"], "description": "Input A: bool or bool array." }, "b": { "type": ["bool", "bool[]"], "description": "Input B: bool or bool array." } }, "outputs": { "result": { "type": ["bool", "bool[]"], "description": "The result of the boolean OR - an array of booleans if either input is an array, otherwise a boolean.", "uiName": "Result" } }, "tests": [ { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool", "value": true}, "outputs:result": true }, { "inputs:a": {"type": "bool[]", "value": [false, false, true, true]}, "inputs:b": {"type": "bool[]", "value": [false, true, false, true]}, "outputs:result": [false, true, true, true] }, { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool[]", "value": [false, true]}, "outputs:result": [false, true] }, { "inputs:a": {"type": "bool[]", "value": [false, true]}, "inputs:b": {"type": "bool", "value": false}, "outputs:result": [false, true] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnBooleanExpr.ogn
{ "BooleanExpr": { "version": 1, "description": [ "NOTE: DEPRECATED AS OF 1.26.0 IN FAVOUR OF INDIVIDAL BOOLEAN OP NODES", "Boolean operation on two inputs.", "The supported operations are:\n", "AND, OR, NAND, NOR, XOR, XNOR" ], "language": "Python", "uiName": "Boolean Expression", "metadata": {"hidden": "true"}, "categories": ["math:operator"], "inputs": { "a": { "type": "bool", "description": "Input A" }, "b": { "type": "bool", "description": "Input B" }, "operator": { "type": "token", "description": "The boolean operation to perform (AND, OR, NAND, NOR, XOR, XNOR)", "uiName": "Operator", "default": "AND", "metadata": { "allowedTokens": { "AND": "AND", "OR": "OR", "NAND": "NAND", "NOR": "NOR", "XOR": "XOR", "XNOR": "XNOR" } } } }, "outputs": { "result": { "type": "bool", "description": "The result of the boolean expression", "uiName": "Result" } }, "tests": [ { "inputs:a": true, "inputs:b": true, "inputs:operator": "XOR", "outputs:result": false }, { "inputs:a": true, "inputs:b": true, "inputs:operator": "XNOR", "outputs:result": true }, { "inputs:a": true, "inputs:b": false, "inputs:operator": "OR", "outputs:result": true }, { "inputs:a": true, "inputs:b": false, "inputs:operator": "AND", "outputs:result": false } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/ResolveBooleanOpAttributes.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 "ResolveBooleanOpAttributes.h" #include <omni/graph/core/iComputeGraph.h> #include <algorithm> #include <array> namespace omni { namespace graph { namespace nodes { void resolveBooleanOpAttributes(const core::NodeObj& node, const core::NameToken aToken, const core::NameToken bToken, const core::NameToken resultToken) { auto a = node.iNode->getAttributeByToken(node, aToken); auto b = node.iNode->getAttributeByToken(node, bToken); auto result = node.iNode->getAttributeByToken(node, resultToken); auto aType = a.iAttribute->getResolvedType(a); auto bType = b.iAttribute->getResolvedType(b); // Require inputs to be resolved before determining result type if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 3> attrs { a, b, result }; std::array<uint8_t, 3> arrayDepths { aType.arrayDepth, bType.arrayDepth, // Allow for a mix of singular and array inputs. If any input is an array, the output must be an array std::max(aType.arrayDepth, bType.arrayDepth) }; std::array<AttributeRole, 3> rolesBuf { aType.role, bType.role, // Copy the attribute role from the resolved type to the output type AttributeRole::eUnknown }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), nullptr, // tupleCounts default to scalar arrayDepths.data(), rolesBuf.data(), attrs.size()); } } void resolveBooleanOpDynamicAttributes(const core::NodeObj& node, const core::NameToken resultToken) { auto totalCount = node.iNode->getAttributeCount(node); std::vector<AttributeObj> allAttributes(totalCount); node.iNode->getAttributes(node, allAttributes.data(), totalCount); std::vector<AttributeObj> attributes; std::vector<uint8_t> arrayDepths; std::vector<AttributeRole> roles; attributes.reserve(totalCount - 2); arrayDepths.reserve(totalCount - 2); roles.reserve(totalCount - 2); uint8_t maxArrayDepth = 0; uint8_t maxComponentCount = 0; for (auto const& attr : allAttributes) { if (attr.iAttribute->getPortType(attr) == AttributePortType::kAttributePortType_Input) { auto resolvedType = attr.iAttribute->getResolvedType(attr); // all inputs must be connected and resolved to complete the output port type resolution if (resolvedType.baseType == BaseDataType::eUnknown) return; arrayDepths.push_back(resolvedType.arrayDepth); roles.push_back(resolvedType.role); maxComponentCount = std::max(maxComponentCount, resolvedType.componentCount); maxArrayDepth = std::max(maxArrayDepth, resolvedType.arrayDepth); attributes.push_back(attr); } } attributes.push_back(node.iNode->getAttributeByToken(node, resultToken)); // Allow for a mix of singular and array inputs. If any input is an array, the output must be an array arrayDepths.push_back(maxArrayDepth); // Copy the attribute role from the resolved type to the output type roles.push_back(AttributeRole::eUnknown); node.iNode->resolvePartiallyCoupledAttributes( node, attributes.data(), nullptr, // tupleCounts default to scalar arrayDepths.data(), roles.data(), attributes.size()); } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnAnd.ogn
{ "BooleanAnd": { "version": 2, "description": [ "Boolean AND on two or more inputs.", "If the inputs are arrays, AND operations will be performed pair-wise. The input sizes must match.", "If only one input is an array, the other input will be broadcast to the size of the array.", "Returns an array of booleans if either input is an array, otherwise returning a boolean." ], "uiName": "Boolean AND", "categories": ["math:condition"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["bool", "bool[]"], "description": "Input A: bool or bool array." }, "b": { "type": ["bool", "bool[]"], "description": "Input B: bool or bool array." } }, "outputs": { "result": { "type": ["bool", "bool[]"], "description": "The result of the boolean AND - an array of booleans if either input is an array, otherwise a boolean.", "uiName": "Result" } }, "tests": [ { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool", "value": true}, "outputs:result": false }, { "inputs:a": {"type": "bool[]", "value": [false, false, true, true]}, "inputs:b": {"type": "bool[]", "value": [false, true, false, true]}, "outputs:result": [false, false, false, true] }, { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type":"bool[]", "value": [false, true]}, "outputs:result": [false, false] }, { "inputs:a": {"type":"bool[]", "value": [false, true]}, "inputs:b": {"type": "bool", "value": false}, "outputs:result": [false, false] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OperatorComputeWrapper.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/logging/Log.h> namespace omni { namespace graph { namespace nodes { template <typename T, typename F> static bool tryComputeOperator(F&& f, T t) { try { return f(t); } catch (std::exception &error) { t.logError("Could not perform function: %s", error.what()); } return false; } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/ResolveBooleanOpAttributes.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "omni/graph/core/Handle.h" namespace omni { namespace graph { namespace core { struct NodeObj; } namespace nodes { extern void resolveBooleanOpAttributes(const core::NodeObj&, const core::NameToken aToken, const core::NameToken bToken, const core::NameToken resultToken); extern void resolveBooleanOpDynamicAttributes(const core::NodeObj& node, const core::NameToken resultToken); } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnBooleanExpr.py
""" NOTE: DEPRECATED AS OF 1.26.0 IN FAVOUR OF INDIVIDAL BOOLEAN OP NODES This is the implementation of the OGN node defined in OgnBooleanExpr.ogn """ class OgnBooleanExpr: """ Boolean AND of two inputs """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" # convert to numpy bool arrays a = db.inputs.a b = db.inputs.b op = db.inputs.operator.lower() if not op: return False if op == "and": result = a and b elif op == "or": result = a or b elif op == "nand": result = not (a and b) elif op == "nor": result = not (a or b) elif op in ["xor", "!="]: result = a != b elif op in ["xnor", "=="]: result = a == b else: return False db.outputs.result = result return True
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnOr.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION Or its licensors retain all intellectual property // Or proprietary rights in nor to this software, related documentation // Or any modifications thereto. Any use, reproduction, disclosure or // distribution of this software Or related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnOrDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include "ResolveBooleanOpAttributes.h" #include "OperatorComputeWrapper.h" namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Boolean OR on two inputs. * If a and b are arrays, OR operations will be performed pair-wise. Sizes of a and b must match. * If only one input is an array, the other input will be broadcast to the size of the array. * Returns an array of booleans if either input is an array, otherwise returning a boolean. * * @param db: database object * @return True if we can get a result properly, false if not */ bool tryCompute(OgnOrDatabase& db) { auto const& dynamicInputs = db.getDynamicInputs(); if (dynamicInputs.empty()) { auto functor = [](bool const& a, bool const& b, bool& result) { result = static_cast<bool>(a || b); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor); } else { std::vector<ogn::InputAttribute> inputs{ db.inputs.a(), db.inputs.b() }; inputs.reserve(dynamicInputs.size() + 2); for (auto const& input : dynamicInputs) inputs.emplace_back(input()); auto functor = [](bool const& a, bool& result) { result = static_cast<bool>(result || a); }; return ogn::compute::tryComputeInputsWithArrayBroadcasting<bool>(inputs, db.outputs.result(), functor); } } } // namespace class OgnOr { public: static bool compute(OgnOrDatabase& db) { return tryComputeOperator<OgnOrDatabase>(tryCompute, db); } static void onConnectionTypeResolve(const NodeObj& node) { resolveBooleanOpDynamicAttributes(node, outputs::result.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnXor.ogn
{ "BooleanXor": { "version": 1, "description": [ "Boolean XOR on two inputs.", "If a and b are arrays, XOR operations will be performed pair-wise. Sizes of a and b must match.", "If only one input is an array, the other input will be broadcast to the size of the array.", "Returns an array of booleans if either input is an array, otherwise returning a boolean." ], "uiName": "Boolean XOR", "categories": ["math:condition"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["bool", "bool[]"], "description": "Input A: bool or bool array." }, "b": { "type": ["bool", "bool[]"], "description": "Input B: bool or bool array." } }, "outputs": { "result": { "type": ["bool", "bool[]"], "description": "The result of the boolean XOR - an array of booleans if either input is an array, otherwise a boolean.", "uiName": "Result" } }, "tests": [ { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool", "value": true}, "outputs:result": true }, { "inputs:a": {"type": "bool[]", "value": [false, false, true, true]}, "inputs:b": {"type": "bool[]", "value": [false, true, false, true]}, "outputs:result": [false, true, true, false] }, { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool[]", "value": [false, true]}, "outputs:result": [false, true] }, { "inputs:a": {"type": "bool[]", "value": [false, true]}, "inputs:b": {"type": "bool", "value": false}, "outputs:result": [false, true] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnAttrType.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 "OgnAttrTypeDatabase.h" namespace omni { namespace graph { namespace core { class OgnAttrType { public: // Queries information about the type of a specified attribute in an input prim static bool compute(OgnAttrTypeDatabase& db) { auto bundledAttribute = db.inputs.data().attributeByName(db.inputs.attrName()); if (!bundledAttribute.isValid()) { db.outputs.baseType() = -1; db.outputs.componentCount() = -1; db.outputs.arrayDepth() = -1; db.outputs.role() = -1; db.outputs.fullType() = -1; } else { auto& attributeType = bundledAttribute.type(); db.outputs.baseType() = int(attributeType.baseType); db.outputs.componentCount() = attributeType.componentCount; db.outputs.arrayDepth() = attributeType.arrayDepth; db.outputs.role() = int(attributeType.role); db.outputs.fullType() = int(omni::fabric::TypeC(attributeType).type); } return true; } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnExtractAttr.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 "OgnExtractAttrDatabase.h" namespace omni { namespace graph { namespace core { class OgnExtractAttr { public: // Copies a single attribute from an input prim to an output attribute directly on the node, // if it exists in the input prim and matches the type of the output attribute. static bool compute(OgnExtractAttrDatabase& db) { const auto& inputToken = db.inputs.attrName(); auto extractedBundledAttribute = db.inputs.data().attributeByName(inputToken); if (!extractedBundledAttribute.isValid()) { db.logWarning("No attribute matching '%s' was found in the input bundle", db.tokenToString(inputToken)); return false; } const Type& inputType = extractedBundledAttribute.type(); auto& outputAttribute = db.outputs.output(); // This compute is not creating the attribute data, that should have been done externally. // The attribute type should match the one extracted though, otherwise connections can go astray. if (!outputAttribute.resolved()) { // Not resolved, so we have to resolve it now. This node is unusual in that the resolved output type // depends on run-time state of the bundle. AttributeObj out = db.abi_node().iNode->getAttributeByToken(db.abi_node(), outputs::output.m_token); out.iAttribute->setResolvedType(out, inputType); outputAttribute.reset( db.abi_context(), out.iAttribute->getAttributeDataHandle(out, db.getInstanceIndex()), out); } else { Type outType = outputAttribute.type(); if (!inputType.compatibleRawData(outType)) { db.logWarning("Attribute '%s' of type %s in the input bundle is not compatible with type %s", db.tokenToString(inputToken), getOgnTypeName(inputType).c_str(), getOgnTypeName(outType).c_str()); return false; } } outputAttribute.copyData( extractedBundledAttribute ); return true; } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnIsPrimActive.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 "OgnIsPrimActiveDatabase.h" #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usdUtils/stageCache.h> #include <omni/graph/core/PostUsdInclude.h> #include <omni/fabric/FabricUSD.h> namespace omni { namespace graph { namespace nodes { class OgnIsPrimActive { public: // ---------------------------------------------------------------------------- static bool compute(OgnIsPrimActiveDatabase& db) { // At some point, only target input types will be supported, so at the time that the path input is deprecated, // also rename "primTarget" to "prim" auto const& primPath = db.inputs.prim(); auto const& prim = db.inputs.primTarget(); if(prim.size() > 0 || pxr::SdfPath::IsValidPathString(primPath)) { // Find our stage const GraphContextObj& context = db.abi_context(); long stageId = context.iContext->getStageId(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 targetPrim = stage->GetPrimAtPath(prim.size() == 0 ? pxr::SdfPath(primPath) : omni::fabric::toSdfPath(prim[0])); if (!targetPrim) { // Should this really be an error?? When prim path input is removed, might be worth changing this to // just a warning instead db.logError("Could not find prim \"%s\" in USD stage", prim.size() == 0 ? primPath.data() : db.pathToString(prim[0])); db.outputs.active() = false; return false; } db.outputs.active() = targetPrim.IsActive(); } return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnCopyAttr.ogn
{ "CopyAttribute": { "version": 1, "description": ["Copies all attributes from one input bundle and specified attributes from a", "second input bundle to the output bundle."], "metadata": { "uiName": "Copy Attributes From Bundles" }, "categories": ["bundle"], "inputs": { "fullData": { "type": "bundle", "description": "Collection of attributes to fully copy to the output", "metadata": { "uiName": "Full Bundle To Copy" } }, "$constraint": "Length of inputAttrNames should always be equal to the length of outputAttrNames", "inputAttrNames": { "type": "token", "description": "Comma or space separated text, listing the names of attributes to copy from partialData", "default": "", "metadata": { "uiName": "Extracted Names For Partial Copy" } }, "outputAttrNames": { "type": "token", "description": "Comma or space separated text, listing the new names of attributes copied from partialData", "default": "", "metadata": { "uiName": "New Names For Partial Copy" } }, "partialData": { "type": "bundle", "optional": true, "description": "Collection of attributes from which to select named attributes", "metadata": { "uiName": "Partial Bundle To Copy" } } }, "outputs": { "data": { "type": "bundle", "description": ["Collection of attributes consisting of all attributes from input 'fullData' and", "selected inputs from input 'partialData'"], "metadata": { "uiName": "Bundle Of Copied Attributes" } } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWriteSetting.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 <OgnWriteSettingDatabase.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 { bool isValidInput(OgnWriteSettingDatabase& db) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); Type valueType = db.inputs.value().type(); ItemType pathType; if (settings->isAccessibleAsArray(settingPath)) pathType = settings->getPreferredArrayType(settingPath); else pathType = settings->getItemType(settingPath); if (pathType == ItemType::eCount) return true; if (pathType == ItemType::eDictionary) return false; if (pathType == ItemType::eBool && valueType.baseType != BaseDataType::eBool) return false; if (pathType == ItemType::eInt && valueType.baseType != BaseDataType::eInt && valueType.baseType != BaseDataType::eInt64) return false; if (pathType == ItemType::eFloat && valueType.baseType != BaseDataType::eFloat && valueType.baseType != BaseDataType::eDouble) return false; if (pathType == ItemType::eString && valueType.baseType != BaseDataType::eToken) return false; size_t arrayLen = settings->getArrayLength(settingPath); if (valueType.componentCount > 1 && valueType.arrayDepth == 0) return arrayLen == valueType.componentCount; else if (valueType.componentCount == 1 && valueType.arrayDepth == 0) return arrayLen == 0; else if (valueType.componentCount == 1 && valueType.arrayDepth == 1) return true; else return false; } template<typename T> void setSetting(OgnWriteSettingDatabase& db) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); auto const inputValue = db.inputs.value().template get<T>(); settings->set(settingPath, *inputValue); } template<typename T> void setSettingArray(OgnWriteSettingDatabase& db) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); auto const inputValue = db.inputs.value().template get<T[]>(); size_t arrayLen = (size_t)settings->getArrayLength(settingPath); settings->setArray(settingPath, inputValue->data(), arrayLen); } template<typename T, size_t N> void setSettingArray(OgnWriteSettingDatabase& db) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); auto const inputValue = db.inputs.value().template get<T[N]>(); settings->setArray(settingPath, *inputValue, N); } } // namespace class OgnWriteSetting { public: static bool compute(OgnWriteSettingDatabase& db) { auto const valueType = db.inputs.value().type(); carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); if (!isValidInput(db)) { std::stringstream ss; ss << valueType; db.logError("Setting Path '%s' is not compatible with type '%s'", settingPath, ss.str()); return false; } switch (valueType.baseType) { case BaseDataType::eBool: switch (valueType.arrayDepth) { case 0: setSetting<bool>(db); break; case 1: setSettingArray<bool>(db); break; } break; case BaseDataType::eInt: switch (valueType.componentCount) { case 1: switch (valueType.arrayDepth) { case 0: setSetting<int32_t>(db); break; case 1: setSettingArray<int32_t>(db); break; } break; case 2: setSettingArray<int32_t, 2>(db); break; case 3: setSettingArray<int32_t, 3>(db); break; case 4: setSettingArray<int32_t, 4>(db); break; } break; case BaseDataType::eInt64: switch (valueType.arrayDepth) { case 0: setSetting<int64_t>(db); break; case 1: setSettingArray<int64_t>(db); break; } break; case BaseDataType::eFloat: switch (valueType.componentCount) { case 1: switch (valueType.arrayDepth) { case 0: setSetting<float>(db); break; case 1: setSettingArray<float>(db); break; } break; case 2: setSettingArray<float, 2>(db); break; case 3: setSettingArray<float, 3>(db); break; case 4: setSettingArray<float, 4>(db); break; } break; case BaseDataType::eDouble: switch (valueType.componentCount) { case 1: switch (valueType.arrayDepth) { case 0: setSetting<double>(db); break; case 1: setSettingArray<double>(db); break; } break; case 2: setSettingArray<double, 2>(db); break; case 3: setSettingArray<double, 3>(db); break; case 4: setSettingArray<double, 4>(db); break; } break; case BaseDataType::eToken: switch (valueType.arrayDepth) { case 0: { auto const inputValue = db.inputs.value().template get<OgnToken>(); char const* inputString = db.tokenToString(*inputValue); settings->set(settingPath, inputString); break; } case 1: { auto const inputValue = db.inputs.value().template get<OgnToken[]>(); std::vector<char const*> inputString(inputValue.size()); for (size_t i = 0; i < inputValue.size(); i++) inputString[i] = db.tokenToString((*inputValue)[i]); size_t arrayLen = settings->getArrayLength(settingPath); settings->setArray(settingPath, inputString.data(), arrayLen); break; } } break; default: { db.logError("Type %s not supported", getOgnTypeName(valueType).c_str()); return false; } } db.outputs.execOut() = kExecutionAttributeStateEnabled; return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadTime.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. // #include <OgnReadTimeDatabase.h> namespace omni { namespace graph { namespace nodes { class OgnReadTime { public: static bool compute(OgnReadTimeDatabase& db) { const auto& contextObj = db.abi_context(); const IGraphContext* const iContext = contextObj.iContext; db.outputs.deltaSeconds() = iContext->getElapsedTime(contextObj); db.outputs.isPlaying() = iContext->getIsPlaying(contextObj); db.outputs.time() = iContext->getTime(contextObj); db.outputs.frame() = iContext->getFrame(contextObj); db.outputs.timeSinceStart() = iContext->getTimeSinceStart(contextObj); db.outputs.absoluteSimTime() = iContext->getAbsoluteSimTime(contextObj); return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnInsertAttr.ogn
{ "InsertAttribute": { "version": 1, "description": ["Copies all attributes from an input bundle to the output bundle, as well as copying an", "additional 'attrToInsert' attribute from the node itself with a specified name."], "metadata": { "uiName": "Insert Attribute" }, "categories": ["bundle"], "inputs": { "attrToInsert": { "type": "any", "description": "The the attribute to be copied from the node to the output bundle", "metadata": { "uiName": "Attribute To Insert" } }, "outputAttrName": { "type": "token", "description": "The name of the new output attribute in the bundle", "default": "attr0", "metadata": { "uiName": "Attribute Name" } }, "data": { "type": "bundle", "description": "Initial bundle of attributes", "metadata": { "uiName": "Original Bundle" } } }, "outputs": { "data": { "type": "bundle", "description": "Bundle of input attributes with the new one inserted with the specified name", "metadata": { "uiName": "Bundle With Inserted Attribute" } } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnHasAttr.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 "OgnHasAttrDatabase.h" namespace omni { namespace graph { namespace core { class OgnHasAttr { public: // Checks whether an input prim contains the specified attribute static bool compute(OgnHasAttrDatabase& db) { db.outputs.output() = db.inputs.data().attributeByName(db.inputs.attrName()).isValid(); return true; } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnExtractBundle.cpp
// Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include "OgnExtractBundleDatabase.h" #include "ReadPrimCommon.h" #include <omni/fabric/FabricUSD.h> #include <omni/kit/commands/ICommandBridge.h> namespace omni { namespace graph { namespace nodes { class OgnExtractBundle { private: 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, OgnExtractBundleAttributes::inputs::bundle.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; } GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj); cleanOutput(context, nodeObj, kAccordingToContextIndex); } static void cleanOutput(GraphContextObj const& contextObj, NodeObj const& nodeObj, InstanceIndex instanceIdx) { // clear the output bundles auto outputTokens = { OgnExtractBundleAttributes::outputs::passThrough.m_token }; for (auto& outputToken : outputTokens) { BundleHandle outBundle = contextObj.iContext->getOutputBundle(contextObj, nodeObj.nodeContextHandle, outputToken, instanceIdx); contextObj.iContext->clearBundleContents(contextObj, outBundle); } // remove dynamic attributes BundleType empty; updateAttributes(contextObj, nodeObj, empty, instanceIdx); } static void updateAttributes(GraphContextObj const& contextObj, NodeObj const& nodeObj, BundleType const& bundle, InstanceIndex instIdx) { OgnExtractBundle& state = OgnExtractBundleDatabase::sInternalState<OgnExtractBundle>(nodeObj); omni::kit::commands::ICommandBridge::ScopedUndoGroup scopedUndoGroup; extractBundle_reflectBundleDynamicAttributes(nodeObj, contextObj, bundle, state.m_added, instIdx); } // Copies attributes from an input bundle to attributes directly on the node static bool compute(OgnExtractBundleDatabase& db) { auto& contextObj = db.abi_context(); auto& nodeObj = db.abi_node(); auto const& inputBundle = db.inputs.bundle(); if (!inputBundle.isValid()) { cleanOutput(contextObj, nodeObj, db.getInstanceIndex()); return false; } // extract attributes directly from input bundle updateAttributes(contextObj, nodeObj, inputBundle, db.getInstanceIndex()); db.outputs.passThrough() = inputBundle; return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadVariable.ogn
{ "omni.graph.core.ReadVariable": { "version": 2, "description": [ "Node that reads a value from a variable" ], "uiName": "Read Variable", "categories": [ "internal" ], "scheduling": ["threadsafe"], "metadata": { "hidden": "true" }, "inputs": { "variableName": { "type": "token", "description": "The name of the graph variable to use.", "metadata": { "hidden": "true", "literalOnly": "1" } }, "targetPath": { "type": "token", "description": "Ignored. Do not use.", "optional": true, "metadata": { "hidden": "true" } }, "graph": { "type": "target", "description": "Ignored. Do not use", "optional": true, "metadata": { "hidden": "true" } } }, "outputs": { "value": { "type": "any", "description": "The variable value that we returned.", "unvalidated": true } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrim.ogn
{ "ReadPrim": { "version": 9, "description": [ "DEPRECATED - use ReadPrimAttributes!" ], "uiName": "Read Prim", "metadata": { "hidden": "true" }, "scheduling": [ "usd-read" ], "categories": [ "sceneGraph", "bundle" ], "inputs": { "prim": { "type": "bundle", "description": "The prims to be read from when 'usePathPattern' is false", "optional": true }, "attrNamesToImport": { "uiName": "Attributes To Import", "type": "token", "default": "*", "description": [ "A list of wildcard patterns used to match the attribute names that are to be imported", "", "Supported syntax of wildcard pattern:", " '*' - match an arbitrary number of any characters", " '?' - match any single character", " '^' - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['points', 'faceVertexCount', 'faceVertexIndices', 'size']", " '*' - match any", " '* ^points' - match any, but exclude 'points'", " '* ^face*' - match any, but exclude 'faceVertexCount' and 'faceVertexIndices'" ] }, "usdTimecode": { "uiName": "Time", "type": "timecode", "default": "NaN", "description": "The time at which to evaluate the transform of the USD prim. A value of \"NaN\" indicates that the default USD time stamp should be used" }, "computeBoundingBox": { "uiName": "Compute Bounding Box", "type": "bool", "default": false, "description": "For each primitive compute local bounding box and store them as 'bboxMinCorner', 'bboxMaxCorner' and 'bboxTransform' attributes." } }, "outputs": { "primBundle": { "type": "bundle", "description": [ "A bundle of the target Prim attributes.", "In addition to the data attributes, there is a token attribute named sourcePrimPath", "which contains the path of the Prim being read" ] } }, "state": { "primPath": { "type": "uint64", "description": "State from previous evaluation" }, "primTypes": { "type": "uint64", "description": "State from previous evaluation" }, "attrNamesToImport": { "type": "uint64", "description": "State from previous evaluation" }, "usdTimecode": { "type": "timecode", "default": "NaN", "description": "State from previous evaluation" }, "computeBoundingBox": { "type": "bool", "default": false, "description": "State from previous evaluation" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetPrims.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 "OgnGetPrimsDatabase.h" #include "PrimCommon.h" namespace omni { namespace graph { namespace nodes { class OgnGetPrims { public: static bool compute(OgnGetPrimsDatabase& db) { IBundle2* outputBundle = db.outputs.bundle().abi_bundleInterface(); outputBundle->clearContents(true); IConstBundle2* inputBundle = db.inputs.bundle().abi_bundleInterface(); size_t const childBundleCount = inputBundle->getChildBundleCount(); // nothing to do if (childBundleCount == 0) { return true; } std::vector<ConstBundleHandle> childBundleHandles(childBundleCount); inputBundle->getConstChildBundles(childBundleHandles.data(), childBundleHandles.size()); std::vector<ConstBundleHandle> bundles; bundles.reserve(childBundleCount); GraphContextObj const& context = db.abi_context(); if (db.inputs.prims().size() != 0) { // We want to have same order of `prims` input in the output. // Unfortunately, the order of child bundles is not preserved, OM- // Construct children lookup map std::unordered_map<fabric::TokenC, ConstBundleHandle> pathToChildMap; for (ConstBundleHandle const& childBundleHandle : childBundleHandles) { ConstAttributeDataHandle const attr = getAttributeR(context, childBundleHandle, PrimAdditionalAttrs::kSourcePrimPathToken); if (fabric::Token const* data = getDataR<fabric::Token>(context, attr)) { pathToChildMap.emplace(data->asTokenC(), childBundleHandle); } } // Search for inputTargets auto const& inputPrims = db.inputs.prims(); for (auto const& inputTarget : inputPrims) { auto const asToken = fabric::asInt(fabric::toSdfPath(inputTarget).GetToken()); if(auto it = pathToChildMap.find(asToken); it != pathToChildMap.end()) { bundles.push_back(it->second); } } } else { // By default all primitives matching the path/type patterns are added to the output bundle; // when the "inverse" option is on, all mismatching primitives will be added instead. bool const inverse = db.inputs.inverse(); // Use wildcard pattern matching for prim type. std::string const typePattern(db.inputs.typePattern()); PatternMatcher const typeMatcher(typePattern); // Use wildcard pattern matching for prim path. std::string const pathPattern(db.inputs.pathPattern()); PatternMatcher const pathMatcher(pathPattern); auto matchesPattern = [&context](ConstBundleHandle& bundle, NameToken attrName, PatternMatcher const& patternMatcher) { ConstAttributeDataHandle attr = getAttributeR(context, bundle, attrName); return attr.isValid() && patternMatcher.matches(*getDataR<NameToken>(context, attr)); }; for (ConstBundleHandle& childBundleHandle : childBundleHandles) { bool const matched = matchesPattern(childBundleHandle, PrimAdditionalAttrs::kSourcePrimTypeToken, typeMatcher) && matchesPattern(childBundleHandle, PrimAdditionalAttrs::kSourcePrimPathToken, pathMatcher); if (matched != inverse) { bundles.push_back(childBundleHandle); } } } if (!bundles.empty()) { outputBundle->copyChildBundles(bundles.data(), bundles.size()); } return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGraphTarget.ogn
{ "GraphTarget": { "version": 1, "description": [ "Access the target prim the graph is being executed on. If the graph is executing itself,", "this will output the prim path of the graph. Otherwise the graph is being executed via ", "instancing, then this will output the prim path of the target instance." ], "metadata": { "uiName": "Get Graph Target" }, "categories": [ "sceneGraph" ], "scheduling": ["threadsafe"], "inputs": { "targetPath": { "description": [ "Deprecated. Do not use." ], "type": "token", "metadata": { "hidden": "true" } } }, "outputs": { "primPath": { "description": [ "The target prim path" ], "type": "token" } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGpuInteropCudaEntry.ogn
{ "GpuInteropCudaEntry": { "version": 1, "description": [ "Entry point for Cuda RTX Renderer Postprocessing" ], "scheduling": ["threadsafe"], "metadata": { "uiName": "GpuInterop Cuda Entry" }, "inputs": { "sourceName": { "type": "string", "description": "Source name of the AOV", "default": "ldrColor" } }, "outputs": { "cudaMipmappedArray": { "type": "uint64", "description": "Pointer to the CUDA Mipmapped Array", "metadata": { "uiName": "cudaMipmappedArray" } }, "width": { "type": "uint", "description": "Width", "metadata": { "uiName": "width" } }, "height": { "type": "uint", "description": "Height", "metadata": { "uiName": "height" } }, "isBuffer": { "type": "bool", "description" : "True if the entry exposes a buffer as opposed to a texture", "metadata": { "uiName": "isBuffer" } }, "bufferSize": { "type": "uint", "description": "Size of the buffer", "metadata": { "uiName": "bufferSize" } }, "mipCount": { "type": "uint", "description": "Mip Count", "metadata": { "uiName": "mipCount" } }, "format": { "type": "uint64", "description": "Format", "metadata": { "uiName": "format" } }, "simTime": { "type": "double", "description": "Simulation time", "metadata": { "uiName": "simTime" } }, "hydraTime": { "type": "double", "description": "Hydra time in stage", "metadata": { "uiName": "hydraTime" } }, "externalTimeOfSimFrame": { "type": "int64", "description": "The external time on the master node, matching the simulation frame used to render this frame", "metadata": { "uiName": "externalTimeOfSimFrame" } }, "frameId": { "type": "int64", "description": "Frame identifier", "metadata": { "uiName": "frameId" } }, "stream": { "type": "uint64", "description": "Pointer to the CUDA Stream", "metadata": { "uiName": "stream" } } } } }
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() } } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimBundle.ogn
{ "ReadPrimBundle": { "version": 7, "description": [ "DEPRECATED - use ReadPrims!" ], "uiName": "Read Prim into Bundle", "metadata": { "hidden": "true" }, "scheduling": [ "usd-read" ], "categories": [ "sceneGraph", "bundle" ], "inputs": { "prim": { "type": "target", "description": "The prims to be read from when 'usePath' is false", "optional": true }, "usePath": { "uiName": "Use Path", "type": "bool", "default": false, "description": "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "primPath": { "uiName": "Prim Path", "type": "token", "description": "The paths of the prims to be read from when 'usePath' is true", "optional": true, "default": "", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "attrNamesToImport": { "uiName": "Attributes To Import", "type": "token", "default": "*", "description": [ "A list of wildcard patterns used to match the attribute names that are to be imported", "", "Supported syntax of wildcard pattern:", " '*' - match an arbitrary number of any characters", " '?' - match any single character", " '^' - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['points', 'faceVertexCount', 'faceVertexIndices', 'size']", " '*' - match any", " '* ^points' - match any, but exclude 'points'", " '* ^face*' - match any, but exclude 'faceVertexCount' and 'faceVertexIndices'" ] }, "usdTimecode": { "uiName": "Time", "type": "timecode", "default": "NaN", "description": [ "The time at which to evaluate the transform of the USD prim. A value of \"NaN\" indicates that the default USD time stamp should be used" ] }, "computeBoundingBox": { "uiName": "Compute Bounding Box", "type": "bool", "default": false, "description": "For each primitive compute local bounding box and store them as 'bboxMinCorner', 'bboxMaxCorner' and 'bboxTransform' attributes." } }, "outputs": { "primBundle": { "type": "bundle", "description": [ "A bundle containing multiple prims as children.", "Each child contains data attributes and two additional token attributes named sourcePrimPath and sourcePrimType", "which contain the path and the type of the Prim being read" ] } }, "state": { "primPath": { "type": "uint64", "description": "State from previous evaluation" }, "usePath": { "type": "bool", "default": false, "description": "State from previous evaluation" }, "attrNamesToImport": { "type": "uint64", "description": "State from previous evaluation" }, "usdTimecode": { "type": "timecode", "default": "NaN", "description": "State from previous evaluation" }, "computeBoundingBox": { "type": "bool", "default": false, "description": "State from previous evaluation" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadTime.ogn
{ "ReadTime": { "version": 1, "description": "Holds the values related to the current global time and the timeline", "uiName": "Read Time", "categories": "time", "scheduling": ["threadsafe"], "inputs": { }, "outputs": { "isPlaying": { "type": "bool", "description": "True during global animation timeline playback", "uiName": "Is Playing" }, "deltaSeconds": { "type": "double", "description": "The number of seconds elapsed since the last OmniGraph update", "uiName": "Delta (Seconds)" }, "timeSinceStart": { "type": "double", "description": "Elapsed time since the App started", "uiName": "Time Since Start (Seconds)" }, "time": { "type": "double", "description": "The global animation time in seconds during playback", "uiName": "Animation Time (Seconds)" }, "frame": { "type": "double", "description": "The global animation time in frames, equivalent to (time * fps), during playback", "uiName": "Animation Time (Frames)" }, "absoluteSimTime": { "type": "double", "description": "The accumulated total of elapsed times between rendered frames", "uiName": "Absolute Simulation Time (Seconds)" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimsBundle.ogn
{ "ReadPrimsBundle": { "version": 3, "description": [ "Reads primitives and outputs multiple primitive in a bundle." ], "uiName": "Read Prims into Bundle", "metadata": { "hidden": "true" }, "scheduling": [ "usd-read" ], "categories": [ "sceneGraph", "bundle" ], "inputs": { "prims": { "type": "target", "description": "The prims to be read from when 'usePaths' is false", "optional": true, "metadata": { "allowMultiInputs": "1" } }, "usePaths": { "uiName": "Use Paths", "type": "bool", "default": false, "description": "When true, the 'primPaths' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute" }, "primPaths": { "uiName": "Prim Paths", "type": [ "token", "token[]", "path" ], "description": "The paths of the prims to be read from when 'usePaths' is true", "optional": true }, "attrNamesToImport": { "uiName": "Attributes To Import", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match the attribute names that are to be imported", "", "Supported syntax of wildcard pattern:", " '*' - match an arbitrary number of any characters", " '?' - match any single character", " '^' - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['points', 'faceVertexCount', 'faceVertexIndices', 'size']", " '*' - match any", " '* ^points' - match any, but exclude 'points'", " '* ^face*' - match any, but exclude 'faceVertexCount' and 'faceVertexIndices'" ] }, "usdTimecode": { "uiName": "Time", "type": "timecode", "default": "NaN", "description": [ "The time at which to evaluate the transform of the USD prim. A value of \"NaN\" indicates that the default USD time stamp should be used" ] } }, "outputs": { "primsBundle": { "type": "bundle", "description": [ "An output bundle containing multiple prims as children.", "Each child contains data attributes and two additional token attributes named sourcePrimPath and sourcePrimType", "which contain the path and the type of the Prim being read" ] } }, "state": { "primPaths": { "type": "uint64[]", "description": "State from previous evaluation" }, "usePaths": { "type": "bool", "default": false, "description": "State from previous evaluation" }, "attrNamesToImport": { "type": "string", "description": "State from previous evaluation" }, "usdTimecode": { "type": "timecode", "default": "NaN", "description": "State from previous evaluation" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimAttributes.ogn
{ "ReadPrimAttributes": { "version": 3, "description": [ "Read Prim attributes and exposes them as dynamic attributes", "Does not produce output bundle." ], "uiName": "Read Prim Attributes", "scheduling": [ "usd-read" ], "categories": [ "sceneGraph", "bundle" ], "inputs": { "prim": { "type": "target", "description": "The prim to be read from when 'usePath' is false", "optional": false }, "usePath": { "uiName": "Use Path", "type": "bool", "default": false, "description": "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "primPath": { "uiName": "Prim Path", "type": "path", "description": "The path of the prim to be read from when 'usePath' is true", "optional": true, "default": "", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "attrNamesToImport": { "uiName": "Attribute Name Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match the attribute names that are to be imported", "", "Supported syntax of wildcard pattern:", " '*' - match an arbitrary number of any characters", " '?' - match any single character", " '^' - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['points', 'faceVertexCount', 'faceVertexIndices', 'size']", " '*' - match any", " '* ^points' - match any, but exclude 'points'", " '* ^face*' - match any, but exclude 'faceVertexCount' and 'faceVertexIndices'" ] }, "usdTimecode": { "uiName": "Time", "type": "timecode", "default": "NaN", "description": "The time at which to evaluate the transform of the USD prim. A value of \"NaN\" indicates that the default USD time stamp should be used" } }, "outputs": { "primBundle": { "type": "bundle", "description": [ "A bundle of the target Prim attributes.", "In addition to the data attributes, there are token attributes named sourcePrimPath and sourcePrimType", "which contains the path of the Prim being read" ], "metadata": { "hidden": "true", "literalOnly": "1" } } }, "state": { "primPath": { "type": "uint64", "description": "State from previous evaluation" }, "attrNamesToImport": { "type": "string", "description": "State from previous evaluation" }, "usdTimecode": { "type": "timecode", "default": "NaN", "description": "State from previous evaluation" } } } }
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
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrim.ogn
{ "WritePrim": { "version": 3, "description": [ "Exposes attributes for a single Prim on the USD stage as inputs to this node.", "When this node computes it writes any of these connected inputs to the target Prim. Any inputs", "which are not connected will not be written." ], "uiName": "Write Prim Attributes", "categories": ["sceneGraph"], "scheduling": ["usd-write"], "inputs": { "execIn": { "type": "execution", "description": "The input execution port" }, "prim": { "uiName": "Prim", "type": "target", "description": "The prim to be written to" }, "usdWriteBack": { "uiName": "Persist To USD", "type": "bool", "default": true, "description": "Whether or not the value should be written back to USD, or kept a Fabric only value" } }, "outputs": { "execOut": { "type": "execution", "description": "The output execution port" } } } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetAttrNames.ogn
{ "GetAttributeNames": { "version": 1, "description": ["Retrieves the names of all of the attributes contained in the input bundle, optionally sorted."], "metadata": { "uiName": "Get Attribute Names From Bundle" }, "categories": ["bundle"], "scheduling": ["threadsafe"], "inputs": { "data": { "type": "bundle", "description": "Collection of attributes from which to extract names", "metadata": { "uiName": "Bundle To Examine" } }, "sort": { "type": "bool", "description": ["If true, the names will be output in sorted order (default, for consistency).", "If false, the order is not be guaranteed to be consistent between systems or over", "time, so do not rely on the order downstream in this case."], "default": true, "metadata": { "uiName": "Sort Output" } } }, "outputs": { "output": { "type": "token[]", "description": ["Names of all of the attributes contained in the input bundle"], "metadata": { "uiName": "Attribute Names" } } } } }
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetPrims.ogn
{ "GetPrims": { "version": 2, "description": [ "Filters primitives in the input bundle by path and type." ], "uiName": "Get Prims", "categories": [ "bundle" ], "inputs": { "bundle": { "type": "bundle", "description": "The bundle to be read from" }, "inverse": { "uiName": "Inverse", "type": "bool", "default": false, "description": [ "By default all primitives matching the path patterns and types are added to the output bundle;", "when this option is on, all mismatching primitives will be added instead." ] }, "pathPattern": { "uiName": "Path Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match primitive path.", "", "Supported syntax of wildcard pattern:", " `*` - match an arbitrary number of any characters", " `?` - match any single character", " `^` - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['/Cube0', '/Cube1', '/Box']", " '*' - match any", " '* ^/Box' - match any, but exclude '/Box'", " '* ^/Cube*' - match any, but exclude '/Cube0' and '/Cube1'" ] }, "typePattern": { "uiName": "Type Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match primitive type.", "", "Supported syntax of wildcard pattern:", " `*` - match an arbitrary number of any characters", " `?` - match any single character", " `^` - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['Mesh', 'Cone', 'Cube']", " '*' - match any", " '* ^Mesh' - match any, but exclude 'Mesh'", " '* ^Cone ^Cube' - match any, but exclude 'Cone' and 'Cube'" ] }, "prims": { "type": "target", "description": "The prim to be extracted from Multiple Primitives in Bundle.", "optional": true, "metadata": { "allowMultiInputs": "1" } } }, "outputs": { "bundle": { "type": "bundle", "description": "The output bundle that contains filtered primitives" } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnRenderPreprocessEntry.ogn
{ "RenderPreProcessEntry": { "version": 1, "description": [ "Entry point for RTX Renderer Preprocessing" ], "metadata": { "uiName": "Render Preprocess Entry" }, "inputs": { }, "outputs": { "simTime": { "type": "double", "description": "Simulation time", "metadata": { "uiName": "simTime" } }, "hydraTime": { "type": "double", "description": "Hydra time in stage", "metadata": { "uiName": "hydraTime" } }, "stream": { "type": "uint64", "description": "Pointer to the CUDA Stream", "metadata": { "uiName": "stream" } } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrimsV2.ogn
{ "WritePrimsV2": { "version": 1, "description": [ "Write back bundle(s) containing multiple prims to the stage." ], "uiName": "Write Prims", "categories": [ "sceneGraph", "bundle" ], "scheduling": [ "usd-write" ], "inputs": { "execIn": { "type": "execution", "description": "The input execution (for action graphs only)" }, "primsBundle": { "uiName": "Prims Bundle", "type": "bundle", "description": [ "The bundle(s) of multiple prims to be written back.", "The sourcePrimPath attribute is used to find the destination prim." ], "metadata": { "allowMultiInputs": "1" } }, "prims": { "uiName": "Prims", "description": [ "Target(s) to which the prims in 'primsBundle' will be written to.", "There is a 1:1 mapping between root prims paths in 'primsBundle' and the Target Prims targets", "*For advanced usage, if 'primsBundle' contains hierarchy, the unique common ancesor paths will have ", " the 1:1 mapping to Target Prims targets, with the descendant paths remapped.", "*NOTE* See 'scatterUnderTargets' input for modified exporting behavior", "*WARNING* this can create new prims on the stage.", "If attributes or prims are removed from 'primsBundle' in subsequent evaluation, they will be removed from targets as well." ], "type": "target", "metadata": { "allowMultiInputs": "1" } }, "scatterUnderTargets": { "uiName": "Scatter Under Targets", "type": "bool", "default": false, "description": [ "If true, the target prims become the parent prims that the bundled prims will be exported *UNDER*. ", "If multiple prims targets are provided, the primsBundle will be duplicated *UNDER* each ", "target prims." ] }, "attrNamesToExport": { "uiName": "Attribute Name Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match primitive attributes by name.", "", "Supported syntax of wildcard pattern:", " `*` - match an arbitrary number of any characters", " `?` - match any single character", " `^` - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['xFormOp:translate', 'xformOp:scale','radius']", " '*' - match any", " 'xformOp:*' - matches 'xFormOp:translate' and 'xformOp:scale'", " '* ^radius' - match any, but exclude 'radius'", " '* ^xformOp*' - match any, but exclude 'xFormOp:translate', 'xformOp:scale'" ] }, "pathPattern": { "uiName": "Prim Path Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match primitives by path.", "", "Supported syntax of wildcard pattern:", " `*` - match an arbitrary number of any characters", " `?` - match any single character", " `^` - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['/Cube0', '/Cube1', '/Box']", " '*' - match any", " '* ^/Box' - match any, but exclude '/Box'", " '* ^/Cube*' - match any, but exclude '/Cube0' and '/Cube1'" ] }, "typePattern": { "uiName": "Prim Type Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match primitives by type.", "", "Supported syntax of wildcard pattern:", " `*` - match an arbitrary number of any characters", " `?` - match any single character", " `^` - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['Mesh', 'Cone', 'Cube']", " '*' - match any", " '* ^Mesh' - match any, but exclude 'Mesh'", " '* ^Cone ^Cube' - match any, but exclude 'Cone' and 'Cube'" ] }, "usdWriteBack": { "uiName": "Persist To USD", "type": "bool", "default": true, "description": "Whether or not the value should be written back to USD, or kept a Fabric only value" }, "layerIdentifier": { "type": "token", "description": [ "Identifier of the layer to export to. If empty, it'll be exported to the current edit target at the time of usd wirte back.'", "This is only used when \"Persist To USD\" is enabled." ], "default": "", "metadata": { "uiName": "Layer Identifier" } } }, "state": { "primBundleDirtyId": { "type": "uint64", "description": "State from previous evaluation" }, "attrNamesToExport": { "type": "string", "default": "*", "description": "State from previous evaluation" }, "pathPattern": { "type": "string", "default": "*", "description": "State from previous evaluation" }, "typePattern": { "type": "string", "default": "*", "description": "State from previous evaluation" }, "usdWriteBack": { "type": "bool", "default": true, "description": "State from previous evaluation" }, "scatterUnderTargets": { "type": "bool", "default": false, "description": "State from previous evaluation" }, "layerIdentifier": { "type": "token", "default": "", "description": "State from previous evaluation" } }, "outputs": { "execOut": { "type": "execution", "description": "The output execution port (for action graphs only)" } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnExtractBundle.ogn
{ "ExtractBundle": { "version": 3, "description": [ "Exposes readable attributes for a bundle as outputs on this node.", "When this node computes it will read the latest attribute values from the target bundle into these", "node attributes" ], "uiName": "Extract Bundle", "categories": [ "bundle" ], "inputs": { "bundle": { "type": "bundle", "description": "The bundle to be read from." } }, "outputs": { "passThrough": { "type": "bundle", "description": [ "The input bundle passed as-is" ] } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnIsPrimActive.ogn
{ "IsPrimActive": { "version": 1, "description": [ "Query if a Prim is active or not in the stage." ], "uiName": "Is Prim Active", "scheduling": [ "usd-read", "threadsafe" ], "categories": [ "sceneGraph" ], "inputs": { "prim": { "uiName": "Prim Path", "type": "path", "description": "The prim path to be queried", "deprecated": "Use primTarget instead" }, "primTarget": { "uiName": "Prim", "type": "target", "description": "The prim to be queried" } }, "outputs": { "active": { "type": "bool", "description": "Whether the prim is active or not" } } } }
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() } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrimRelationship.ogn
{ "WritePrimRelationship": { "version": 1, "description": "Writes the target(s) to a relationship on a given prim", "uiName": "Write Prim Relationship", "categories": ["sceneGraph"], "scheduling": ["usd-write"], "exclude": ["usd"], "inputs": { "execIn": { "type": "execution", "description": "The input execution port" }, "prim": { "type": "target", "description": "The prim to write the relationship to" }, "name": { "type": "token", "uiName": "Relationship Name", "description": "The name of the relationship to write" }, "value": { "type": "target", "description": "The target(s) to write to the relationship" }, "usdWriteBack": { "uiName": "Persist To USD", "type": "bool", "default": true, "description": "Whether or not the value should be written back to USD, or kept a Fabric only value" } }, "outputs": { "execOut": { "type": "execution", "description": "The output execution port" } }, "state": { "correctlySetup": { "type": "bool", "description": "Whether or not the instance is properly setup", "default": false }, "prim": { "type": "target", "description": "The currently prefetched prim" }, "name": { "type": "token", "description": "The prefetched relationship name" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnNoOp.cpp
// Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnNoOpDatabase.h> namespace omni { namespace graph { namespace nodes { class OgnNoOp { public: // Do nothing static bool compute(OgnNoOpDatabase&) { return true; } }; REGISTER_OGN_NODE() } } }
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrims.ogn
{ "ReadPrims": { "version": 3, "description": [ "DEPRECATED - use ReadPrimsV2!" ], "uiName": "Read Prims (Legacy)", "metadata": { "hidden": "true" }, "scheduling": [ "usd-read" ], "categories": [ "sceneGraph", "bundle" ], "inputs": { "prims": { "type": "target", "description": "The prims to be read from when 'useFindPrims' is false", "optional": true, "metadata": { "allowMultiInputs": "1" } }, "useFindPrims": { "uiName": "Use Find Prims", "type": "bool", "default": false, "description": [ "When true, the 'pathPattern' and 'typePattern' attribute is used as the pattern to search for the prims to read", "otherwise it will read the connection at the 'prim' attribute." ] }, "pathPattern": { "uiName": "Prim Path Pattern", "type": "string", "default": "", "description": [ "A list of wildcard patterns used to match the prim paths that are to be imported", "", "Supported syntax of wildcard pattern:", " '*' - match an arbitrary number of any characters", " '?' - match any single character", " '^' - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['/Cube0', '/Cube1', '/Box']", " '*' - match any", " '* ^/Box' - match any, but exclude '/Box'", " '* ^/Cube*' - match any, but exclude '/Cube0' and '/Cube1'" ] }, "typePattern": { "uiName": "Prim Type Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match the prim types that are to be imported", "", "Supported syntax of wildcard pattern:", " '*' - match an arbitrary number of any characters", " '?' - match any single character", " '^' - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['Mesh', 'Cone', 'Cube']", " '*' - match any", " '* ^Mesh' - match any, but exclude 'Mesh'", " '* ^Cone ^Cube' - match any, but exclude 'Cone' and 'Cube'" ] }, "attrNamesToImport": { "uiName": "Attribute Name Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match the attribute names that are to be imported", "", "Supported syntax of wildcard pattern:", " '*' - match an arbitrary number of any characters", " '?' - match any single character", " '^' - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['points', 'faceVertexCount', 'faceVertexIndices', 'size']", " '*' - match any", " '* ^points' - match any, but exclude 'points'", " '* ^face*' - match any, but exclude 'faceVertexCount' and 'faceVertexIndices'" ] }, "usdTimecode": { "uiName": "Time", "type": "timecode", "default": "NaN", "description": "The time at which to evaluate the transform of the USD prim. A value of \"NaN\" indicates that the default USD time stamp should be used" }, "computeBoundingBox": { "uiName": "Compute Bounding Box", "type": "bool", "default": false, "description": "For each primitive compute local bounding box and store them as 'bboxMinCorner', 'bboxMaxCorner' and 'bboxTransform' attributes." }, "applySkelBinding": { "uiName": "Apply Skel Binding", "type": "bool", "default": false, "description": [ "If an input USD prim is skinnable and has the SkelBindingAPI schema applied, read skeletal data and apply SkelBinding to deform the prim.", "The output bundle will have additional child bundles created to hold data for the skeleton and skel animation prims if present. After", "evaluation, deformed points and normals will be written to the `points` and `normals` attributes, while non-deformed points and normals", "will be copied to the `points:default` and `normals:default` attributes." ] } }, "outputs": { "primsBundle": { "type": "bundle", "description": [ "An output bundle containing multiple prims as children.", "Each child contains data attributes and two additional token attributes named sourcePrimPath and sourcePrimType", "which contains the path of the Prim being read" ] } }, "state": { "primPaths": { "type": "uint64[]", "description": "State from previous evaluation" }, "useFindPrims": { "type": "bool", "default": false, "description": "State from previous evaluation" }, "pathPattern": { "type": "string", "description": "State from previous evaluation" }, "typePattern": { "type": "string", "description": "State from previous evaluation" }, "attrNamesToImport": { "type": "string", "description": "State from previous evaluation" }, "usdTimecode": { "type": "timecode", "default": -1, "description": "State from previous evaluation" }, "computeBoundingBox": { "type": "bool", "default": false, "description": "State from previous evaluation" }, "applySkelBinding": { "type": "bool", "default": false, "description": "State from previous evaluation" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnRenameAttr.ogn
{ "RenameAttribute": { "version": 1, "description": ["Changes the names of attributes from an input bundle for the corresponding output bundle.", "Attributes whose names are not in the 'inputAttrNames' list will be copied from the", "input bundle to the output bundle without changing the name."], "metadata": { "uiName": "Rename Attributes In Bundles" }, "categories": ["bundle"], "inputs": { "$constraint": "Length of inputAttrNames should always be equal to the length of outputAttrNames", "inputAttrNames": { "type": "token", "description": "Comma or space separated text, listing the names of attributes in the input data to be renamed", "default": "", "metadata": { "uiName": "Attributes To Rename" } }, "outputAttrNames": { "type": "token", "description": "Comma or space separated text, listing the new names for the attributes listed in inputAttrNames", "default": "", "metadata": { "uiName": "New Attribute Names" } }, "data": { "type": "bundle", "description": "Collection of attributes to be renamed", "metadata": { "uiName": "Original Attribute Bundle" } } }, "outputs": { "data": { "type": "bundle", "description": ["Final bundle of attributes, with attributes renamed based on inputAttrNames and outputAttrNames"], "metadata": { "uiName": "Bundle Of Renamed Attributes" } } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnArrayLength.ogn
{ "ArrayLength": { "version": 1, "description": ["Outputs the length of a specified array attribute in an input bundle,", "or 1 if the attribute is not an array attribute"], "metadata": { "uiName": "Extract Attribute Array Length" }, "categories": ["math:array"], "scheduling": ["threadsafe"], "inputs": { "attrName": { "type": "token", "description": "Name of the attribute whose array length will be queried", "default": "points", "metadata": { "uiName": "Attribute Name" } }, "data": { "type": "bundle", "description": "Collection of attributes that may contain the named attribute", "metadata": { "uiName": "Attribute Bundle" } } }, "outputs": { "length": { "type": "uint64", "description": "The length of the array attribute in the input bundle", "metadata": { "uiName": "Array Length" } } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetGraphTargetId.ogn
{ "GetGraphTargetId": { "version": 1, "description": [ "Access a unique id for the target prim the graph is being executed on." ], "categories": [ "sceneGraph" ], "scheduling": ["threadsafe"], "inputs": { }, "outputs": { "targetId": { "description": [ "The target prim id" ], "type": "uint64" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrims.ogn
{ "WritePrims": { "version": 1, "description": [ "DEPRECATED - use WritePrimsV2!" ], "uiName": "Write Prims (Legacy)", "metadata": { "hidden": "true" }, "categories": [ "sceneGraph", "bundle" ], "scheduling": [ "usd-write" ], "inputs": { "execIn": { "type": "execution", "description": "The input execution (for action graphs only)" }, "primsBundle": { "uiName": "Prims Bundle", "type": "bundle", "description": [ "The bundle(s) of multiple prims to be written back.", "The sourcePrimPath attribute is used to find the destination prim." ], "metadata": { "allowMultiInputs": "1" } }, "attrNamesToExport": { "uiName": "Attribute Name Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match primitive attributes by name.", "", "Supported syntax of wildcard pattern:", " `*` - match an arbitrary number of any characters", " `?` - match any single character", " `^` - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['xFormOp:translate', 'xformOp:scale','radius']", " '*' - match any", " 'xformOp:*' - matches 'xFormOp:translate' and 'xformOp:scale'", " '* ^radius' - match any, but exclude 'radius'", " '* ^xformOp*' - match any, but exclude 'xFormOp:translate', 'xformOp:scale'" ] }, "pathPattern": { "uiName": "Prim Path Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match primitives by path.", "", "Supported syntax of wildcard pattern:", " `*` - match an arbitrary number of any characters", " `?` - match any single character", " `^` - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['/Cube0', '/Cube1', '/Box']", " '*' - match any", " '* ^/Box' - match any, but exclude '/Box'", " '* ^/Cube*' - match any, but exclude '/Cube0' and '/Cube1'" ] }, "typePattern": { "uiName": "Prim Type Pattern", "type": "string", "default": "*", "description": [ "A list of wildcard patterns used to match primitives by type.", "", "Supported syntax of wildcard pattern:", " `*` - match an arbitrary number of any characters", " `?` - match any single character", " `^` - (caret) is used to define a pattern that is to be excluded", "", "Example of wildcard patterns, input: ['Mesh', 'Cone', 'Cube']", " '*' - match any", " '* ^Mesh' - match any, but exclude 'Mesh'", " '* ^Cone ^Cube' - match any, but exclude 'Cone' and 'Cube'" ] }, "usdWriteBack": { "uiName": "Persist To USD", "type": "bool", "default": false, "description": "Whether or not the value should be written back to USD, or kept a Fabric only value" } }, "outputs": { "execOut": { "type": "execution", "description": "The output execution port (for action graphs only)" } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimAttribute.ogn
{ "ReadPrimAttribute": { "version": 3, "description": [ "Given a path to a prim on the current USD stage and the name of an attribute on", " that prim, gets the value of that attribute, at the global timeline value." ], "uiName": "Read Prim Attribute", "categories": [ "sceneGraph" ], "scheduling": [ "usd-read", "threadsafe" ], "exclude": [ "usd" ], "inputs": { "primPath": { "type": "token", "description": "The path of the prim to be modified when 'usePath' is true", "optional": true, "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "usePath": { "type": "bool", "default": false, "description": "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "prim": { "type": "target", "description": "The prim to be read from when 'usePath' is false", "optional": true }, "name": { "uiName": "Attribute Name", "type": "token", "description": "The name of the attribute to get on the specified prim" }, "usdTimecode": { "uiName": "Time", "type": "timecode", "default": "NaN", "description": [ "The time at which to evaluate the transform of the USD prim attribute. A value of \"NaN\" indicates that the default USD time stamp should be used" ] } }, "outputs": { "value": { "type": "any", "description": "The attribute value", "unvalidated": true } }, "state": { "correctlySetup": { "type": "bool", "description": "Wheter or not the instance is properly setup", "default": false }, "srcPath": { "type": "uint64", "description": "A PathC to the source prim" }, "srcPathAsToken": { "type": "uint64", "description": "A TokenC to the source prim" }, "srcAttrib": { "type": "uint64", "description": "A TokenC to the source attribute" }, "importPath": { "type": "uint64", "description": "Path at which data has been imported" }, "time": { "type": "double", "description": "The timecode at which we have imported the value" } } } }
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
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetGraphTargetPrim.ogn
{ "GetGraphTargetPrim": { "version": 1, "description": [ "Access the target prim the graph is being executed on. If the graph is executing itself,", "this will output the prim of the graph. Otherwise the graph is being executed via ", "instancing, then this will output the prim of the target instance." ], "metadata": { "uiName": "Get Graph Target Prim" }, "categories": [ "sceneGraph" ], "inputs": { }, "outputs": { "prim": { "type": "target", "description" : ["The graph target as a prim"] } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnEventUpdateTick.ogn
{ "UpdateTickEvent": { "version": 1, "description": ["Triggers on update ticks."], "metadata": { "uiName": "Update Tick Event" }, "scheduling": ["threadsafe"], "outputs": { "event": { "type": "uint64", "description": "Currently incomplete - always 0. Eventually should use a bundle for this.", "metadata": { "uiName": "event" } } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadOmniGraphValue.ogn
{ "ReadOmniGraphValue": { "version": 1, "description": [ "Imports a data value from the Fabric cache that is located at the given path and attribute name.", "This is for data that is not already present in OmniGraph as that data can be accessed through a direct connection to the underlying OmniGraph node." ], "uiName": "Read OmniGraph Value", "categories": [ "sceneGraph" ], "scheduling": [ "global-read", "threadsafe" ], "inputs": { "path": { "type": "path", "description": "The path to the Fabric data bucket in which the attribute being queried lives." }, "name": { "type": "token", "description": "The name of the attribute to be queried" } }, "outputs": { "value": { "type": "any", "description": "The attribute value", "unvalidated": true } } } }