file_path
stringlengths 21
224
| content
stringlengths 0
80.8M
|
---|---|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnInvertMatrix.cpp | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnInvertMatrixDatabase.h>
#include <omni/math/linalg/matrix.h>
#include <exception>
using omni::math::linalg::matrix3d;
using omni::math::linalg::matrix4d;
namespace omni
{
namespace graph
{
namespace nodes
{
void computeMatrix4Inverse(const double input[16], double result[16])
{
auto& output = *reinterpret_cast<matrix4d*>(result);
output = reinterpret_cast<const matrix4d*>(input)->GetInverse();
}
void computeMatrix3Inverse(const double input[9], double result[9])
{
auto& output = *reinterpret_cast<matrix3d*>(result);
output = reinterpret_cast<const matrix3d*>(input)->GetInverse();
}
class OgnInvertMatrix
{
public:
static bool compute(OgnInvertMatrixDatabase& db)
{
auto& matrixInput = db.inputs.matrix();
auto& matrixOutput = db.outputs.invertedMatrix();
if (auto matrix = matrixInput.get<double[9]>())
{
if (auto output = matrixOutput.get<double[9]>())
{
computeMatrix3Inverse(*matrix, *output);
}
}
else if (auto matrix = matrixInput.get<double[16]>())
{
if (auto output = matrixOutput.get<double[16]>())
{
computeMatrix4Inverse(*matrix, *output);
}
}
else if (auto matrices = matrixInput.get<double[][9]>())
{
if (auto output = matrixOutput.get<double[][9]>())
{
output->resize(matrices->size());
for (size_t i = 0; i < matrices.size(); i++)
{
computeMatrix3Inverse((*matrices)[i], (*output)[i]);
}
}
}
else if (auto matrices = matrixInput.get<double[][16]>())
{
if (auto output = matrixOutput.get<double[][16]>())
{
output->resize(matrices->size());
for (size_t i = 0; i < matrices.size(); i++)
{
computeMatrix4Inverse((*matrices)[i], (*output)[i]);
}
}
}
else
{
db.logWarning("OgnInvertMatrix: Failed to resolve input types");
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node) {
std::array<AttributeObj, 2> attrs {
node.iNode->getAttributeByToken(node, inputs::matrix.token()),
node.iNode->getAttributeByToken(node, outputs::invertedMatrix.token())
};
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnSin.ogn | {
"Sin": {
"version": 1,
"description": [
"Trigonometric operation sine of one input in degrees."
],
"uiName": "Sine",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "Angle in degrees whose sine value is to be found"
}
},
"outputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "The sine value of the input angle",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:value": {"type": "float", "value": 45.0},
"outputs:value": {"type": "float", "value": 0.707107}
},
{
"inputs:value": {"type": "double", "value": 30.0},
"outputs:value": {"type": "double", "value": 0.5}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnToDeg.ogn | {
"ToDeg": {
"version": 1,
"description": [
"Convert radian input into degrees"
],
"uiName": "To Degrees",
"categories": ["math:conversion"],
"scheduling": ["threadsafe"],
"inputs": {
"radians": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "Angle value in radians to be converted",
"uiName": "Radians"
}
},
"outputs": {
"degrees": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "Angle value in degrees",
"uiName": "Degrees"
}
},
"tests" : [
{
"inputs:radians": {"type": "double", "value": -1.0},
"outputs:degrees": {"type": "double", "value": -57.2958}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCeil.cpp | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnCeilDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnCeilDatabase& db)
{
auto functor = [](auto const& a, auto& result) { result = static_cast<int>(std::ceil(a)); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, int>(db.inputs.a(), db.outputs.result(), functor);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnCeilDatabase& db)
{
auto functor = [](auto const& a, auto& result) { result = static_cast<int>(std::ceil(a)); };
return ogn::compute::tryComputeWithTupleBroadcasting<N, T, int>(db.inputs.a(), db.outputs.result(), functor);
}
} // namespace
class OgnCeil
{
public:
static bool compute(OgnCeilDatabase& db)
{
try
{
auto& aType = db.inputs.a().type();
switch (aType.baseType)
{
case BaseDataType::eDouble:
switch (aType.componentCount)
{
case 1:
return tryComputeAssumingType<double>(db);
case 2:
return tryComputeAssumingType<double, 2>(db);
case 3:
return tryComputeAssumingType<double, 3>(db);
case 4:
return tryComputeAssumingType<double, 4>(db);
}
break;
case BaseDataType::eFloat:
switch (aType.componentCount)
{
case 1:
return tryComputeAssumingType<float>(db);
case 2:
return tryComputeAssumingType<float, 2>(db);
case 3:
return tryComputeAssumingType<float, 3>(db);
case 4:
return tryComputeAssumingType<float, 4>(db);
}
break;
case BaseDataType::eHalf:
switch (aType.componentCount)
{
case 1:
return tryComputeAssumingType<pxr::GfHalf>(db);
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db);
}
break;
default:
break;
}
throw ogn::compute::InputError("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto valueType = a.iAttribute->getResolvedType(a);
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eInt, valueType.componentCount, valueType.arrayDepth);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnToRad.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 <OgnToRadDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/math.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnToRadDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<T>(pxr::GfDegreesToRadians(a));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.degrees(), db.outputs.radians(), functor);
}
template <>
bool tryComputeAssumingType<pxr::GfHalf>(OgnToRadDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfDegreesToRadians(a)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf>(db.inputs.degrees(), db.outputs.radians(), functor);
}
} // namespace
class OgnToRad
{
public:
static bool compute(OgnToRadDatabase& db)
{
try
{
// All possible types excluding ogn::string and bool
// scalers
if (tryComputeAssumingType<double>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf>(db)) return true; // Specifically for pxr::GfHalf
else if (tryComputeAssumingType<float>(db)) return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (std::exception &error)
{
db.logError("Could not convert into radians : %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto degrees = node.iNode->getAttributeByToken(node, inputs::degrees.token());
auto radians = node.iNode->getAttributeByToken(node, outputs::radians.token());
auto degreeType = degrees.iAttribute->getResolvedType(degrees);
// Require inputs to be resolved before determining output's type
if (degreeType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { degrees, radians };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAdd.ogn | {
"Add": {
"version": 2,
"description": [
"Add two or more values of any numeric type (element-wise). This includes simple values, tuples, arrays,",
"and arrays of tuples. ",
"If one input has a higher dimension than the other, ",
"then the input with lower dimension will be repeated to match the dimension of the other input (broadcasting). ",
"eg: scalar + tuple, tuple + array of tuples, scalar + array of tuples."
],
"uiName": "Add",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"a": {
"type": ["numerics"],
"description": "First number or collection of numbers to add"
},
"b": {
"type": ["numerics"],
"description": "Second number or collection of numbers to add"
}
},
"outputs": {
"sum": {
"type": ["numerics"],
"description": "Sum of the two numbers or collection of numbers"
}
},
"tests": [
{"inputs:a": {"type": "float[2]", "value": [1.0, 2.0]}, "inputs:b": {"type": "float[2]", "value": [0.5, 1.0]},
"outputs:sum": {"type": "float[2]", "value": [1.5, 3.0]}},
{"inputs:a": {"type": "int64", "value": 10}, "inputs:b": {"type": "int64", "value": 6},
"outputs:sum": {"type": "int64", "value": 16}},
{"inputs:a": {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, "inputs:b": {"type": "double[2]", "value": [5, 5]},
"outputs:sum": {"type": "double[2][]", "value": [[15, 10], [6, 6]]}},
{"inputs:a": {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, "inputs:b": {"type": "double", "value": 5},
"outputs:sum": {"type": "double[2][]", "value": [[15, 10], [6, 6]]}}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnFMod.py | """
Module contains the OmniGraph node implementation of omni.graph.fmod
"""
import carb
import numpy as np
import omni.graph.core as og
class OgnFMod:
"""Node to find floating point remainder"""
@staticmethod
def compute(db) -> bool:
try:
db.outputs.result.value = np.fmod(db.inputs.a.value, db.inputs.b.value)
except TypeError as error:
db.log_error(f"Remainder could not be performed: {error}")
return False
return True
@staticmethod
def on_connection_type_resolve(node) -> None:
atype = node.get_attribute("inputs:a").get_resolved_type()
btype = node.get_attribute("inputs:b").get_resolved_type()
resultattr = node.get_attribute("outputs:result")
resulttype = resultattr.get_resolved_type()
# we can only infer the output given both inputs are resolved and they are the same.
if (
atype.base_type != og.BaseDataType.UNKNOWN
and btype.base_type != og.BaseDataType.UNKNOWN
and resulttype.base_type == og.BaseDataType.UNKNOWN
):
if atype.base_type == btype.base_type:
sum_type = og.Type(
atype.base_type,
max(atype.tuple_count, btype.tuple_count),
max(atype.array_depth, btype.array_depth),
)
resultattr.set_resolved_type(sum_type)
else:
carb.log_warn(f"Can not compute remainder of types {atype} and {btype}")
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivide_Scalars.cpp | #include "OgnDivideHelper.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace OGNDivideHelper
{
// AType is a scalar float or double
template <typename AType, typename BType>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<!std::is_integral<AType>::value && !std::is_same<AType, pxr::GfHalf>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<AType>(static_cast<double>(a) / static_cast<double>(b));
};
return ogn::compute::tryComputeWithArrayBroadcasting<AType, BType, AType>(
a, b, result, functor, count);
}
// AType is a scalar half
template <typename AType, typename BType>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<std::is_same<AType, pxr::GfHalf>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<AType>(static_cast<float>(static_cast<double>(a) / static_cast<double>(b)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<AType, BType, AType>(
a, b, result, functor, count);
}
// AType is a scalar integral => Force result to be a scalar double
template <typename AType, typename BType>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<std::is_integral<AType>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<double>(a) / static_cast<double>(b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<AType, BType, double>(
a, b, result, functor, count);
}
bool tryComputeScalars(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
if (tryComputeAssumingType<double, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, uint64_t>(db, a, b, result, count)) return true;
return false;
}
} // namespace OGNDivideHelper
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivide.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 <OgnDivideDatabase.h>
#include "OgnDivideHelper.h"
#include <carb/logging/Log.h>
#include <type_traits>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnDivide
{
public:
static bool computeVectorized(OgnDivideDatabase& db, size_t count)
{
auto const& a = db.inputs.a();
auto const& b = db.inputs.b();
auto& result = db.outputs.result();
try
{
if (OGNDivideHelper::tryComputeScalars(db, a, b, result, count))
return true;
if (OGNDivideHelper::tryComputeTuple2(db, a, b, result, count))
return true;
if (OGNDivideHelper::tryComputeTuple3(db, a, b, result, count))
return true;
if (OGNDivideHelper::tryComputeTuple4(db, a, b, result, count))
return true;
if (OGNDivideHelper::tryComputeMatrices(db, a, b, result, count))
return true;
db.logWarning("OgnDivide: Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnDivide: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto aType = a.iAttribute->getResolvedType(a);
// Require inputs to be resolved before determining result's type
if (aType.baseType != BaseDataType::eUnknown)
{
// In the case of A being an integral - then we force a double
auto newType = aType;
if (aType.baseType == BaseDataType::eUChar
|| aType.baseType == BaseDataType::eInt
|| aType.baseType == BaseDataType::eUInt
|| aType.baseType == BaseDataType::eInt64
|| aType.baseType == BaseDataType::eUInt64)
{
newType.baseType = BaseDataType::eDouble;
}
result.iAttribute->setResolvedType(result, newType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomUnitQuaternion.ogn | {
"RandomUnitQuaternion": {
"version": 1,
"description": "Generates a random unit quaternion with uniform distribution.",
"uiName": "Random Unit Quaternion",
"categories": [ "math:operator" ],
"scheduling": [ "threadsafe" ],
"inputs": {
"execIn": {
"type": "execution",
"description": "The input execution port to output a new random value"
},
"seed": {
"type": "uint64",
"description": "The seed of the random generator.",
"uiName": "Seed",
"$optional": "Setting optional=true is a workaround to avoid the USD generated tests for checking the default value of 0, since we override the default seed with a random one",
"optional": true
},
"useSeed": {
"type": "bool",
"description": "Use the custom seed instead of a random one",
"uiName": "Use seed",
"default": false
},
"isNoise": {
"type": "bool",
"description": [
"Turn this node into a noise generator function",
"For a given seed, it will then always output the same number(s)"
],
"uiName": "Is noise function",
"default": false,
"metadata": {
"hidden": "true",
"literalOnly": "1"
}
}
},
"outputs": {
"random": {
"type": "quatf[4]",
"description": "The random unit quaternion that was generated",
"uiName": "Random Unit Quaternion"
},
"execOut": {
"type": "execution",
"description": "The output execution port"
}
},
"state": {
"gen": {
"type": "matrixd[3]",
"description": "Random number generator internal state (abusing matrix3d because it is large enough)"
}
},
"tests": [
{
"inputs:useSeed": true,
"inputs:seed": 123456789,
"inputs:execIn": 1,
"outputs:random": [ 0.02489632, -0.05617058, 0.23986788, 0.9688594 ],
"outputs:execOut": 1,
"inputs:isNoise": true
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnTan.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 <OgnTanDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/math.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnTanDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<T>(std::tan(pxr::GfDegreesToRadians(a)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.value(), db.outputs.value(), functor);
}
template <>
bool tryComputeAssumingType<pxr::GfHalf>(OgnTanDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(std::tan(pxr::GfDegreesToRadians(a))));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf>(db.inputs.value(), db.outputs.value(), functor);
}
} // namespace
class OgnTan
{
public:
static bool compute(OgnTanDatabase& db)
{
try
{
// All possible types excluding ogn::string and bool
// scalers
if (tryComputeAssumingType<double>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf>(db)) return true; // Specifically for pxr::GfHalf
else if (tryComputeAssumingType<float>(db)) return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (std::exception &error)
{
db.logError("Could not perform Tangent funtion : %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto value = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::value.token());
auto valueType = value.iAttribute->getResolvedType(value);
// Require inputs to be resolved before determining output's type
if (valueType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { value, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDistance3D.ogn | {
"Distance3D": {
"version": 1,
"description": [
"Computes the distance between two 3D points A and B. ",
"Which is the length of the vector with start and end points A and B",
"If one input is an array and the other is a single point, the scaler will ",
"be broadcast to the size of the array"
],
"uiName": "Distance3D",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"a": {
"type": ["pointd[3]", "pointf[3]", "pointh[3]", "pointd[3][]", "pointf[3][]", "pointh[3][]"],
"description": ["Vector A"],
"uiName": "A"
},
"b": {
"type": ["pointd[3]", "pointf[3]", "pointh[3]", "pointd[3][]", "pointf[3][]", "pointh[3][]"],
"description": ["Vector B"],
"uiName": "B"
}
},
"outputs": {
"distance": {
"type": [ "double", "float", "half", "double[]", "float[]", "half[]" ],
"description": ["The distance between the input vectors"]
}
},
"tests": [
{ "inputs:a": {"type": "float[3]", "value": [1,2,3]}, "inputs:b": {"type": "float[3]", "value": [4,6,8]},
"outputs:distance": {"type": "float", "value":7.07107} },
{ "inputs:a": {"type": "float[3][]", "value": [[1,2,3], [1,2,3]]}, "inputs:b": {"type": "float[3][]", "value": [[1,2,3],[4,6,8]]},
"outputs:distance": {"type": "float[]", "value":[0, 7.07107]} },
{ "inputs:a": {"type": "half[3][]", "value": [[1,2,3], [4,6,8]]}, "inputs:b": {"type": "half[3]", "value": [1,2,3]},
"outputs:distance": {"type": "half[]", "value":[0, 7.0703125]} },
{ "inputs:a": {"type": "double[3]", "value": [1,2,3]}, "inputs:b": {"type": "double[3]", "value": [4,6,8]},
"outputs:distance": {"type": "double", "value":7.07107} }
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMultiply.ogn | {
"Multiply": {
"version": 2,
"description": [
"Computes the element-wise product of two or more inputs (multiplication).",
" If one input has a higher dimension than the others, then the input with lower dimension will be repeated",
" to match the dimension of the higher dimension input (broadcasting). ",
"eg: scalar * tuple, tuple * array of tuples, scalar * array of tuples."
],
"uiName": "Multiply",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"a": {
"type": ["numerics"],
"description": "First number to multiply"
},
"b": {
"type": ["numerics"],
"description": "Second number to multiply"
}
},
"outputs": {
"product": {
"type": ["numerics"],
"description": "Product of the two numbers"
}
},
"tests" : [
{
"inputs:a": {"type": "float", "value": 42.0}, "inputs:b": {"type": "float", "value": 2.0},
"outputs:product": {"type": "float", "value": 84.0}
},
{
"inputs:a": {"type": "double[2]", "value": [1.0, 42.0]}, "inputs:b": {"type": "double[2]", "value": [2.0, 1.0]},
"outputs:product": {"type": "double[2]", "value": [2.0, 42.0]}
},
{
"inputs:a": {"type": "double[]", "value": [1.0, 42.0]}, "inputs:b": {"type": "double", "value": 2.0},
"outputs:product": {"type": "double[]", "value": [2.0, 84.0]}
},
{
"inputs:a": {"type": "double[2][]", "value": [[10, 5], [1, 1]]},
"inputs:b": {"type": "double[2]", "value": [5, 5]},
"outputs:product": {"type": "double[2][]", "value": [[50, 25], [5, 5]]}
},
{
"inputs:a": {"type": "double[2][]", "value": [[10, 5], [1, 1]]},
"inputs:b": {"type": "double", "value": 2},
"outputs:product": {"type": "double[2][]", "value": [[20, 10], [2, 2]]}
},
{
"inputs:a": {"type": "double[2]", "value": [10, 5]},
"inputs:b": {"type": "double", "value": 2},
"outputs:product": {"type": "double[2]", "value": [20, 10]}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomBoolean.ogn | {
"RandomBoolean": {
"version": 1,
"description": "Generates a random boolean value.",
"uiName": "Random Boolean",
"categories": [ "math:operator" ],
"scheduling": [ "threadsafe" ],
"inputs": {
"execIn": {
"type": "execution",
"description": "The input execution port to output a new random value"
},
"seed": {
"type": "uint64",
"description": "The seed of the random generator.",
"uiName": "Seed",
"$optional": "Setting optional=true is a workaround to avoid the USD generated tests for checking the default value of 0, since we override the default seed with a random one",
"optional": true
},
"useSeed": {
"type": "bool",
"description": "Use the custom seed instead of a random one",
"uiName": "Use seed",
"default": false
},
"isNoise": {
"type": "bool",
"description": [
"Turn this node into a noise generator function",
"For a given seed, it will then always output the same number(s)"
],
"uiName": "Is noise function",
"default": false,
"metadata": {
"hidden": "true",
"literalOnly": "1"
}
}
},
"outputs": {
"random": {
"type": "bool",
"description": "The random boolean value that was generated",
"uiName": "Random Boolean"
},
"execOut": {
"type": "execution",
"description": "The output execution port"
}
},
"state": {
"gen": {
"type": "matrixd[3]",
"description": "Random number generator internal state (abusing matrix3d because it is large enough)"
}
},
"tests": [
{
"$description": "Checks the uint64 random number 0 becomes false",
"inputs:useSeed": true,
"inputs:seed": 14092058508772706262,
"inputs:execIn": 1,
"outputs:random": false,
"outputs:execOut": 1,
"inputs:isNoise": true
},
{
"$description": "Checks the uint64 random number 1<<63-1 becomes false",
"inputs:useSeed": true,
"inputs:seed": 5527295704097554033,
"inputs:execIn": 1,
"outputs:random": false,
"outputs:execOut": 1,
"inputs:isNoise": true
},
{
"inputs:useSeed": true,
"inputs:seed": 9302349107990861236,
"inputs:execIn": 1,
"outputs:random": true,
"outputs:execOut": 1,
"inputs:isNoise": true
},
{
"inputs:useSeed": true,
"inputs:seed": 1955209015103813879,
"inputs:execIn": 1,
"outputs:random": true,
"outputs:execOut": 1,
"inputs:isNoise": true
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnSin.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 <OgnSinDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/math.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnSinDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<T>(std::sin(pxr::GfDegreesToRadians(a)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.value(), db.outputs.value(), functor);
}
template <>
bool tryComputeAssumingType<pxr::GfHalf>(OgnSinDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(std::sin(pxr::GfDegreesToRadians(a))));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf>(db.inputs.value(), db.outputs.value(), functor);
}
} // namespace
class OgnSin
{
public:
static bool compute(OgnSinDatabase& db)
{
try
{
// All possible types excluding ogn::string and bool
// scalers
if (tryComputeAssumingType<double>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf>(db)) return true; // Specifically for pxr::GfHalf
else if (tryComputeAssumingType<float>(db)) return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (std::exception &error)
{
db.logError("Could not perform Sine funtion : %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto value = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::value.token());
auto valueType = value.iAttribute->getResolvedType(value);
// Require inputs to be resolved before determining output's type
if (valueType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { value, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNthRoot.ogn | {
"NthRoot": {
"version": 1,
"description": [
"Computes the nth root of value. The result is the same type as the input value if the numerator",
"is a decimal type. Otherwise the result is a double.",
"If the input is a vector or matrix, then the node will calculate the square root of each element",
", and output a vector or matrix of the same size.",
"Note that there are combinations of inputs that can result in a loss of precision due to different ",
"value ranges. Taking roots of a negative number will give a result of NaN except for cube root."
],
"uiName": "Nth Root",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"nthRoot": {
"type": "int",
"description": "Take the nth root",
"uiName": "Nth Root",
"default": 2
},
"value": {
"type": ["numerics"],
"description": "The input value",
"uiName": "Value"
}
},
"outputs": {
"result": {
"type": ["numerics"],
"description": "Result of square root",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:value": {"type": "float", "value": 36.0},
"outputs:result": {"type": "float", "value": 6.0}
},
{
"inputs:value": {"type": "double", "value": 27.0}, "inputs:nthRoot": 3,
"outputs:result": {"type": "double", "value": 3.0}
},
{
"inputs:value": {"type": "float[2]", "value": [0.25, 4.0]},
"outputs:result": {"type": "float[2]", "value": [0.5, 2.0]}
},
{
"inputs:value": {"type": "float[]", "value": [1.331, 8.0]}, "inputs:nthRoot": 3,
"outputs:result": {"type": "float[]", "value": [1.1, 2.0]}
},
{
"inputs:value": {"type": "float[2][]", "value": [[4.0, 16.0], [2.25, 64.0]]},
"outputs:result": {"type": "float[2][]", "value": [[2.0, 4.0], [1.5, 8.0]]}
},
{
"inputs:value": {"type": "int64", "value": 9223372036854775807}, "inputs:nthRoot": 1,
"outputs:result": {"type": "double", "value": 9223372036854775807.0}
},
{
"inputs:value": {"type": "int", "value": 256}, "inputs:nthRoot": 4,
"outputs:result": {"type": "double", "value": 4.0}
},
{
"inputs:value": {"type": "uint64", "value": 8}, "inputs:nthRoot": 3,
"outputs:result": {"type": "double", "value": 2.0}
},
{
"inputs:value": {"type": "half[2]", "value": [0.125, 1.0]}, "inputs:nthRoot": 3,
"outputs:result": {"type": "half[2]", "value": [0.5, 1.0]}
},
{
"inputs:value": {"type": "uchar", "value": 25},
"outputs:result": {"type": "double", "value": 5.0}
},
{
"inputs:value": {"type": "int64", "value": 16}, "inputs:nthRoot": -2,
"outputs:result": {"type": "double", "value": 0.25}
},
{
"inputs:value": {"type": "double", "value": 0.125}, "inputs:nthRoot": -3,
"outputs:result": {"type": "double", "value": 2}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCrossProduct.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 <OgnCrossProductDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/math/linalg/vec.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T, size_t N>
bool tryComputeAssumingType(OgnCrossProductDatabase& db)
{
auto functor = [](auto const& a, auto const& b, auto& product)
{
const auto& vecA = *reinterpret_cast<const omni::math::linalg::base_vec<T, N>*>(a);
const auto& vecB = *reinterpret_cast<const omni::math::linalg::base_vec<T, N>*>(b);
auto& prod = *reinterpret_cast<omni::math::linalg::base_vec<T, N>*>(product);
prod = GfCross(vecA, vecB);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], T[N]>(db.inputs.a(), db.inputs.b(), db.outputs.product(), functor);
}
} // namespace
class OgnCrossProduct
{
public:
static bool compute(OgnCrossProductDatabase& db)
{
try
{
auto& aType = db.inputs.a().type();
switch(aType.baseType)
{
case BaseDataType::eDouble:
switch(aType.componentCount)
{
case 3: return tryComputeAssumingType<double, 3>(db);
}
case BaseDataType::eFloat:
switch(aType.componentCount)
{
case 3: return tryComputeAssumingType<float, 3>(db);
}
case BaseDataType::eHalf:
switch(aType.componentCount)
{
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db);
}
default: db.logError("Failed to resolve input types");
}
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto b = node.iNode->getAttributeByToken(node, inputs::b.token());
auto product = node.iNode->getAttributeByToken(node, outputs::product.token());
// Require inputs to be resolved before determining product's type
auto aType = a.iAttribute->getResolvedType(a);
auto bType = b.iAttribute->getResolvedType(b);
if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown)
{
if ((aType.role != AttributeRole::eVector && bType.role == AttributeRole::eNone) ||
(bType.role != AttributeRole::eVector && aType.role == AttributeRole::eNone))
{
node.iNode->logComputeMessageOnInstance(node, kAuthoringGraphIndex, ogn::Severity::eWarning,
formatString("Cross product with non-vector input of types: %s, %s",
getAttributeRoleName(aType.role).c_str(), getAttributeRoleName(bType.role).c_str()).c_str()
);
}
std::array<AttributeObj, 3> attrs { a, b, product };
// a, b, product should all have the same tuple count
std::array<uint8_t, 3> tupleCounts {
aType.componentCount,
bType.componentCount,
std::max(aType.componentCount, bType.componentCount)
};
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(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomUnitVector.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 "random/RandomNodeBase.h"
#include <OgnRandomUnitVectorDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
using namespace random;
class OgnRandomUnitVector : public NodeBase<OgnRandomUnitVector, OgnRandomUnitVectorDatabase>
{
public:
static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed);
}
static bool onCompute(OgnRandomUnitVectorDatabase& db, size_t count)
{
// TODO: Specify output type, we should be able to generate double precision output too...
return computeRandoms(db, count, [](GeneratorState& gen) { return gen.nextUnitVec3f(); });
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAcos.ogn | {
"Acos": {
"version": 1,
"description": [
"Trigonometric operation arccosine of one input in degrees."
],
"uiName": "Arccos",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "Angle value in degrees whose inverse cosine is to be found"
}
},
"outputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "The arccos value of the input angle in degrees",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:value": {"type": "float", "value": 0.707107},
"outputs:value": {"type": "float", "value": 45.0}
},
{
"inputs:value": {"type": "double[]", "value": [-0.5, -1.0]},
"outputs:value": {"type": "double[]", "value": [120, 180]}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNormalize.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnNormalizeDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/math/linalg/vec.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T, size_t N>
bool tryComputeAssumingType(OgnNormalizeDatabase& db, size_t count)
{
auto functor = [](auto const& vector, auto& result)
{
const auto& vec = *reinterpret_cast<const omni::math::linalg::base_vec<T, N>*>(vector);
auto& res = *reinterpret_cast<omni::math::linalg::base_vec<T, N>*>(result);
res = vec.GetNormalized();
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N]>(db.inputs.vector(), db.outputs.result(), functor, count);
}
} // namespace
class OgnNormalize
{
public:
static bool computeVectorized(OgnNormalizeDatabase& db, size_t count)
{
try
{
auto& type = db.inputs.vector().type();
switch (type.baseType)
{
case BaseDataType::eDouble:
switch (type.componentCount)
{
case 2:
return tryComputeAssumingType<double, 2>(db, count);
case 3:
return tryComputeAssumingType<double, 3>(db, count);
case 4:
return tryComputeAssumingType<double, 4>(db, count);
}
break;
case BaseDataType::eFloat:
switch (type.componentCount)
{
case 2:
return tryComputeAssumingType<float, 2>(db, count);
case 3:
return tryComputeAssumingType<float, 3>(db, count);
case 4:
return tryComputeAssumingType<float, 4>(db, count);
}
break;
case BaseDataType::eHalf:
switch (type.componentCount)
{
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
}
break;
default:
break;
}
throw ogn::compute::InputError("Failed to resolve input type");
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto vector = node.iNode->getAttributeByToken(node, inputs::vector.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
// Require input to be resolved before determining result's type
auto vectorType = vector.iAttribute->getResolvedType(vector);
if (vectorType.baseType != BaseDataType::eUnknown)
{
Type resultType(vectorType.baseType, vectorType.componentCount, vectorType.arrayDepth);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAbsolute.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 <carb/logging/Log.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <OgnAbsoluteDatabase.h>
#include <NumericUtils.h>
#include <cmath>
#include <type_traits>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename T>
T ogAbs(T const& input) noexcept
{
if constexpr (std::is_unsigned_v<T>)
{
return input;
}
else
{
return std::abs(input);
}
}
template <typename T, size_t N>
struct ComputeAbsoluteValueAssumingType
{
bool operator()(OgnAbsoluteDatabase& db) const
{
if constexpr (N == 1)
{
auto functor = [](T const& input, T& absolute) { absolute = ogAbs(input); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, T>(db.inputs.input(), db.outputs.absolute(), functor);
}
else
{
auto functor = [](auto const& input, auto& absolute)
{
for (size_t i = 0; i < N; ++i)
{
absolute[i] = ogAbs(input[i]);
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N]>(
db.inputs.input(), db.outputs.absolute(), functor);
}
}
};
}
class OgnAbsolute
{
public:
static bool compute(OgnAbsoluteDatabase& db)
{
try
{
auto const& type = db.inputs.input().type();
if (!callForNumericAttribute<ComputeAbsoluteValueAssumingType>(db, type))
{
throw ogn::compute::InputError("Failed to resolve input type");
}
}
catch (ogn::compute::InputError& error)
{
db.logError("OgnAbsolute: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto input = node.iNode->getAttributeByToken(node, inputs::input.token());
auto absolute = node.iNode->getAttributeByToken(node, outputs::absolute.token());
auto inputType = input.iAttribute->getResolvedType(input);
if (inputType.baseType != BaseDataType::eUnknown)
{
absolute.iAttribute->setResolvedType(absolute, inputType);
}
}
};
REGISTER_OGN_NODE()
}
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/warp_noise.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
// This file contains code taken from Warp for implementing noise functions.
// Once Warp is released this file will be deleted and the nodes which use
// it rewritten to use Warp.
#include <cmath>
#include <sys/types.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#ifndef _EPSILON
#define _EPSILON 1e-6
#endif
#define M_PIf 3.14159265358979323846f
namespace omni {
namespace graph {
namespace nodes {
typedef pxr::GfVec2f vec2;
typedef pxr::GfVec3f vec3;
typedef pxr::GfVec4f vec4;
// Adapted from warp/warp/native/rand.h
//
inline uint32_t rand_pcg(uint32_t state)
{
uint32_t b = state * 747796405u + 2891336453u;
uint32_t c = ((b >> ((b >> 28u) + 4u)) ^ b) * 277803737u;
return (c >> 22u) ^ c;
}
inline uint32_t rand_init(int seed) { return rand_pcg(uint32_t(seed)); }
inline uint32_t rand_init(int seed, int offset) { return rand_pcg(uint32_t(seed) + rand_pcg(uint32_t(offset))); }
inline int randi(uint32_t& state) { state = rand_pcg(state); return int(state); }
inline int randi(uint32_t& state, int min, int max) { state = rand_pcg(state); return state % (max - min) + min; }
inline float randf(uint32_t& state) { state = rand_pcg(state); return float(state) / 0xffffffff; }
inline float randf(uint32_t& state, float min, float max) { return (max - min) * randf(state) + min; }
// Box-Muller method
inline float randn(uint32_t& state) { return std::sqrt(-2.f * std::log(randf(state))) * std::cos(2.f * M_PIf * randf(state)); }
// Adapted from warp/warp/native/noise.h
//
inline float smootherstep(float t)
{
return t * t * t * (t * (t * 6.f - 15.f) + 10.f);
}
inline float smootherstep_gradient(float t)
{
return 30.f * t * t * (t * (t - 2.f) + 1.f);
}
inline float interpolate(float a0, float a1, float t)
{
return (a1 - a0) * smootherstep(t) + a0;
}
inline float interpolate_gradient(float a0, float a1, float t, float d_a0, float d_a1, float d_t)
{
return (d_a1 - d_a0) * smootherstep(t) + (a1 - a0) * smootherstep_gradient(t) * d_t + d_a0;
}
inline float random_gradient_1d(uint32_t seed, int ix)
{
const uint32_t p1 = 73856093;
uint32_t idx = ix*p1;
uint32_t state = seed + idx;
return randf(state, -1.f, 1.f);
}
inline vec2 random_gradient_2d(uint32_t seed, int ix, int iy)
{
const uint32_t p1 = 73856093;
const uint32_t p2 = 19349663;
uint32_t idx = ix*p1 ^ iy*p2;
uint32_t state = seed + idx;
float phi = randf(state, 0.f, 2.f*M_PIf);
float x = std::cos(phi);
float y = std::sin(phi);
return vec2(x, y);
}
inline vec3 random_gradient_3d(uint32_t seed, int ix, int iy, int iz)
{
const uint32_t p1 = 73856093;
const uint32_t p2 = 19349663;
const uint32_t p3 = 53471161;
uint32_t idx = ix*p1 ^ iy*p2 ^ iz*p3;
uint32_t state = seed + idx;
float x = randn(state);
float y = randn(state);
float z = randn(state);
return vec3(x, y, z).GetNormalized();
}
inline vec4 random_gradient_4d(uint32_t seed, int ix, int iy, int iz, int it)
{
const uint32_t p1 = 73856093;
const uint32_t p2 = 19349663;
const uint32_t p3 = 53471161;
const uint32_t p4 = 10000019;
uint32_t idx = ix*p1 ^ iy*p2 ^ iz*p3 ^ it*p4;
uint32_t state = seed + idx;
float x = randn(state);
float y = randn(state);
float z = randn(state);
float t = randn(state);
return vec4(x, y, z, t).GetNormalized();
}
inline float dot_grid_gradient_1d(uint32_t seed, int ix, float dx)
{
float gradient = random_gradient_1d(seed, ix);
return dx*gradient;
}
inline float dot_grid_gradient_1d_gradient(uint32_t seed, int ix, float d_dx)
{
float gradient = random_gradient_1d(seed, ix);
return d_dx*gradient;
}
inline float dot_grid_gradient_2d(uint32_t seed, int ix, int iy, float dx, float dy)
{
vec2 gradient = random_gradient_2d(seed, ix, iy);
return (dx*gradient[0] + dy*gradient[1]);
}
inline float dot_grid_gradient_2d_gradient(uint32_t seed, int ix, int iy, float d_dx, float d_dy)
{
vec2 gradient = random_gradient_2d(seed, ix, iy);
return (d_dx*gradient[0] + d_dy*gradient[1]);
}
inline float dot_grid_gradient_3d(uint32_t seed, int ix, int iy, int iz, float dx, float dy, float dz)
{
vec3 gradient = random_gradient_3d(seed, ix, iy, iz);
return (dx*gradient[0] + dy*gradient[1] + dz*gradient[2]);
}
inline float dot_grid_gradient_3d_gradient(uint32_t seed, int ix, int iy, int iz, float d_dx, float d_dy, float d_dz)
{
vec3 gradient = random_gradient_3d(seed, ix, iy, iz);
return (d_dx*gradient[0] + d_dy*gradient[1] + d_dz*gradient[2]);
}
inline float dot_grid_gradient_4d(uint32_t seed, int ix, int iy, int iz, int it, float dx, float dy, float dz, float dt)
{
vec4 gradient = random_gradient_4d(seed, ix, iy, iz, it);
return (dx*gradient[0] + dy*gradient[1] + dz*gradient[2] + dt*gradient[3]);
}
inline float dot_grid_gradient_4d_gradient(uint32_t seed, int ix, int iy, int iz, int it, float d_dx, float d_dy, float d_dz, float d_dt)
{
vec4 gradient = random_gradient_4d(seed, ix, iy, iz, it);
return (d_dx*gradient[0] + d_dy*gradient[1] + d_dz*gradient[2] + d_dt*gradient[3]);
}
inline float noise_1d(uint32_t seed, int x0, int x1, float dx)
{
//vX
float v0 = dot_grid_gradient_1d(seed, x0, dx);
float v1 = dot_grid_gradient_1d(seed, x1, dx-1.f);
return interpolate(v0, v1, dx);
}
inline float noise_1d_gradient(uint32_t seed, int x0, int x1, float dx, float heaviside_x)
{
float v0 = dot_grid_gradient_1d(seed, x0, dx);
float d_v0_dx = dot_grid_gradient_1d_gradient(seed, x0, heaviside_x);
float v1 = dot_grid_gradient_1d(seed, x1, dx-1.f);
float d_v1_dx = dot_grid_gradient_1d_gradient(seed, x1, heaviside_x);
return interpolate_gradient(v0, v1, dx, d_v0_dx, d_v1_dx, heaviside_x);
}
inline float noise_2d(uint32_t seed, int x0, int y0, int x1, int y1, float dx, float dy)
{
//vXY
float v00 = dot_grid_gradient_2d(seed, x0, y0, dx, dy);
float v10 = dot_grid_gradient_2d(seed, x1, y0, dx-1.f, dy);
float xi0 = interpolate(v00, v10, dx);
float v01 = dot_grid_gradient_2d(seed, x0, y1, dx, dy-1.f);
float v11 = dot_grid_gradient_2d(seed, x1, y1, dx-1.f, dy-1.f);
float xi1 = interpolate(v01, v11, dx);
return interpolate(xi0, xi1, dy);
}
inline vec2 noise_2d_gradient(uint32_t seed, int x0, int y0, int x1, int y1, float dx, float dy, float heaviside_x, float heaviside_y)
{
float v00 = dot_grid_gradient_2d(seed, x0, y0, dx, dy);
float d_v00_dx = dot_grid_gradient_2d_gradient(seed, x0, y0, heaviside_x, 0.f);
float d_v00_dy = dot_grid_gradient_2d_gradient(seed, x0, y0, 0.0, heaviside_y);
float v10 = dot_grid_gradient_2d(seed, x1, y0, dx-1.f, dy);
float d_v10_dx = dot_grid_gradient_2d_gradient(seed, x1, y0, heaviside_x, 0.f);
float d_v10_dy = dot_grid_gradient_2d_gradient(seed, x1, y0, 0.0, heaviside_y);
float v01 = dot_grid_gradient_2d(seed, x0, y1, dx, dy-1.f);
float d_v01_dx = dot_grid_gradient_2d_gradient(seed, x0, y1, heaviside_x, 0.f);
float d_v01_dy = dot_grid_gradient_2d_gradient(seed, x0, y1, 0.0, heaviside_y);
float v11 = dot_grid_gradient_2d(seed, x1, y1, dx-1.f, dy-1.f);
float d_v11_dx = dot_grid_gradient_2d_gradient(seed, x1, y1, heaviside_x, 0.f);
float d_v11_dy = dot_grid_gradient_2d_gradient(seed, x1, y1, 0.0, heaviside_y);
float xi0 = interpolate(v00, v10, dx);
float d_xi0_dx = interpolate_gradient(v00, v10, dx, d_v00_dx, d_v10_dx, heaviside_x);
float d_xi0_dy = interpolate_gradient(v00, v10, dx, d_v00_dy, d_v10_dy, 0.0);
float xi1 = interpolate(v01, v11, dx);
float d_xi1_dx = interpolate_gradient(v01, v11, dx, d_v01_dx, d_v11_dx, heaviside_x);
float d_xi1_dy = interpolate_gradient(v01, v11, dx, d_v01_dy, d_v11_dy, 0.0);
float gradient_x = interpolate_gradient(xi0, xi1, dy, d_xi0_dx, d_xi1_dx, 0.0);
float gradient_y = interpolate_gradient(xi0, xi1, dy, d_xi0_dy, d_xi1_dy, heaviside_y);
return vec2(gradient_x, gradient_y);
}
inline float noise_3d(uint32_t seed, int x0, int y0, int z0, int x1, int y1, int z1, float dx, float dy, float dz)
{
//vXYZ
float v000 = dot_grid_gradient_3d(seed, x0, y0, z0, dx, dy, dz);
float v100 = dot_grid_gradient_3d(seed, x1, y0, z0, dx-1.f, dy, dz);
float xi00 = interpolate(v000, v100, dx);
float v010 = dot_grid_gradient_3d(seed, x0, y1, z0, dx, dy-1.f, dz);
float v110 = dot_grid_gradient_3d(seed, x1, y1, z0, dx-1.f, dy-1.f, dz);
float xi10 = interpolate(v010, v110, dx);
float yi0 = interpolate(xi00, xi10, dy);
float v001 = dot_grid_gradient_3d(seed, x0, y0, z1, dx, dy, dz-1.f);
float v101 = dot_grid_gradient_3d(seed, x1, y0, z1, dx-1.f, dy, dz-1.f);
float xi01 = interpolate(v001, v101, dx);
float v011 = dot_grid_gradient_3d(seed, x0, y1, z1, dx, dy-1.f, dz-1.f);
float v111 = dot_grid_gradient_3d(seed, x1, y1, z1, dx-1.f, dy-1.f, dz-1.f);
float xi11 = interpolate(v011, v111, dx);
float yi1 = interpolate(xi01, xi11, dy);
return interpolate(yi0, yi1, dz);
}
inline vec3 noise_3d_gradient(uint32_t seed, int x0, int y0, int z0, int x1, int y1, int z1, float dx, float dy, float dz, float heaviside_x, float heaviside_y, float heaviside_z)
{
float v000 = dot_grid_gradient_3d(seed, x0, y0, z0, dx, dy, dz);
float d_v000_dx = dot_grid_gradient_3d_gradient(seed, x0, y0, z0, heaviside_x, 0.f, 0.f);
float d_v000_dy = dot_grid_gradient_3d_gradient(seed, x0, y0, z0, 0.f, heaviside_y, 0.f);
float d_v000_dz = dot_grid_gradient_3d_gradient(seed, x0, y0, z0, 0.f, 0.f, heaviside_z);
float v100 = dot_grid_gradient_3d(seed, x1, y0, z0, dx-1.f, dy, dz);
float d_v100_dx = dot_grid_gradient_3d_gradient(seed, x1, y0, z0, heaviside_x, 0.f, 0.f);
float d_v100_dy = dot_grid_gradient_3d_gradient(seed, x1, y0, z0, 0.f, heaviside_y, 0.f);
float d_v100_dz = dot_grid_gradient_3d_gradient(seed, x1, y0, z0, 0.f, 0.f, heaviside_z);
float v010 = dot_grid_gradient_3d(seed, x0, y1, z0, dx, dy-1.f, dz);
float d_v010_dx = dot_grid_gradient_3d_gradient(seed, x0, y1, z0, heaviside_x, 0.f, 0.f);
float d_v010_dy = dot_grid_gradient_3d_gradient(seed, x0, y1, z0, 0.f, heaviside_y, 0.f);
float d_v010_dz = dot_grid_gradient_3d_gradient(seed, x0, y1, z0, 0.f, 0.f, heaviside_z);
float v110 = dot_grid_gradient_3d(seed, x1, y1, z0, dx-1.f, dy-1.f, dz);
float d_v110_dx = dot_grid_gradient_3d_gradient(seed, x1, y1, z0, heaviside_x, 0.f, 0.f);
float d_v110_dy = dot_grid_gradient_3d_gradient(seed, x1, y1, z0, 0.f, heaviside_y, 0.f);
float d_v110_dz = dot_grid_gradient_3d_gradient(seed, x1, y1, z0, 0.f, 0.f, heaviside_z);
float v001 = dot_grid_gradient_3d(seed, x0, y0, z1, dx, dy, dz-1.f);
float d_v001_dx = dot_grid_gradient_3d_gradient(seed, x0, y0, z1, heaviside_x, 0.f, 0.f);
float d_v001_dy = dot_grid_gradient_3d_gradient(seed, x0, y0, z1, 0.f, heaviside_y, 0.f);
float d_v001_dz = dot_grid_gradient_3d_gradient(seed, x0, y0, z1, 0.f, 0.f, heaviside_z);
float v101 = dot_grid_gradient_3d(seed, x1, y0, z1, dx-1.f, dy, dz-1.f);
float d_v101_dx = dot_grid_gradient_3d_gradient(seed, x1, y0, z1, heaviside_x, 0.f, 0.f);
float d_v101_dy = dot_grid_gradient_3d_gradient(seed, x1, y0, z1, 0.f, heaviside_y, 0.f);
float d_v101_dz = dot_grid_gradient_3d_gradient(seed, x1, y0, z1, 0.f, 0.f, heaviside_z);
float v011 = dot_grid_gradient_3d(seed, x0, y1, z1, dx, dy-1.f, dz-1.f);
float d_v011_dx = dot_grid_gradient_3d_gradient(seed, x0, y1, z1, heaviside_x, 0.f, 0.f);
float d_v011_dy = dot_grid_gradient_3d_gradient(seed, x0, y1, z1, 0.f, heaviside_y, 0.f);
float d_v011_dz = dot_grid_gradient_3d_gradient(seed, x0, y1, z1, 0.f, 0.f, heaviside_z);
float v111 = dot_grid_gradient_3d(seed, x1, y1, z1, dx-1.f, dy-1.f, dz-1.f);
float d_v111_dx = dot_grid_gradient_3d_gradient(seed, x1, y1, z1, heaviside_x, 0.f, 0.f);
float d_v111_dy = dot_grid_gradient_3d_gradient(seed, x1, y1, z1, 0.f, heaviside_y, 0.f);
float d_v111_dz = dot_grid_gradient_3d_gradient(seed, x1, y1, z1, 0.f, 0.f, heaviside_z);
float xi00 = interpolate(v000, v100, dx);
float d_xi00_dx = interpolate_gradient(v000, v100, dx, d_v000_dx, d_v100_dx, heaviside_x);
float d_xi00_dy = interpolate_gradient(v000, v100, dx, d_v000_dy, d_v100_dy, 0.f);
float d_xi00_dz = interpolate_gradient(v000, v100, dx, d_v000_dz, d_v100_dz, 0.f);
float xi10 = interpolate(v010, v110, dx);
float d_xi10_dx = interpolate_gradient(v010, v110, dx, d_v010_dx, d_v110_dx, heaviside_x);
float d_xi10_dy = interpolate_gradient(v010, v110, dx, d_v010_dy, d_v110_dy, 0.f);
float d_xi10_dz = interpolate_gradient(v010, v110, dx, d_v010_dz, d_v110_dz, 0.f);
float xi01 = interpolate(v001, v101, dx);
float d_xi01_dx = interpolate_gradient(v001, v101, dx, d_v001_dx, d_v101_dx, heaviside_x);
float d_xi01_dy = interpolate_gradient(v001, v101, dx, d_v001_dy, d_v101_dy, 0.f);
float d_xi01_dz = interpolate_gradient(v001, v101, dx, d_v001_dz, d_v101_dz, 0.f);
float xi11 = interpolate(v011, v111, dx);
float d_xi11_dx = interpolate_gradient(v011, v111, dx, d_v011_dx, d_v111_dx, heaviside_x);
float d_xi11_dy = interpolate_gradient(v011, v111, dx, d_v011_dy, d_v111_dy, 0.f);
float d_xi11_dz = interpolate_gradient(v011, v111, dx, d_v011_dz, d_v111_dz, 0.f);
float yi0 = interpolate(xi00, xi10, dy);
float d_yi0_dx = interpolate_gradient(xi00, xi10, dy, d_xi00_dx, d_xi10_dx, 0.f);
float d_yi0_dy = interpolate_gradient(xi00, xi10, dy, d_xi00_dy, d_xi10_dy, heaviside_y);
float d_yi0_dz = interpolate_gradient(xi00, xi10, dy, d_xi00_dz, d_xi10_dz, 0.f);
float yi1 = interpolate(xi01, xi11, dy);
float d_yi1_dx = interpolate_gradient(xi01, xi11, dy, d_xi01_dx, d_xi11_dx, 0.f);
float d_yi1_dy = interpolate_gradient(xi01, xi11, dy, d_xi01_dy, d_xi11_dy, heaviside_y);
float d_yi1_dz = interpolate_gradient(xi01, xi11, dy, d_xi01_dz, d_xi11_dz, 0.f);
float gradient_x = interpolate_gradient(yi0, yi1, dz, d_yi0_dy, d_yi1_dy, 0.f);
float gradient_y = interpolate_gradient(yi0, yi1, dz, d_yi0_dx, d_yi1_dx, 0.f);
float gradient_z = interpolate_gradient(yi0, yi1, dz, d_yi0_dz, d_yi1_dz, heaviside_z);
return vec3(gradient_x, gradient_y, gradient_z);
}
inline float noise_4d(uint32_t seed, int x0, int y0, int z0, int t0, int x1, int y1, int z1, int t1, float dx, float dy, float dz, float dt)
{
//vXYZT
float v0000 = dot_grid_gradient_4d(seed, x0, y0, z0, t0, dx, dy, dz, dt);
float v1000 = dot_grid_gradient_4d(seed, x1, y0, z0, t0, dx-1.f, dy, dz, dt);
float xi000 = interpolate(v0000, v1000, dx);
float v0100 = dot_grid_gradient_4d(seed, x0, y1, z0, t0, dx, dy-1.f, dz, dt);
float v1100 = dot_grid_gradient_4d(seed, x1, y1, z0, t0, dx-1.f, dy-1.f, dz, dt);
float xi100 = interpolate(v0100, v1100, dx);
float yi00 = interpolate(xi000, xi100, dy);
float v0010 = dot_grid_gradient_4d(seed, x0, y0, z1, t0, dx, dy, dz-1.f, dt);
float v1010 = dot_grid_gradient_4d(seed, x1, y0, z1, t0, dx-1.f, dy, dz-1.f, dt);
float xi010 = interpolate(v0010, v1010, dx);
float v0110 = dot_grid_gradient_4d(seed, x0, y1, z1, t0, dx, dy-1.f, dz-1.f, dt);
float v1110 = dot_grid_gradient_4d(seed, x1, y1, z1, t0, dx-1.f, dy-1.f, dz-1.f, dt);
float xi110 = interpolate(v0110, v1110, dx);
float yi10 = interpolate(xi010, xi110, dy);
float zi0 = interpolate(yi00, yi10, dz);
float v0001 = dot_grid_gradient_4d(seed, x0, y0, z0, t1, dx, dy, dz, dt-1.f);
float v1001 = dot_grid_gradient_4d(seed, x1, y0, z0, t1, dx-1.f, dy, dz, dt-1.f);
float xi001 = interpolate(v0001, v1001, dx);
float v0101 = dot_grid_gradient_4d(seed, x0, y1, z0, t1, dx, dy-1.f, dz, dt-1.f);
float v1101 = dot_grid_gradient_4d(seed, x1, y1, z0, t1, dx-1.f, dy-1.f, dz, dt-1.f);
float xi101 = interpolate(v0101, v1101, dx);
float yi01 = interpolate(xi001, xi101, dy);
float v0011 = dot_grid_gradient_4d(seed, x0, y0, z1, t1, dx, dy, dz-1.f, dt-1.f);
float v1011 = dot_grid_gradient_4d(seed, x1, y0, z1, t1, dx-1.f, dy, dz-1.f, dt-1.f);
float xi011 = interpolate(v0011, v1011, dx);
float v0111 = dot_grid_gradient_4d(seed, x0, y1, z1, t1, dx, dy-1.f, dz-1.f, dt-1.f);
float v1111 = dot_grid_gradient_4d(seed, x1, y1, z1, t1, dx-1.f, dy-1.f, dz-1.f, dt-1.f);
float xi111 = interpolate(v0111, v1111, dx);
float yi11 = interpolate(xi011, xi111, dy);
float zi1 = interpolate(yi01, yi11, dz);
return interpolate(zi0, zi1, dt);
}
inline vec4 noise_4d_gradient(uint32_t seed, int x0, int y0, int z0, int t0, int x1, int y1, int z1, int t1, float dx, float dy, float dz, float dt, float heaviside_x, float heaviside_y, float heaviside_z, float heaviside_t)
{
float v0000 = dot_grid_gradient_4d(seed, x0, y0, z0, t0, dx, dy, dz, dt);
float d_v0000_dx = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v0000_dy = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v0000_dz = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v0000_dt = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t0, 0.f, 0.f, 0.f, heaviside_t);
float v1000 = dot_grid_gradient_4d(seed, x1, y0, z0, t0, dx-1.f, dy, dz, dt);
float d_v1000_dx = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v1000_dy = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v1000_dz = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v1000_dt = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t0, 0.f, 0.f, 0.f, heaviside_t);
float v0100 = dot_grid_gradient_4d(seed, x0, y1, z0, t0, dx, dy-1.f, dz, dt);
float d_v0100_dx = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v0100_dy = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v0100_dz = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v0100_dt = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t0, 0.f, 0.f, 0.f, heaviside_t);
float v1100 = dot_grid_gradient_4d(seed, x1, y1, z0, t0, dx-1.f, dy-1.f, dz, dt);
float d_v1100_dx = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v1100_dy = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v1100_dz = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v1100_dt = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t0, 0.f, 0.f, 0.f, heaviside_t);
float v0010 = dot_grid_gradient_4d(seed, x0, y0, z1, t0, dx, dy, dz-1.f, dt);
float d_v0010_dx = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v0010_dy = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v0010_dz = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v0010_dt = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t0, 0.f, 0.f, 0.f, heaviside_t);
float v1010 = dot_grid_gradient_4d(seed, x1, y0, z1, t0, dx-1.f, dy, dz-1.f, dt);
float d_v1010_dx = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v1010_dy = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v1010_dz = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v1010_dt = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t0, 0.f, 0.f, 0.f, heaviside_t);
float v0110 = dot_grid_gradient_4d(seed, x0, y1, z1, t0, dx, dy-1.f, dz-1.f, dt);
float d_v0110_dx = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v0110_dy = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v0110_dz = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v0110_dt = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t0, 0.f, 0.f, 0.f, heaviside_t);
float v1110 = dot_grid_gradient_4d(seed, x1, y1, z1, t0, dx-1.f, dy-1.f, dz-1.f, dt);
float d_v1110_dx = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v1110_dy = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v1110_dz = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v1110_dt = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t0, 0.f, 0.f, 0.f, heaviside_t);
float v0001 = dot_grid_gradient_4d(seed, x0, y0, z0, t1, dx, dy, dz, dt-1.f);
float d_v0001_dx = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v0001_dy = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v0001_dz = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v0001_dt = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t1, 0.f, 0.f, 0.f, heaviside_t);
float v1001 = dot_grid_gradient_4d(seed, x1, y0, z0, t1, dx-1.f, dy, dz, dt-1.f);
float d_v1001_dx = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v1001_dy = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v1001_dz = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v1001_dt = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t1, 0.f, 0.f, 0.f, heaviside_t);
float v0101 = dot_grid_gradient_4d(seed, x0, y1, z0, t1, dx, dy-1.f, dz, dt-1.f);
float d_v0101_dx = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v0101_dy = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v0101_dz = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v0101_dt = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t1, 0.f, 0.f, 0.f, heaviside_t);
float v1101 = dot_grid_gradient_4d(seed, x1, y1, z0, t1, dx-1.f, dy-1.f, dz, dt-1.f);
float d_v1101_dx = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v1101_dy = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v1101_dz = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v1101_dt = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t1, 0.f, 0.f, 0.f, heaviside_t);
float v0011 = dot_grid_gradient_4d(seed, x0, y0, z1, t1, dx, dy, dz-1.f, dt-1.f);
float d_v0011_dx = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v0011_dy = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v0011_dz = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v0011_dt = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t1, 0.f, 0.f, 0.f, heaviside_t);
float v1011 = dot_grid_gradient_4d(seed, x1, y0, z1, t1, dx-1.f, dy, dz-1.f, dt-1.f);
float d_v1011_dx = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v1011_dy = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v1011_dz = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v1011_dt = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t1, 0.f, 0.f, 0.f, heaviside_t);
float v0111 = dot_grid_gradient_4d(seed, x0, y1, z1, t1, dx, dy-1.f, dz-1.f, dt-1.f);
float d_v0111_dx = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v0111_dy = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v0111_dz = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v0111_dt = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t1, 0.f, 0.f, 0.f, heaviside_t);
float v1111 = dot_grid_gradient_4d(seed, x1, y1, z1, t1, dx-1.f, dy-1.f, dz-1.f, dt-1.f);
float d_v1111_dx = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v1111_dy = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v1111_dz = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v1111_dt = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t1, 0.f, 0.f, 0.f, heaviside_t);
float xi000 = interpolate(v0000, v1000, dx);
float d_xi000_dx = interpolate_gradient(v0000, v1000, dx, d_v0000_dx, d_v1000_dx, heaviside_x);
float d_xi000_dy = interpolate_gradient(v0000, v1000, dx, d_v0000_dy, d_v1000_dy, 0.f);
float d_xi000_dz = interpolate_gradient(v0000, v1000, dx, d_v0000_dz, d_v1000_dz, 0.f);
float d_xi000_dt = interpolate_gradient(v0000, v1000, dx, d_v0000_dt, d_v1000_dt, 0.f);
float xi100 = interpolate(v0100, v1100, dx);
float d_xi100_dx = interpolate_gradient(v0100, v1100, dx, d_v0100_dx, d_v1100_dx, heaviside_x);
float d_xi100_dy = interpolate_gradient(v0100, v1100, dx, d_v0100_dy, d_v1100_dy, 0.f);
float d_xi100_dz = interpolate_gradient(v0100, v1100, dx, d_v0100_dz, d_v1100_dz, 0.f);
float d_xi100_dt = interpolate_gradient(v0100, v1100, dx, d_v0100_dt, d_v1100_dt, 0.f);
float xi010 = interpolate(v0010, v1010, dx);
float d_xi010_dx = interpolate_gradient(v0010, v1010, dx, d_v0010_dx, d_v1010_dx, heaviside_x);
float d_xi010_dy = interpolate_gradient(v0010, v1010, dx, d_v0010_dy, d_v1010_dy, 0.f);
float d_xi010_dz = interpolate_gradient(v0010, v1010, dx, d_v0010_dz, d_v1010_dz, 0.f);
float d_xi010_dt = interpolate_gradient(v0010, v1010, dx, d_v0010_dt, d_v1010_dt, 0.f);
float xi110 = interpolate(v0110, v1110, dx);
float d_xi110_dx = interpolate_gradient(v0110, v1110, dx, d_v0110_dx, d_v1110_dx, heaviside_x);
float d_xi110_dy = interpolate_gradient(v0110, v1110, dx, d_v0110_dy, d_v1110_dy, 0.f);
float d_xi110_dz = interpolate_gradient(v0110, v1110, dx, d_v0110_dz, d_v1110_dz, 0.f);
float d_xi110_dt = interpolate_gradient(v0110, v1110, dx, d_v0110_dt, d_v1110_dt, 0.f);
float xi001 = interpolate(v0001, v1001, dx);
float d_xi001_dx = interpolate_gradient(v0001, v1001, dx, d_v0001_dx, d_v1001_dx, heaviside_x);
float d_xi001_dy = interpolate_gradient(v0001, v1001, dx, d_v0001_dy, d_v1001_dy, 0.f);
float d_xi001_dz = interpolate_gradient(v0001, v1001, dx, d_v0001_dz, d_v1001_dz, 0.f);
float d_xi001_dt = interpolate_gradient(v0001, v1001, dx, d_v0001_dt, d_v1001_dt, 0.f);
float xi101 = interpolate(v0101, v1101, dx);
float d_xi101_dx = interpolate_gradient(v0101, v1101, dx, d_v0101_dx, d_v1101_dx, heaviside_x);
float d_xi101_dy = interpolate_gradient(v0101, v1101, dx, d_v0101_dy, d_v1101_dy, 0.f);
float d_xi101_dz = interpolate_gradient(v0101, v1101, dx, d_v0101_dz, d_v1101_dz, 0.f);
float d_xi101_dt = interpolate_gradient(v0101, v1101, dx, d_v0101_dt, d_v1101_dt, 0.f);
float xi011 = interpolate(v0011, v1011, dx);
float d_xi011_dx = interpolate_gradient(v0011, v1011, dx, d_v0011_dx, d_v1011_dx, heaviside_x);
float d_xi011_dy = interpolate_gradient(v0011, v1011, dx, d_v0011_dy, d_v1011_dy, 0.f);
float d_xi011_dz = interpolate_gradient(v0011, v1011, dx, d_v0011_dz, d_v1011_dz, 0.f);
float d_xi011_dt = interpolate_gradient(v0011, v1011, dx, d_v0011_dt, d_v1011_dt, 0.f);
float xi111 = interpolate(v0111, v1111, dx);
float d_xi111_dx = interpolate_gradient(v0111, v1111, dx, d_v0111_dx, d_v1111_dx, heaviside_x);
float d_xi111_dy = interpolate_gradient(v0111, v1111, dx, d_v0111_dy, d_v1111_dy, 0.f);
float d_xi111_dz = interpolate_gradient(v0111, v1111, dx, d_v0111_dz, d_v1111_dz, 0.f);
float d_xi111_dt = interpolate_gradient(v0111, v1111, dx, d_v0111_dt, d_v1111_dt, 0.f);
float yi00 = interpolate(xi000, xi100, dy);
float d_yi00_dx = interpolate_gradient(xi000, xi100, dy, d_xi000_dx, d_xi100_dx, 0.f);
float d_yi00_dy = interpolate_gradient(xi000, xi100, dy, d_xi000_dy, d_xi100_dy, heaviside_y);
float d_yi00_dz = interpolate_gradient(xi000, xi100, dy, d_xi000_dz, d_xi100_dz, 0.f);
float d_yi00_dt = interpolate_gradient(xi000, xi100, dy, d_xi000_dt, d_xi100_dt, 0.f);
float yi10 = interpolate(xi010, xi110, dy);
float d_yi10_dx = interpolate_gradient(xi010, xi110, dy, d_xi010_dx, d_xi110_dx, 0.f);
float d_yi10_dy = interpolate_gradient(xi010, xi110, dy, d_xi010_dy, d_xi110_dy, heaviside_y);
float d_yi10_dz = interpolate_gradient(xi010, xi110, dy, d_xi010_dz, d_xi110_dz, 0.f);
float d_yi10_dt = interpolate_gradient(xi010, xi110, dy, d_xi010_dt, d_xi110_dt, 0.f);
float yi01 = interpolate(xi001, xi101, dy);
float d_yi01_dx = interpolate_gradient(xi001, xi101, dy, d_xi001_dx, d_xi101_dx, 0.f);
float d_yi01_dy = interpolate_gradient(xi001, xi101, dy, d_xi001_dy, d_xi101_dy, heaviside_y);
float d_yi01_dz = interpolate_gradient(xi001, xi101, dy, d_xi001_dz, d_xi101_dz, 0.f);
float d_yi01_dt = interpolate_gradient(xi001, xi101, dy, d_xi001_dt, d_xi101_dt, 0.f);
float yi11 = interpolate(xi011, xi111, dy);
float d_yi11_dx = interpolate_gradient(xi011, xi111, dy, d_xi011_dx, d_xi111_dx, 0.f);
float d_yi11_dy = interpolate_gradient(xi011, xi111, dy, d_xi011_dy, d_xi111_dy, heaviside_y);
float d_yi11_dz = interpolate_gradient(xi011, xi111, dy, d_xi011_dz, d_xi111_dz, 0.f);
float d_yi11_dt = interpolate_gradient(xi011, xi111, dy, d_xi011_dt, d_xi111_dt, 0.f);
float zi0 = interpolate(yi00, yi10, dz);
float d_zi0_dx = interpolate_gradient(yi00, yi10, dz, d_yi00_dx, d_yi10_dx, 0.f);
float d_zi0_dy = interpolate_gradient(yi00, yi10, dz, d_yi00_dy, d_yi10_dy, 0.f);
float d_zi0_dz = interpolate_gradient(yi00, yi10, dz, d_yi00_dz, d_yi10_dz, heaviside_z);
float d_zi0_dt = interpolate_gradient(yi00, yi10, dz, d_yi00_dt, d_yi10_dt, 0.f);
float zi1 = interpolate(yi01, yi11, dz);
float d_zi1_dx = interpolate_gradient(yi01, yi11, dz, d_yi01_dx, d_yi11_dx, 0.f);
float d_zi1_dy = interpolate_gradient(yi01, yi11, dz, d_yi01_dy, d_yi11_dy, 0.f);
float d_zi1_dz = interpolate_gradient(yi01, yi11, dz, d_yi01_dz, d_yi11_dz, heaviside_z);
float d_zi1_dt = interpolate_gradient(yi01, yi11, dz, d_yi01_dt, d_yi11_dt, 0.f);
float gradient_x = interpolate_gradient(zi0, zi1, dt, d_zi0_dx, d_zi1_dx, 0.f);
float gradient_y = interpolate_gradient(zi0, zi1, dt, d_zi0_dy, d_zi1_dy, 0.f);
float gradient_z = interpolate_gradient(zi0, zi1, dt, d_zi0_dz, d_zi1_dz, 0.f);
float gradient_t = interpolate_gradient(zi0, zi1, dt, d_zi0_dt, d_zi1_dt, heaviside_t);
return vec4(gradient_x, gradient_y, gradient_z, gradient_t);
}
// non-periodic Perlin noise
inline float noise(uint32_t seed, float x)
{
float dx = x - floor(x);
int x0 = (int)floor(x);
int x1 = x0 + 1;
return noise_1d(seed, x0, x1, dx);
}
inline float noise(uint32_t seed, const vec2& xy)
{
float dx = xy[0] - floor(xy[0]);
float dy = xy[1] - floor(xy[1]);
int x0 = (int)floor(xy[0]);
int y0 = (int)floor(xy[1]);
int x1 = x0 + 1;
int y1 = y0 + 1;
return noise_2d(seed, x0, y0, x1, y1, dx, dy);
}
inline float noise(uint32_t seed, const vec3& xyz)
{
float dx = xyz[0] - floor(xyz[0]);
float dy = xyz[1] - floor(xyz[1]);
float dz = xyz[2] - floor(xyz[2]);
int x0 = (int)floor(xyz[0]);
int y0 = (int)floor(xyz[1]);
int z0 = (int)floor(xyz[2]);
int x1 = x0 + 1;
int y1 = y0 + 1;
int z1 = z0 + 1;
return noise_3d(seed, x0, y0, z0, x1, y1, z1, dx, dy, dz);
}
inline float noise(uint32_t seed, const vec4& xyzt)
{
float dx = xyzt[0] - floor(xyzt[0]);
float dy = xyzt[1] - floor(xyzt[1]);
float dz = xyzt[2] - floor(xyzt[2]);
float dt = xyzt[3] - floor(xyzt[3]);
int x0 = (int)floor(xyzt[0]);
int y0 = (int)floor(xyzt[1]);
int z0 = (int)floor(xyzt[2]);
int t0 = (int)floor(xyzt[3]);
int x1 = x0 + 1;
int y1 = y0 + 1;
int z1 = z0 + 1;
int t1 = t0 + 1;
return noise_4d(seed, x0, y0, z0, t0, x1, y1, z1, t1, dx, dy, dz, dt);
}
// periodic Perlin noise
inline float pnoise(uint32_t seed, float x, int px)
{
float dx = x - floor(x);
int x0 = ((int)floor(x)) % px;
int x1 = (x0 + 1) % px;
return noise_1d(seed, x0, x1, dx);
}
inline float pnoise(uint32_t seed, const vec2& xy, int px, int py)
{
float dx = xy[0] - floor(xy[0]);
float dy = xy[1] - floor(xy[1]);
int x0 = ((int)floor(xy[0])) % px;
int y0 = ((int)floor(xy[1])) % py;
int x1 = (x0 + 1) % px;
int y1 = (y0 + 1) % py;
return noise_2d(seed, x0, y0, x1, y1, dx, dy);
}
inline float pnoise(uint32_t seed, const vec3& xyz, int px, int py, int pz)
{
float dx = xyz[0] - floor(xyz[0]);
float dy = xyz[1] - floor(xyz[1]);
float dz = xyz[2] - floor(xyz[2]);
int x0 = ((int)floor(xyz[0])) % px;
int y0 = ((int)floor(xyz[1])) % py;
int z0 = ((int)floor(xyz[2])) % pz;
int x1 = (x0 + 1) % px;
int y1 = (y0 + 1) % py;
int z1 = (z0 + 1) % pz;
return noise_3d(seed, x0, y0, z0, x1, y1, z1, dx, dy, dz);
}
inline float pnoise(uint32_t seed, const vec4& xyzt, int px, int py, int pz, int pt)
{
float dx = xyzt[0] - floor(xyzt[0]);
float dy = xyzt[1] - floor(xyzt[1]);
float dz = xyzt[2] - floor(xyzt[2]);
float dt = xyzt[3] - floor(xyzt[3]);
int x0 = ((int)floor(xyzt[0])) % px;
int y0 = ((int)floor(xyzt[1])) % py;
int z0 = ((int)floor(xyzt[2])) % pz;
int t0 = ((int)floor(xyzt[3])) % pt;
int x1 = (x0 + 1) % px;
int y1 = (y0 + 1) % py;
int z1 = (z0 + 1) % pz;
int t1 = (t0 + 1) % pt;
return noise_4d(seed, x0, y0, z0, t0, x1, y1, z1, t1, dx, dy, dz, dt);
}
// curl noise
inline vec2 curlnoise(uint32_t seed, const vec2& xy)
{
float dx = xy[0] - floor(xy[0]);
float dy = xy[1] - floor(xy[1]);
float heaviside_x = 1.f;
float heaviside_y = 1.f;
if (dx < _EPSILON) heaviside_x = 0.f;
if (dy < _EPSILON) heaviside_y = 0.f;
int x0 = (int)floor(xy[0]);
int y0 = (int)floor(xy[1]);
int x1 = x0 + 1;
int y1 = y0 + 1;
vec2 grad_field = noise_2d_gradient(seed, x0, y0, x1, y1, dx, dy, heaviside_x, heaviside_y);
return vec2(-grad_field[1], grad_field[0]);
}
inline vec3 curlnoise(uint32_t seed, const vec3& xyz)
{
float dx = xyz[0] - floor(xyz[0]);
float dy = xyz[1] - floor(xyz[1]);
float dz = xyz[2] - floor(xyz[2]);
float heaviside_x = 1.f;
float heaviside_y = 1.f;
float heaviside_z = 1.f;
if (dx < _EPSILON) heaviside_x = 0.f;
if (dy < _EPSILON) heaviside_y = 0.f;
if (dz < _EPSILON) heaviside_z = 0.f;
int x0 = (int)floor(xyz[0]);
int y0 = (int)floor(xyz[1]);
int z0 = (int)floor(xyz[2]);
int x1 = x0 + 1;
int y1 = y0 + 1;
int z1 = z0 + 1;
vec3 grad_field_1 = noise_3d_gradient(seed, x0, y0, z0, x1, y1, z1, dx, dy, dz, heaviside_x, heaviside_y, heaviside_z);
seed = rand_init(seed, 10019689);
vec3 grad_field_2 = noise_3d_gradient(seed, x0, y0, z0, x1, y1, z1, dx, dy, dz, heaviside_x, heaviside_y, heaviside_z);
seed = rand_init(seed, 13112221);
vec3 grad_field_3 = noise_3d_gradient(seed, x0, y0, z0, x1, y1, z1, dx, dy, dz, heaviside_x, heaviside_y, heaviside_z);
return vec3(
grad_field_3[1] - grad_field_2[2],
grad_field_1[2] - grad_field_3[0],
grad_field_2[0] - grad_field_1[1]);
}
inline vec3 curlnoise(uint32_t seed, const vec4& xyzt)
{
float dx = xyzt[0] - floor(xyzt[0]);
float dy = xyzt[1] - floor(xyzt[1]);
float dz = xyzt[2] - floor(xyzt[2]);
float dt = xyzt[3] - floor(xyzt[3]);
float heaviside_x = 1.f;
float heaviside_y = 1.f;
float heaviside_z = 1.f;
float heaviside_t = 1.f;
if (dx < _EPSILON) heaviside_x = 0.f;
if (dy < _EPSILON) heaviside_y = 0.f;
if (dz < _EPSILON) heaviside_z = 0.f;
if (dt < _EPSILON) heaviside_t = 0.f;
int x0 = (int)floor(xyzt[0]);
int y0 = (int)floor(xyzt[1]);
int z0 = (int)floor(xyzt[2]);
int t0 = (int)floor(xyzt[3]);
int x1 = x0 + 1;
int y1 = y0 + 1;
int z1 = z0 + 1;
int t1 = t0 + 1;
vec4 grad_field_1 = noise_4d_gradient(seed, x0, y0, z0, t0, x1, y1, z1, t1, dx, dy, dz, dt, heaviside_x, heaviside_y, heaviside_z, heaviside_t);
seed = rand_init(seed, 10019689);
vec4 grad_field_2 = noise_4d_gradient(seed, x0, y0, z0, t0, x1, y1, z1, t1, dx, dy, dz, dt, heaviside_x, heaviside_y, heaviside_z, heaviside_t);
seed = rand_init(seed, 13112221);
vec4 grad_field_3 = noise_4d_gradient(seed, x0, y0, z0, t0, x1, y1, z1, t1, dx, dy, dz, dt, heaviside_x, heaviside_y, heaviside_z, heaviside_t);
return vec3(
grad_field_3[1] - grad_field_2[2],
grad_field_1[2] - grad_field_3[0],
grad_field_2[0] - grad_field_1[1]);
}
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomUnitQuaternion.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 "random/RandomNodeBase.h"
#include <OgnRandomUnitQuaternionDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
using namespace random;
class OgnRandomUnitQuaternion : public NodeBase<OgnRandomUnitQuaternion, OgnRandomUnitQuaternionDatabase>
{
public:
static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed);
}
static bool onCompute(OgnRandomUnitQuaternionDatabase& db, size_t count)
{
// TODO: Specify output type, we should be able to generate double precision output too...
return computeRandoms(db, count, [](GeneratorState& gen) { return gen.nextUnitQuatf(); });
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnEase.cpp | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#define _USE_MATH_DEFINES
#include <OgnEaseDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <cmath>
#include <functional>
#include "XformUtils.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
std::function<T(const T&, const T&, const float&)> getOperation(OgnEaseDatabase& db)
{
const auto& easeFunc = db.inputs.easeFunc();
auto exponent = std::max(std::min(db.inputs.blendExponent(), 10), 0);
// Find the desired comparison
std::function<T(const T&, const T&, const float&)> fn;
if (easeFunc == db.tokens.EaseIn)
fn = [=](const T& start, const T& end, const float& alpha) { return easeIn(start, end, alpha, exponent); };
else if (easeFunc == db.tokens.EaseOut)
fn = [=](const T& start, const T& end, const float& alpha) { return easeOut(start, end, alpha, exponent); };
else if (easeFunc == db.tokens.EaseInOut)
fn = [=](const T& start, const T& end, const float& alpha) { return easeInOut(start, end, alpha, exponent); };
else if (easeFunc == db.tokens.Linear)
fn = [=](const T& start, const T& end, const float& alpha) { return lerp(start, end, alpha); };
else if (easeFunc == db.tokens.SinIn)
fn = [=](const T& start, const T& end, const float& alpha) { return easeSinIn(start, end, alpha, exponent); };
else if (easeFunc == db.tokens.SinOut)
fn = [=](const T& start, const T& end, const float& alpha) { return easeSinOut(start, end, alpha, exponent); };
else if (easeFunc == db.tokens.SinInOut)
fn = [=](const T& start, const T& end, const float& alpha) { return easeSinInOut(start, end, alpha, exponent); };
else
{
throw ogn::compute::InputError("Failed to resolve token " + std::string(db.tokenToString(easeFunc)) +
", expected one of EaseIn, EaseOut, EaseInOut, Linear, SinIn, SinOut, SinInOut");
}
return fn;
}
template<typename T>
bool tryComputeAssumingType(OgnEaseDatabase& db, size_t count)
{
auto op = getOperation<T>(db);
auto functor = [&](auto& start, auto& end, auto& alpha, auto& result)
{
auto a = std::min(std::max(alpha, (float) 0.0), (float) 1.0);
result = op(start, end, a);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T, float, T>(
db.inputs.start(), db.inputs.end(), db.inputs.alpha(), db.outputs.result(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnEaseDatabase& db, size_t count)
{
auto op = getOperation<T>(db);
auto functor = [&](auto& start, auto& end, auto& alpha, auto& result)
{
auto a = std::min(std::max(alpha, (float) 0.0), (float) 1.0);
for (size_t i = 0; i < N; i++)
{
result[i] = op(start[i], end[i], a);
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], float, T[N]>(
db.inputs.start(), db.inputs.end(), db.inputs.alpha(), db.outputs.result(), functor, count);
}
} // namespace
class OgnEase
{
public:
static bool computeVectorized(OgnEaseDatabase& db, size_t count)
{
auto& inputType = db.inputs.start().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnEase: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto start = node.iNode->getAttributeByToken(node, inputs::start.token());
auto end = node.iNode->getAttributeByToken(node, inputs::end.token());
auto alpha = node.iNode->getAttributeByToken(node, inputs::alpha.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto startType = start.iAttribute->getResolvedType(start);
auto endType = end.iAttribute->getResolvedType(end);
auto alphaType = alpha.iAttribute->getResolvedType(alpha);
// Require start, end, and alpha to be resolved before determining result's type
if (startType.baseType != BaseDataType::eUnknown && endType.baseType != BaseDataType::eUnknown
&& alphaType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { start, end, result };
std::array<uint8_t, 3> tupleCounts {
startType.componentCount,
endType.componentCount,
std::max(startType.componentCount, endType.componentCount)
};
std::array<uint8_t, 3> arrayDepths {
startType.arrayDepth,
endType.arrayDepth,
std::max(alphaType.arrayDepth, std::max(startType.arrayDepth, endType.arrayDepth))
};
std::array<AttributeRole, 3> rolesBuf {
startType.role,
endType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
const INode* const iNode = nodeObj.iNode;
if (oldVersion < 2)
{
auto const instanceIdx = kAccordingToContextIndex;
auto oldAttrObj = iNode->getAttribute(nodeObj, "inputs:exponent");
auto oldAttrDataHandle = oldAttrObj.iAttribute->getAttributeDataHandle(oldAttrObj, instanceIdx);
ConstRawPtr srcDataPtr{ nullptr };
size_t srcDataSize{ 0 };
context.iAttributeData->getDataReferenceR(oldAttrDataHandle, context, srcDataPtr, srcDataSize);
if (srcDataPtr)
{
float exponentFloat = *(const float*)srcDataPtr;
auto newAttrObj = iNode->getAttribute(nodeObj, "inputs:blendExponent");
auto newAttrDataHandle = newAttrObj.iAttribute->getAttributeDataHandle(newAttrObj, instanceIdx);
RawPtr dstDataPtr{ nullptr };
size_t srcDataSize{ 0 };
context.iAttributeData->getDataReferenceW(newAttrDataHandle, context, dstDataPtr, srcDataSize);
if (dstDataPtr)
{
*dstDataPtr = (int)exponentFloat;
}
}
iNode->removeAttribute(nodeObj, "inputs:exponent");
}
return true;
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRound.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnRoundDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnRoundDatabase& db, size_t count)
{
int decimals = db.inputs.decimals();
float k = powf(10.0f, static_cast<float>(decimals));
auto functor = [&](auto const& input, auto& output)
{
output = static_cast<T>(round(input * k) / k);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.input(), db.outputs.output(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnRoundDatabase& db, size_t count)
{
int decimals = db.inputs.decimals();
float k = powf(10.0f, static_cast<float>(decimals));
auto functor = [&](auto const& input, auto& output)
{
for (size_t i = 0; i < N; ++i)
{
output[i] = static_cast<T>(round(input[i] * k) / k);
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N]>(db.inputs.input(), db.outputs.output(), functor, count);
}
} // namespace
class OgnRound
{
public:
static bool computeVectorized(OgnRoundDatabase& db, size_t count)
{
auto& inputType = db.inputs.input().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnRound: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto input = node.iNode->getAttributeByToken(node, inputs::input.token());
auto output = node.iNode->getAttributeByToken(node, outputs::output.token());
auto inputType = input.iAttribute->getResolvedType(input);
// Require input to be resolved before determining output's type
if (inputType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { input, output };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLocationAtDistanceOnCurve2.ogn | {
"GetLocationAtDistanceOnCurve2": {
"version": 1,
"description": [
"Given a set of curve points and a normalized distance between 0-1.0, ",
"return the location on a closed curve. 0 is the first point on the curve, 1.0 is also the first point",
"because the is an implicit segment connecting the first and last points. Values outside the range 0-1.0",
"will be wrapped to that range, for example -0.4 is equivalent to 0.6 and 1.3 is equivalent to 0.3",
"This is a simplistic curve-following node, intended for curves in a plane, for prototyping purposes."
],
"uiName": "Get Locations At Distances On Curve",
"categories": ["internal"],
"scheduling": [ "threadsafe" ],
"metadata": {"hidden": "true"},
"inputs": {
"curve": {
"type": "pointd[3][]",
"description": "The curve to be examined",
"uiName": "Curve"
},
"distance": {
"type": "double",
"description": "The distance along the curve, wrapped to the range 0-1.0",
"uiName": "Distance"
},
"forwardAxis": {
"type": "token",
"description": ["The direction vector from which the returned rotation is relative, one of X, Y, Z"],
"uiName": "Forward",
"default": "X"
},
"upAxis": {
"type": "token",
"description": ["The world Up vector, the curve should be in a plane perpendicular with this - one of X, Y, Z"],
"uiName": "Up",
"default": "Y"
}
},
"outputs": {
"location": {
"type": "pointd[3]",
"description": "Location",
"uiName": "Location on curve at the given distance in world space"
},
"rotateXYZ": {
"type": "vectord[3]",
"description": "Rotations",
"uiName": "World space rotation of the curve at the given distance, may not be smooth for some curves"
},
"orientation": {
"type": "quatf[4]",
"description": "Orientation",
"uiName": "World space orientation of the curve at the given distance, may not be smooth for some curves"
}
},
"tokens": [
"x", "y", "z", "X", "Y", "Z"
],
"tests": [
{"inputs:curve": [[1, 2, 3]], "inputs:distance": 0.5, "outputs:location": [1, 2, 3]},
{"inputs:curve": [[0, 0, 0], [0, 0, 1]], "inputs:distance": 0.75, "inputs:forwardAxis": "X", "inputs:upAxis": "Y",
"outputs:location": [0, 0, 0.5], "outputs:rotateXYZ": [0, 90, 0]}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivide_Tuple2.cpp | #include "OgnDivideHelper.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace OGNDivideHelper
{
bool tryComputeTuple2(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
return _tryComputeTuple<2>(db, a, b, result, count);
}
} // namespace OGNDivideHelper
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAdd.cpp | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnAddDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnAddDatabase& db, size_t count)
{
auto const& dynamicInputs = db.getDynamicInputs();
if (dynamicInputs.empty())
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + b;
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.a(), db.inputs.b(), db.outputs.sum(), functor, count);
}
else
{
std::vector<ogn::InputAttribute> inputArray{ db.inputs.a(), db.inputs.b() };
inputArray.reserve(dynamicInputs.size() + 2);
for (auto const& input : dynamicInputs)
{
inputArray.emplace_back(input());
}
auto functor = [](const auto& input, auto& result)
{
result = result + input;
};
return ogn::compute::tryComputeInputsWithArrayBroadcasting<T>(inputArray, db.outputs.sum(), functor, count);
}
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnAddDatabase& db, size_t count)
{
auto const& dynamicInputs = db.getDynamicInputs();
if (dynamicInputs.empty())
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + b;
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, T>(db.inputs.a(), db.inputs.b(), db.outputs.sum(), functor, count);
}
else
{
std::vector<ogn::InputAttribute> inputArray{ db.inputs.a(), db.inputs.b() };
inputArray.reserve(dynamicInputs.size() + 2);
for (auto const& input : dynamicInputs)
{
inputArray.emplace_back(input());
}
auto functor = [](const auto& input, auto& result)
{
result = result + input;
};
return ogn::compute::tryComputeInputsWithTupleBroadcasting<N, T>(inputArray, db.outputs.sum(), functor, count);
}
}
} // namespace
class OgnAdd
{
public:
static bool computeVectorized(OgnAddDatabase& db, size_t count)
{
auto& sumType = db.outputs.sum().type();
try
{
switch (sumType.baseType)
{
case BaseDataType::eDouble:
switch (sumType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (sumType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (sumType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (sumType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnAdd: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
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> componentCounts;
std::vector<uint8_t> arrayDepths;
std::vector<AttributeRole> roles;
attributes.reserve(totalCount - 2);
componentCounts.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);
// if some inputs are not connected stop - the output port resolution is only completed when all inputs are connected
if (resolvedType.baseType == BaseDataType::eUnknown)
return;
componentCounts.push_back(resolvedType.componentCount);
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);
}
}
auto sum = node.iNode->getAttributeByToken(node, outputs::sum.token());
attributes.push_back(sum);
// All inputs and the output should have the same tuple count
componentCounts.push_back(maxComponentCount);
// 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(), componentCounts.data(), arrayDepths.data(), roles.data(), attributes.size());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnToDeg.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 <OgnToDegDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/math.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnToDegDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<T>(pxr::GfRadiansToDegrees(a));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.radians(), db.outputs.degrees(), functor);
}
template <>
bool tryComputeAssumingType<pxr::GfHalf>(OgnToDegDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfRadiansToDegrees(a)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf>(db.inputs.radians(), db.outputs.degrees(), functor);
}
} // namespace
class OgnToDeg
{
public:
// Convert radians into degrees
static bool compute(OgnToDegDatabase& db)
{
try
{
// All possible types excluding ogn::string and bool
// scalers
if (tryComputeAssumingType<double>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf>(db)) return true; // Specifically for pxr::GfHalf
else if (tryComputeAssumingType<float>(db)) return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (std::exception &error)
{
db.logError("Could not convert into degrees : %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto radians = node.iNode->getAttributeByToken(node, inputs::radians.token());
auto degrees = node.iNode->getAttributeByToken(node, outputs::degrees.token());
auto radianType = radians.iAttribute->getResolvedType(radians);
// Require inputs to be resolved before determining output's type
if (radianType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { radians, degrees };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAnyZero.ogn | {
"AnyZero": {
"version": 1,
"description": [
"Outputs a boolean indicating if any of the input values are zero within a specified tolerance."
],
"uiName": "Any Zero",
"categories": ["math:condition"],
"scheduling": ["threadsafe"],
"inputs": {
"value": {
"type": ["numerics"],
"description": "Value(s) to check for zero.",
"uiName": "Value"
},
"tolerance": {
"type": "double",
"description": [
"How close the value must be to 0 to be considered \"zero\"."
],
"uiName": "Tolerance",
"minimum": 0.0
}
},
"outputs": {
"result": {
"type": "bool",
"description": [
"If 'value' is a scalar then 'result' will be true if 'value' is zero. If 'value' is non-scalar",
"(array, tuple, matrix, etc) then 'result' will be true if any of its elements are zero. If those",
"elements are themselves non-scalar (e.g. an array of vectors) they will be considered zero only if",
"all of the sub-elements are zero. For example, if 'value' is [3, 0, 1] then 'result' will be true",
"because the second element is zero. But if 'value' is [[3, 0, 1], [-5, 4, 17]] then 'result' will",
"be false because neither of the two vectors is fully zero."
],
"uiName": "Result"
}
},
"tests" : [
{
"inputs:value": {"type": "int", "value": 6},
"outputs:result": false
},
{
"inputs:value": {"type": "int", "value": -3},
"outputs:result": false
},
{
"inputs:value": {"type": "int", "value": 0},
"outputs:result": true
},
{
"inputs:value": {"type": "float", "value": 42.5},
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": -7.1},
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": 0.0},
"outputs:result": true
},
{
"inputs:value": {"type": "float", "value": 0.01},
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": -0.01},
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": 42.5},
"inputs:tolerance": 0.1,
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": -7.1},
"inputs:tolerance": 0.1,
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": 0.0},
"inputs:tolerance": 0.1,
"outputs:result": true
},
{
"inputs:value": {"type": "float", "value": 0.01},
"inputs:tolerance": 0.1,
"outputs:result": true
},
{
"inputs:value": {"type": "float", "value": -0.01},
"inputs:tolerance": 0.1,
"outputs:result": true
},
{
"inputs:value": {"type": "int", "value": 6},
"inputs:tolerance": 0.1,
"outputs:result": false
},
{
"inputs:value": {"type": "int", "value": -3},
"inputs:tolerance": 0.1,
"outputs:result": false
},
{
"inputs:value": {"type": "int", "value": 0},
"inputs:tolerance": 0.1,
"outputs:result": true
},
{
"inputs:value": {"type": "int", "value": 6},
"inputs:tolerance": 10.0,
"outputs:result": true
},
{
"inputs:value": {"type": "int", "value": -3},
"inputs:tolerance": 10.0,
"outputs:result": true
},
{
"inputs:value": {"type": "int", "value": 0},
"inputs:tolerance": 10.0,
"outputs:result": true
},
{
"inputs:value": {"type": "int[2]", "value": [ 0, 0 ]},
"outputs:result": true
},
{
"inputs:value": {"type": "int[2]", "value": [ 0, 3 ]},
"outputs:result": true
},
{
"inputs:value": {"type": "int[2]", "value": [ 3, 0 ]},
"outputs:result": true
},
{
"inputs:value": {"type": "int[2]", "value": [ 3, 5 ]},
"outputs:result": false
},
{
"inputs:value": {"type": "float[3]", "value": [1.7, 0.05, -4.3]},
"inputs:tolerance": 0.1,
"outputs:result": true
},
{
"inputs:value": {"type": "float[3][]", "value": [ [1.7, 0.05, -4.3], [0.0, -0.1, 0.3] ]},
"inputs:tolerance": 0.1,
"outputs:result": false
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnConcatenateFloat3Arrays.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 <OgnConcatenateFloat3ArraysDatabase.h>
#include <carb/Framework.h>
#include <carb/Types.h>
#include <omni/graph/core/Accessors.h>
#include <omni/graph/core/IGatherPrototype.h>
#include <omni/math/linalg/vec.h>
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConcatenateFloat3Arrays
{
public:
static bool compute(OgnConcatenateFloat3ArraysDatabase& db)
{
auto iGatherPrototype = carb::getCachedInterface<IGatherPrototype>();
if (!iGatherPrototype)
{
db.logError("Could not acquire IGatherPrototype and therefore could not compute");
return false;
}
auto& outputArray = db.outputs.outputArray();
auto& outputSizesArray = db.outputs.arraySizes();
// TODO: This uses the legacy approach instead of the database until gather arrays are supported
AttributeObj inputArrayObj = db.abi_node().iNode->getAttribute(db.abi_node(), "inputs:inputArrays");
AttributeObj inputArraySrcObj = getNthUpstreamAttributeOrSelf<0>(inputArrayObj);
auto inputArrayValues = reinterpret_cast<const vec3f* const* const>(
iGatherPrototype->getGatherArray(db.abi_context(), inputArraySrcObj, kReadOnly)
);
if (!inputArrayValues)
{
return false;
}
auto inputArraySizes = iGatherPrototype->getGatherArrayAttributeSizes(db.abi_context(), inputArraySrcObj, kReadOnly);
const size_t inputArrayCount = iGatherPrototype->getElementCount(db.abi_context(), inputArraySrcObj);
// Find the total output size.
size_t outputCount = 0;
for (size_t arrayi = 0; arrayi < inputArrayCount; ++arrayi)
{
outputCount += inputArraySizes[arrayi];
}
outputArray.resize(outputCount);
outputSizesArray.resize(inputArrayCount);
for (size_t arrayi = 0, outputi = 0; arrayi < inputArrayCount; ++arrayi)
{
const vec3f* const currentInputArray = inputArrayValues[arrayi];
size_t currentSize = inputArraySizes[arrayi];
outputSizesArray[arrayi] = int(currentSize);
for (size_t inputi = 0; inputi < currentSize; ++inputi, ++outputi)
{
outputArray[outputi] = currentInputArray[inputi];
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAtan.ogn | {
"Atan": {
"version": 1,
"description": [
"Trigonometric operation arctangent of one input in degrees."
],
"uiName": "Arctangent",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "Angle value in degrees whose inverse tan is to be found"
}
},
"outputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "The atan value of the input angle in degrees",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:value": {"type": "float", "value": 1},
"outputs:value": {"type": "float", "value": 45.0}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAsin.ogn | {
"Asin": {
"version": 1,
"description": [
"Trigonometric operation arcsin of one input in degrees."
],
"uiName": "Arcsine",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "Angle value in degrees whose inverse sine is to be found"
}
},
"outputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "The arcsin value of the input angle in degrees",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:value": {"type": "float", "value": 0.707107},
"outputs:value": {"type": "float", "value": 45.0}
},
{
"inputs:value": {"type": "double", "value": 0.5},
"outputs:value": {"type": "double", "value": 30.0}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomGaussian.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 "OgnRandomGaussianDatabase.h"
#include "random/RandomNodeBase.h"
#include <omni/graph/core/ogn/ComputeHelpers.h>
namespace omni
{
namespace graph
{
namespace nodes
{
using namespace random;
class OgnRandomGaussian : public NodeBase<OgnRandomGaussian, OgnRandomGaussianDatabase>
{
template <typename T>
static bool tryComputeAssumingType(OgnRandomGaussianDatabase& db, size_t count)
{
if (db.inputs.useLog())
{
return ogn::compute::tryComputeWithArrayBroadcasting<T>(
db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextLogNormal(mean, stdev);
},
count);
}
return ogn::compute::tryComputeWithArrayBroadcasting<T>(
db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextNormal(mean, stdev);
},
count);
}
template <typename T, size_t N>
static bool tryComputeAssumingType(OgnRandomGaussianDatabase& db, size_t count)
{
if (db.inputs.useLog())
{
return ogn::compute::tryComputeWithTupleBroadcasting<N, T>(
db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextLogNormal(mean, stdev);
},
count);
}
return ogn::compute::tryComputeWithTupleBroadcasting<N, T>(
db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextNormal(mean, stdev);
},
count);
}
static bool defaultCompute(OgnRandomGaussianDatabase& db, size_t count)
{
auto const genBuffers = db.state.gen.vectorized(count);
if (genBuffers.size() != count)
{
db.logWarning("Failed to write to output standard normal distribution (wrong genBuffers size)");
return false;
}
for (size_t i = 0; i < count; ++i)
{
auto outPtr = db.outputs.random(i).get<double>();
if (!outPtr)
{
db.logWarning("Failed to write to output standard normal distribution (null output pointer)");
return false;
}
*outPtr = asGenerator(genBuffers[i]).nextNormal<double>(0.0, 1.0);
}
return true;
}
public:
static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed);
// HACK: onConnectionTypeResolve is not called the first time,
// but by setting the output type, we force it to be called.
//
// TODO: OGN should really support default inputs for union types!
// See https://nvidia-omniverse.atlassian.net/browse/OM-67739
setDefaultOutputType(nodeObj, outputs::random.token());
}
static bool onCompute(OgnRandomGaussianDatabase& db, size_t count)
{
auto const& meanAttr{ db.inputs.mean() };
auto const& stdevAttr{ db.inputs.stdev() };
auto const& outAttr{ db.outputs.random() };
if (!outAttr.resolved())
{
// Output type not yet resolved, can't compute
db.logWarning("Unsupported input types");
return false;
}
if (!meanAttr.resolved() && !stdevAttr.resolved())
{
// Output using default mean and stdev
return defaultCompute(db, count);
}
// Inputs and outputs are resolved, try all real types
auto const outType = outAttr.type();
switch (outType.baseType) // NOLINT(clang-diagnostic-switch-enum)
{
case BaseDataType::eDouble:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<double>(db, count);
case 2:
return tryComputeAssumingType<double, 2>(db, count);
case 3:
return tryComputeAssumingType<double, 3>(db, count);
case 4:
return tryComputeAssumingType<double, 4>(db, count);
case 9:
return tryComputeAssumingType<double, 9>(db, count);
case 16:
return tryComputeAssumingType<double, 16>(db, count);
default:
break;
}
case BaseDataType::eFloat:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<float>(db, count);
case 2:
return tryComputeAssumingType<float, 2>(db, count);
case 3:
return tryComputeAssumingType<float, 3>(db, count);
case 4:
return tryComputeAssumingType<float, 4>(db, count);
default:
break;
}
case BaseDataType::eHalf:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default:
break;
}
default:
break;
}
db.logWarning("Unsupported input types");
return false;
}
static void onConnectionTypeResolve(NodeObj const& node)
{
resolveOutputType(node, inputs::mean.token(), inputs::stdev.token(), outputs::random.token());
}
};
#undef TRY_CASE
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMultiply.cpp | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnMultiplyDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnMultiplyDatabase& db, size_t count)
{
auto const& dynamicInputs = db.getDynamicInputs();
if (dynamicInputs.empty())
{
auto functor = [](T const& a, T const& b, T& result)
{
result = a * b;
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.a(), db.inputs.b(), db.outputs.product(), functor, count);
}
else
{
std::vector<ogn::InputAttribute> inputArray{ db.inputs.a(), db.inputs.b() };
inputArray.reserve(dynamicInputs.size() + 2);
for (auto const& input : dynamicInputs)
inputArray.emplace_back(input());
auto functor = [](const auto& input, auto& result)
{
result = result * input;
};
return ogn::compute::tryComputeInputsWithArrayBroadcasting<T>(inputArray, db.outputs.product(), functor, count);
}
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnMultiplyDatabase& db, size_t count)
{
auto const& dynamicInputs = db.getDynamicInputs();
if (dynamicInputs.empty())
{
auto functor = [](T const& a, T const& b, T& result)
{
result = a * b;
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, T>(db.inputs.a(), db.inputs.b(), db.outputs.product(), functor, count);
}
else
{
std::vector<ogn::InputAttribute> inputArray{ db.inputs.a(), db.inputs.b() };
inputArray.reserve(dynamicInputs.size() + 2);
for (auto const& input : dynamicInputs)
inputArray.emplace_back(input());
auto functor = [](const auto& input, auto& result)
{
result = result * input;
};
return ogn::compute::tryComputeInputsWithTupleBroadcasting<N, T>(inputArray, db.outputs.product(), functor, count);
}
}
} // namespace
class OgnMultiply
{
public:
static size_t computeVectorized(OgnMultiplyDatabase& db, size_t count)
{
auto& productType = db.outputs.product().type();
try
{
switch (productType.baseType)
{
case BaseDataType::eDouble:
switch (productType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (productType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (productType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (productType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnMultiply: %s", error.what());
}
return 0;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
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> componentCounts;
std::vector<uint8_t> arrayDepths;
std::vector<AttributeRole> roles;
attributes.reserve(totalCount - 2);
componentCounts.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);
// if some inputs are not connected stop - the output port resolution is only completed when all inputs
// are connected
if (resolvedType.baseType == BaseDataType::eUnknown)
return;
componentCounts.push_back(resolvedType.componentCount);
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);
}
}
auto output = node.iNode->getAttributeByToken(node, outputs::product.token());
attributes.push_back(output);
// All inputs and the output should have the same tuple count
componentCounts.push_back(maxComponentCount);
// 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(), componentCounts.data(), arrayDepths.data(), roles.data(), attributes.size());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnInterpolateTo.ogn | {
"InterpolateTo": {
"version": 2,
"description": [
"Function which iterpolates one step from a current value to a target value with a given speed.",
"Vectors are interpolated component-wise. Interpolation can be applied to decimal types.",
"The interpolation provides an eased approach to the target, adjust speed and exponent to tweak the curve.",
"The formula is:",
"result = current + (target - current) * (1 - clamp(0, speed * deltaSeconds, 1))^exp.",
"For quaternions, the node performs a spherical linear interpolation (SLERP) with ",
"alpha = (1 - clamp(0, speed * deltaSeconds, 1))^exp"
],
"uiName": "Interpolate To",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"current": {
"type": ["decimal_scalers", "decimal_tuples", "decimal_arrays"],
"description": "The current value"
},
"target": {
"type": ["decimal_scalers", "decimal_tuples", "decimal_arrays"],
"description": "The target value"
},
"speed": {
"type": "double",
"description": "The peak speed of approach (Units / Second)",
"minimum": 0.0,
"default": 1.0
},
"deltaSeconds": {
"type": "double",
"description": "The step time for the interpolation (Seconds)",
"minimum": 0.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": {
"result": {
"type": ["numerics"],
"description": "The interpolated result",
"uiName": "Result"
}
},
"tests" : [
{
"inputs": {
"current": {"type": "float", "value": 0.0},
"target": {"type": "float", "value": 10.0},
"deltaSeconds": 0.1
},
"outputs": {"result": {"type": "float", "value": 1.9}}
},
{
"inputs": {
"current": {"type": "double[3]", "value": [0.0, 1.0, 2.0]},
"target": {"type": "double[3]", "value": [10.0, 11.0, 12.0]},
"deltaSeconds": 0.1
},
"outputs": {"result": {"type": "double[3]", "value": [1.9, 2.9, 3.9]}}
},
{
"inputs": {
"current": {"type": "float[]", "value": [0.0, 1.0, 2.0]},
"target": {"type": "float[]", "value": [10.0, 11.0, 12.0]},
"deltaSeconds": 0.1
},
"outputs": {"result": {"type": "float[]", "value": [1.9, 2.9, 3.9]}}
},
{
"inputs": {
"current": {"type": "double[3][]", "value": [[0.0, 1.0, 2.0],[0.0, 1.0, 2.0]]},
"target": {"type": "double[3][]", "value": [[10.0, 11.0, 12.0], [10.0, 11.0, 12.0]]},
"deltaSeconds": 0.1
},
"outputs": {"result": {"type": "double[3][]", "value": [[1.9, 2.9, 3.9], [1.9, 2.9, 3.9]]}}
},
{
"inputs": {
"current": {"type": "quatd[4]", "value": [0, 0, 0, 1]},
"target": {"type": "quatd[4]", "value": [0.7071068, 0, 0, 0.7071068]},
"deltaSeconds": 0.5,
"exponent": 1
},
"outputs": {"result": {"type": "quatd[4]", "value": [0.3826834, 0, 0, 0.9238795]}}
},
{
"inputs": {
"current": {"type": "quatf[4]", "value": [0, 0, 0, 1]},
"target": {"type": "quatf[4]", "value": [0.7071068, 0, 0, 0.7071068]},
"deltaSeconds": 0.5,
"exponent": 1
},
"outputs": {"result": {"type": "quatf[4]", "value": [0.3826834, 0, 0, 0.9238795]}}
},
{
"inputs": {
"current": {"type": "float[4]", "value": [0, 0, 0, 1]},
"target": {"type": "float[4]", "value": [0.7071068, 0, 0, 0.7071068]},
"deltaSeconds": 0.5,
"exponent": 1
},
"outputs": {"result": {"type": "float[4]", "value": [0.3535534, 0, 0, 0.8535534]}}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnSubtract.ogn | {
"Subtract": {
"version": 2,
"description": [
"Subtracts from the first input the following inputs. The inputs can be of any numeric type."
],
"uiName": "Subtract",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"a": {
"type": ["numerics"],
"description": "The number B is subtracted from",
"uiName": "A"
},
"b": {
"type": ["numerics"],
"description": "The number to subtract from A",
"uiName": "B"
}
},
"outputs": {
"difference": {
"type": ["numerics"],
"description": "Result of A-B",
"uiName": "Difference"
}
},
"tests": [
{"inputs:a": {"type": "double", "value": 1.0}, "inputs:b": {"type": "double", "value": 0.5},
"outputs:difference": {"type": "double", "value": 0.5}},
{"inputs:a": {"type": "float", "value": 1.0}, "inputs:b": {"type": "float", "value": 0.5},
"outputs:difference": {"type": "float", "value": 0.5}},
{"inputs:a": {"type": "half", "value": 1.0}, "inputs:b": {"type": "half", "value": 0.5},
"outputs:difference": {"type": "half", "value": 0.5}},
{"inputs:a": {"type": "int", "value": 10}, "inputs:b": {"type": "int", "value": 6},
"outputs:difference": {"type": "int", "value": 4}},
{"inputs:a": {"type": "int64", "value": 10}, "inputs:b": {"type": "int64", "value": 6},
"outputs:difference": {"type": "int64", "value": 4}},
{"inputs:a": {"type": "uchar", "value": 10}, "inputs:b": {"type": "uchar", "value": 6},
"outputs:difference": {"type": "uchar", "value": 4}},
{"inputs:a": {"type": "uint", "value": 10}, "inputs:b": {"type": "uint", "value": 6},
"outputs:difference": {"type": "uint", "value": 4}},
{"inputs:a": {"type": "uint64", "value": 10}, "inputs:b": {"type": "uint64", "value": 6},
"outputs:difference": {"type": "uint64", "value": 4}},
{"inputs:a": {"type": "float[2]", "value": [1.0, 2.0]}, "inputs:b": {"type": "float[2]", "value": [0.5, 1.0]},
"outputs:difference": {"type": "float[2]", "value": [0.5, 1.0]}},
{"inputs:a": {"type": "float[3]", "value": [1.0, 2.0, 3.0]}, "inputs:b": {"type": "float[3]", "value": [0.5, 1.0, 1.5]},
"outputs:difference": {"type": "float[3]", "value": [0.5, 1.0, 1.5]}},
{"inputs:a": {"type": "float[4]", "value": [1.0, 2.0, 3.0, 4.0]}, "inputs:b": {"type": "float[4]", "value": [0.5, 1.0, 1.5, 2.0]},
"outputs:difference": {"type": "float[4]", "value": [0.5, 1.0, 1.5, 2.0]}},
{"inputs:a": {"type": "float[2]", "value": [2.0, 3.0]}, "inputs:b": {"type": "float", "value": 1.0},
"outputs:difference": {"type": "float[2]", "value": [1.0, 2.0]}},
{"inputs:a": {"type": "float", "value": 1.0}, "inputs:b": {"type": "float[2]", "value": [1.0, 2.0]},
"outputs:difference": {"type": "float[2]", "value": [0.0, -1.0]}},
{"inputs:a": {"type": "float[]", "value": [2.0, 3.0]}, "inputs:b": {"type": "float", "value": 1.0},
"outputs:difference": {"type": "float[]", "value": [1.0, 2.0]}},
{"inputs:a": {"type": "float", "value": 1.0}, "inputs:b": {"type": "float[]", "value": [1.0, 2.0]},
"outputs:difference": {"type": "float[]", "value": [0.0, -1.0]}},
{"inputs:a": {"type": "int64[]", "value": [10]}, "inputs:b": {"type": "int64[]", "value": [5]},
"outputs:difference": {"type": "int64[]", "value": [5]}},
{"inputs:a": {"type": "int64[]", "value": [10, 20]}, "inputs:b": {"type": "int64[]", "value": [5, 10]},
"outputs:difference": {"type": "int64[]", "value": [5, 10]}},
{"inputs:a": {"type": "int64[]", "value": [10, 20, 30]}, "inputs:b": {"type": "int64[]", "value": [5, 10, 15]},
"outputs:difference": {"type": "int64[]", "value": [5, 10, 15]}},
{"inputs:a": {"type": "int64[]", "value": [10, 20, 30, 40]}, "inputs:b": {"type": "int64[]", "value": [5, 10, 15, 20]},
"outputs:difference": {"type": "int64[]", "value": [5, 10, 15, 20]}},
{"inputs:a": {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, "inputs:b": {"type": "int[3]", "value": [5, 10, 15]},
"outputs:difference": {"type": "int[3][]", "value": [[5, 10, 15], [35, 40, 45]]}},
{"inputs:a": {"type": "int[3]", "value": [5, 10, 15]}, "inputs:b": {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]},
"outputs:difference": {"type": "int[3][]", "value": [[-5, -10, -15], [-35, -40, -45]]}},
{"inputs:a": {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, "inputs:b": {"type": "int[2]", "value": [5, 10]},
"outputs:difference": {"type": "int[2][]", "value": [[5, 10], [25, 30], [45, 50]]}},
{"inputs:a": {"type": "int[2]", "value": [5, 10]}, "inputs:b": {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]},
"outputs:difference": {"type": "int[2][]", "value": [[-5, -10], [-25, -30], [-45, -50]]}}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnPartialSum.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 <OgnPartialSumDatabase.h>
#include <numeric>
class OgnPartialSum
{
public:
static bool compute(OgnPartialSumDatabase& db)
{
auto inputs = db.inputs.array();
auto outputs = db.outputs.partialSum();
outputs.resize(inputs.size() + 1);
outputs[0] = 0;
std::partial_sum(inputs.begin(), inputs.end(), outputs.begin() + 1);
return true;
}
};
REGISTER_OGN_NODE()
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnFloor.cpp | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnFloorDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnFloorDatabase& db)
{
auto functor = [](auto const& a, auto& result) { result = static_cast<int>(std::floor(a)); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, int>(db.inputs.a(), db.outputs.result(), functor);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnFloorDatabase& db)
{
auto functor = [](auto const& a, auto& result) { result = static_cast<int>(std::floor(a)); };
return ogn::compute::tryComputeWithTupleBroadcasting<N, T, int>(db.inputs.a(), db.outputs.result(), functor);
}
} // namespace
class OgnFloor
{
public:
static bool compute(OgnFloorDatabase& db)
{
try
{
auto& aType = db.inputs.a().type();
switch (aType.baseType)
{
case BaseDataType::eDouble:
switch (aType.componentCount)
{
case 1:
return tryComputeAssumingType<double>(db);
case 2:
return tryComputeAssumingType<double, 2>(db);
case 3:
return tryComputeAssumingType<double, 3>(db);
case 4:
return tryComputeAssumingType<double, 4>(db);
}
case BaseDataType::eFloat:
switch (aType.componentCount)
{
case 1:
return tryComputeAssumingType<float>(db);
case 2:
return tryComputeAssumingType<float, 2>(db);
case 3:
return tryComputeAssumingType<float, 3>(db);
case 4:
return tryComputeAssumingType<float, 4>(db);
}
case BaseDataType::eHalf:
switch (aType.componentCount)
{
case 1:
return tryComputeAssumingType<pxr::GfHalf>(db);
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db);
}
default:
break;
}
throw ogn::compute::InputError("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnFloor: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto valueType = a.iAttribute->getResolvedType(a);
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eInt, valueType.componentCount, valueType.arrayDepth);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnExponent.ogn | {
"Exponent": {
"version": 1,
"description": [
"Computes the base input raised to the power of the exponent. The result is the same type as the base",
"input for floating point types. The result is double for integral values to allow for negative exponents.",
"If the input is a vector or matrix, then the node calculates the exponent for each element and output",
"a vector or matrix of the same size."],
"uiName": "Exponent",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"base": {
"type": ["numerics"],
"description": "Base value that will be raised to the power of exponent",
"uiName": "Base"
},
"exponent": {
"type": "int",
"description": "Power to raise the base value to",
"uiName": "Exponent",
"default": 2
}
},
"outputs": {
"result": {
"type": ["numerics"],
"description": "Result of base raised to exponent",
"uiName": "Result"
}
},
"tests": [
{
"inputs:base": {"type": "float", "value": 2.0},
"outputs:result": {"type": "float", "value": 4.0}
},
{
"inputs:base": {"type": "double", "value": 0.5}, "inputs:exponent": 3,
"outputs:result": {"type": "double", "value": 0.125}
},
{
"inputs:base": {"type": "half[2]", "value": [5.0, 0.5]}, "inputs:exponent": 3,
"outputs:result": {"type": "half[2]", "value": [125.0, 0.125]}
},
{
"inputs:base": {"type": "float[]", "value": [1.0, 3.0]}, "inputs:exponent": 3,
"outputs:result": {"type": "float[]", "value": [1.0, 27.0]}
},
{
"inputs:base": {"type": "float[2][]", "value": [[1.0, 0.3], [0.5, 3.0]]},
"outputs:result": {"type": "float[2][]", "value": [[1.0, 0.09], [0.25, 9.0]]}
},
{
"inputs:base": {"type": "int", "value": 2147483647}, "inputs:exponent": 0,
"outputs:result": {"type": "double", "value": 1.0}
},
{
"inputs:base": {"type": "int64", "value": 9223372036854775807}, "inputs:exponent": 1,
"outputs:result": {"type": "double", "value": 9223372036854775807.0}
},
{
"inputs:base": {"type": "int", "value": 5}, "inputs:exponent": -1,
"outputs:result": {"type": "double", "value": 0.2}
},
{
"inputs:base": {"type": "float", "value": -2.0},
"outputs:result": {"type": "float", "value": 4.0}
},
{
"inputs:base": {"type": "float", "value": -2.0}, "inputs:exponent": 3,
"outputs:result": {"type": "float", "value": -8.0}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCrossProduct.ogn | {
"CrossProduct": {
"version": 1,
"description": [
"Compute the cross product of two (arrays of) vectors of the same size",
"The cross product of two 3d vectors is a vector perpendicular to both inputs",
"If arrays of vectors are provided, the cross-product is computed row-wise between a and b"
],
"uiName": "Cross Product",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"a": {
"type": ["vectord[3]", "vectorf[3]", "vectorh[3]", "vectord[3][]", "vectorf[3][]", "vectorh[3][]"],
"description": "The first vector in the cross product",
"uiName": "A"
},
"b": {
"type": ["vectord[3]", "vectorf[3]", "vectorh[3]", "vectord[3][]", "vectorf[3][]", "vectorh[3][]"],
"description": "The second vector in the cross product",
"uiName": "B"
}
},
"outputs": {
"product": {
"type": ["vectord[3]", "vectorf[3]", "vectorh[3]", "vectord[3][]", "vectorf[3][]", "vectorh[3][]"],
"description": "The resulting product",
"uiName": "Product"
}
},
"tests": [
{
"inputs:a": {"type": "half[3]", "value": [1, 2, 3]},
"inputs:b": {"type": "half[3]", "value": [5, 6, 7]},
"outputs:product": {"type": "half[3]", "value": [-4, 8, -4]}
},
{
"inputs:a": {"type": "float[3]", "value": [1, 2, 3]},
"inputs:b": {"type": "float[3]", "value": [5, 6, 7]},
"outputs:product": {"type": "float[3]", "value": [-4, 8, -4]}
},
{
"inputs:a": {"type": "double[3]", "value": [1, 2, 3]},
"inputs:b": {"type": "double[3]", "value": [5, 6, 7]},
"outputs:product": {"type": "double[3]", "value": [-4, 8, -4]}
},
{
"inputs:a": {"type": "double[3][]", "value": [[1, 2, 3], [10.2, 3.5, 7]]},
"inputs:b": {"type": "double[3][]", "value": [[5, 6, 7], [5, 6.1, 4.2]]},
"outputs:product": {"type": "double[3][]", "value": [[-4, 8, -4], [-28, -7.84, 44.72]]}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnSourceIndices.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 <OgnSourceIndicesDatabase.h>
class OgnSourceIndices
{
public:
static bool compute(OgnSourceIndicesDatabase& db)
{
auto inputValues = db.inputs.sourceStartsInTarget();
auto sourceCount = inputValues.size();
auto sourceIndices = db.outputs.sourceIndices();
if (sourceCount <= 1)
{
sourceIndices.resize(0);
return true;
}
--sourceCount;
int32_t targetCount = inputValues[sourceCount];
if (targetCount < 0)
{
sourceIndices.resize(0);
return true;
}
sourceIndices.resize(targetCount);
int32_t i = 0;
for (size_t sourcei = 0; sourcei < sourceCount; ++sourcei)
{
const int32_t sourceEnd = inputValues[sourcei + 1];
while (i < sourceEnd)
{
sourceIndices[i] = (int32_t)sourcei;
++i;
}
}
return true;
}
};
REGISTER_OGN_NODE()
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMagnitude.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 <OgnMagnitudeDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <cmath>
#include <type_traits>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnMagnitudeDatabase& db)
{
auto functor = [](auto const& input, auto& magnitude)
{
magnitude = static_cast<T>(std::abs(static_cast<double>(input)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T>(db.inputs.input(), db.outputs.magnitude(), functor);
}
template<>
bool tryComputeAssumingType<pxr::GfHalf>(OgnMagnitudeDatabase& db)
{
auto functor = [](auto const& input, auto& magnitude)
{
magnitude = static_cast<pxr::GfHalf>(std::abs(static_cast<float>(input)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf, pxr::GfHalf>(db.inputs.input(), db.outputs.magnitude(), functor);
}
template<typename T, size_t N,
std::enable_if_t<!std::is_same<T, int>::value && !std::is_same<T, pxr::GfHalf>::value, bool> = true>
bool tryComputeAssumingType(OgnMagnitudeDatabase& db)
{
auto functor = [](auto const& input, auto& magnitude)
{
double acc = 0.0;
for (size_t i = 0; i < N; ++i)
{
acc += static_cast<double>(input[i]) * static_cast<double>(input[i]);
}
acc = std::sqrt(acc);
magnitude = static_cast<T>(acc);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T>(db.inputs.input(), db.outputs.magnitude(), functor);
}
template<typename T, size_t N,
std::enable_if_t<std::is_same<T, int>::value, bool> = true>
bool tryComputeAssumingType(OgnMagnitudeDatabase& db)
{
auto functor = [](auto const& input, auto& magnitude)
{
double acc = 0.0;
for (size_t i = 0; i < N; ++i)
{
acc += static_cast<double>(input[i]) * static_cast<double>(input[i]);
}
acc = std::sqrt(acc);
magnitude = acc;
};
return ogn::compute::tryComputeWithArrayBroadcasting<int[N], double>(db.inputs.input(), db.outputs.magnitude(), functor);
}
template<typename T, size_t N,
std::enable_if_t<std::is_same<T, pxr::GfHalf>::value, bool> = true>
bool tryComputeAssumingType(OgnMagnitudeDatabase& db)
{
auto functor = [](auto const& input, auto& magnitude)
{
float acc = 0.0f;
for (size_t i = 0; i < N; ++i)
{
acc += static_cast<float>(input[i]) * static_cast<float>(input[i]);
}
acc = std::sqrt(acc);
magnitude = static_cast<pxr::GfHalf>(acc);
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf[N], pxr::GfHalf>(db.inputs.input(), db.outputs.magnitude(), functor);
}
} // namespace
class OgnMagnitude
{
public:
static bool compute(OgnMagnitudeDatabase& db)
{
try
{
auto& type = db.inputs.input().type();
// All possible types excluding ogn::string and bool
switch (type.baseType)
{
case BaseDataType::eDouble:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<double>(db);
case 2:
return tryComputeAssumingType<double, 2>(db);
case 3:
return tryComputeAssumingType<double, 3>(db);
case 4:
return tryComputeAssumingType<double, 4>(db); // quaternion (XYZW), RGBA, etc
case 9:
return tryComputeAssumingType<double, 9>(db); // Matrix3f type
case 16:
return tryComputeAssumingType<double, 16>(db); // Matrix4f type
}
break;
case BaseDataType::eFloat:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<float>(db);
case 2:
return tryComputeAssumingType<float, 2>(db);
case 3:
return tryComputeAssumingType<float, 3>(db);
case 4:
return tryComputeAssumingType<float, 4>(db); // quaternion (XYZW), RGBA, etc
}
break;
case BaseDataType::eHalf:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<pxr::GfHalf>(db);
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db); // quaternion (XYZW), RGBA, etc
}
break;
case BaseDataType::eInt:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<int32_t>(db);
case 2:
return tryComputeAssumingType<int32_t, 2>(db);
case 3:
return tryComputeAssumingType<int32_t, 3>(db);
case 4:
return tryComputeAssumingType<int32_t, 4>(db);
}
break;
case BaseDataType::eUInt:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<uint32_t>(db);
}
break;
case BaseDataType::eInt64:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<int64_t>(db);
}
break;
case BaseDataType::eUInt64:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<uint64_t>(db);
}
break;
case BaseDataType::eUChar:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<unsigned char>(db);
}
break;
default:
break;
}
throw ogn::compute::InputError("Failed to resolve input type");
}
catch (ogn::compute::InputError &error)
{
db.logError("OgnMagnitude: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto input = node.iNode->getAttributeByToken(node, inputs::input.token());
auto magnitude = node.iNode->getAttributeByToken(node, outputs::magnitude.token());
auto inputType = input.iAttribute->getResolvedType(input);
// Require input to be resolved before determining magnitude's type
if (inputType.baseType != BaseDataType::eUnknown)
{
if (inputType.baseType == BaseDataType::eInt && inputType.componentCount > 1)
{
// int[N] => double
auto newType = inputType;
newType.baseType = BaseDataType::eDouble;
newType.componentCount = 1;
magnitude.iAttribute->setResolvedType(magnitude, newType);
}
else
{
// T => T
// T[N] => T
std::array<AttributeObj, 2> attrs { input, magnitude };
std::array<uint8_t, 2> tupleCounts {
inputType.componentCount,
1
};
std::array<uint8_t, 2> arrayDepths {
inputType.arrayDepth,
inputType.arrayDepth
};
std::array<AttributeRole, 2> rolesBuf {
inputType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMatrixMultiply.cpp | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnMatrixMultiplyDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/vec.h>
#include <type_traits>
using omni::math::linalg::base_matrix;
using omni::math::linalg::base_vec;
using ogn::compute::tryComputeWithArrayBroadcasting;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
// Base type T, dimension N (eg: 2,3,4)
template<typename T, size_t N>
bool tryComputeAssumingType(OgnMatrixMultiplyDatabase& db)
{
auto matrixMatrixFn = [](auto const& a, auto const& b, auto& result)
{
const auto& aMatrix = *reinterpret_cast<const base_matrix<T, N>*>(a);
const auto& bMatrix = *reinterpret_cast<const base_matrix<T, N>*>(b);
auto& resultMatrix = *reinterpret_cast<base_matrix<T, N>*>(result);
resultMatrix = aMatrix * bMatrix;
};
auto matrixVectorFn = [](auto const& a, auto const& b, auto& result)
{
const auto& aMatrix = *reinterpret_cast<const base_matrix<T, N>*>(a);
const auto& bVec = *reinterpret_cast<const base_vec<T, N>*>(b);
auto& resultVec = *reinterpret_cast<base_vec<T, N>*>(result);
resultVec = aMatrix * bVec;
};
auto vectorMatrixFn = [](auto const& a, auto const& b, auto& result)
{
const auto& aVec = *reinterpret_cast<const base_vec<T, N>*>(a);
const auto& bMatrix = *reinterpret_cast<const base_matrix<T, N>*>(b);
auto& resultVec = *reinterpret_cast<base_vec<T, N>*>(result);
resultVec = aVec * bMatrix;
};
auto vectorVectorFn = [](auto const& a, auto const& b, auto& result)
{
const auto& aVec = *reinterpret_cast<const base_vec<T, N>*>(a);
const auto& bVec = *reinterpret_cast<const base_vec<T, N>*>(b);
result = aVec * bVec;
};
if (N >= 3 && tryComputeWithArrayBroadcasting<T[N*N]>(db.inputs.a(), db.inputs.b(), db.outputs.output(), matrixMatrixFn))
return true;
else if (N >= 3 && tryComputeWithArrayBroadcasting<T[N*N], T[N], T[N]>(db.inputs.a(), db.inputs.b(), db.outputs.output(), matrixVectorFn))
return true;
else if (N >= 3 && tryComputeWithArrayBroadcasting<T[N], T[N*N], T[N]>(db.inputs.a(), db.inputs.b(), db.outputs.output(), vectorMatrixFn))
return true;
else if (tryComputeWithArrayBroadcasting<T[N], T[N], T>(db.inputs.a(), db.inputs.b(), db.outputs.output(), vectorVectorFn))
return true;
return false;
}
} // namespace
class OgnMatrixMultiply
{
public:
static bool compute(OgnMatrixMultiplyDatabase& db)
{
try
{
if (tryComputeAssumingType<double, 2>(db)) return true;
else if (tryComputeAssumingType<double, 3>(db)) return true;
else if (tryComputeAssumingType<double, 4>(db)) return true;
else if (tryComputeAssumingType<float, 2>(db)) return true;
else if (tryComputeAssumingType<float, 3>(db)) return true;
else if (tryComputeAssumingType<float, 4>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf, 2>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf, 3>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf, 4>(db)) return true;
else
{
db.logWarning("OgnMatrixMultiply: Failed to resolve input types");
}
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnMatrixMultiply: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto b = node.iNode->getAttributeByToken(node, inputs::b.token());
auto output = node.iNode->getAttributeByToken(node, outputs::output.token());
auto aType = a.iAttribute->getResolvedType(a);
auto bType = b.iAttribute->getResolvedType(b);
// Require inputs to be resolved before determining output's type
if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown)
{
auto biggerDim = std::max(aType.componentCount, bType.componentCount);
auto smallerDim = std::min(aType.componentCount, bType.componentCount);
if (biggerDim != smallerDim && biggerDim != smallerDim * smallerDim)
{
CARB_LOG_WARN_ONCE("OgnMatrixMultiply: Inputs are not compatible with tuple counts %d and %d", aType.componentCount, bType.componentCount);
return;
}
// Vector4 * Matrix4 = Vector4, Matrix4 * Vector4 = Vector4 and etc.
auto tupleCount = smallerDim;
auto role = aType.componentCount < bType.componentCount ? aType.role : bType.role;
if (smallerDim == biggerDim && smallerDim <= 4)
{
// equivalent to dot product of two vectors
tupleCount = 1;
role = AttributeRole::eNone;
}
std::array<AttributeObj, 3> attrs { a, b, output };
std::array<uint8_t, 3> tupleCounts {
aType.componentCount,
bType.componentCount,
tupleCount
};
std::array<uint8_t, 3> arrayDepths {
aType.arrayDepth,
bType.arrayDepth,
std::max(aType.arrayDepth, bType.arrayDepth)
};
std::array<AttributeRole, 3> rolesBuf {
aType.role,
bType.role,
role
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMatrixMultiply.ogn | {
"MatrixMultiply": {
"version": 1,
"description": [
"Computes the matrix product of the inputs. Inputs must be compatible. ",
"Also accepts tuples (treated as vectors) as inputs. Tuples in input A will be treated as row vectors. ",
"Tuples in input B will be treated as column vectors. ",
"Arrays of inputs will be computed element-wise with broadcasting if necessary. "
],
"uiName": "Matrix Multiply",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"a": {
"type": ["matrices", "matrixd[3][]", "matrixd[4][]",
"decimal_tuples", "double[2][]", "double[3][]", "double[4][]",
"float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]"],
"description": "First matrix or row vector to multiply",
"uiName": "A"
},
"b": {
"type": ["matrices", "matrixd[3][]", "matrixd[4][]",
"decimal_tuples", "double[2][]", "double[3][]", "double[4][]",
"float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]"],
"description": "Second matrix or column vector to multiply",
"uiName": "B"
}
},
"outputs": {
"output": {
"type": ["matrices", "matrixd[3][]", "matrixd[4][]",
"decimal_tuples", "double[2][]", "double[3][]", "double[4][]",
"float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]",
"float", "double", "half", "float[]", "double[]", "half[]"],
"description": "Product of the two matrices",
"uiName": "Product"
}
},
"tests" : [
{
"inputs:a": {"type": "matrixd[3]", "value": [1,2,3, 4,5,6, 7,8,9]},
"inputs:b": {"type": "matrixd[3]", "value": [10,11,12, 13,14,15, 16,17,18]},
"outputs:output": {"type": "matrixd[3]", "value": [84,90,96, 201,216,231, 318,342,366]}
},
{
"inputs:a": {"type": "matrixd[4]", "value": [1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4]},
"inputs:b": {"type": "matrixd[4]", "value": [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]},
"outputs:output": {"type": "matrixd[4]", "value": [1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4]}
},
{
"inputs:a": {"type": "matrixd[4]", "value": [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]},
"inputs:b": {"type": "double[4]", "value": [1,2,3,4]},
"outputs:output": {"type": "double[4]", "value": [1,2,3,4]}
},
{
"inputs:a": {"type": "double[4]", "value": [1,2,3,4]},
"inputs:b": {"type": "matrixd[4]", "value": [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]},
"outputs:output": {"type": "double[4]", "value": [1,2,3,4]}
},
{
"inputs:a": {"type": "double[4]", "value": [1,2,3,4]},
"inputs:b": {"type": "double[4]", "value": [1,2,3,4]},
"outputs:output": {"type": "double", "value": 30}
},
{
"inputs:a": {"type": "double[4][]", "value": [[1,2,3,4], [1,2,3,4]]},
"inputs:b": {"type": "matrixd[4][]", "value": [[1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1], [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]]},
"outputs:output": {"type": "double[4][]", "value": [[1,2,3,4], [1,2,3,4]]}
},
{
"inputs:a": {"type": "double[4][]", "value": [[1,2,3,4], [1,2,3,4]]},
"inputs:b": {"type": "matrixd[4]", "value": [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]},
"outputs:output": {"type": "double[4][]", "value": [[1,2,3,4], [1,2,3,4]]}
},
{
"inputs:a": {"type": "double[4]", "value": [1,2,3,4]},
"inputs:b": {"type": "matrixd[4][]", "value": [[1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1], [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]]},
"outputs:output": {"type": "double[4][]", "value": [[1,2,3,4], [1,2,3,4]]}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnTan.ogn | {
"Tan": {
"version": 1,
"description": [
"Trigonometric operation tangent of one input in degrees."
],
"uiName": "Tan",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "Angle in degrees whose tangent value is to be found"
}
},
"outputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "The tangent value of the input angle in degrees",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:value": {"type": "float", "value": 45.0},
"outputs:value": {"type": "float", "value": 1.0}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDotProduct.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 <OgnDotProductDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/math/linalg/vec.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T, size_t N>
bool tryComputeAssumingType(OgnDotProductDatabase& db)
{
auto functor = [](auto const& a, auto const& b, auto& product)
{
const auto& vecA = *reinterpret_cast<const omni::math::linalg::base_vec<T, N>*>(a);
const auto& vecB = *reinterpret_cast<const omni::math::linalg::base_vec<T, N>*>(b);
product = vecA.Dot(vecB);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], T>(db.inputs.a(), db.inputs.b(), db.outputs.product(), functor);
}
} // namespace
class OgnDotProduct
{
public:
static bool compute(OgnDotProductDatabase& db)
{
try
{
auto& aType = db.inputs.a().type();
switch(aType.baseType)
{
case BaseDataType::eDouble:
switch(aType.componentCount)
{
case 2: return tryComputeAssumingType<double, 2>(db);
case 3: return tryComputeAssumingType<double, 3>(db);
case 4: return tryComputeAssumingType<double, 4>(db);
}
case BaseDataType::eFloat:
switch(aType.componentCount)
{
case 2: return tryComputeAssumingType<float, 2>(db);
case 3: return tryComputeAssumingType<float, 3>(db);
case 4: return tryComputeAssumingType<float, 4>(db);
}
case BaseDataType::eHalf:
switch(aType.componentCount)
{
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db);
}
default: db.logError("Failed to resolve input types");
}
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto b = node.iNode->getAttributeByToken(node, inputs::b.token());
auto product = node.iNode->getAttributeByToken(node, outputs::product.token());
// Require inputs to be resolved before determining product's type
auto aType = a.iAttribute->getResolvedType(a);
auto bType = b.iAttribute->getResolvedType(b);
if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { a, b, product };
// a, b should all have the same tuple count
std::array<uint8_t, 3> tupleCounts {
aType.componentCount,
bType.componentCount,
1
};
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,
AttributeRole::eNone
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLookAtRotation.ogn | {
"GetLookAtRotation": {
"version": 1,
"description": [
"Computes the rotation angles to align a forward direction vector to a direction vector formed by",
" starting at 'start' and pointing at 'target'. The forward vector is the 'default' orientation of",
" the asset being rotated, usually +X or +Z"
],
"uiName": "Get Look At Rotation",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"start": {
"type": "pointd[3]",
"description": ["The position to look from"]
},
"target": {
"type": "pointd[3]",
"description": ["The position to look at"]
},
"forward": {
"type": "double[3]",
"description": ["The direction vector to be aligned with the look vector"],
"default": [0.0, 0.0, 1.0]
},
"up": {
"type": "double[3]",
"description": ["The direction considered to be 'up'. If not specified scene-up will be used."],
"optional": true
}
},
"outputs": {
"rotateXYZ": {
"type": "double[3]",
"description": ["The rotation vector [X, Y, Z]"]
},
"orientation": {
"type": "quatd[4]",
"description": ["The orientation quaternion equivalent to outputs:rotateXYZ"]
}
},
"tests": [
{
"inputs:start": [0.0, 0.0, 0.0], "inputs:target": [100.0, 0.0, 0.0], "inputs:forward": [1.0, 0.0, 0.0],
"outputs:rotateXYZ": [0.0, 0.0, 0.0], "outputs:orientation": [0.0, 0.0, 0.0, 1.0]
},
{
"inputs:start": [0.0, 0.0, 0.0], "inputs:target": [100.0, 0.0, 0.0], "inputs:forward": [0.0, 0.0, 1.0],
"outputs:rotateXYZ": [0.0, 90, 0.0], "outputs:orientation": [0.0, 0.70710678, 0.0, 0.70710678]
},
{
"inputs:start": [0.0, 0.0, 0.0], "inputs:target": [100.0, 0.0, 100.0],"inputs:forward": [1.0, 0.0, 0.0],
"outputs:rotateXYZ": [0.0, -45.0, 0.0], "outputs:orientation": [0.0, -0.3826834, 0.0, 0.92387953]
},
{
"inputs:start": [100.0, 0.0, 100.0], "inputs:target": [200.0, 0.0, 100.0], "inputs:forward": [1.0, 0.0, 0.0],
"outputs:rotateXYZ": [0.0, 0.0, 0.0], "outputs:orientation": [0.0, 0.0, 0.0, 1.0]
},
{
"inputs:start": [100.0, 0.0, -100.0], "inputs:target": [-100.0, 200.0, -300.0], "inputs:forward": [1.0, 0.0, 0.0],
"outputs:rotateXYZ": [150.0, 35.26439, 135.0], "outputs:orientation": [0.27984814, 0.88047624, 0.115916896, 0.3647052]
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNegate.ogn | {
"Negate": {
"version": 1,
"description": [
"Computes the result of multiplying a vector, scalar, or array of vectors or scalars by -1.",
"The input must not be unsigned."
],
"uiName": "Negate",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"input": {
"type": ["numerics"],
"description": "The vector(s) or scalar(s) to negate"
}
},
"outputs": {
"output": {
"type": ["numerics"],
"description": "The resulting negated value(s)"
}
},
"tests" : [
{
"inputs:input": {"type": "double", "value": 1.0},
"outputs:output": {"type": "double", "value": -1.0}
},
{
"inputs:input": {"type": "float[2]", "value": [0.0, 1.0]},
"outputs:output": {"type": "float[2]", "value": [-0.0, -1.0]}
},
{
"inputs:input": {"type": "half[3]", "value": [-1.0, -0.0, 1.0]},
"outputs:output": {"type": "half[3]", "value": [1.0, 0.0, -1.0]}
},
{
"inputs:input": {"type": "int[4]", "value": [-1, 0, 1, 2]},
"outputs:output": {"type": "int[4]", "value": [1, 0, -1, -2]}
},
{
"inputs:input": {"type": "int64[]", "value": [-1, 0, 1, 2]},
"outputs:output": {"type": "int64[]", "value": [1, 0, -1, -2]}
},
{
"inputs:input": {"type": "double[][2]", "value": [[-1.0, 0.0], [1.0, 2.0]]},
"outputs:output": {"type": "double[][2]", "value": [[1.0, -0.0], [-1.0, -2.0]]}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnModulo.ogn | {
"Modulo": {
"version": 1,
"description": [
"Computes the modulo of integer inputs (A % B), which is the remainder of A / B",
" If B is zero, the result is zero. If A and B are both non-negative the result is non-negative,",
" otherwise the sign of the result is undefined."
],
"uiName": "Modulo",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"a": {
"type": ["integral_scalers"],
"description": "The dividend of (A % B)",
"uiName": "A"
},
"b": {
"type":["integral_scalers"],
"description": "The divisor of (A % B)",
"uiName": "B"
}
},
"outputs": {
"result": {
"type": ["integral_scalers"],
"description": "Modulo (A % B), the remainder of A / B",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:a": {"type": "uint64", "value": 4}, "inputs:b": {"type": "uint64", "value": 3},
"outputs:result": {"type": "uint64", "value": 1}
},
{
"inputs:a": {"type": "int", "value": 4}, "inputs:b": {"type": "int", "value": 0},
"outputs:result": {"type": "int", "value": 0}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomBoolean.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 "random/RandomNodeBase.h"
#include <OgnRandomBooleanDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
using namespace random;
class OgnRandomBoolean : public NodeBase<OgnRandomBoolean, OgnRandomBooleanDatabase>
{
public:
static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed);
}
static bool onCompute(OgnRandomBooleanDatabase& db, size_t count)
{
return computeRandoms(db, count, [](GeneratorState& gen) { return gen.nextUniformBool(); });
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCos.ogn | {
"Cos": {
"version": 1,
"description": [
"Trigonometric operation cosine of one input in degrees."
],
"uiName": "Cosine",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "Angle in degrees whose cosine value is to be found"
}
},
"outputs": {
"value": {
"type": ["decimal_scalers", "double[]", "float[]", "half[]"],
"description": "The cosine value of the input angle in degrees",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:value": {"type": "float", "value": 45.0},
"outputs:value": {"type": "float", "value": 0.707107}
},
{
"inputs:value": {"type": "double", "value": 120.0},
"outputs:value": {"type": "double", "value": -0.5}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLocationAtDistanceOnCurve.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 <OgnGetLocationAtDistanceOnCurveDatabase.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/vec.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/base/gf/rotation.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/math/linalg/SafeCast.h>
#include <cmath>
#include "XformUtils.h"
using omni::math::linalg::quatf;
using omni::math::linalg::quatd;
using omni::math::linalg::vec3d;
using omni::math::linalg::matrix4d;
// return the named unit vector X,Y or Z
static vec3d axisToVec(NameToken axisToken, OgnGetLocationAtDistanceOnCurveDatabase::TokenManager& tokens)
{
if (axisToken == tokens.y || axisToken == tokens.Y)
return vec3d::YAxis();
if (axisToken == tokens.z || axisToken == tokens.Z)
return vec3d::ZAxis();
return vec3d::XAxis();
}
class OgnGetLocationAtDistanceOnCurve
{
public:
static bool compute(OgnGetLocationAtDistanceOnCurveDatabase& db)
{
/* This is a simple closed poly-line interpolation to find p, the point on the curve
1. find the total length of the curve
2. find the start and end cvs of the line segment which contains p
3. calculate the position on that line segment, and the rotation
*/
bool ok = false;
const auto& curve_cvs_in = db.inputs.curve();
auto& locations = db.outputs.location();
auto& rotations = db.outputs.rotateXYZ();
auto& orientations = db.outputs.orientation();
const auto& distances = db.inputs.distance();
double curve_length = 0; // The total curve length
std::vector<double> accumulated_lengths; // the length of the curve at each the end of each segment
std::vector<double> segment_lengths; // the length of each segment
size_t num_cvs = curve_cvs_in.size();
if (num_cvs == 0)
return false;
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "resize");
locations.resize(distances.size());
rotations.resize(distances.size());
orientations.resize(distances.size());
}
if (num_cvs == 1)
{
std::fill(locations.begin(), locations.end(), curve_cvs_in[0]);
std::fill(rotations.begin(), rotations.end(), vec3d(0, 0, 0));
return true;
}
std::vector<vec3d> curve_cvs;
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "PreprocessCurve");
curve_cvs.resize(curve_cvs_in.size() + 1);
std::copy(curve_cvs_in.begin(), curve_cvs_in.end(), curve_cvs.begin());
// add a cv to make a closed curve
curve_cvs[curve_cvs_in.size()] = curve_cvs_in[0];
// calculate the total curve length and the length at the end of each segment
const vec3d* p_a = curve_cvs.data();
for (size_t i = 1; i < curve_cvs.size(); ++i)
{
const vec3d& p_b = curve_cvs[i];
double segment_length = (p_b - *p_a).GetLength();
segment_lengths.push_back(segment_length);
curve_length += segment_length;
accumulated_lengths.push_back(curve_length);
p_a = &p_b;
}
}
const vec3d forwardAxis = axisToVec(db.inputs.forwardAxis(), db.tokens);
const vec3d upAxis = axisToVec(db.inputs.upAxis(), db.tokens);
// Calculate eye frame
auto eyeUL = forwardAxis;
auto eyeVL = upAxis;
auto eyeWL = (eyeUL ^ eyeVL).GetNormalized();
eyeVL = eyeWL ^ eyeUL;
// local transform from forward axis
matrix4d localMat, localMatInv;
localMat.SetIdentity();
localMat.SetRow3(0, eyeUL);
localMat.SetRow3(1, eyeVL);
localMat.SetRow3(2, eyeWL);
localMatInv = localMat.GetInverse();
auto distanceIter = distances.begin();
auto locationIter = locations.begin();
auto rotationIter = rotations.begin();
auto orientationIter = orientations.begin();
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "ScanCurve");
for (; distanceIter != distances.end(); ++distanceIter, ++locationIter, ++rotationIter, ++orientationIter)
{
// wrap distance to range [0, 1.0]
double normalized_distance = std::fmod(*distanceIter, 1.0);
// the distance along the curve in world space
double distance = curve_length * normalized_distance;
// Find the location and direction
double remaining_dist = 0;
for (size_t i = 0; i < accumulated_lengths.size(); ++i)
{
double segment_length = accumulated_lengths[i];
if (segment_length >= distance)
{
if (i > 0)
remaining_dist = distance - accumulated_lengths[i - 1];
else
remaining_dist = distance;
const auto& start_cv = curve_cvs[i];
const auto& end_cv = curve_cvs[i + 1];
const auto aimVec = end_cv - start_cv;
const auto segment_unit_vec = aimVec / segment_lengths[i];
const auto point_on_segment = start_cv + segment_unit_vec * remaining_dist;
*locationIter = point_on_segment;
// calculate the rotation
vec3d eyeU = segment_unit_vec;
vec3d eyeV = upAxis;
auto eyeW = (eyeU ^ eyeV).GetNormalized();
eyeV = eyeW ^ eyeU;
matrix4d eyeMtx;
eyeMtx.SetIdentity();
eyeMtx.SetTranslateOnly(point_on_segment);
// eye aiming
eyeMtx.SetRow3(0, eyeU);
eyeMtx.SetRow3(1, eyeV);
eyeMtx.SetRow3(2, eyeW);
matrix4d orientMtx = localMatInv * eyeMtx;
const quatd q = omni::graph::nodes::extractRotationQuatd(orientMtx);
const pxr::GfRotation rotation(omni::math::linalg::safeCastToUSD(q));
const auto eulerRotations =
rotation.Decompose(pxr::GfVec3d::ZAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::XAxis());
pxr::GfVec3d eulerRotationsXYZ(eulerRotations[2], eulerRotations[1], eulerRotations[0]);
*rotationIter = omni::math::linalg::safeCastToOmni(eulerRotationsXYZ);
*orientationIter = quatf(q);
ok = true;
break;
}
}
}
}
return ok;
}
};
REGISTER_OGN_NODE()
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnATan2.py | """
This is the implementation of the OGN node defined in OgnATan2.ogn
"""
import math
import omni.graph.core as og
class OgnATan2:
"""
Calculates the arc tangent of A,B. This is the angle in radians between the ray ending at the origin and
passing through the point (B, A).
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
db.outputs.result.value = math.degrees(math.atan2(db.inputs.a.value, db.inputs.b.value))
except TypeError as error:
db.log_error(f"atan2 could not be performed: {error}")
return False
return True
@staticmethod
def on_connection_type_resolve(node) -> None:
aattr = node.get_attribute("inputs:a")
battr = node.get_attribute("inputs:b")
resultattr = node.get_attribute("outputs:result")
og.resolve_fully_coupled([aattr, battr, resultattr])
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnSourceIndices.ogn | {
"SourceIndices": {
"version": 1,
"description": ["Takes an input array of index values in 'sourceStartsInTarget' encoded as the list of ",
"index values at which the output array value will be incremented, starting at the second ",
"entry, and with the last entry into the array being the desired sized of the output array ",
"'sourceIndices'. For example the input [1,2,3,5,6,6] would generate an output array of ",
"size 5 (last index) consisting of the values [0,0,2,3,3,3]:\n",
" - the first two 0s to fill the output array up to index input[1]=2\n",
" - the first two 0s to fill the output array up to index input[1]=2\n",
" - the 2 to fill the output array up to index input[2]=3\n",
" - the three 3s to fill the output array up to index input[3]=6"
],
"metadata" : {
"uiName": "Extract Source Index Array"
},
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"sourceStartsInTarget": {
"description": "List of index values encoding the increments for the output array values",
"type": "int[]",
"default": []
}
},
"outputs": {
"sourceIndices": {
"description": "Decoded list of index values as described by the node algorithm",
"type": "int[]",
"default": []
}
},
"tests": [
{ "inputs:sourceStartsInTarget": [1, 2, 3, 5, 6, 6], "outputs:sourceIndices": [0, 0, 1, 2, 2, 3] }
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAbsolute.ogn | {
"Absolute":
{
"version": 1,
"description": [
"Compute the absolute value of a vector, array of vectors, scalar or array of scalars",
"If an array of vectors are passed in, the output will be an array of corresponding absolute values"
],
"uiName": "Absolute",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"tags": ["absolute"],
"inputs": {
"input": {
"type": ["decimals", "integrals"],
"description": "The vector(s) or scalar(s) to take the absolute value of"
}
},
"outputs": {
"absolute": {
"type": ["decimals", "integrals"],
"description": "The resulting absolute(s)"
}
},
"tests": [
{
"inputs:input": {"type": "double", "value": -10.0},
"outputs:absolute": {"type": "double", "value": 10.0}
},
{
"inputs:input": {"type": "float", "value": -10.0},
"outputs:absolute": {"type": "float", "value": 10.0}
},
{
"inputs:input": {"type": "half", "value": -10.0},
"outputs:absolute": {"type": "half", "value": 10.0}
},
{
"inputs:input": {"type": "int", "value": -10},
"outputs:absolute": {"type": "int", "value": 10}
},
{
"inputs:input": {"type": "int64", "value": -10},
"outputs:absolute": {"type": "int64", "value": 10}
},
{
"inputs:input": {"type": "uchar", "value": 10},
"outputs:absolute": {"type": "uchar", "value": 10}
},
{
"inputs:input": {"type": "uint", "value": 10},
"outputs:absolute": {"type": "uint", "value": 10}
},
{
"inputs:input": {"type": "uint64", "value": 10},
"outputs:absolute": {"type": "uint64", "value": 10}
},
{
"inputs:input": {"type": "double[3]", "value": [-1.0, -2.0, -3.0]},
"outputs:absolute": {"type": "double[3]", "value": [1.0, 2.0, 3.0]}
},
{
"inputs:input": {"type": "float[4]", "value": [-2.0, 2.0, -2.0, 2.0]},
"outputs:absolute": {"type": "float[4]", "value": [2.0, 2.0, 2.0, 2.0]}
},
{
"inputs:input": {"type": "int[2]", "value": [3, -4]},
"outputs:absolute": {"type": "int[2]", "value": [3, 4]}
},
{
"inputs:input": {"type": "half[2]", "value": [3.0, -4.0]},
"outputs:absolute": {"type": "half[2]", "value": [3.0, 4.0]}
},
{
"inputs:input": {"type": "double[]", "value": [-1.0, -2.0, -2.0]},
"outputs:absolute": {"type": "double[]", "value": [1.0, 2.0, 2.0]}
},
{
"inputs:input": {"type": "float[]", "value": [-2.0, 2.0, -2.0, 2.0]},
"outputs:absolute": {"type": "float[]", "value": [2.0, 2.0, 2.0, 2.0]}
},
{
"inputs:input": {"type": "half[]", "value": [3.0, -4.0]},
"outputs:absolute": {"type": "half[]", "value": [3.0, 4.0]}
},
{
"inputs:input": {"type": "int[]", "value": [3, -4]},
"outputs:absolute": {"type": "int[]", "value": [3, 4]}
},
{
"inputs:input": {"type": "int64[]", "value": [3, -4]},
"outputs:absolute": {"type": "int64[]", "value": [3, 4]}
},
{
"inputs:input": {"type": "uchar[]", "value": [3, 4]},
"outputs:absolute": {"type": "uchar[]", "value": [3, 4]}
},
{
"inputs:input": {"type": "uint[]", "value": [3, 4]},
"outputs:absolute": {"type": "uint[]", "value": [3, 4]}
},
{
"inputs:input": {"type": "uint64[]", "value": [3, 4]},
"outputs:absolute": {"type": "uint64[]", "value": [3, 4]}
},
{
"inputs:input": {"type": "int[3][]", "value": [[1, -2, -2], [-4, 2, 6], [3, -2, 4], [1, -4, 2]]},
"outputs:absolute": {"type": "int[3][]", "value": [[1, 2, 2], [4, 2, 6], [3, 2, 4], [1, 4, 2]]}
},
{
"inputs:input": {"type": "double[3][]", "value": [[1.0, -2.0, -2.0], [-4.0, 2.0, 6.0], [3.0, -2.0, 4.0], [1.0, -4.0, 2.0]]},
"outputs:absolute": {"type": "double[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, 4.0, 2.0]]}
},
{
"inputs:input": {"type": "float[3][]", "value": [[1.0, -2.0, -2.0], [-4.0, 2.0, 6.0], [3.0, -2.0, 4.0], [1.0, -4.0, 2.0]]},
"outputs:absolute": {"type": "float[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, 4.0, 2.0]]}
},
{
"inputs:input": {"type": "half[3][]", "value": [[1.0, -2.0, -2.0], [-4.0, 2.0, 6.0], [3.0, -2.0, 4.0], [1.0, -4.0, 2.0]]},
"outputs:absolute": {"type": "half[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, 4.0, 2.0]]}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomGaussian.ogn | {
"RandomGaussian": {
"version": 1,
"description": [
"Generates a random numeric value using a Gaussian (aka normal) distribution.",
"The shape can be controlled with two inputs: mean and standard deviation.",
"These inputs can be numbers, vectors, tuples or arrays of these.",
"If one input has a higher dimension than the other, ",
"then the input with lower dimension will be repeated to match the dimension of the other input (broadcasting). "
],
"uiName": "Random Gaussian",
"categories": [ "math:operator" ],
"scheduling": [ "threadsafe" ],
"inputs": {
"execIn": {
"type": "execution",
"description": "The input execution port to output a new random value"
},
"seed": {
"type": "uint64",
"description": "The seed of the random generator.",
"uiName": "Seed",
"$optional": "Setting optional=true is a workaround to avoid the USD generated tests for checking the default value of 0, since we override the default seed with a random one",
"optional": true
},
"useSeed": {
"type": "bool",
"description": "Use the custom seed instead of a random one",
"uiName": "Use seed",
"default": false
},
"isNoise": {
"type": "bool",
"description": [
"Turn this node into a noise generator function",
"For a given seed, it will then always output the same number(s)"
],
"uiName": "Is noise function",
"default": false,
"metadata": {
"hidden": "true",
"literalOnly": "1"
}
},
"mean": {
"type": [ "decimals" ],
"description": [
"The mean of the normal distribution.",
"Can be a number, vector, tuple, or array of these.",
"The default value is double 0."
],
"uiName": "Mean",
"optional": true
},
"stdev": {
"type": [ "decimals" ],
"description": [
"The standard deviation of the normal distribution.",
"Can be a number, vector, tuple, or array of these.",
"The default value is double 1."
],
"uiName": "Standard Deviation",
"optional": true
},
"useLog": {
"type": "bool",
"description": "Use a log-normal distribution instead",
"uiName": "Use log-normal",
"default": false
}
},
"state": {
"gen": {
"type": "matrixd[3]",
"description": "Random number generator internal state (abusing matrix3d because it is large enough)"
}
},
"outputs": {
"random": {
"type": [ "decimals" ],
"description": "The random Gaussian value that was generated",
"uiName": "Random Gaussian",
"unvalidated": true
},
"execOut": {
"type": "execution",
"description": "The output execution port"
}
},
"tests": [
{
"$description": "Checks that float 123 is generated",
"inputs:useSeed": true,
"inputs:seed": 123456789,
"inputs:mean": {
"type": "float",
"value": 123.0
},
"inputs:stdev": {
"type": "float",
"value": 0.0
},
"inputs:execIn": 1,
"outputs:random": {
"type": "float",
"value": 123.0
},
"outputs:execOut": 1,
"inputs:isNoise": true
},
{
"$description": "Checks double array broadcasting",
"inputs:useSeed": true,
"inputs:seed": 123456789,
"inputs:mean": {
"type": "double[]",
"value": [ -100, 100 ]
},
"inputs:stdev": {
"type": "double",
"value": 1
},
"inputs:execIn": 1,
"outputs:random": {
"type": "double[]",
"value": [ -98.27423617, 100.04434614 ]
},
"outputs:execOut": 1,
"inputs:isNoise": true
},
{
"$description": "Checks half tuple broadcasting",
"inputs:useSeed": true,
"inputs:seed": 123456789,
"inputs:mean": {
"type": "half",
"value": 0
},
"inputs:stdev": {
"type": "half[2]",
"value": [ 1, 2 ]
},
"inputs:execIn": 1,
"outputs:random": {
"type": "half[2]",
"value": [ 1.7255859, 0.08868408 ]
},
"outputs:execOut": 1,
"inputs:isNoise": true
},
{
"$description": "Checks float array tuple broadcasting and log-normal mean",
"inputs:useSeed": true,
"inputs:seed": 123456789,
"inputs:mean": {
"type": "float[2][]",
"value": [
[ 1, 2 ],
[ 3, 4 ]
]
},
"inputs:stdev": {
"type": "float",
"value": 0
},
"inputs:useLog": true,
"inputs:execIn": 1,
"outputs:random": {
"type": "float[2][]",
"value": [
[ 1, 2 ],
[ 3, 4 ]
]
},
"outputs:execOut": 1,
"inputs:isNoise": true
},
{
"$description": "Checks log-normal stdev",
"inputs:useSeed": true,
"inputs:seed": 123456789,
"inputs:mean": {
"type": "float",
"value": 100
},
"inputs:stdev": {
"type": "float[]",
"value": [ 1, 1, 1, 1, 1 ]
},
"inputs:useLog": true,
"inputs:execIn": 1,
"outputs:random": {
"type": "float[]",
"value": [ 101.735756, 100.03935, 99.89501, 100.42319, 99.54652 ]
},
"outputs:execOut": 1,
"inputs:isNoise": true
},
{
"$description": "Checks that the default input values are used",
"inputs:useSeed": true,
"inputs:seed": 9302349107990861236,
"inputs:execIn": 1,
"outputs:random": {
"type": "double",
"value": 0.6957887336760361
},
"outputs:execOut": 1,
"inputs:isNoise": true
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnModulo.cpp | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnModuloDatabase.h>
#include <cmath>
#include <algorithm>
#include <array>
template <typename T, typename AttrInType, typename AttrOutType>
void modulo(AttrInType& a, AttrInType& b, AttrOutType& result)
{
T bval = *b.template get<T>();
if (bval == 0)
{
*result.template get<T>() = 0;
return;
}
*result.template get<T>() = *a.template get<T>() % bval;
}
class OgnModulo
{
public:
static bool compute(OgnModuloDatabase& db)
{
const auto& a = db.inputs.a();
const auto& b = db.inputs.b();
auto& result = db.outputs.result();
if (!a.resolved())
return true;
switch(a.type().baseType)
{
case BaseDataType::eInt:
modulo<int>(a, b, result);
break;
case BaseDataType::eUInt:
modulo<uint32_t>(a, b, result);
break;
case BaseDataType::eInt64:
modulo<int64_t>(a, b, result);
break;
case BaseDataType::eUInt64:
modulo<uint64_t>(a, b, result);
break;
default:
break;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node){
// Resolve fully-coupled types for the 3 attributes
std::array<AttributeObj, 3> attrs {
node.iNode->getAttribute(node, OgnModuloAttributes::inputs::a.m_name),
node.iNode->getAttribute(node, OgnModuloAttributes::inputs::b.m_name),
node.iNode->getAttribute(node, OgnModuloAttributes::outputs::result.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/math/OgnDivide_Matrices.cpp | #include "OgnDivideHelper.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace OGNDivideHelper
{
template<size_t N>
bool _tryCompute(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
if (tryComputeAssumingType<double, double, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, float, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, pxr::GfHalf, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, int32_t, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, int64_t, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, unsigned char, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, uint32_t, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, uint64_t, N>(db, a, b, result, count)) return true;
return false;
}
bool tryComputeMatrices(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
// Matrix3f type
if (_tryCompute<9>(db, a, b, result, count)) return true;
// Matrix4f type
if (_tryCompute<16>(db, a, b, result, count)) return true;
return false;
}
} // namespace OGNDivideHelper
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLocationAtDistanceOnCurve2.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 <OgnGetLocationAtDistanceOnCurve2Database.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/vec.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/base/gf/rotation.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/math/linalg/SafeCast.h>
#include <cmath>
#include "XformUtils.h"
using omni::math::linalg::quatf;
using omni::math::linalg::quatd;
using omni::math::linalg::vec3d;
using omni::math::linalg::matrix4d;
// return the named unit vector X,Y or Z
static vec3d axisToVec(NameToken axisToken, OgnGetLocationAtDistanceOnCurve2Database::TokenManager& tokens)
{
if (axisToken == tokens.y || axisToken == tokens.Y)
return vec3d::YAxis();
if (axisToken == tokens.z || axisToken == tokens.Z)
return vec3d::ZAxis();
return vec3d::XAxis();
}
class OgnGetLocationAtDistanceOnCurve2
{
public:
static bool computeVectorized(OgnGetLocationAtDistanceOnCurve2Database& db, size_t count)
{
/* This is a simple closed poly-line interpolation to find p, the point on the curve
1. find the total length of the curve
2. find the start and end cvs of the line segment which contains p
3. calculate the position on that line segment, and the rotation
*/
bool ok = false;
const auto& curve_cvs_in = db.inputs.curve();
auto locations = db.outputs.location.vectorized(count);
auto rotations = db.outputs.rotateXYZ.vectorized(count);
auto orientations = db.outputs.orientation.vectorized(count);
const auto distances = db.inputs.distance.vectorized(count);
double curve_length = 0; // The total curve length
std::vector<double> accumulated_lengths; // the length of the curve at each the end of each segment
std::vector<double> segment_lengths; // the length of each segment
size_t num_cvs = curve_cvs_in.size();
if (num_cvs == 0)
return false;
if (num_cvs == 1)
{
std::fill(locations.begin(), locations.end(), curve_cvs_in[0]);
std::fill(rotations.begin(), rotations.end(), vec3d(0, 0, 0));
return true;
}
std::vector<vec3d> curve_cvs;
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "PreprocessCurve");
curve_cvs.resize(curve_cvs_in.size() + 1);
std::copy(curve_cvs_in.begin(), curve_cvs_in.end(), curve_cvs.begin());
// add a cv to make a closed curve
curve_cvs[curve_cvs_in.size()] = curve_cvs_in[0];
// calculate the total curve length and the length at the end of each segment
const vec3d* p_a = curve_cvs.data();
for (size_t i = 1; i < curve_cvs.size(); ++i)
{
const vec3d& p_b = curve_cvs[i];
double segment_length = (p_b - *p_a).GetLength();
segment_lengths.push_back(segment_length);
curve_length += segment_length;
accumulated_lengths.push_back(curve_length);
p_a = &p_b;
}
}
const vec3d forwardAxis = axisToVec(db.inputs.forwardAxis(), db.tokens);
const vec3d upAxis = axisToVec(db.inputs.upAxis(), db.tokens);
// Calculate eye frame
auto eyeUL = forwardAxis;
auto eyeVL = upAxis;
auto eyeWL = (eyeUL ^ eyeVL).GetNormalized();
eyeVL = eyeWL ^ eyeUL;
// local transform from forward axis
matrix4d localMat, localMatInv;
localMat.SetIdentity();
localMat.SetRow3(0, eyeUL);
localMat.SetRow3(1, eyeVL);
localMat.SetRow3(2, eyeWL);
localMatInv = localMat.GetInverse();
auto distanceIter = distances.begin();
auto locationIter = locations.begin();
auto rotationIter = rotations.begin();
auto orientationIter = orientations.begin();
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "ScanCurve");
for (; distanceIter != distances.end(); ++distanceIter, ++locationIter, ++rotationIter, ++orientationIter)
{
// wrap distance to range [0, 1.0]
double normalized_distance = std::fmod(*distanceIter, 1.0);
// the distance along the curve in world space
double distance = curve_length * normalized_distance;
// Find the location and direction
double remaining_dist = 0;
for (size_t i = 0; i < accumulated_lengths.size(); ++i)
{
double segment_length = accumulated_lengths[i];
if (segment_length >= distance)
{
if (i > 0)
remaining_dist = distance - accumulated_lengths[i - 1];
else
remaining_dist = distance;
const auto& start_cv = curve_cvs[i];
const auto& end_cv = curve_cvs[i + 1];
const auto aimVec = end_cv - start_cv;
const auto segment_unit_vec = aimVec / segment_lengths[i];
const auto point_on_segment = start_cv + segment_unit_vec * remaining_dist;
*locationIter = point_on_segment;
// calculate the rotation
vec3d eyeU = segment_unit_vec;
vec3d eyeV = upAxis;
auto eyeW = (eyeU ^ eyeV).GetNormalized();
eyeV = eyeW ^ eyeU;
matrix4d eyeMtx;
eyeMtx.SetIdentity();
eyeMtx.SetTranslateOnly(point_on_segment);
// eye aiming
eyeMtx.SetRow3(0, eyeU);
eyeMtx.SetRow3(1, eyeV);
eyeMtx.SetRow3(2, eyeW);
matrix4d orientMtx = localMatInv * eyeMtx;
const quatd q = omni::graph::nodes::extractRotationQuatd(orientMtx);
const pxr::GfRotation rotation(omni::math::linalg::safeCastToUSD(q));
const auto eulerRotations =
rotation.Decompose(pxr::GfVec3d::ZAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::XAxis());
pxr::GfVec3d eulerRotationsXYZ(eulerRotations[2], eulerRotations[1], eulerRotations[0]);
*rotationIter = omni::math::linalg::safeCastToOmni(eulerRotationsXYZ);
*orientationIter = quatf(q);
ok = true;
break;
}
}
}
}
return ok;
}
};
REGISTER_OGN_NODE()
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnExponent.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 <OgnExponentDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
//
bool tryComputeAssumingScalarHalf(OgnExponentDatabase& db)
{
auto functor = [](auto const& base, auto const& exp, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(std::pow(static_cast<double>(static_cast<float>(base)), exp)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf, int, pxr::GfHalf>(db.inputs.base(),
db.inputs.exponent(),
db.outputs.result(),
functor);
}
template <typename T, typename M>
bool tryComputeAssumingScalarType(OgnExponentDatabase& db)
{
auto functor = [](auto const& base, auto const& exp, auto& result)
{
result = static_cast<M>(std::pow(base, exp));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, int, M>(db.inputs.base(), db.inputs.exponent(),
db.outputs.result(), functor);
}
template <size_t N>
bool tryComputeAssumingTupleHalf(OgnExponentDatabase& db)
{
auto functor = [](auto const& base, auto const& exp, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(std::pow(static_cast<double>(static_cast<float>(base)), exp)));
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, pxr::GfHalf, int, pxr::GfHalf>(db.inputs.base(),
db.inputs.exponent(),
db.outputs.result(),
functor);
}
template <typename T, size_t N, typename M>
bool tryComputeAssumingTupleType(OgnExponentDatabase& db)
{
auto functor = [](auto const& base, auto const& exp, auto& result)
{
result = static_cast<M>(std::pow(base, exp));
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, T, int, M>(db.inputs.base(), db.inputs.exponent(),
db.outputs.result(), functor);
}
} // unnamed namespace
class OgnExponent
{
public:
static bool compute(OgnExponentDatabase& db)
{
try
{
const auto& bType = db.inputs.base().type();
switch (bType.componentCount)
{
case 1:
switch (bType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingScalarType<int32_t, double>(db);
case BaseDataType::eInt64:
return tryComputeAssumingScalarType<int64_t, double>(db);
case BaseDataType::eUInt:
return tryComputeAssumingScalarType<uint32_t, double>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingScalarType<uint64_t, double>(db);
case BaseDataType::eUChar:
return tryComputeAssumingScalarType<unsigned char, double>(db);
case BaseDataType::eHalf:
return tryComputeAssumingScalarHalf(db);
case BaseDataType::eDouble:
return tryComputeAssumingScalarType<double, double>(db);
case BaseDataType::eFloat:
return tryComputeAssumingScalarType<float, float>(db);
default:
break;
}
case 2:
switch (bType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingTupleType<int32_t, 2, double>(db);
case BaseDataType::eDouble:
return tryComputeAssumingTupleType<double, 2, double>(db);
case BaseDataType::eFloat:
return tryComputeAssumingTupleType<float, 2, float>(db);
case BaseDataType::eHalf:
return tryComputeAssumingTupleHalf<2>(db);
default:
break;
}
case 3:
switch (bType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingTupleType<int32_t, 3, double>(db);
case BaseDataType::eDouble:
return tryComputeAssumingTupleType<double, 3, double>(db);
case BaseDataType::eFloat:
return tryComputeAssumingTupleType<float, 3, float>(db);
case BaseDataType::eHalf:
return tryComputeAssumingTupleHalf<3>(db);
default:
break;
}
case 4:
switch (bType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingTupleType<int32_t, 4, double>(db);
case BaseDataType::eDouble:
return tryComputeAssumingTupleType<double, 4, double>(db);
case BaseDataType::eFloat:
return tryComputeAssumingTupleType<float, 4, float>(db);
case BaseDataType::eHalf:
return tryComputeAssumingTupleHalf<4>(db);
default:
break;
}
case 9:
if (bType.baseType == BaseDataType::eDouble )
{
return tryComputeAssumingTupleType<double, 9, double>(db);
}
case 16:
if (bType.baseType == BaseDataType::eDouble )
{
return tryComputeAssumingTupleType<double, 16, double>(db);
}
}
throw ogn::compute::InputError("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto base = node.iNode->getAttributeByToken(node, inputs::base.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto bType = base.iAttribute->getResolvedType(base);
Type newType(BaseDataType::eDouble, bType.componentCount, bType.arrayDepth, bType.role);
if (bType.baseType != BaseDataType::eUnknown)
{
switch (bType.baseType)
{
case BaseDataType::eUChar:
case BaseDataType::eInt:
case BaseDataType::eUInt:
case BaseDataType::eInt64:
case BaseDataType::eUInt64:
result.iAttribute->setResolvedType(result, newType);
break;
default:
std::array<AttributeObj, 2> attrs { base, result};
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
break;
}
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnIncrement.ogn | {
"Increment": {
"version": 1,
"description": [
"Add a double argument to any type (element-wise). This includes simple values, tuples, arrays,",
"and arrays of tuples. ",
"The output type is always the same as the type of input:value. ",
"For example: tuple + double results a tuple. ",
"Chopping is used for approximation. For example: 4 + 3.2 will result 7. ",
"The default increment value is 1.0. "
],
"uiName": "Increment",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"value": {
"type": ["numerics"],
"description": "The operand that to be increased",
"uiName": "Value"
},
"increment": {
"type": "double",
"description": "The number added to the first operand",
"uiName": "Increment amount",
"default": 1.0
}
},
"outputs": {
"result": {
"type": ["numerics"],
"description": "Result of the increment",
"uiName": "Result"
}
},
"tests": [
{
"inputs:value": {"type": "float[2]", "value": [1.0, 2.0]},
"inputs:increment": 0.5,
"outputs:result": {"type": "float[2]", "value": [ 1.5, 2.5 ] }
},
{
"inputs:value": {"type": "int64", "value": 10},
"inputs:increment": 1.2,
"outputs:result": {"type": "int64", "value": 11}
},
{
"inputs:value": {"type": "double[2][]", "value": [[10, 5], [1, 1]]},
"inputs:increment": 5.4,
"outputs:result": {"type": "double[2][]", "value": [[ 15.4, 10.4 ],[ 6.4, 6.4 ]]}
},
{
"inputs:value": {"type": "double[2][]", "value": [[10, 5], [1, 1]]},
"inputs:increment": 5,
"outputs:result": {"type": "double[2][]", "value": [[15, 10], [6, 6]]}
},
{
"inputs:value": {"type": "double", "value": 2.22045e-16},
"outputs:result": {"type": "double", "value": 1.000000000000000222045}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnInterpolateTo.cpp | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <algorithm>
#include <OgnInterpolateToDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/quat.h>
#include "XformUtils.h"
using omni::math::linalg::quatd;
using omni::math::linalg::GfSlerp;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnInterpolateToDatabase& db, double alpha, size_t count)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Linear interpolation between a and b, alpha in [0, 1]
result = a + (b - a) * (float) alpha;
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnInterpolateToDatabase& db, double alpha, size_t count)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Linear interpolation between a and b, alpha in [0, 1]
for (size_t i = 0; i < N; i++)
{
result[i] = a[i] + (b[i] - a[i]) * (float) alpha;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N]>(db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
template<>
bool tryComputeAssumingType<double, 4>(OgnInterpolateToDatabase& db, double alpha, size_t count)
{
auto currentAttribute =
db.abi_node().iNode->getAttribute(db.abi_node(), OgnInterpolateToAttributes::inputs::current.m_name);
auto currentRole = currentAttribute.iAttribute->getResolvedType(currentAttribute).role;
if (currentRole == AttributeRole::eQuaternion)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Note that in Fabric, quaternions are stored as XYZW, but quatd constructor requires WXYZ
auto q = GfSlerp(quatd(a[3], a[0], a[1], a[2]), quatd(b[3], b[0], b[1], b[2]), alpha);
result[0] = q.GetImaginary()[0];
result[1] = q.GetImaginary()[1];
result[2] = q.GetImaginary()[2];
result[3] = q.GetReal();
};
return ogn::compute::tryComputeWithArrayBroadcasting<double[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
else
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Linear interpolation between a and b, alpha in [0, 1]
for (size_t i = 0; i < 4; i++)
{
result[i] = a[i] + (b[i] - a[i]) * (float)alpha;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<double[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
}
template<>
bool tryComputeAssumingType<float, 4>(OgnInterpolateToDatabase& db, double alpha, size_t count)
{
auto currentAttribute =
db.abi_node().iNode->getAttribute(db.abi_node(), OgnInterpolateToAttributes::inputs::current.m_name);
auto currentRole = currentAttribute.iAttribute->getResolvedType(currentAttribute).role;
if (currentRole == AttributeRole::eQuaternion)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Note that in Fabric, quaternions are stored as XYZW, but quatd constructor requires WXYZ
auto q = GfSlerp(quatd(a[3], a[0], a[1], a[2]), quatd(b[3], b[0], b[1], b[2]), alpha);
result[0] = (float)q.GetImaginary()[0];
result[1] = (float)q.GetImaginary()[1];
result[2] = (float)q.GetImaginary()[2];
result[3] = (float)q.GetReal();
};
return ogn::compute::tryComputeWithArrayBroadcasting<float[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
else
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Linear interpolation between a and b, alpha in [0, 1]
for (size_t i = 0; i < 4; i++)
{
result[i] = a[i] + (b[i] - a[i]) * (float)alpha;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<float[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
};
}
template<>
bool tryComputeAssumingType<pxr::GfHalf, 4>(OgnInterpolateToDatabase& db, double alpha, size_t count)
{
auto currentAttribute =
db.abi_node().iNode->getAttribute(db.abi_node(), OgnInterpolateToAttributes::inputs::current.m_name);
auto currentRole = currentAttribute.iAttribute->getResolvedType(currentAttribute).role;
if (currentRole == AttributeRole::eQuaternion)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Note that in Fabric, quaternions are stored as XYZW, but quatd constructor requires WXYZ
auto q = GfSlerp(quatd(a[3], a[0], a[1], a[2]), quatd(b[3], b[0], b[1], b[2]), alpha);
result[0] = (float)q.GetImaginary()[0];
result[1] = (float)q.GetImaginary()[1];
result[2] = (float)q.GetImaginary()[2];
result[3] = (float)q.GetReal();
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
else
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Linear interpolation between a and b, alpha in [0, 1]
for (size_t i = 0; i < 4; i++)
{
result[i] = a[i] + (b[i] - a[i]) * (float)alpha;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
};
}
} // namespace
class OgnInterpolateTo
{
public:
static bool computeVectorized(OgnInterpolateToDatabase& db, size_t count)
{
int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10);
float speed = std::max(0.f, float(db.inputs.speed()));
float deltaSeconds = std::max(0.f, float(db.inputs.deltaSeconds()));
// delta step
float alpha = std::min(std::max(speed * deltaSeconds, 0.f), 1.f);
// Ease out by applying a shifted exponential to the alpha
double alpha2 = 1.f - exponent(1.f - alpha, exp);
auto& inputType = db.inputs.current().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, alpha2, count);
case 2: return tryComputeAssumingType<double, 2>(db, alpha2, count);
case 3: return tryComputeAssumingType<double, 3>(db, alpha2, count);
case 4: return tryComputeAssumingType<double, 4>(db, alpha2, count);
case 9: return tryComputeAssumingType<double, 9>(db, alpha2, count);
case 16: return tryComputeAssumingType<double, 16>(db, alpha2, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, alpha2, count);
case 2: return tryComputeAssumingType<float, 2>(db, alpha2, count);
case 3: return tryComputeAssumingType<float, 3>(db, alpha2, count);
case 4: return tryComputeAssumingType<float, 4>(db, alpha2, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, alpha2, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, alpha2, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, alpha2, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, alpha2, count);
default: break;
}
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnInterpolateTo: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto current = node.iNode->getAttributeByToken(node, inputs::current.token());
auto target = node.iNode->getAttributeByToken(node, inputs::target.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto currentType = current.iAttribute->getResolvedType(current);
auto targetType = target.iAttribute->getResolvedType(target);
// Require current, target, and alpha to be resolved before determining result's type
if (currentType.baseType != BaseDataType::eUnknown && targetType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { current, target, result };
std::array<uint8_t, 3> tupleCounts {
currentType.componentCount,
targetType.componentCount,
std::max(currentType.componentCount, targetType.componentCount)
};
std::array<uint8_t, 3> arrayDepths {
currentType.arrayDepth,
targetType.arrayDepth,
std::max(currentType.arrayDepth, targetType.arrayDepth)
};
std::array<AttributeRole, 3> rolesBuf {
currentType.role,
targetType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnEachZero.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnEachZeroDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
static constexpr char kValueTypeUnresolved[] = "Failed to resolve type of 'value' input";
// Check whether a scalar attribute contains a value which lies within 'tolerance' of 0.
//
// 'tolerance' must be non-negative. It is ignored for bool values.
// 'isZero' will be set true if 'value' contains a zero value, false otherwise.
//
// The return value is true if 'value' is a supported scalar type, false otherwise.
//
bool checkScalarForZero(OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eBool: isZero = ! *(value.get<bool>()); break;
case BaseDataType::eDouble: isZero = std::abs(*(value.get<double>())) <= tolerance; break;
case BaseDataType::eFloat: isZero = std::abs(*(value.get<float>())) <= tolerance; break;
case BaseDataType::eHalf: isZero = std::abs(*(value.get<pxr::GfHalf>())) <= tolerance; break;
case BaseDataType::eInt: isZero = std::abs(*(value.get<int32_t>())) <= (int32_t)tolerance; break;
case BaseDataType::eInt64: isZero = std::abs(*(value.get<int64_t>())) <= (int64_t)tolerance; break;
case BaseDataType::eUChar: isZero = *(value.get<unsigned char>()) <= (unsigned char)tolerance; break;
case BaseDataType::eUInt: isZero = *(value.get<uint32_t>()) <= (uint32_t)tolerance; break;
case BaseDataType::eUInt64: isZero = *(value.get<uint64_t>()) <= (uint64_t)tolerance; break;
default:
return false;
}
return true;
}
// Determine which components of a decimal tuple attribute are within a given tolerance of zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - type of the components of the tuple.
// N - number of components in the tuple
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each component of the tuple. On return the elements
// will be set true where the corresponding components lie within 'tolerance' of zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T, uint8_t N>
bool getTupleZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
if (auto const tuple = value.get<T[N]>())
{
for (uint8_t i = 0; i < N; ++i)
{
isZero[i] = (std::abs(tuple[i]) <= tolerance);
}
return true;
}
return false;
}
// Determine which components of a tuple attribute are zero
// (i.e. they lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each component of the tuple. On return the elements
// will be set true where the corresponding components are zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
bool getTupleZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eDouble:
switch (value.type().componentCount)
{
case 2: return getTupleZeroes<double, 2>(value, tolerance, isZero);
case 3: return getTupleZeroes<double, 3>(value, tolerance, isZero);
case 4: return getTupleZeroes<double, 4>(value, tolerance, isZero);
case 9: return getTupleZeroes<double, 9>(value, tolerance, isZero);
case 16: return getTupleZeroes<double, 16>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eFloat:
switch (value.type().componentCount)
{
case 2: return getTupleZeroes<float, 2>(value, tolerance, isZero);
case 3: return getTupleZeroes<float, 3>(value, tolerance, isZero);
case 4: return getTupleZeroes<float, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eHalf:
switch (value.type().componentCount)
{
case 2: return getTupleZeroes<pxr::GfHalf, 2>(value, tolerance, isZero);
case 3: return getTupleZeroes<pxr::GfHalf, 3>(value, tolerance, isZero);
case 4: return getTupleZeroes<pxr::GfHalf, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eInt:
switch (value.type().componentCount)
{
case 2: return getTupleZeroes<int32_t, 2>(value, tolerance, isZero);
case 3: return getTupleZeroes<int32_t, 3>(value, tolerance, isZero);
case 4: return getTupleZeroes<int32_t, 4>(value, tolerance, isZero);
default: break;
}
break;
default: break;
}
return false;
}
// Determine which elements of an unsigned array attribute are zero (i.e. they lie
// within 'tolerance' of 0).
//
// T - type of the elements of the array. Must be an unsigned type, other than bool.
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each element of the unsigned array. On return the elements
// of 'isZero' will be set true where the corresponding elements in the unsigned array are zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T>
bool getUnsignedArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
static_assert(std::is_unsigned<T>::value && !std::is_same<T, bool>::value, "Unsigned integer type required.");
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[]>())
{
for (size_t i = 0; i < array.size(); ++i)
isZero[i] = (array->at(i) <= (T)tolerance);
return true;
}
return false;
}
// Determine which elements of a bool array attribute are zero/false. No tolerance
// value is applied since tolerance is meaningless for bool.
//
// 'isZero' is an array of bool with one element for each element of the 'value' array. On return the elements
// of 'isZero' will be set true where the corresponding elements in the 'value' array are zero, false otherwise.
//
// The return value is true if 'value' is a bool array type, false otherwise.
//
bool getBoolArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, ogn::array<bool>& isZero)
{
if (auto const array = value.get<bool[]>())
{
for (size_t i = 0; i < array.size(); ++i)
isZero[i] = !array->at(i);
return true;
}
return false;
}
// Determine which elements of a signed array attribute are within a given tolerance of zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - type of the elements of the array. Must be a signed type.
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each element of the signed array. On return the elements
// of 'isZero' will be set true where the corresponding elements in the unsigned array are within 'tolerance'
// of 0.0, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T>
bool getSignedArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
static_assert(std::is_signed<T>::value || pxr::GfIsFloatingPoint<T>::value, "Signed integer or decimal type required.");
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[]>())
{
for (size_t i = 0; i < array.size(); ++i)
isZero[i] = (std::abs(array->at(i)) <= tolerance);
return true;
}
return false;
}
// Determine which elements of a scalar array attribute are zero (i.e. they lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each element of the scalar array. On return the elements
// of 'isZero' will be set true where the corresponding elements in the scalar array are zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
bool getScalarArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eBool: return getBoolArrayZeroes(value, isZero);
case BaseDataType::eDouble: return getSignedArrayZeroes<double>(value, tolerance, isZero);
case BaseDataType::eFloat: return getSignedArrayZeroes<float>(value, tolerance, isZero);
case BaseDataType::eHalf: return getSignedArrayZeroes<pxr::GfHalf>(value, tolerance, isZero);
case BaseDataType::eInt: return getSignedArrayZeroes<int32_t>(value, tolerance, isZero);
case BaseDataType::eInt64: return getSignedArrayZeroes<int64_t>(value, tolerance, isZero);
case BaseDataType::eUChar: return getUnsignedArrayZeroes<unsigned char>(value, tolerance, isZero);
case BaseDataType::eUInt: return getUnsignedArrayZeroes<uint32_t>(value, tolerance, isZero);
case BaseDataType::eUInt64: return getUnsignedArrayZeroes<uint64_t>(value, tolerance, isZero);
default: break;
}
return false;
}
// Returns true if all components of the tuple are zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - base type of the tuple (e.g. float if tuple is float[2]).
// N - number of components in the tuple (e.g. '2' in the example above).
//
// 'tolerance' must be non-negative
//
template <typename T, uint8_t N>
bool isTupleZero(const T tuple[N], double tolerance)
{
CARB_ASSERT(tolerance >= 0.0);
for (uint8_t i = 0; i < N; ++i)
{
if (std::abs(tuple[i]) > tolerance) return false;
}
return true;
}
// Determine which elements of a tuple array attribute are zero (i.e. all of the tuple's
// components lie within a 'tolerance' of 0).
//
// T - type of the components of the tuple.
// N - number of components in the tuple
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each tuple in the tuple array. On return the elements
// of 'isZero' will be set true where the corresponding tuples are zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T, uint8_t N>
bool getTupleArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, double tolerance, ogn::array<bool>& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[][N]>())
{
for (size_t i = 0; i < array.size(); ++i)
isZero[i] = isTupleZero<T, N>(array->at(i), tolerance);
return true;
}
return false;
}
// Determine which elements of a tuple array attribute are zero (i.e. all of the tuple's components
// lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each tuple in the tuple array. On return the elements
// of 'isZero' will be set true where the corresponding tuples are zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
bool getTupleArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eDouble:
switch (value.type().componentCount)
{
case 2: return getTupleArrayZeroes<double, 2>(value, tolerance, isZero);
case 3: return getTupleArrayZeroes<double, 3>(value, tolerance, isZero);
case 4: return getTupleArrayZeroes<double, 4>(value, tolerance, isZero);
case 9: return getTupleArrayZeroes<double, 9>(value, tolerance, isZero);
case 16: return getTupleArrayZeroes<double, 16>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eFloat:
switch (value.type().componentCount)
{
case 2: return getTupleArrayZeroes<float, 2>(value, tolerance, isZero);
case 3: return getTupleArrayZeroes<float, 3>(value, tolerance, isZero);
case 4: return getTupleArrayZeroes<float, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eHalf:
switch (value.type().componentCount)
{
case 2: return getTupleArrayZeroes<pxr::GfHalf, 2>(value, tolerance, isZero);
case 3: return getTupleArrayZeroes<pxr::GfHalf, 3>(value, tolerance, isZero);
case 4: return getTupleArrayZeroes<pxr::GfHalf, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eInt:
switch (value.type().componentCount)
{
case 2: return getTupleArrayZeroes<int32_t, 2>(value, tolerance, isZero);
case 3: return getTupleArrayZeroes<int32_t, 3>(value, tolerance, isZero);
case 4: return getTupleArrayZeroes<int32_t, 4>(value, tolerance, isZero);
default: break;
}
break;
default: break;
}
return false;
}
} // namespace
class OgnEachZero
{
public:
static bool compute(OgnEachZeroDatabase& db)
{
const auto& value = db.inputs.value();
if (!value.resolved())
return true;
const auto& tolerance = db.inputs.tolerance();
auto& result = db.outputs.result();
try
{
bool foundType{ false };
// Arrays
if (value.type().arrayDepth > 0)
{
if (auto resultArray = result.get<bool[]>())
{
resultArray.resize(value.size());
// Arrays of tuples.
if (value.type().componentCount > 1)
{
foundType = getTupleArrayZeroes(value, tolerance, *resultArray);
}
// Arrays of scalars.
else
{
foundType = getScalarArrayZeroes(value, tolerance, *resultArray);
}
}
else
{
throw ogn::compute::InputError("input value is an array but result is not bool[]");
}
}
// Tuples
else if (value.type().componentCount > 1)
{
if (auto resultArray = result.get<bool[]>())
{
resultArray.resize(value.type().componentCount);
foundType = getTupleZeroes(value, tolerance, *resultArray);
}
else
{
throw ogn::compute::InputError("input value is a tuple but result is not bool[]");
}
}
// Scalars
else
{
if (auto resultScalar = result.get<bool>())
{
*resultScalar = false;
foundType = checkScalarForZero(value, tolerance, *resultScalar);
}
else
{
throw ogn::compute::InputError("input value is a scalar but result is not bool");
}
}
if (! foundType)
{
throw ogn::compute::InputError(kValueTypeUnresolved);
}
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto value = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto valueType = value.iAttribute->getResolvedType(value);
// Require value to be resolved before determining result's type
if (valueType.baseType != BaseDataType::eUnknown)
{
// The result is bool for scalar values, and bool array for arrays and tuples.
bool resultIsArray = ((valueType.arrayDepth > 0) || (valueType.componentCount > 1));
Type resultType(BaseDataType::eBool, 1, (resultIsArray ? 1 : 0));
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCos.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 <OgnCosDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/math.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnCosDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<T>(std::cos(pxr::GfDegreesToRadians(a)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.value(), db.outputs.value(), functor);
}
template <>
bool tryComputeAssumingType<pxr::GfHalf>(OgnCosDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(std::cos(pxr::GfDegreesToRadians(a))));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf>(db.inputs.value(), db.outputs.value(), functor);
}
} // namespace
class OgnCos
{
public:
static bool compute(OgnCosDatabase& db)
{
try
{
// All possible types excluding ogn::string and bool
// scalers
if (tryComputeAssumingType<double>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf>(db)) return true; // Specifically for pxr::GfHalf
else if (tryComputeAssumingType<float>(db)) return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (std::exception &error)
{
db.logError("Could not perform Cosine funtion : %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto value = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::value.token());
auto valueType = value.iAttribute->getResolvedType(value);
// Require inputs to be resolved before determining output's type
if (valueType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { value, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnATan2.ogn | {
"ATan2": {
"version": 1,
"description": "Outputs the arc tangent of a/b in degrees",
"language": "python",
"categories": ["math:operator"],
"uiName": "Atan2",
"inputs": {
"a": {
"type": ["decimal_scalers"],
"description": "Input A"
},
"b": {
"type": ["decimal_scalers"],
"description": "Input B"
}
},
"outputs": {
"result": {
"type": ["decimal_scalers"],
"description": "The result of ATan2(A,B)",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:a": {"type": "float", "value": 5.0}, "inputs:b": {"type": "float", "value": 3.0},
"outputs:result": {"type": "float", "value": 59.0362434679}
},
{
"inputs:a": {"type": "double", "value": 70.0}, "inputs:b": {"type": "double", "value": 10.0},
"outputs:result": {"type": "double", "value": 81.8698976458}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnClamp.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnClampDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename T>
void clamp(T const& input, T const& lower, T const& upper, T& result)
{
if (lower > upper)
{
throw ogn::compute::InputError("Lower is greater than upper!");
}
if (input <= lower)
{
result = lower;
}
else if (input < upper)
{
result = input;
}
else
{
result = upper;
}
}
template <typename T>
bool tryComputeAssumingType(OgnClampDatabase& db, size_t count)
{
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.input(), db.inputs.lower(), db.inputs.upper(), db.outputs.result(), &clamp<T>, count);
}
template<typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnClampDatabase& db, size_t count)
{
return ogn::compute::tryComputeWithTupleBroadcasting<tupleSize, T>(
db.inputs.input(), db.inputs.lower(), db.inputs.upper(), db.outputs.result(), &clamp<T>, count);
}
} // namespace
// Node to clamp an input value or array of values to some range [lower, upper],
class OgnClamp
{
public:
// Clamp a number or array of numbers to a specified range
// If an array of numbers is provided as the input and lower/upper are scalers
// Then each input numeric will be clamped to the range [lower, upper]
// If all inputs are arrays, clamping will be done element-wise. lower & upper are broadcast against input
static bool computeVectorized(OgnClampDatabase& db, size_t count)
{
auto& inputType = db.inputs.input().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (const std::exception& e)
{
db.logError("Clamping could not be performed: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto inputAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::input.token());
auto lowerAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::lower.token());
auto upperAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::upper.token());
auto resultAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::result.token());
auto inputType = inputAttr.iAttribute->getResolvedType(inputAttr);
auto lowerType = lowerAttr.iAttribute->getResolvedType(lowerAttr);
auto upperType = upperAttr.iAttribute->getResolvedType(upperAttr);
// If one of the upper or lower is resolved we can resolve the other because they should match
if ((lowerType == BaseDataType::eUnknown) != (upperType == BaseDataType::eUnknown))
{
std::array<AttributeObj, 2> attrs { lowerAttr, upperAttr };
nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size());
lowerType = lowerAttr.iAttribute->getResolvedType(lowerAttr);
upperType = upperAttr.iAttribute->getResolvedType(upperAttr);
}
// The output shape must match the input shape and visa-versa, however we can't say anything
// about the input base type until it's connected
if (inputType.baseType != BaseDataType::eUnknown && lowerType != BaseDataType::eUnknown && upperType != BaseDataType::eUnknown)
{
if (inputType.baseType != lowerType.baseType || inputType.baseType != upperType.baseType)
{
nodeObj.iNode->logComputeMessageOnInstance(
nodeObj, kAuthoringGraphIndex, ogn::Severity::eError, "Unable to connect inputs to clamp with different base types");
return;
}
std::array<AttributeObj, 2> attrs { inputAttr, resultAttr };
nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivideHelper.h | #include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <omni/graph/core/ogn/Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace OGNDivideHelper
{
using InType = ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu>;
using ResType = ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>;
// Allow (AType[N] / BType) and (AType[N] / BType[N]) but not (AType / BType[N])
template<typename AType, typename BType, typename CType, size_t N, typename Functor>
bool tryComputeWithLimitedTupleBroadcasting(
InType const& a, InType const& b, ResType& result, Functor functor, size_t count)
{
if (ogn::compute::tryComputeWithArrayBroadcasting<AType[N], BType[N], CType[N]>(a, b, result,
[&](auto const& a, auto const& b, auto& result) { for (size_t i = 0; i < N; i++) functor(a[i], b[i], result[i]); }, count))
return true;
else if (ogn::compute::tryComputeWithArrayBroadcasting<AType[N], BType, CType[N]>(a, b, result,
[&](auto const& a, auto const& b, auto& result) { for (size_t i = 0; i < N; i++) functor(a[i], b, result[i]); }, count))
return true;
return false;
}
// AType is a vector of float's or double's
template<typename AType, typename BType, size_t N>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<!std::is_integral<AType>::value && !std::is_same<AType, pxr::GfHalf>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<AType>(static_cast<double>(a) / static_cast<double>(b));
};
return tryComputeWithLimitedTupleBroadcasting<AType, BType, AType, N>(a, b, result, functor, count);
}
// AType is a vector of half's
template<typename AType, typename BType, size_t N>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<std::is_same<AType, pxr::GfHalf>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<AType>(static_cast<float>(static_cast<double>(a) / static_cast<double>(b)));
};
return tryComputeWithLimitedTupleBroadcasting<AType, BType, AType, N>(a, b, result, functor, count);
}
// AType is a vector of integrals => Force result to be a vector of doubles
template<typename AType, typename BType, size_t N>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<std::is_integral<AType>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<double>(a) / static_cast<double>(b);
};
return tryComputeWithLimitedTupleBroadcasting<AType, BType, double, N>(a, b, result, functor, count);
}
template<typename T, size_t N>
bool _tryComputeAssuming(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
if (tryComputeAssumingType<double, T, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, T, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, T, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, T, N>(db, a, b, result, count)) return true;
return false;
}
template<size_t N>
bool _tryComputeTuple(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
if (_tryComputeAssuming<double, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<float, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<pxr::GfHalf, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<int32_t, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<int64_t, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<unsigned char, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<uint32_t, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<uint64_t, N>(db, a, b, result, count)) return true;
return false;
}
bool tryComputeScalars(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count);
bool tryComputeTuple2(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count);
bool tryComputeTuple3(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count);
bool tryComputeTuple4(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count);
bool tryComputeMatrices(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count);
} // namespace OGNDivideHelper
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAsin.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 <OgnAsinDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/math.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnAsinDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<T>(pxr::GfRadiansToDegrees(std::asin(a)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.value(), db.outputs.value(), functor);
}
template <>
bool tryComputeAssumingType<pxr::GfHalf>(OgnAsinDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfRadiansToDegrees(std::asin(a))));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf>(db.inputs.value(), db.outputs.value(), functor);
}
} // namespace
class OgnAsin
{
public:
static bool compute(OgnAsinDatabase& db)
{
try
{
// All possible types excluding ogn::string and bool
// scalers
if (tryComputeAssumingType<double>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf>(db)) return true; // Specifically for pxr::GfHalf
else if (tryComputeAssumingType<float>(db)) return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (std::exception &error)
{
db.logError("Could not perform Arcsine funtion : %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto value = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::value.token());
auto valueType = value.iAttribute->getResolvedType(value);
// Require inputs to be resolved before determining output's type
if (valueType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { value, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomNumeric.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 "OgnRandomNumericDatabase.h"
#include "random/RandomNodeBase.h"
#include <omni/graph/core/ogn/ComputeHelpers.h>
namespace omni
{
namespace graph
{
namespace nodes
{
using namespace random;
class OgnRandomNumeric : public NodeBase<OgnRandomNumeric, OgnRandomNumericDatabase>
{
template <typename T>
static bool tryComputeAssumingType(OgnRandomNumericDatabase& db, size_t count)
{
return ogn::compute::tryComputeWithArrayBroadcasting<T>(
db.state.gen(), db.inputs.min(), db.inputs.max(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& min, T const& max, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextUniform(min, max);
},
count);
}
template <typename T, size_t N>
static bool tryComputeAssumingType(OgnRandomNumericDatabase& db, size_t count)
{
return ogn::compute::tryComputeWithTupleBroadcasting<N, T>(
db.state.gen(), db.inputs.min(), db.inputs.max(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& min, T const& max, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextUniform(min, max);
},
count);
}
static bool defaultCompute(OgnRandomNumericDatabase& db, size_t count)
{
auto const genBuffers = db.state.gen.vectorized(count);
if (genBuffers.size() != count)
{
db.logWarning("Failed to write to output using default range [0..1) (wrong genBuffers size)");
return false;
}
for (size_t i = 0; i < count; ++i)
{
auto outPtr = db.outputs.random(i).get<double>();
if (!outPtr)
{
db.logWarning("Failed to write to output using default range [0..1) (null output pointer)");
return false;
}
*outPtr = asGenerator(genBuffers[i]).nextUniform<double>(0.0, 1.0);
}
return true;
}
public:
static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed);
// HACK: onConnectionTypeResolve is not called the first time,
// but by setting the output type, we force it to be called.
//
// TODO: OGN should really support default inputs for union types!
// See https://nvidia-omniverse.atlassian.net/browse/OM-67739
setDefaultOutputType(nodeObj, outputs::random.token());
}
static bool onCompute(OgnRandomNumericDatabase& db, size_t count)
{
auto const& minAttr{ db.inputs.min() };
auto const& maxAttr{ db.inputs.max() };
auto const& outAttr{ db.outputs.random() };
if (!outAttr.resolved())
{
// Output type not yet resolved, can't compute
db.logWarning("Unsupported input types");
return false;
}
if (!minAttr.resolved() && !maxAttr.resolved())
{
// Output using default min and max
return defaultCompute(db, count);
}
// Inputs and outputs are resolved, try all possible types, excluding bool and ogn::string
auto const outType = outAttr.type();
switch (outType.baseType) // NOLINT(clang-diagnostic-switch-enum)
{
case BaseDataType::eDouble:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<double>(db, count);
case 2:
return tryComputeAssumingType<double, 2>(db, count);
case 3:
return tryComputeAssumingType<double, 3>(db, count);
case 4:
return tryComputeAssumingType<double, 4>(db, count);
case 9:
return tryComputeAssumingType<double, 9>(db, count);
case 16:
return tryComputeAssumingType<double, 16>(db, count);
default:
break;
}
case BaseDataType::eFloat:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<float>(db, count);
case 2:
return tryComputeAssumingType<float, 2>(db, count);
case 3:
return tryComputeAssumingType<float, 3>(db, count);
case 4:
return tryComputeAssumingType<float, 4>(db, count);
default:
break;
}
case BaseDataType::eHalf:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default:
break;
}
case BaseDataType::eInt:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<int32_t>(db, count);
case 2:
return tryComputeAssumingType<int32_t, 2>(db, count);
case 3:
return tryComputeAssumingType<int32_t, 3>(db, count);
case 4:
return tryComputeAssumingType<int32_t, 4>(db, count);
default:
break;
}
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default:
break;
}
db.logWarning("Unsupported input types");
return false;
}
static void onConnectionTypeResolve(NodeObj const& node)
{
resolveOutputType(node, inputs::min.token(), inputs::max.token(), outputs::random.token());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnIncrement.cpp | // Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnIncrementDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Helper functions to try doing an addition operation on two input attributes.
* We assume the runtime attributes have type T and the other one is double.
* The first input is either an array or a singular value, and the second input is a single double value
*
* @param db: database object
* @return True if we can get a result properly, false if not
*/
/**
* Used when input type is resolved as Half
*/
bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + static_cast<float>(b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf, double, pxr::GfHalf>(db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as any numeric type other than Half
*/
template<typename T>
bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + static_cast<T>(b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, double, T>(db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as Half
*/
template <size_t N>
bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + static_cast<float>(b);
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, pxr::GfHalf, double, pxr::GfHalf>(
db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as any numeric type other than Half
*/
template<typename T, size_t N>
bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + static_cast<T>(b);
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, T, double, T>(db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count);
}
} // namespace
class OgnIncrement
{
public:
static size_t computeVectorized(OgnIncrementDatabase& db, size_t count)
{
auto& inputType = db.inputs.value().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType(db, count);
case 2: return tryComputeAssumingType<2>(db, count);
case 3: return tryComputeAssumingType<3>(db, count);
case 4: return tryComputeAssumingType<4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return 0;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto value = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto valueType = value.iAttribute->getResolvedType(value);
// Require inputs to be resolved before determining sum's type
if (valueType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { value, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnTrig.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnTrigDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/math.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
_____ ____ _ _ ____ _______ _____ ____ _______ __
| __ \ / __ \ | \ | |/ __ \__ __| / ____/ __ \| __ \ \ / /
| | | | | | | | \| | | | | | | | | | | | | |__) \ \_/ /
| | | | | | | | . ` | | | | | | | | | | | | ___/ \ /
| |__| | |__| | | |\ | |__| | | | | |___| |__| | | | |
|_____/ \____/ |_| \_|\____/ |_| \_____\____/|_| |_|
This node uses a large cascading "if" to select operation type, which is not efficient. It will be eventually be
refactored but until then do not propagate this anti-pattern. Thanks for keeping things fast!
*/
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnTrigDatabase& db, NameToken operation, size_t count)
{
if (operation == db.tokens.SIN) // Sine
{
auto functor = [](auto const& a, auto& result) { result = static_cast<T>(std::sin(pxr::GfDegreesToRadians(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.COS) // Cosine
{
auto functor = [](auto const& a, auto& result) { result = static_cast<T>(std::cos(pxr::GfDegreesToRadians(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.TAN) // Tangent
{
auto functor = [](auto const& a, auto& result) { result = static_cast<T>(std::tan(pxr::GfDegreesToRadians(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.ARCSIN) // Arcsine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<T>(pxr::GfRadiansToDegrees(std::asin(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.ARCCOS) // Arccosine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<T>(pxr::GfRadiansToDegrees(std::acos(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.ARCTAN) // Arctangent
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<T>(pxr::GfRadiansToDegrees(std::atan(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.DEGREES) // Degrees
{
auto functor = [](auto const& a, auto& result) { result = static_cast<T>(pxr::GfRadiansToDegrees(a)); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.RADIANS) // Radians
{
auto functor = [](auto const& a, auto& result) { result = static_cast<T>(pxr::GfDegreesToRadians(a)); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
throw ogn::compute::InputError("Operation not one of sin, cos, tan, asin, acos, degrees, radians");
}
template <>
bool tryComputeAssumingType<pxr::GfHalf>(OgnTrigDatabase& db, NameToken operation, size_t count)
{
if (operation == db.tokens.SIN) // Sine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::sin(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.COS) // Cosine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::cos(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.TAN) // Tangent
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::tan(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.ARCSIN) // Arcsine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::asin(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.ARCCOS) // Arccosine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::acos(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.ARCTAN) // Arctangent
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::atan(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.DEGREES) // Degrees
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfRadiansToDegrees(a))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.RADIANS) // Radians
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfDegreesToRadians(a))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
throw ogn::compute::InputError("Operation not one of sin, cos, tan, asin, acos, degrees, radians");
}
} // namespace
class OgnTrig
{
public:
static size_t computeVectorized(OgnTrigDatabase& db, size_t count)
{
NameToken const& operation = db.inputs.operation();
try
{
if (tryComputeAssumingType<double>(db, operation, count)) return count;
else if (tryComputeAssumingType<pxr::GfHalf>(db, operation, count)) return count;
else if (tryComputeAssumingType<float>(db, operation, count)) return count;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (std::exception &error)
{
db.logError("Operation %s could not be performed : %s", db.tokenToString(operation), error.what());
}
return 0;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto aType = a.iAttribute->getResolvedType(a);
// Require inputs to be resolved before determining output's type
if (aType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { a, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNegate.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnNegateDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnNegateDatabase& db, size_t count)
{
auto functor = [](auto const& input, auto& output)
{
output = input * -1;
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T>(db.inputs.input(), db.outputs.output(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnNegateDatabase& db, size_t count)
{
auto functor = [](auto const& input, auto& output)
{
for (size_t i = 0; i < N; ++i)
{
output[i] = input[i] * -1;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N]>(db.inputs.input(), db.outputs.output(), functor, count);
}
} // namespace
class OgnNegate
{
public:
static bool computeVectorized(OgnNegateDatabase& db, size_t count)
{
auto& inputType = db.inputs.input().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto input = node.iNode->getAttributeByToken(node, inputs::input.token());
auto output = node.iNode->getAttributeByToken(node, outputs::output.token());
auto inputType = input.iAttribute->getResolvedType(input);
// Require input to be resolved before determining output's type
if (inputType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { input, output };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLocationAtDistanceOnCurve.ogn | {
"GetLocationAtDistanceOnCurve": {
"version": 1,
"description": [
"DEPRECATED: Use GetLocationAtDistanceOnCurve2"
],
"uiName": "Get Locations At Distances On Curve",
"categories": ["internal"],
"metadata": {"hidden": "true"},
"scheduling": ["threadsafe"],
"inputs": {
"curve": {
"type": "pointd[3][]",
"description": "The curve to be examined",
"uiName": "Curve"
},
"distance": {
"type": "double[]",
"description": "The distances along the curve, wrapped to the range 0-1.0",
"uiName": "Distances"
},
"forwardAxis": {
"type": "token",
"description": ["The direction vector from which the returned rotation is relative, one of X, Y, Z"],
"uiName": "Forward",
"default": "X"
},
"upAxis": {
"type": "token",
"description": ["The world Up vector, the curve should be in a plane perpendicular with this - one of X, Y, Z"],
"uiName": "Up",
"default": "Y"
}
},
"outputs": {
"location": {
"type": "pointd[3][]",
"description": "Locations",
"uiName": "Locations on curve at the given distances in world space"
},
"rotateXYZ": {
"type": "vectord[3][]",
"description": "Rotations",
"uiName": "World space rotations of the curve at the given distances, may not be smooth for some curves"
},
"orientation": {
"type": "quatf[4][]",
"description": "Orientations",
"uiName": "World space orientations of the curve at the given distances, may not be smooth for some curves"
}
},
"tokens": [
"x", "y", "z", "X", "Y", "Z"
],
"tests": [
{"inputs:curve": [[1, 2, 3]], "inputs:distance": [0.5], "outputs:location": [[1, 2, 3]]},
{"inputs:curve": [[0, 0, 0], [0, 0, 1]], "inputs:distance": [0.75, 0], "inputs:forwardAxis": "X", "inputs:upAxis": "Y",
"outputs:location": [[0, 0, 0.5], [0, 0, 0]], "outputs:rotateXYZ": [[0, 90, 0], [0, -90, 0]]}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnEase.ogn | {
"Ease": {
"version": 2,
"description": [
"Easing function which iterpolates between a start and end value.",
"Vectors are eased component-wise. The easing functions can be applied to decimal types.",
"Linear: Interpolates between start and finish at a fixed rate.",
"EaseIn: Starts slowly and ends fast according to an exponential, the slope is determined by the 'exponent' input.",
"EaseOut: Same as EaseIn, but starts fast and ends slow",
"EaseInOut: Combines EaseIn and EaseOut",
"SinIn: Starts slowly and ends fast according to a sinusoidal curve",
"SinOut: Same as SinIn, but starts fast and ends slow",
"SinInOut: Combines SinIn and SinOut"
],
"uiName": "Easing Function",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"start": {
"type": ["decimal_scalers", "decimal_tuples", "decimal_arrays"],
"description": "The start value"
},
"end": {
"type": ["decimal_scalers", "decimal_tuples", "decimal_arrays"],
"description": "The end value"
},
"alpha": {
"type": ["float", "float[]"],
"description": "The normalized time (0 - 1.0). Values outside this range will be clamped"
},
"blendExponent": {
"type": "int",
"description": ["The blend exponent, which is the degree of the ease curve",
" (1 = linear, 2 = quadratic, 3 = cubic, etc). ",
"This only applies to the Ease* functions"],
"minimum": 1,
"maximum": 10,
"default": 2
},
"easeFunc": {
"type": "token",
"description": "The easing function to apply (EaseIn, EaseOut, EaseInOut, Linear, SinIn, SinOut, SinInOut)",
"uiName": "Operation",
"default": "EaseInOut",
"metadata": {
"allowedTokens": ["EaseIn", "EaseOut", "EaseInOut", "Linear", "SinIn", "SinOut", "SinInOut"]
}
}
},
"outputs": {
"result": {
"type": ["decimal_scalers", "decimal_tuples", "decimal_arrays"],
"description": "The eased result of the function applied to value",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:start": {"type": "float", "value": 0}, "inputs:end": {"type": "float", "value": 10},
"inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float", "value": 0.5}, "outputs:result": {"type": "float", "value": 5}
},
{
"inputs:start": {"type": "float[]", "value": [0, 1]}, "inputs:end": {"type": "float[]", "value": [10, 11]},
"inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float[]", "value": [0.5, 0.6]},
"outputs:result": {"type": "float[]", "value": [5, 7]}
},
{
"inputs:start": {"type": "float[]", "value": [0, 0]}, "inputs:end": {"type": "float", "value": 10},
"inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float[]", "value": [0.5, 0.6]}, "outputs:result": {"type": "float[]", "value": [5, 6]}
},
{
"inputs:start": {"type": "float", "value": 0}, "inputs:end": {"type": "float", "value": 10},
"inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float[]", "value": [0.5, 0.6]},
"outputs:result": {"type": "float[]", "value": [5, 6]}
},
{
"inputs:start": {"type": "float[2]", "value": [0,0]}, "inputs:end": {"type": "float[2]", "value": [10,10]},
"inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float[]", "value": [0.5, 0.6]},
"outputs:result": {"type": "float[2][]", "value": [[5, 5],[6,6]]}
},
{
"inputs:start": {"type": "float[2][]", "value": [[0, 0], [10, 10]]}, "inputs:end": {"type": "float[2]", "value": [10, 20]},
"inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float[]", "value": [0.5, 0.5]}, "outputs:result": {"type": "float[2][]", "value": [[5, 10],[10,15]]}
},
{
"inputs:start": {"type": "double", "value": 0.0}, "inputs:end": {"type": "double", "value": 10.0},
"inputs:easeFunc": "EaseInOut", "inputs:alpha": {"type": "float", "value": 0.25}, "outputs:result": {"type": "double", "value": 1.25}
},
{
"inputs:start": {"type": "double", "value": 0.0}, "inputs:end": {"type": "double", "value": 10.0},
"inputs:easeFunc": "SinOut", "inputs:alpha": {"type": "float", "value": 0.75}, "outputs:result": {"type": "double", "value": 9.238795}
},
{
"inputs:start": {"type": "float[2]", "value": [0, 1]},
"inputs:end": {"type": "float[2]", "value": [10.0, 11.0]},
"inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float", "value": 0.5},
"outputs:result": {"type": "float[2]", "value": [5.0, 6.0]}
},
{
"inputs:start": {"type": "half[3]", "value": [0, 1, 2]},
"inputs:end": {"type": "half[3]", "value": [10.0, 11.0, 12.0]},
"inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float", "value": 0.5},
"outputs:result": {"type": "half[3]", "value": [5.0, 6.0, 7.0]}
},
{
"inputs:start": {"type": "float", "value": 0}, "inputs:end": {"type": "float", "value": 10},
"inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float", "value": 1.524}, "outputs:result": {"type": "float", "value": 10}
},
{
"inputs:start": {"type": "float", "value": 0}, "inputs:end": {"type": "float", "value": 10},
"inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float", "value": -20}, "outputs:result": {"type": "float", "value": 0}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNoise.ogn | {
"Noise": {
"version": 1,
"description": [
"Sample values from a Perlin noise field.\n",
"The noise field for any given seed is static: the same input position will always",
"give the same result. This is useful in many areas, such as texturing and animation,",
"where repeatability is essential. If you want a result that varies then you will need",
"to vary either the position or the seed. For example, connecting the 'frame' output of",
"an OnTick node to position will provide a noise result which varies from frame to frame.",
"Perlin noise is locally smooth, meaning that small changes in the sample position will",
"produce small changes in the resulting noise. Varying the seed value will produce a more",
"chaotic result.\n",
"Another characteristic of Perlin noise is that it is zero at the corners of each cell in",
"the field. In practical terms this means that integral positions, such as 5.0 in a",
"one-dimensional field or (3.0, -1.0) in a two-dimensional field, will return a result",
"of 0.0. Thus, if the source of your sample positions provides only integral values then all of",
"your results will be zero. To avoid this try offsetting your position values by a fractional",
"amount, such as 0.5."
],
"uiName": "Noise",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"seed": {
"type": "uint",
"description": [
"Seed for generating the noise field."
],
"default": 0
},
"position": {
"type": [ "float", "float[]", "float[2]", "float[2][]", "float[3]", "float[3][]", "float[4]", "float[4][]" ],
"description": [
"Position(s) within the noise field to be sampled. For a given seed, the same position ",
"will always return the same noise value."
]
}
},
"outputs": {
"result": {
"type": [ "float", "float[]" ],
"description": "Value at the selected position(s) in the noise field."
}
},
"tests": [
{
"inputs:seed": 5,
"inputs:position": {"type": "float", "value": 1.4},
"outputs:result": {"type": "float", "value": 0.03438323736190796}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float", "value": -1.4},
"outputs:result": {"type": "float", "value": -0.03764888644218445}
},
{
"inputs:seed": 23,
"inputs:position": {"type": "float", "value": 1.4},
"outputs:result": {"type": "float", "value": -0.1955927014350891}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[2]", "value": [1.7, -0.4]},
"outputs:result": {"type": "float", "value": -0.10021606087684631}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[2]", "value": [-0.4, 1.7]},
"outputs:result": {"type": "float", "value": -0.4338015019893646}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[3]", "value": [1.4, -0.8, 0.5]},
"outputs:result": {"type": "float", "value": -0.14821206033229828}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[3]", "value": [1.5, -0.8, 0.5]},
"outputs:result": {"type": "float", "value": -0.11368121206760406}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[3]", "value": [1.4, -0.9, 0.5]},
"outputs:result": {"type": "float", "value": -0.16395819187164307}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[3]", "value": [1.4, -0.8, 0.8]},
"outputs:result": {"type": "float", "value": 0.00016325712203979492}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[3]", "value": [1.5, -0.9, 0.8]},
"outputs:result": {"type": "float", "value": -0.03829096257686615}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[3]", "value": [2.5, -0.9, 0.8]},
"outputs:result": {"type": "float", "value": 0.034046247601509094}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[4]", "value": [2.5, -0.9, 0.8, 0.0]},
"outputs:result": {"type": "float", "value": -0.009762797504663467}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[4]", "value": [2.5, -0.9, 0.8, 0.1]},
"outputs:result": {"type": "float", "value": -0.07352154701948166}
},
{
"inputs:seed": 6,
"inputs:position": {"type": "float[4]", "value": [2.5, -0.9, 0.8, 0.1]},
"outputs:result": {"type": "float", "value": 0.2615857422351837}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[]", "value": [-1.4]},
"outputs:result": {"type": "float[]", "value": [-0.03764889]}
},
{
"inputs:seed": 5,
"inputs:position": {"type": "float[]", "value": [0.5, -1.4]},
"outputs:result": {"type": "float[]", "value": [0.18699697, -0.03764889]}
},
{
"inputs:seed": 5,
"inputs:position": {
"type": "float[2][]",
"value": [[1.5, -0.8]]
},
"outputs:result": {"type": "float[]", "value": [0.16450586915016174] }
},
{
"inputs:seed": 5,
"inputs:position": {
"type": "float[2][]",
"value": [[1.5, -0.8], [2.5, -0.9]]
},
"outputs:result": {"type": "float[]", "value": [0.16450587, 0.08753645] }
},
{
"inputs:seed": 5,
"inputs:position": {
"type": "float[3][]",
"value": [[1.5, -0.8, 0.5]]
},
"outputs:result": {"type": "float[]", "value": [-0.11368121206760406] }
},
{
"inputs:seed": 5,
"inputs:position": {
"type": "float[3][]",
"value": [[1.5, -0.8, 0.5], [1.4, -0.8, 0.5]]
},
"outputs:result": {"type": "float[]", "value": [-0.11368121206760406, -0.14821206033229828] }
},
{
"inputs:seed": 5,
"inputs:position": {
"type": "float[3][]",
"value": [[2.5, -0.9, 0.8], [1.5, -0.8, 0.5], [1.4, -0.8, 0.5]]
},
"outputs:result": {"type": "float[]", "value": [0.034046247601509094, -0.11368121206760406, -0.14821206033229828] }
},
{
"inputs:seed": 5,
"inputs:position": {
"type": "float[4][]",
"value": [[2.5, -0.9, 0.8, 0.0], [2.5, -0.9, 0.8, 0.1]]
},
"outputs:result": {"type": "float[]", "value": [-0.009762797504663467, -0.07352154701948166] }
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnIsZero.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnIsZeroDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
static constexpr char kValueTypeUnresolved[] = "Failed to resolve type of 'value' input";
// Check whether a scalar attribute contains a value which lies within 'tolerance' of 0.
//
// 'tolerance' must be non-negative. It is ignored for bool values.
// 'isZero' will be set true if 'value' contains a zero value, false otherwise.
//
// The return value is true if 'value' is a supported scalar type, false otherwise.
//
bool checkScalarForZero(OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eBool: isZero = ! *(value.get<bool>()); break;
case BaseDataType::eDouble: isZero = std::abs(*(value.get<double>())) <= tolerance; break;
case BaseDataType::eFloat: isZero = std::abs(*(value.get<float>())) <= tolerance; break;
case BaseDataType::eHalf: isZero = std::abs(*(value.get<pxr::GfHalf>())) <= tolerance; break;
case BaseDataType::eInt: isZero = std::abs(*(value.get<int32_t>())) <= (int32_t)tolerance; break;
case BaseDataType::eInt64: isZero = std::abs(*(value.get<int64_t>())) <= (int64_t)tolerance; break;
case BaseDataType::eUChar: isZero = *(value.get<unsigned char>()) <= (unsigned char)tolerance; break;
case BaseDataType::eUInt: isZero = *(value.get<uint32_t>()) <= (uint32_t)tolerance; break;
case BaseDataType::eUInt64: isZero = *(value.get<uint64_t>()) <= (uint64_t)tolerance; break;
default:
return false;
}
return true;
}
// Check whether a tuple attribute contains a tuple whose components are all zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - type of the components of the tuple.
// N - number of components in the tuple
//
// 'tolerance' must be non-negative
// 'isZero' is assumed to be true on entry and will be set false if any component of the tuple is not zero.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T, int N>
bool checkTupleForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
CARB_ASSERT(isZero);
if (auto const tuple = value.get<T[N]>())
{
for (int i = 0; isZero && (i < N); ++i)
{
isZero = (std::abs(tuple[i]) <= tolerance);
}
return true;
}
return false;
}
// Check whether a tuple attribute contains a tuple whose components are all zero
// (i.e. they lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' is assumed to be true on entry and will be set false if any component of the tuple is not zero.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
bool checkTupleForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
CARB_ASSERT(isZero);
switch (value.type().baseType)
{
case BaseDataType::eDouble:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<double, 2>(value, tolerance, isZero);
case 3: return checkTupleForZeroes<double, 3>(value, tolerance, isZero);
case 4: return checkTupleForZeroes<double, 4>(value, tolerance, isZero);
case 9: return checkTupleForZeroes<double, 9>(value, tolerance, isZero);
case 16: return checkTupleForZeroes<double, 16>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eFloat:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<float, 2>(value, tolerance, isZero);
case 3: return checkTupleForZeroes<float, 3>(value, tolerance, isZero);
case 4: return checkTupleForZeroes<float, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eHalf:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<pxr::GfHalf, 2>(value, tolerance, isZero);
case 3: return checkTupleForZeroes<pxr::GfHalf, 3>(value, tolerance, isZero);
case 4: return checkTupleForZeroes<pxr::GfHalf, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eInt:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<int32_t, 2>(value, tolerance, isZero);
case 3: return checkTupleForZeroes<int32_t, 3>(value, tolerance, isZero);
case 4: return checkTupleForZeroes<int32_t, 4>(value, tolerance, isZero);
default: break;
}
break;
default: break;
}
return false;
}
// Check whether an unsigned array attribute's elements are all zero (i.e. they lie
// within 'tolerance' of 0).
//
// T - type of the elements of the array. Must be an unsigned type, other than bool.
//
// 'tolerance' must be non-negative
// 'isZero' will be set true if all elements of the array are zero, false otherwise.
//
// The return value is true if 'value' is a supported unsigned integer array type, false otherwise.
//
template <typename T>
bool checkUnsignedArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const int& tolerance, bool& isZero)
{
static_assert(std::is_unsigned<T>::value && !std::is_same<T, bool>::value, "Unsigned integer type required.");
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[]>())
{
isZero = std::all_of(array->begin(), array->end(), [tolerance](auto element){ return element <= (T)tolerance; });
return true;
}
return false;
}
// Check whether a bool array attribute's elements are all zero/false. No tolerance
// value is applied since tolerance is meaningless for bool.
//
// 'isZero' will be set true if all elements of the array are zero, false otherwise.
//
// The return value is true if 'value' is a bool array type, false otherwise.
//
bool checkBoolArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, bool& isZero)
{
if (auto const array = value.get<bool[]>())
{
isZero = std::all_of(array->begin(), array->end(), [](auto element){ return !element; });
return true;
}
return false;
}
// Check whether a signed array attribute's elements are all zero (i.e. they lie
// within 'tolerance' of 0).
//
// T - type of the elements of the array. Must be a signed type.
//
// 'tolerance' must be non-negative
// 'isZero' will be set true if all elements of the array are zero, false otherwise.
//
// The return value is true if 'value' is a supported signed array type, false otherwise.
//
template <typename T>
bool checkSignedArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
static_assert(std::is_signed<T>::value || pxr::GfIsFloatingPoint<T>::value, "Signed integer or decimal type required.");
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[]>())
{
isZero = std::all_of(array->begin(), array->end(), [tolerance](auto element){ return (std::abs(element) <= tolerance); });
return true;
}
return false;
}
// Check whether a scalar array attribute's elements are all zero (i.e. they lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' will be set true if all elements of the array are zero, false otherwise.
//
// The return value is true if 'value' is a supported scalar array type, false otherwise.
//
bool checkScalarArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eBool: return checkBoolArrayForZeroes(value, isZero);
case BaseDataType::eDouble: return checkSignedArrayForZeroes<double>(value, tolerance, isZero);
case BaseDataType::eFloat: return checkSignedArrayForZeroes<float>(value, tolerance, isZero);
case BaseDataType::eHalf: return checkSignedArrayForZeroes<pxr::GfHalf>(value, tolerance, isZero);
case BaseDataType::eInt: return checkSignedArrayForZeroes<int32_t>(value, tolerance, isZero);
case BaseDataType::eInt64: return checkSignedArrayForZeroes<int64_t>(value, tolerance, isZero);
case BaseDataType::eUChar: return checkUnsignedArrayForZeroes<unsigned char>(value, (int)tolerance, isZero);
case BaseDataType::eUInt: return checkUnsignedArrayForZeroes<uint32_t>(value, (int)tolerance, isZero);
case BaseDataType::eUInt64: return checkUnsignedArrayForZeroes<uint64_t>(value, (int)tolerance, isZero);
default: break;
}
return false;
}
// Returns true if all components of the tuple are zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - base type of the tuple (e.g. float if tuple is float[2]).
// N - number of components in the tuple (e.g. '2' in the example above).
//
// 'tolerance' must be non-negative
//
template <typename T, int N>
bool isTupleZero(const T tuple[N], double tolerance)
{
CARB_ASSERT(tolerance >= 0.0);
for (int i = 0; i < N; ++i)
{
if (std::abs(tuple[i]) > tolerance) return false;
}
return true;
}
// Check whether a tuple array attribute's elements are all zero tuples
// (i.e. all of their components are within 'tolerance' of 0).
//
// T - type of the components of the tuple.
// N - number of components in the tuple
//
// 'tolerance' must be non-negative
// 'isZero' will be set true if all tuples in the array is are zero, false otherwise.
//
// The return value is true if 'value' is a supported decimal tuple array type, false otherwise.
//
template <typename T, int N>
bool checkTupleArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, double tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[][N]>())
{
isZero = std::all_of(array->begin(), array->end(), [tolerance](auto element){ return isTupleZero<T, N>(element, tolerance); });
return true;
}
return false;
}
// Check whether a tuple array attribute's elements are all zero tuples (i.e. all of their components
// lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' will be set true if all tuples in the array is are zero, false otherwise.
//
// The return value is true if 'value' is a supported decimal tuple array type, false otherwise.
//
bool checkTupleArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eDouble:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<double, 2>(value, tolerance, isZero);
case 3: return checkTupleArrayForZeroes<double, 3>(value, tolerance, isZero);
case 4: return checkTupleArrayForZeroes<double, 4>(value, tolerance, isZero);
case 9: return checkTupleArrayForZeroes<double, 9>(value, tolerance, isZero);
case 16: return checkTupleArrayForZeroes<double, 16>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eFloat:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<float, 2>(value, tolerance, isZero);
case 3: return checkTupleArrayForZeroes<float, 3>(value, tolerance, isZero);
case 4: return checkTupleArrayForZeroes<float, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eHalf:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<pxr::GfHalf, 2>(value, tolerance, isZero);
case 3: return checkTupleArrayForZeroes<pxr::GfHalf, 3>(value, tolerance, isZero);
case 4: return checkTupleArrayForZeroes<pxr::GfHalf, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eInt:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<int32_t, 2>(value, tolerance, isZero);
case 3: return checkTupleArrayForZeroes<int32_t, 3>(value, tolerance, isZero);
case 4: return checkTupleArrayForZeroes<int32_t, 4>(value, tolerance, isZero);
default: break;
}
break;
default: break;
}
return false;
}
} // namespace
class OgnIsZero
{
public:
static bool compute(OgnIsZeroDatabase& db)
{
const auto& value = db.inputs.value();
if (!value.resolved())
return true;
const auto& tolerance = std::abs(db.inputs.tolerance());
auto& result = db.outputs.result();
try
{
// Some of the functions below return as soon as they find a non-zero value, so
// we start out assuming all values are zero and let them change that to false.
//
result = true;
bool foundType{ false };
// Arrays
if (value.type().arrayDepth > 0)
{
// Arrays of tuples.
if (value.type().componentCount > 1)
{
foundType = checkTupleArrayForZeroes(value, tolerance, result);
}
// Arrays of scalars.
else
{
foundType = checkScalarArrayForZeroes(value, tolerance, result);
}
}
// Tuples
else if (value.type().componentCount > 1)
{
foundType = checkTupleForZeroes(value, tolerance, result);
}
// Scalars
else
{
foundType = checkScalarForZero(value, tolerance, result);
}
if (! foundType)
{
throw ogn::compute::InputError(kValueTypeUnresolved);
}
}
catch (ogn::compute::InputError &error)
{
db.logError("OgnIsZero: %s", error.what());
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/math/OgnDivide_Tuple4.cpp | #include "OgnDivideHelper.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace OGNDivideHelper
{
bool tryComputeTuple4(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
return _tryComputeTuple<4>(db, a, b, result, count);
}
} // namespace OGNDivideHelper
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnIsZero.ogn | {
"IsZero": {
"version": 1,
"description": [
"Outputs a boolean indicating if all of the input values are zero within a specified tolerance."
],
"uiName": "Is Zero",
"categories": ["math:condition"],
"scheduling": ["threadsafe"],
"inputs": {
"value": {
"type": ["numerics"],
"description": "Value(s) to check for zero.",
"uiName": "Value"
},
"tolerance": {
"type": "double",
"description": [
"How close the value must be to 0 to be considered \"zero\"."
],
"uiName": "Tolerance",
"minimum": 0.0
}
},
"outputs": {
"result": {
"type": "bool",
"description": [
"If 'value' is a scalar then 'result' will be true if 'value' is zero. If 'value' is non-scalar",
"(array, tuple, matrix, etc) then 'result' will be true if all of its elements/components are zero."
],
"uiName": "Result"
}
},
"tests" : [
{
"inputs:value": {"type": "int", "value": 6},
"outputs:result": false
},
{
"inputs:value": {"type": "int", "value": -3},
"outputs:result": false
},
{
"inputs:value": {"type": "int", "value": 0},
"outputs:result": true
},
{
"inputs:value": {"type": "float", "value": 42.5},
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": -7.1},
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": 0.0},
"outputs:result": true
},
{
"inputs:value": {"type": "float", "value": 0.01},
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": -0.01},
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": 42.5},
"inputs:tolerance": 0.1,
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": -7.1},
"inputs:tolerance": 0.1,
"outputs:result": false
},
{
"inputs:value": {"type": "float", "value": 0.0},
"inputs:tolerance": 0.1,
"outputs:result": true
},
{
"inputs:value": {"type": "float", "value": 0.01},
"inputs:tolerance": 0.1,
"outputs:result": true
},
{
"inputs:value": {"type": "float", "value": -0.01},
"inputs:tolerance": 0.1,
"outputs:result": true
},
{
"inputs:value": {"type": "int", "value": 6},
"inputs:tolerance": 0.1,
"outputs:result": false
},
{
"inputs:value": {"type": "int", "value": -3},
"inputs:tolerance": 0.1,
"outputs:result": false
},
{
"inputs:value": {"type": "int", "value": 0},
"inputs:tolerance": 0.1,
"outputs:result": true
},
{
"inputs:value": {"type": "int", "value": 6},
"inputs:tolerance": 10.0,
"outputs:result": true
},
{
"inputs:value": {"type": "int", "value": -3},
"inputs:tolerance": 10.0,
"outputs:result": true
},
{
"inputs:value": {"type": "int", "value": 0},
"inputs:tolerance": 10.0,
"outputs:result": true
},
{
"inputs:value": {"type": "int[2]", "value": [ 0, 0 ]},
"outputs:result": true
},
{
"inputs:value": {"type": "int[2]", "value": [ 0, 3 ]},
"outputs:result": false
},
{
"inputs:value": {"type": "int[2]", "value": [ 3, 0 ]},
"outputs:result": false
},
{
"inputs:value": {"type": "int[2]", "value": [ 3, 5 ]},
"outputs:result": false
},
{
"inputs:value": {"type": "float[3]", "value": [1.7, 0.05, -4.3]},
"inputs:tolerance": 0.1,
"outputs:result": false
},
{
"inputs:value": {"type": "float[3]", "value": [0.02, 0.05, -0.03]},
"inputs:tolerance": 0.1,
"outputs:result": true
},
{
"inputs:value": {"type": "float[3][]", "value": [ [1.7, 0.05, -4.3], [0.02, 0.05, -0.03] ]},
"inputs:tolerance": 0.1,
"outputs:result": false
},
{
"inputs:value": {"type": "float[3][]", "value": [ [0.0, 0.0, 0.0], [0.02, 0.05, -0.03] ]},
"inputs:tolerance": 0.1,
"outputs:result": true
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAnyZero.cpp | // Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnAnyZeroDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
static constexpr char kValueTypeUnresolved[] = "Failed to resolve type of 'value' input";
// Check whether a scalar attribute contains a value which lies within 'tolerance' of 0.
//
// 'tolerance' must be non-negative. It is ignored for bool values.
// 'isZero' will be set true if 'value' contains a zero value, false otherwise.
//
// The return value is true if 'value' is a supported scalar type, false otherwise.
//
bool checkScalarForZero(OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eBool: isZero = ! *(value.get<bool>()); break;
case BaseDataType::eDouble: isZero = std::abs(*(value.get<double>())) <= tolerance; break;
case BaseDataType::eFloat: isZero = std::abs(*(value.get<float>())) <= tolerance; break;
case BaseDataType::eHalf: isZero = std::abs(*(value.get<pxr::GfHalf>())) <= tolerance; break;
case BaseDataType::eInt: isZero = std::abs(*(value.get<int32_t>())) <= (int32_t)tolerance; break;
case BaseDataType::eInt64: isZero = std::abs(*(value.get<int64_t>())) <= (int64_t)tolerance; break;
case BaseDataType::eUChar: isZero = *(value.get<unsigned char>()) <= (unsigned char)tolerance; break;
case BaseDataType::eUInt: isZero = *(value.get<uint32_t>()) <= (uint32_t)tolerance; break;
case BaseDataType::eUInt64: isZero = *(value.get<uint64_t>()) <= (uint64_t)tolerance; break;
default:
return false;
}
return true;
}
// Check whether a tuple attribute contains a value with at least one zero component
// (i.e. its value lies within 'tolerance' of 0).
//
// T - type of the components of the tuple.
// N - number of components in the tuple
//
// 'tolerance' must be non-negative
// 'hasZero' is assumed to be false on entry and will be set true if any component of the tuple is zero.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T, int N>
bool checkTupleForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero)
{
CARB_ASSERT(tolerance >= 0.0);
CARB_ASSERT(!hasZero);
if (auto const tuple = value.get<T[N]>())
{
for (int i = 0; !hasZero && (i < N); ++i)
{
hasZero = (std::abs(tuple[i]) <= tolerance);
}
return true;
}
return false;
}
// Check whether a tuple attribute contains a value with at least one zero component
// (i.e. its value lies within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'hasZero' is assumed to be false on entry and will be set true if any component of the tuple is zero.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
bool checkTupleForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero)
{
CARB_ASSERT(tolerance >= 0.0);
CARB_ASSERT(!hasZero);
switch (value.type().baseType)
{
case BaseDataType::eDouble:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<double, 2>(value, tolerance, hasZero);
case 3: return checkTupleForZeroes<double, 3>(value, tolerance, hasZero);
case 4: return checkTupleForZeroes<double, 4>(value, tolerance, hasZero);
case 9: return checkTupleForZeroes<double, 9>(value, tolerance, hasZero);
case 16: return checkTupleForZeroes<double, 16>(value, tolerance, hasZero);
}
break;
case BaseDataType::eFloat:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<float, 2>(value, tolerance, hasZero);
case 3: return checkTupleForZeroes<float, 3>(value, tolerance, hasZero);
case 4: return checkTupleForZeroes<float, 4>(value, tolerance, hasZero);
}
break;
case BaseDataType::eHalf:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<pxr::GfHalf, 2>(value, tolerance, hasZero);
case 3: return checkTupleForZeroes<pxr::GfHalf, 3>(value, tolerance, hasZero);
case 4: return checkTupleForZeroes<pxr::GfHalf, 4>(value, tolerance, hasZero);
}
break;
case BaseDataType::eInt:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<int32_t, 2>(value, tolerance, hasZero);
case 3: return checkTupleForZeroes<int32_t, 3>(value, tolerance, hasZero);
case 4: return checkTupleForZeroes<int32_t, 4>(value, tolerance, hasZero);
}
break;
default: break;
}
return false;
}
// Check whether an unsigned array attribute contains at least one element with a value of zero
// (i.e. it lies within 'tolerance' of 0).
//
// T - type of the elements of the array. Must be an unsigned type, other than bool.
//
// 'tolerance' must be non-negative
// 'hasZero' will be set true if any element of the array is zero, false otherwise.
//
// The return value is true if 'value' is a supported integer array type, false otherwise.
//
template <typename T>
bool checkUnsignedArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero)
{
static_assert(std::is_unsigned<T>::value && !std::is_same<T, bool>::value, "Unsigned integer type required.");
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[]>())
{
hasZero = std::any_of(array->begin(), array->end(), [tolerance](auto element){ return element <= (T)tolerance; });
return true;
}
return false;
}
// Check whether a bool array attribute contains at least one element with a value of zero (i.e. false).
// No tolerance value is applied since tolerance is meaningless for bool.
//
// 'hasZero' will be set true if any element of the array is zero, false otherwise.
//
// The return value is true if 'value' is a bool array type, false otherwise.
//
bool checkBoolArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, bool& hasZero)
{
if (auto const array = value.get<bool[]>())
{
hasZero = std::any_of(array->begin(), array->end(), [](auto element){ return !element; });
return true;
}
return false;
}
// Check whether a signed array attribute contains at least one element with a value of zero
// (i.e. its value lies within 'tolerance' of 0).
//
// T - type of the elements of the array. Must be a decimal type.
//
// 'tolerance' must be non-negative
// 'hasZero' will be set true if any element of the array is zero, false otherwise.
//
// The return value is true if 'value' is a supported decimal array type, false otherwise.
//
template <typename T>
bool checkSignedArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero)
{
static_assert(std::is_signed<T>::value || pxr::GfIsFloatingPoint<T>::value, "Signed integer or decimal type required.");
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[]>())
{
hasZero = std::any_of(array->begin(), array->end(), [tolerance](auto element){ return (std::abs(element) <= tolerance); });
return true;
}
return false;
}
// Check whether a scalar array attribute contains at least one element with a value of zero
// (i.e. its value lies within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'hasZero' will be set true if any element of the array is zero, false otherwise.
//
// The return value is true if 'value' is a supported scalar array type, false otherwise.
//
bool checkScalarArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eBool: return checkBoolArrayForZeroes(value, hasZero);
case BaseDataType::eDouble: return checkSignedArrayForZeroes<double>(value, tolerance, hasZero);
case BaseDataType::eFloat: return checkSignedArrayForZeroes<float>(value, tolerance, hasZero);
case BaseDataType::eHalf: return checkSignedArrayForZeroes<pxr::GfHalf>(value, tolerance, hasZero);
case BaseDataType::eInt: return checkSignedArrayForZeroes<int32_t>(value, tolerance, hasZero);
case BaseDataType::eInt64: return checkSignedArrayForZeroes<int64_t>(value, tolerance, hasZero);
case BaseDataType::eUChar: return checkUnsignedArrayForZeroes<unsigned char>(value, tolerance, hasZero);
case BaseDataType::eUInt: return checkUnsignedArrayForZeroes<uint32_t>(value, tolerance, hasZero);
case BaseDataType::eUInt64: return checkUnsignedArrayForZeroes<uint64_t>(value, tolerance, hasZero);
default: break;
}
return false;
}
// Returns true if all components of the tuple are zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - base type of the tuple (e.g. float if tuple is float[2]).
// N - number of components in the tuple (e.g. '2' in the example above).
//
// 'tolerance' must be non-negative
//
template <typename T, int N>
bool isTupleZero(const T tuple[N], double tolerance)
{
CARB_ASSERT(tolerance >= 0.0);
for (int i = 0; i < N; ++i)
{
if (std::abs(tuple[i]) > tolerance) return false;
}
return true;
}
// Check whether a tuple array attribute contains at least one element which is zero
// (i.e. all of their components are within 'tolerance' of 0).
//
// T - type of the components of the tuple. Must be a decimal type.
// N - number of components in the tuple
//
// 'tolerance' must be non-negative
// 'hasZero' will be set true if any tuple in the array is zero, false otherwise.
//
// The return value is true if 'value' is a supported decimal tuple array type, false otherwise.
//
template <typename T, int N>
bool checkTupleArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, double tolerance, bool& hasZero)
{
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[][N]>())
{
hasZero = std::any_of(array->begin(), array->end(), [tolerance](auto element){ return isTupleZero<T, N>(element, tolerance); });
return true;
}
return false;
}
// Check whether a tuple array attribute contains at least one element which is zero
// (i.e. all of their components are within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'hasZero' will be set true if any tuple in the array is zero, false otherwise.
//
// The return value is true if 'value' is a supported decimal tuple array type, false otherwise.
//
bool checkTupleArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eDouble:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<double, 2>(value, tolerance, hasZero);
case 3: return checkTupleArrayForZeroes<double, 3>(value, tolerance, hasZero);
case 4: return checkTupleArrayForZeroes<double, 4>(value, tolerance, hasZero);
case 9: return checkTupleArrayForZeroes<double, 9>(value, tolerance, hasZero);
case 16: return checkTupleArrayForZeroes<double, 16>(value, tolerance, hasZero);
}
break;
case BaseDataType::eFloat:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<float, 2>(value, tolerance, hasZero);
case 3: return checkTupleArrayForZeroes<float, 3>(value, tolerance, hasZero);
case 4: return checkTupleArrayForZeroes<float, 4>(value, tolerance, hasZero);
}
break;
case BaseDataType::eHalf:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<pxr::GfHalf, 2>(value, tolerance, hasZero);
case 3: return checkTupleArrayForZeroes<pxr::GfHalf, 3>(value, tolerance, hasZero);
case 4: return checkTupleArrayForZeroes<pxr::GfHalf, 4>(value, tolerance, hasZero);
}
break;
case BaseDataType::eInt:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<int32_t, 2>(value, tolerance, hasZero);
case 3: return checkTupleArrayForZeroes<int32_t, 3>(value, tolerance, hasZero);
case 4: return checkTupleArrayForZeroes<int32_t, 4>(value, tolerance, hasZero);
}
break;
default: break;
}
return false;
}
} // namespace
class OgnAnyZero
{
public:
static bool compute(OgnAnyZeroDatabase& db)
{
const auto& value = db.inputs.value();
if (!value.resolved())
return true;
const auto& tolerance = db.inputs.tolerance();
auto& result = db.outputs.result();
try
{
// Some of the functions below return as soon as they find a zero value, so
// we start out assuming there are no zeroes and let them change that to true.
//
result = false;
bool foundType{ false };
// Arrays
if (value.type().arrayDepth > 0)
{
// Arrays of tuples.
if (value.type().componentCount > 1)
{
foundType = checkTupleArrayForZeroes(value, tolerance, result);
}
else
{
// Arrays of scalars.
foundType = checkScalarArrayForZeroes(value, tolerance, result);
}
}
// Tuples
else if (value.type().componentCount > 1)
{
foundType = checkTupleForZeroes(value, tolerance, result);
}
else
{
// Scalars
foundType = checkScalarForZero(value, tolerance, result);
}
if (! foundType)
{
throw ogn::compute::InputError(kValueTypeUnresolved);
}
}
catch (ogn::compute::InputError &error)
{
db.logError("OgnAnyZero: %s", error.what());
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/math/OgnNoise.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.
//
// This node implements the noise() function from Warp. Once Warp has been released
// it will be reimplemented using Warp.
//
// If you're interested in how to use the output from this node to drive a procedural
// noise texture, take a look at the core_definitions::perlin_noise_texture from the material library,
// documented here:
//
// https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_material-graph/nodes/Texturing_High_Level/perlin-noise.html
//
// Its MDL implementation can be found in the omni-core-materials repo, in mdl/nvidia/core_definitions.mdl
// That in turn calls base::perlin_noise_texture() which is implemented in the MDL-SDK repo, in src/shaders/mdl/base/base.mdl
//
#include <OgnNoiseDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include "warp_noise.h"
namespace omni {
namespace graph {
namespace nodes {
namespace {
template <typename T, typename PXRTYPE>
bool getNoiseValues(uint32_t &rng_state, const OgnNoiseAttributes::inputs::position_t& position, ogn::array<float> &resultArray)
{
if (auto positionArray = position.get<T>())
{
resultArray.resize(positionArray.size());
size_t i = 0;
for (auto pos : *positionArray)
{
resultArray[i++] = noise(rng_state, *(const PXRTYPE*)pos);
}
return true;
}
return false;
}
// Specialization for non-tuple type.
template <>
bool getNoiseValues<float[],float>(uint32_t &rng_state, const OgnNoiseAttributes::inputs::position_t& position, ogn::array<float> &resultArray)
{
if (auto positionArray = position.get<float[]>())
{
resultArray.resize(positionArray.size());
size_t i = 0;
for (auto pos : *positionArray)
{
resultArray[i++] = noise(rng_state, pos);
}
return true;
}
return false;
}
}
class OgnNoise
{
public:
static bool compute(OgnNoiseDatabase& db)
{
const auto& position = db.inputs.position();
// If we don't have any positions to sample then there's nothing to do.
if (!position.resolved())
return true;
auto& result = db.outputs.result();
const auto& seed = db.inputs.seed();
uint32_t rng_state = rand_init(seed);
try
{
if (position.type().arrayDepth == 0)
{
if (auto resultScalar = result.get<float>())
{
switch (position.type().componentCount)
{
case 1:
{
*resultScalar = noise(rng_state, *position.get<float>());
return true;
}
case 2:
{
*resultScalar = noise(rng_state, *(GfVec2f*)(*position.get<float[2]>()));
return true;
}
case 3:
{
*resultScalar = noise(rng_state, *(GfVec3f*)(*position.get<float[3]>()));
return true;
}
case 4:
{
*resultScalar = noise(rng_state, *(GfVec4f*)(*position.get<float[4]>()));
return true;
}
default:
db.logError("'position' has invalid tuple size of %i.", position.type().componentCount);
}
}
else
{
throw ogn::compute::InputError("'result' is an array but 'position' is not");
}
}
else if (auto resultArray = result.get<float[]>())
{
switch (position.type().componentCount)
{
case 1:
{
if (getNoiseValues<float[], float>(rng_state, position, *resultArray)) return true;
throw ogn::compute::InputError("could not resolve 'position' to float[]");
}
case 2:
{
if (getNoiseValues<float[][2], GfVec2f>(rng_state, position, *resultArray)) return true;
throw ogn::compute::InputError("could not resolve 'position' to float[2][]");
}
case 3:
{
if (getNoiseValues<float[][3], GfVec3f>(rng_state, position, *resultArray)) return true;
throw ogn::compute::InputError("could not resolve 'position' to float[3][]");
}
case 4:
{
if (getNoiseValues<float[][4], GfVec4f>(rng_state, position, *resultArray)) return true;
throw ogn::compute::InputError("could not resolve 'position' to float[4][]");
}
default:
db.logError("'position' has invalid tuple size of %i.", position.type().componentCount);
}
}
else
{
throw ogn::compute::InputError("'position' is an array but 'result' is not");
}
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto position = node.iNode->getAttributeByToken(node, inputs::position.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto positionType = position.iAttribute->getResolvedType(position);
if (positionType.baseType != BaseDataType::eUnknown)
{
// 'result' is always float but has the same array depth as 'position'.
Type type(BaseDataType::eFloat, 1, positionType.arrayDepth, AttributeRole::eNone);
result.iAttribute->setResolvedType(result, type);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnTrig.ogn | {
"Trig": {
"version": 1,
"description": [
"Trigonometric operation of one input in degrees.",
"Supported operations are:\n",
"SIN, COS, TAN, ARCSIN, ARCCOS, ARCTAN, DEGREES, RADIANS"
],
"uiName": "Trigonometric Operation",
"categories": ["math:operator", "math:conversion"],
"scheduling": ["threadsafe"],
"metadata": {"hidden": "true"},
"inputs": {
"a": {
"type": ["decimal_scalers"],
"description": "Input to the function"
},
"operation": {
"type": "token",
"description": "The operation to perform",
"uiName": "Operation",
"default": "SIN",
"metadata": {
"allowedTokens": ["SIN","COS","TAN","ARCSIN","ARCCOS", "ARCTAN", "DEGREES","RADIANS"]
}
}
},
"outputs": {
"result": {
"type": ["decimal_scalers"],
"description": "The result of the function",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:a": {"type": "float", "value": 120.0}, "inputs:operation": "COS",
"outputs:result": {"type": "float", "value": -0.5}
},
{
"inputs:a": {"type": "double", "value": -57.2958}, "inputs:operation": "RADIANS",
"outputs:result": {"type": "double", "value": -1.0}
},
{
"inputs:a": {"type": "double", "value": -1.0}, "inputs:operation": "ARCCOS",
"outputs:result": {"type": "double", "value": 180.0}
},
{
"inputs:a": {"type": "float", "value": 45.0}, "inputs:operation": "SIN",
"outputs:result": {"type": "float", "value": 0.707107}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCeil.ogn | {
"Ceil": {
"version": 1,
"description": [
"Computes the ceil of the given decimal number a, which is the smallest integral value greater than a"
],
"uiName": "Ceiling",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"a": {
"type": ["decimals"],
"description": "The decimal number",
"uiName": "A"
}
},
"outputs": {
"result": {
"type": ["int", "integral_tuples", "int[]", "int[2][]", "int[3][]", "int[4][]"],
"description": "The ceil of the input a",
"uiName": "Result"
}
},
"tests" : [
{
"inputs:a": {"type": "float", "value": 4.1}, "outputs:result": 5
},
{
"inputs:a": {"type": "half", "value": -4.9}, "outputs:result": -4
},
{
"inputs:a": {"type": "double[3]", "value": [1.3, 2.4, -3.7]}, "outputs:result": [2, 3, -3]
},
{
"inputs:a": {"type": "double[]", "value": [1.3, 2.4, -3.7, 4.5]}, "outputs:result": [2, 3, -3, 5]
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMagnitude.ogn | {
"Magnitude": {
"version": 1,
"description": [
"Compute the magnitude of a vector, array of vectors, or a scalar",
"If a scalar is passed in, the absolute value will be returned",
"If an array of vectors are passed in, the output will be an array of corresponding magnitudes"
],
"uiName": "Magnitude",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"tags": ["absolute"],
"inputs": {
"input": {
"type": ["decimals", "integrals"],
"description": "The vector(s) or scalar to take the magnitude of"
}
},
"outputs": {
"magnitude": {
"type": ["decimals", "integrals"],
"description": "The resulting magnitude(s)"
}
},
"tests": [
{
"inputs:input": {"type": "double", "value": -10.0},
"outputs:magnitude": {"type": "double", "value": 10.0}
},
{
"inputs:input": {"type": "float", "value": -10.0},
"outputs:magnitude": {"type": "float", "value": 10.0}
},
{
"inputs:input": {"type": "half", "value": -10.0},
"outputs:magnitude": {"type": "half", "value": 10.0}
},
{
"inputs:input": {"type": "int", "value": -10},
"outputs:magnitude": {"type": "int", "value": 10}
},
{
"inputs:input": {"type": "int64", "value": -10},
"outputs:magnitude": {"type": "int64", "value": 10}
},
{
"inputs:input": {"type": "uchar", "value": 10},
"outputs:magnitude": {"type": "uchar", "value": 10}
},
{
"inputs:input": {"type": "uint", "value": 10},
"outputs:magnitude": {"type": "uint", "value": 10}
},
{
"inputs:input": {"type": "uint64", "value": 10},
"outputs:magnitude": {"type": "uint64", "value": 10}
},
{
"inputs:input": {"type": "int[2]", "value": [3, -4]},
"outputs:magnitude": {"type": "double", "value": 5.0}
},
{
"inputs:input": {"type": "double[3]", "value": [1.0, 2.0, 2.0]},
"outputs:magnitude": {"type": "double", "value": 3.0}
},
{
"inputs:input": {"type": "float[4]", "value": [-2.0, 2.0, -2.0, 2.0]},
"outputs:magnitude": {"type": "float", "value": 4.0}
},
{
"inputs:input": {"type": "half[2]", "value": [3.0, -4.0]},
"outputs:magnitude": {"type": "half", "value": 5.0}
},
{
"inputs:input": {"type": "double[]", "value": [1.0, 2.0, 2.0]},
"outputs:magnitude": {"type": "double[]", "value": [1.0, 2.0, 2.0]}
},
{
"inputs:input": {"type": "float[]", "value": [-2.0, 2.0, -2.0, 2.0]},
"outputs:magnitude": {"type": "float[]", "value": [2.0, 2.0, 2.0, 2.0]}
},
{
"inputs:input": {"type": "half[]", "value": [3.0, -4.0]},
"outputs:magnitude": {"type": "half[]", "value": [3.0, 4.0]}
},
{
"inputs:input": {"type": "int[]", "value": [3, -4]},
"outputs:magnitude": {"type": "int[]", "value": [3, 4]}
},
{
"inputs:input": {"type": "int64[]", "value": [3, -4]},
"outputs:magnitude": {"type": "int64[]", "value": [3, 4]}
},
{
"inputs:input": {"type": "uchar[]", "value": [3, 4]},
"outputs:magnitude": {"type": "uchar[]", "value": [3, 4]}
},
{
"inputs:input": {"type": "uint[]", "value": [3, 4]},
"outputs:magnitude": {"type": "uint[]", "value": [3, 4]}
},
{
"inputs:input": {"type": "uint64[]", "value": [3, 4]},
"outputs:magnitude": {"type": "uint64[]", "value": [3, 4]}
},
{
"inputs:input": {"type": "int[3][]", "value": [[1, 2, 2], [4, 2, 6], [3, 2, 4], [1, -4, 2]]},
"outputs:magnitude": {"type": "double[]", "value": [3.0, 7.483314773547883, 5.385164807134504, 4.58257569495584]}
},
{
"inputs:input": {"type": "double[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, -4.0, 2.0]]},
"outputs:magnitude": {"type": "double[]", "value": [3.0, 7.483314773547883, 5.385164807134504, 4.58257569495584]}
},
{
"inputs:input": {"type": "float[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, -4.0, 2.0]]},
"outputs:magnitude": {"type": "float[]", "value": [3.0, 7.483315, 5.3851647, 4.582576]}
},
{
"inputs:input": {"type": "half[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, -4.0, 2.0]]},
"outputs:magnitude": {"type": "half[]", "value": [3.0, 7.484375, 5.3867188, 4.5820312]}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnPartialSum.ogn | {
"PartialSum": {
"description": ["Compute the partial sums of the input integer array named 'array' and put the result in ",
"an output integer array named 'partialSum'. A partial sum is the sum of all of the elements ",
"up to but not including a certain point in an array, so output element 0 is always 0, ",
"element 1 is array[0], element 2 is array[0] + array[1], etc."
],
"metadata" : {
"uiName": "Compute Integer Array Partial Sums"
},
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"array": {
"description": "List of integers whose partial sum is to be computed",
"type": "int[]",
"default": []
}
},
"outputs": {
"partialSum": {
"description": "Array whose nth value equals the nth partial sum of the input 'array'",
"type": "int[]",
"default": []
}
},
"tests": [
{ "inputs:array": [1, 2, 3, 4, 5], "outputs:partialSum": [0, 1, 3, 6, 10, 15] }
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/io/OgnReadKeyboardState.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 <OgnReadKeyboardStateDatabase.h>
#include <carb/input/IInput.h>
#include <carb/input/InputTypes.h>
#include <omni/kit/IAppWindow.h>
using namespace carb::input;
namespace omni {
namespace graph {
namespace action {
// This list matches carb::input::KeyboardInput
constexpr size_t s_numNames = size_t(carb::input::KeyboardInput::eCount);
static constexpr std::array<const char*, s_numNames> s_keyNames = {
"Unknown",
"Space",
"Apostrophe",
"Comma",
"Minus",
"Period",
"Slash",
"Key0",
"Key1",
"Key2",
"Key3",
"Key4",
"Key5",
"Key6",
"Key7",
"Key8",
"Key9",
"Semicolon",
"Equal",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"LeftBracket",
"Backslash",
"RightBracket",
"GraveAccent",
"Escape",
"Tab",
"Enter",
"Backspace",
"Insert",
"Del",
"Right",
"Left",
"Down",
"Up",
"PageUp",
"PageDown",
"Home",
"End",
"CapsLock",
"ScrollLock",
"NumLock",
"PrintScreen",
"Pause",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"Numpad0",
"Numpad1",
"Numpad2",
"Numpad3",
"Numpad4",
"Numpad5",
"Numpad6",
"Numpad7",
"Numpad8",
"Numpad9",
"NumpadDel",
"NumpadDivide",
"NumpadMultiply",
"NumpadSubtract",
"NumpadAdd",
"NumpadEnter",
"NumpadEqual",
"LeftShift",
"LeftControl",
"LeftAlt",
"LeftSuper",
"RightShift",
"RightControl",
"RightAlt",
"RightSuper",
"Menu"
};
static_assert(s_keyNames.size() == size_t(carb::input::KeyboardInput::eCount), "enum must match this table");
static std::array<NameToken, s_numNames> s_keyTokens;
class OgnReadKeyboardState
{
public:
static bool compute(OgnReadKeyboardStateDatabase& db)
{
static NameToken const emptyToken = db.stringToToken("");
NameToken const& keyIn = db.inputs.key();
auto contextObj = db.abi_context();
// First time look up all the token string values
static bool callOnce = ([&contextObj] {
std::transform(s_keyNames.begin(), s_keyNames.end(), s_keyTokens.begin(),
[&contextObj](auto const& s) { return contextObj.iToken->getHandle(s); });
} (), true);
omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow();
if (!appWindow)
{
return false;
}
Keyboard* keyboard = appWindow->getKeyboard();
if (!keyboard)
{
CARB_LOG_ERROR_ONCE("No Keyboard!");
return false;
}
IInput* input = carb::getCachedInterface<IInput>();
if (!input)
{
CARB_LOG_ERROR_ONCE("No Input!");
return false;
}
bool isPressed = false;
// Get the index of the token of the key of interest
auto iter = std::find(s_keyTokens.begin(), s_keyTokens.end(), keyIn);
if (iter != s_keyTokens.end())
{
size_t index = iter - s_keyTokens.begin();
KeyboardInput key = KeyboardInput(index);
isPressed = (carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, key));
}
db.outputs.shiftOut() =
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftShift)) ||
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eRightShift));
db.outputs.ctrlOut() =
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftControl)) ||
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eRightControl));
db.outputs.altOut() =
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftAlt)) ||
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eRightAlt));
db.outputs.isPressed() = isPressed;
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/io/OgnReadKeyboardState.ogn | {
"ReadKeyboardState": {
"description": "Reads the current state of the keyboard",
"version": 1,
"uiName": "Read Keyboard State",
"categories": ["input:keyboard"],
"scheduling": ["threadsafe"],
"inputs": {
"key": {
"type": "token",
"description": "The key to check the state of",
"uiName": "Key",
"default": "A",
"metadata": {
"displayGroup": "parameters",
"allowedTokens": [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"Apostrophe",
"Backslash",
"Backspace",
"CapsLock",
"Comma",
"Del",
"Down",
"End",
"Enter",
"Equal",
"Escape",
"F1",
"F10",
"F11",
"F12",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"GraveAccent",
"Home",
"Insert",
"Key0",
"Key1",
"Key2",
"Key3",
"Key4",
"Key5",
"Key6",
"Key7",
"Key8",
"Key9",
"Left",
"LeftAlt",
"LeftBracket",
"LeftControl",
"LeftShift",
"LeftSuper",
"Menu",
"Minus",
"NumLock",
"Numpad0",
"Numpad1",
"Numpad2",
"Numpad3",
"Numpad4",
"Numpad5",
"Numpad6",
"Numpad7",
"Numpad8",
"Numpad9",
"NumpadAdd",
"NumpadDel",
"NumpadDivide",
"NumpadEnter",
"NumpadEqual",
"NumpadMultiply",
"NumpadSubtract",
"PageDown",
"PageUp",
"Pause",
"Period",
"PrintScreen",
"Right",
"RightAlt",
"RightBracket",
"RightControl",
"RightShift",
"RightSuper",
"ScrollLock",
"Semicolon",
"Slash",
"Space",
"Tab",
"Up"]
}
}
},
"outputs": {
"isPressed": {
"type": "bool",
"description": "True if the key is currently pressed, false otherwise"
},
"shiftOut": {
"type": "bool",
"description": "True if Shift is held",
"uiName": "Shift"
},
"altOut": {
"type": "bool",
"description": "True if Alt is held",
"uiName": "Alt"
},
"ctrlOut": {
"type": "bool",
"description": "True if Ctrl is held",
"uiName": "Ctrl"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/io/OgnReadGamepadState.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 <OgnReadGamepadStateDatabase.h>
#include <carb/input/IInput.h>
#include <carb/input/InputTypes.h>
#include <omni/kit/IAppWindow.h>
using namespace carb::input;
namespace omni {
namespace graph {
namespace nodes {
// This is different from carb::input::GamepadInput::eCount by 4 because we combine the joystick inputs by axis (x/y)
constexpr size_t s_numNames = size_t(carb::input::GamepadInput::eCount) - 4;
static std::array<NameToken, s_numNames> s_elementTokens;
class OgnReadGamepadState
{
public:
static bool compute(OgnReadGamepadStateDatabase& db)
{
NameToken const& elementIn = db.inputs.gamepadElement();
const unsigned int gamepadId = db.inputs.gamepadId();
const float deadzone = db.inputs.deadzone();
// First time initialization of all the token values
static bool callOnce = ([&db] {
s_elementTokens = {
db.tokens.LeftStickXAxis,
db.tokens.LeftStickYAxis,
db.tokens.RightStickXAxis,
db.tokens.RightStickYAxis,
db.tokens.LeftTrigger,
db.tokens.RightTrigger,
db.tokens.FaceButtonBottom,
db.tokens.FaceButtonRight,
db.tokens.FaceButtonLeft,
db.tokens.FaceButtonTop,
db.tokens.LeftShoulder,
db.tokens.RightShoulder,
db.tokens.SpecialLeft,
db.tokens.SpecialRight,
db.tokens.LeftStickButton,
db.tokens.RightStickButton,
db.tokens.DpadUp,
db.tokens.DpadRight,
db.tokens.DpadDown,
db.tokens.DpadLeft
};
} (), true);
omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow();
if (!appWindow)
{
return false;
}
Gamepad* gamepad = appWindow->getGamepad(gamepadId);
if (!gamepad)
{
db.logWarning("No Gamepad!");
return false;
}
IInput* input = carb::getCachedInterface<IInput>();
if (!input)
{
db.logWarning("No Input!");
return false;
}
bool isPressed = false;
float value = 0.0;
// Get the index of the token of the element of interest
auto iter = std::find(s_elementTokens.begin(), s_elementTokens.end(), elementIn);
if (iter != s_elementTokens.end())
{
size_t index = iter - s_elementTokens.begin();
if (index < 4)
{
// We want to combine the joystick inputs by its axis (x/y instead of right/left/up/down)
GamepadInput positiveElement = GamepadInput(2*index);
GamepadInput negativeElement = GamepadInput(2*index+1);
value = input->getGamepadValue(gamepad, positiveElement) - input->getGamepadValue(gamepad, negativeElement);
}
else
{
// index is offset by 4 because we combine the joystick x/y axis
GamepadInput element = GamepadInput(index + 4);
value = input->getGamepadValue(gamepad, element);
}
// Check for deadzone threshold
if (std::abs(value) < deadzone)
{
value = 0.0;
isPressed = false;
}
else
{
isPressed = true;
}
}
db.outputs.isPressed() = isPressed;
db.outputs.value() = value;
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/io/OgnReadGamepadState.ogn | {
"ReadGamepadState": {
"description": "Reads the current state of the gamepad",
"version": 1,
"uiName": "Read Gamepad State",
"categories": ["input:gamepad"],
"scheduling": ["threadsafe"],
"inputs": {
"gamepadId": {
"type": "uint",
"description": "Gamepad id number starting from 0",
"uiName": "Gamepad ID",
"default": 0
},
"gamepadElement": {
"type": "token",
"description": "The gamepad element to check the state of",
"uiName": "Element",
"default": "Left Stick X Axis",
"metadata": {
"displayGroup": "parameters",
"allowedTokens": {
"LeftStickXAxis": "Left Stick X Axis",
"LeftStickYAxis": "Left Stick Y Axis",
"RightStickXAxis": "Right Stick X Axis",
"RightStickYAxis": "Right Stick Y Axis",
"LeftTrigger": "Left Trigger",
"RightTrigger": "Right Trigger",
"FaceButtonBottom": "Face Button Bottom",
"FaceButtonRight": "Face Button Right",
"FaceButtonLeft": "Face Button Left",
"FaceButtonTop": "Face Button Top",
"LeftShoulder": "Left Shoulder",
"RightShoulder": "Right Shoulder",
"SpecialLeft": "Special Left",
"SpecialRight": "Special Right",
"LeftStickButton": "Left Stick Button",
"RightStickButton": "Right Stick Button",
"DpadUp": "D-Pad Up",
"DpadRight": "D-Pad Right",
"DpadDown": "D-Pad Down",
"DpadLeft": "D-Pad Left"
}
}
},
"deadzone": {
"type": "float",
"description": "Threshold from [0, 1] that the value must pass for it to be registered as input",
"uiName": "Deadzone",
"default": 0.1,
"minimum": 0.0,
"maximum": 1.0
}
},
"outputs": {
"isPressed": {
"type": "bool",
"description": "True if the gamepad element is currently pressed, false otherwise"
},
"value": {
"type": "float",
"description": "Value of how much the gamepad element is being pressed. [0, 1] for buttons [-1, 1] for stick and trigger"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Quaternion.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 <OgnSetMatrix4QuaternionDatabase.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/quat.h>
using omni::math::linalg::matrix4d;
using omni::math::linalg::quatd;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
void updateMatrix(const double input[16], double result[16], const double quaternion[4])
{
matrix4d& resultMat = *reinterpret_cast<matrix4d*>(result);
memcpy(resultMat.data(), input, sizeof(double) * 16);
resultMat.SetRotateOnly(quatd(quaternion[3], quaternion[0], quaternion[1], quaternion[2]));
}
}
class OgnSetMatrix4Quaternion
{
public:
static bool compute(OgnSetMatrix4QuaternionDatabase& db)
{
const auto& matrixInput = db.inputs.matrix();
const auto& quaternionInput = db.inputs.quaternion();
auto matrixOutput = db.outputs.matrix();
bool failed = true;
// Singular case
if (auto matrix = matrixInput.get<double[16]>())
{
if (auto quaternion = quaternionInput.get<double[4]>())
{
if (auto output = matrixOutput.get<double[16]>())
{
updateMatrix(*matrix, *output, *quaternion);
failed = false;
}
}
}
// Array case
else if (auto matrices = matrixInput.get<double[][16]>())
{
if (auto quaternions = quaternionInput.get<double[][4]>())
{
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], (*quaternions)[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, quaternion input with depth %s, and output with depth %s",
matrixInput.type().arrayDepth, quaternionInput.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, OgnSetMatrix4QuaternionAttributes::inputs::matrix.m_name),
node.iNode->getAttribute(node, OgnSetMatrix4QuaternionAttributes::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/OgnRotateToTarget.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 <OgnRotateToTargetDatabase.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 <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;
using namespace omni::fabric;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
constexpr double kUninitializedStartTime = -1.;
}
class OgnRotateToTarget
{
XformUtils::MoveState m_moveState;
public:
static bool compute(OgnRotateToTargetDatabase& 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<OgnRotateToTarget>();
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;
XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode;
if (db.inputs.stop() != kExecutionAttributeStateDisabled)
{
startTime = 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;
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());
if (startTime <= kUninitializedStartTime || now < startTime)
{
std::tie(startOrientation, targetAttribName) =
XformUtils::extractPrimOrientOp(contextObj, sourcePrimPath);
if (targetAttribName.IsEmpty())
{
if (hasRotations)
throw std::runtime_error(
"RotateToTarget 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()));
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)
{
const quatd& targetOrientation = extractRotationQuatd(destLocalTransform).GetNormalized();
quatd quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized();
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);
}
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/OgnTransformVector.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 <OgnTransformVectorDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/vec.h>
using omni::math::linalg::matrix4d;
using omni::math::linalg::matrix3d;
using omni::math::linalg::vec3;
using ogn::compute::tryComputeWithArrayBroadcasting;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeWithMatrix3(OgnTransformVectorDatabase& db)
{
auto functor = [&](auto& matrix, auto& vector, auto& result)
{
auto& transformMat = *reinterpret_cast<const matrix3d*>(matrix);
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 * transformMat);
};
return tryComputeWithArrayBroadcasting<double[9], T[3], T[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor);
}
template<typename T>
bool tryComputeWithMatrix4(OgnTransformVectorDatabase& db)
{
auto functor = [&](auto& matrix, auto& vector, auto& result)
{
auto& transformMat = *reinterpret_cast<const matrix4d*>(matrix);
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<T>*>(result);
resultVec = vec3<T>(transformMat.Transform(sourceVec));
};
return tryComputeWithArrayBroadcasting<double[16], T[3], T[3]>(db.inputs.matrix(), 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>(OgnTransformVectorDatabase& db)
{
auto functor = [&](auto& matrix, auto& vector, auto& result)
{
auto& transformMat = *reinterpret_cast<const matrix3d*>(matrix);
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 * transformMat));
};
return tryComputeWithArrayBroadcasting<double[9], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor);
}
template<>
bool tryComputeWithMatrix4<pxr::GfHalf>(OgnTransformVectorDatabase& db)
{
auto functor = [&](auto& matrix, auto& vector, auto& result)
{
auto& transformMat = *reinterpret_cast<const matrix4d*>(matrix);
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>(transformMat.Transform(sourceVec)));
};
return tryComputeWithArrayBroadcasting<double[16], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor);
}
} // namespace
class OgnTransformVector
{
public:
static bool compute(OgnTransformVectorDatabase& 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;
else
{
db.logWarning("OgnTransformVector: Failed to resolve input types");
}
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnTransformVector: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto vector = node.iNode->getAttributeByToken(node, inputs::vector.token());
auto matrix = node.iNode->getAttributeByToken(node, inputs::matrix.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto vectorType = vector.iAttribute->getResolvedType(vector);
auto matrixType = matrix.iAttribute->getResolvedType(matrix);
// Require vector, matrix to be resolved before determining result's type
if (vectorType.baseType != BaseDataType::eUnknown && matrixType.baseType != BaseDataType::eUnknown)
{
Type resultType(vectorType.baseType, vectorType.componentCount, std::max(vectorType.arrayDepth, matrixType.arrayDepth), vectorType.role);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
}
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTranslateToLocation.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 <OgnTranslateToLocationDatabase.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 TranslateMoveState : public XformUtils::MoveState
{
vec3d targetTranslate;
};
class OgnTranslateToLocation
{
TranslateMoveState m_moveState;
public:
static bool compute(OgnTranslateToLocationDatabase& 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<OgnTranslateToLocation>();
double& startTime = state.m_moveState.startTime;
vec3d& startTranslation = state.m_moveState.startTranslation;
vec3d& targetTranslation = state.m_moveState.targetTranslate;
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
{
startTranslation = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr);
}
catch (std::runtime_error const& error)
{
db.logError(error.what());
return false;
}
startTime = now;
targetTranslation = 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 translation = GfLerp(alpha2, startTranslation, targetTranslation);
// Write back to the prim
try
{
trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr, translation);
}
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/OgnGetPrimDirectionVector.ogn | {
"GetPrimDirectionVector": {
"version": 2,
"description": [
"Given a prim, find its direction vectors (up vector, forward vector, right vector, etc.)"
],
"uiName": "Get Prim Direction Vector",
"scheduling": ["usd-read", "threadsafe"],
"categories": ["sceneGraph"],
"inputs": {
"primPath": {
"type": "token",
"description": "The path of the input prim - this attribute is used when 'usePath' is true",
"deprecated": "Use prim input with a GetPrimsAtPath node instead"
},
"usePath": {
"type": "bool",
"default": true,
"description": "When true, it will use the 'primPath' attribute as the path to the prim, otherwise it will read the connection at the 'prim' attribute",
"deprecated": "Use prim input with a GetPrimsAtPath node instead"
},
"prim": {
"type": "target",
"description": "The connection to the input prim - this attribute is used when 'usePath' is false",
"optional": true
}
},
"outputs": {
"upVector": {
"type": "double[3]",
"description": "The up vector of the prim",
"uiName": "Up Vector"
},
"downVector": {
"type": "double[3]",
"description": "The down vector of the prim",
"uiName": "Down Vector"
},
"forwardVector": {
"type": "double[3]",
"description": "The forward vector of the prim",
"uiName": "Forward Vector"
},
"backwardVector": {
"type": "double[3]",
"description": "The backward vector of the prim",
"uiName": "Backward Vector"
},
"rightVector": {
"type": "double[3]",
"description": "The right vector of the prim",
"uiName": "Right Vector"
},
"leftVector": {
"type": "double[3]",
"description": "The left vector of the prim",
"uiName": "Left Vector"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTransformVector.ogn | {
"TransformVector": {
"version": 1,
"description": [
"Applies a transformation matrix to a row vector, returning the result. returns vector * matrix",
"If the vector is one dimension smaller than the matrix (eg a 4x4 matrix and a 3d vector), ",
"The last component of the vector will be treated as a 1. The result is then projected back to a 3-vector. ",
"Supports mixed array inputs, eg a single matrix and an array of vectors."
],
"uiName": "Transform Vector",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"matrix" : {
"type": ["matrixd[4]", "matrixd[4][]", "matrixd[3]", "matrixd[3][]"],
"uiName": "Matrix",
"description": "The transformation matrix 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 translated"
}
},
"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": {
"matrix": {"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":[81, 32, 3]}
},
{
"inputs": {
"matrix": {"type":"matrixd[4][]", "value":[
[1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1],
[1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]]
},
"vector": {"type": "vectorf[3][]", "value": [[1, 2, 3], [1, 2, 3]]}},
"outputs:result": {"type":"vectorf[3][]", "value" : [[81, 32, 3], [81, 32, 3]]}
},
{
"inputs": {
"matrix": {"type":"matrixd[4]", "value":[1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]},
"vector": {"type": "vectorf[3][]", "value": [[1, 2, 3], [1, 2, 3]]}},
"outputs:result": {"type":"vectorf[3][]", "value" : [[81, 32, 3], [81, 32, 3]]}
},
{
"inputs": {
"matrix": {"type":"matrixd[4][]", "value":[
[1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1],
[1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]]
},
"vector": {"type": "vectorf[3]", "value": [1, 2, 3]}},
"outputs:result": {"type":"vectorf[3][]", "value" : [[81, 32, 3], [81, 32, 3]]}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTranslateToTarget.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 <OgnTranslateToTargetDatabase.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 <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
{
namespace
{
constexpr double kUninitializedStartTime = -1.;
}
class OgnTranslateToTarget
{
XformUtils::MoveState m_moveState;
public:
static bool compute(OgnTranslateToTargetDatabase& 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<OgnTranslateToTarget>();
double& startTime = state.m_moveState.startTime;
vec3d& startTranslation = state.m_moveState.startTranslation;
if (db.inputs.stop() != kExecutionAttributeStateDisabled)
{
startTime = 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;
// First frame of the maneuver.
if (startTime <= kUninitializedStartTime || now < startTime)
{
try
{
startTranslation =
tryGetPrimVec3dAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr);
}
catch (std::runtime_error const& error)
{
db.logError(error.what());
return false;
}
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()));
pxr::UsdPrim sourcePrim = getPrim(contextObj, sourcePrimPath);
pxr::UsdPrim targetPrim = getPrim(contextObj, destPrimPath);
pxr::UsdGeomXformCache xformCache;
// Convert dest prim transform to the source's parent frame
matrix4d destWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(targetPrim));
matrix4d sourceParentTransform = safeCastToOmni(xformCache.GetParentToWorldTransform(sourcePrim));
matrix4d destLocalTransform = destWorldTransform / sourceParentTransform;
const vec3d& targetTranslation = destLocalTransform.ExtractTranslation();
// 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 translation = GfLerp(alpha2, startTranslation, targetTranslation);
// Write back to the prim
try
{
trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr, translation);
}
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 true;
}
}
};
REGISTER_OGN_NODE()
} // action
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTranslateToLocation.ogn | {
"TranslateToLocation": {
"version": 2,
"description": [
"Perform a smooth translation maneuver, translating a prim to a desired point given a speed and easing factor"
],
"uiName": "Translate To Location",
"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 translated",
"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 position"
},
"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/OgnGetMatrix4Translation.ogn | {
"GetMatrix4Translation": {
"version": 1,
"description": [
"Gets the translation of the given matrix4d value which represents a linear transformation.",
"Returns a vector3"
],
"uiName": "Get Translation",
"categories": ["math:operator"],
"scheduling": ["threadsafe"],
"inputs": {
"matrix" : {
"type": ["matrixd[4]", "matrixd[4][]"],
"description": "The matrix to be modified"
}
},
"outputs": {
"translation": {
"type": ["vectord[3]", "vectord[3][]"],
"uiName": "Translation",
"description": [
"The translation from the transformation 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]},
"outputs:translation": {"type": "vectord[3]", "value":[50,0,0]}
},
{
"inputs": {
"matrix": {"type":"matrixd[4][]", "value":[
[1.0,0,3,0, 0,1,0,1, 0,0,1,0, 50,0,0,1],
[1.0,0,0,3, 0,1,0,1, 0,0,1,0, 1,100,4,1]]
}
},
"outputs:translation": {"type":"vectord[3][]", "value":
[[50,0,0],
[1,100,4]]
}
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateToOrientation.ogn | {
"RotateToOrientation": {
"version": 2,
"description": [
"Perform a smooth rotation maneuver, rotating a prim to a desired orientation given a speed and easing factor"
],
"uiName": "Rotate To Orientation",
"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 rotated",
"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 orientation as euler angles (XYZ) in local space",
"uiName": "Target Orientation"
},
"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/OgnMoveToTransform.ogn | {
"MoveToTransform": {
"version": 2,
"description": [
"Perform a transformation maneuver, moving a prim to a target transformation given a speed and easing factor.",
"Transformation, Rotation, and Scale from a 4x4 transformation matrix will be applied",
"Note: The Prim must have xform:orient in transform stack in order to interpolate rotations"
],
"uiName": "Move to Transform",
"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 transformed",
"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": "matrixd[4]",
"description": "The desired local transform",
"uiName": "Target Transform"
},
"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"
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.