file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/include/omni/graph/core/IBundle.gen.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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Provide read write access to recursive bundles.
//!
template <>
class omni::core::Generated<omni::graph::core::IBundle2_abi> : public omni::graph::core::IBundle2_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::IBundle2")
//! Return handle to this bundle. Invalid handle is returned if this bundle is invalid.
omni::graph::core::BundleHandle getHandle() noexcept;
//! Return parent of this bundle, or invalid handle if there is no parent.
omni::graph::core::BundleHandle getParentBundle() noexcept;
//! @brief Get read-write handles to all attributes in this bundle.
//!
//! @copydetails IConstBundle2_abi::getConstAttributes_abi
omni::core::Result getAttributes(omni::graph::core::AttributeDataHandle* const attributes,
size_t* const attributeCount) noexcept;
//! @brief Searches for read-write handles of the attribute in this bundle by using attribute names.
//!
//! @copydetails IConstBundle2_abi::getConstAttributesByName_abi
omni::core::Result getAttributesByName(const omni::graph::core::NameToken* const names,
size_t nameCount,
omni::graph::core::AttributeDataHandle* const attributes) noexcept;
//! @brief Get read write handles to all child bundles in this bundle.
//!
//! @copydetails IConstBundle2_abi::getConstChildBundles_abi
omni::core::Result getChildBundles(omni::graph::core::BundleHandle* const bundles, size_t* const bundleCount) noexcept;
//! @brief Get read write handle to child bundle by index.
//!
//! @copydetails IConstBundle2_abi::getConstChildBundle_abi
omni::core::Result getChildBundle(size_t bundleIndex, omni::graph::core::BundleHandle* const bundle) noexcept;
//! @brief Lookup for read write handles to child bundles under specified names.
//!
//! @copydetails IConstBundle2_abi::getConstChildBundlesByName_abi
omni::core::Result getChildBundlesByName(const omni::graph::core::NameToken* const names,
size_t nameCount,
omni::graph::core::BundleHandle* const foundBundles) noexcept;
//! @brief Create new attributes by copying existing.
//!
//! Source attribute handles' data and metadata are copied. If a handle is invalid,
//! then its source is ignored.
//! Created attributes are owned by this bundle.
//!
//! @param newNames The names for the new attributes, if `nullptr` then names are taken from the source attributes.
//! @param sourceAttributes Handles to attributes whose data type is to be copied.
//! @param attributeCount Number of attributes to be copied.
//! @param overwrite An option to overwrite existing attributes.
//! @param copiedAttributes Output handles to the newly copied attributes. Can be `nullptr` if no output is
//! required.
//! @param copiedCount Number of successfully copied attributes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result copyAttributes(const omni::graph::core::NameToken* const newNames,
const omni::graph::core::ConstAttributeDataHandle* const sourceAttributes,
size_t attributeCount,
bool overwrite,
omni::graph::core::AttributeDataHandle* const copiedAttributes,
size_t* const copiedCount) noexcept;
//! @brief Create attributes based on provided names and types.
//!
//! Created attributes are owned by this bundle.
//!
//! @param names The names of the attributes.
//! @param types The types of the attributes.
//! @param elementCount Number of elements in the array, can be `nullptr` if attribute is not an array.
//! @param attributeCount Number of attributes to be created.
//! @param createdAttributes Output handles to the newly created attributes. Can be nullptr if no output is
//! required.
//! @param createdCount Number of successfully created attributes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result createAttributes(const omni::graph::core::NameToken* const names,
const omni::graph::core::Type* const types,
const size_t* const elementCount,
size_t attributeCount,
omni::graph::core::AttributeDataHandle* const createdAttributes,
size_t* const createdCount) noexcept;
//! @brief Use attribute handles as pattern to create new attributes.
//!
//! The name and type for new attributes are taken from pattern attributes, data and metadata is not copied.
//! If pattern handle is invalid, then attribute creation is skipped.
//! Created attributes are owned by this bundle.
//!
//! @param patternAttributes Attributes whose name and type is to be used to create new attributes.
//! @param patternCount Number of attributes to be created.
//! @param createdAttributes Output handles to the newly created attributes. Can be nullptr if no output is
//! required.
//! @param createdCount Number of successfully created attributes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result createAttributesLike(const omni::graph::core::ConstAttributeDataHandle* const patternAttributes,
size_t patternCount,
omni::graph::core::AttributeDataHandle* const createdAttributes,
size_t* const createdCount) noexcept;
//! @brief Create immediate child bundles under specified names in this bundle.
//!
//! Only immediate children are created. This method does not work recursively.
//! If name token is invalid, then child bundle creation is skipped.
//! Created bundles are owned by this bundle.
//!
//! @param names New children names in this bundle.
//! @param nameCount Number of bundles to be created.
//! @param createdBundles Output handles to the newly created bundles. Can be nullptr if no output is required.
//! @param createdCount Number of successfully created child bundles.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result createChildBundles(const omni::graph::core::NameToken* const names,
size_t nameCount,
omni::graph::core::BundleHandle* const createdBundles,
size_t* const createdCount) noexcept;
//! <b>Feature not implemented yet.</b>
//!
//! @brief Add a set of attributes to this bundle as links.
//!
//! Added attributes are links to other attributes that are part of another bundle.
//! If target handle is invalid, then linking is skipped.
//! The links are owned by this bundle, but targets of the links are not.
//! Removing links from this bundle does not destroy the data links point to.
//!
//! @param linkNames The names for new links.
//! @param targetAttributes Handles to attributes whose data is to be added.
//! @param attributeCount Number of attributes to be added.
//! @param linkedAttributes Output handles to linked attributes. Can be nullptr if no output is required.
//! @param linkedCount Number of attributes successfully linked.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result linkAttributes(const omni::graph::core::NameToken* const linkNames,
const omni::graph::core::ConstAttributeDataHandle* const targetAttributes,
size_t attributeCount,
omni::graph::core::AttributeDataHandle* const linkedAttributes,
size_t* const linkedCount) noexcept;
//! @brief Copy bundle data and metadata from the source bundle to this bundle.
//!
//! If source handle is invalid, then operation is skipped.
//!
//! @param sourceBundle Handle to bundle whose data is to be copied.
//! @param overwrite An option to overwrite existing content of the bundle.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result copyBundle(const omni::graph::core::ConstBundleHandle& sourceBundle, bool overwrite) noexcept;
//! @brief @brief Create new child bundles by copying existing.
//!
//! Source bundle handles' data and metadata are copied. If a handle is invalid,
//! then its source is ignored.
//! Created bundles are owned by this bundle.
//!
//! @param newNames Names for new children, if `nullptr` then names are taken from the source bundles.
//! @param sourceBundles Handles to bundles whose data is to be copied.
//! @param bundleCount Number of bundles to be copied.
//! @param overwrite An option to overwrite existing child bundles.
//! @param copiedBundles Output handles to the newly copied bundles. Can be `nullptr` if no output is required.
//! @param copiedCount Number of successfully copied child bundles.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result copyChildBundles(const omni::graph::core::NameToken* const newNames,
const omni::graph::core::ConstBundleHandle* const sourceBundles,
size_t bundleCount,
bool overwrite,
omni::graph::core::BundleHandle* const copiedBundles,
size_t* const copiedCount) noexcept;
//! <b>Feature not implemented yet.</b>
//!
//! @brief Link content from the source bundle to this bundle.
//!
//! If source handle is invalid, then operation is skipped.
//!
//! @param sourceBundle Handle to bundle whose data is to be linked.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result linkBundle(const omni::graph::core::ConstBundleHandle* const sourceBundle) noexcept;
//! @brief Add a set of bundles as children to this bundle as links.
//!
//! Created bundles are links to other bundles that are part of another bundle.
//! If target handle is invalid, then operation is skipped.
//! The links are owned by this bundle, but targets of the links are not.
//! Removing links from this bundle does not destroy the targets data.
//!
//! @param linkNames Names for new links.
//! @param targetBundles Handles to bundles whose data is to be added.
//! @param bundleCount Number of bundles to be added.
//! @param linkedBundles Handles to linked bundles. Can be nullptr if no output is required.
//! @param linkedCount Number of child bundles successfully linked.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result linkChildBundles(const omni::graph::core::NameToken* const linkNames,
const omni::graph::core::ConstBundleHandle* const targetBundles,
size_t bundleCount,
omni::graph::core::BundleHandle* const linkedBundles,
size_t* const linkedCount) noexcept;
//! @brief Remove attributes based on provided handles.
//!
//! Lookup the attribute handles and if they are part of this bundle then remove attributes' data and
//! metadata. Attribute handles that are not part of this bundle are ignored.
//!
//! @param attributes Handles to attributes whose data is to be removed
//! @param attributeCount Number of attributes to be removed.
//! @param removedCount Number of attributes successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeAttributes(const omni::graph::core::ConstAttributeDataHandle* const attributes,
size_t attributeCount,
size_t* const removedCount) noexcept;
//! @brief Remove attributes based on provided names.
//!
//! Lookup the attribute names and if they are part of this bundle then remove attributes' data and
//! metadata. Attribute names that are not part of this bundle are ignored.
//!
//! @param names The names of the attributes whose data is to be removed.
//! @param nameCount Number of attributes to be removed.
//! @param removedCount Number of attributes successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeAttributesByName(const omni::graph::core::NameToken* const names,
size_t nameCount,
size_t* const removedCount) noexcept;
//! @brief Remove child bundles based on provided handles.
//!
//! Lookup the bundle handles and if they are children of the bundle then remove them and their metadata.
//! Bundle handles that are not children of this bundle are ignored.
//! Only empty child bundles can be removed.
//!
//! @param childHandles Handles to bundles to be removed.
//! @param childCount Number of child bundles to be removed.
//! @param removedCount Number of child bundles successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeChildBundles(const omni::graph::core::ConstBundleHandle* const childHandles,
size_t childCount,
size_t* const removedCount) noexcept;
//! @brief Remove child bundles based on provided names.
//!
//! Lookup the bundle names and if the are children of the bundle then remove them and their metadata.
//! Bundle names that are not children of this bundle are ignored.
//! Only empty child bundles can be removed.
//!
//! @param names The names of the child bundles to be removed.
//! @param nameCount Number of child bundles to be removed.
//! @param removedCount Number of child bundles successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeChildBundlesByName(const omni::graph::core::NameToken* const names,
size_t nameCount,
size_t* const removedCount) noexcept;
//! Return Bundle Handle to Metadata Storage
omni::graph::core::BundleHandle getMetadataStorage() noexcept;
//! @brief Search for bundle metadata fields based on provided names.
//!
//! Invalid attribute handles are returned for not existing names.
//!
//! @param fieldNames Bundle metadata field names to be searched for.
//! @param fieldCount Size of fieldNames and bundleMetadata arrays.
//! @param bundleMetadata Handles to bundle metadata fields in this bundle.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result getBundleMetadataByName(const omni::graph::core::NameToken* const fieldNames,
size_t fieldCount,
omni::graph::core::AttributeDataHandle* const bundleMetadata) noexcept;
//! @brief Create bundle metadata fields in this bundle.
//!
//! @param fieldNames Names of new bundle metadata fields.
//! @param fieldTypes Types of new bundle metadata fields.
//! @param elementCount Number of elements in the array, can be `nullptr` if field is not an array.
//! @param fieldCount Size of fieldNames and fieldTypes arrays.
//! @param bundleMetadata Handles to the newly created bundle metadata fields. Can be `nullptr` if no output is
//! required.
//! @param createdCount Number of child bundles successfully created.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result createBundleMetadata(const omni::graph::core::NameToken* const fieldNames,
const omni::graph::core::Type* const fieldTypes,
const size_t* const elementCount,
size_t fieldCount,
omni::graph::core::AttributeDataHandle* const bundleMetadata,
size_t* const createdCount) noexcept;
//! @brief Remove bundle metadata based on provided field names.
//!
//! @param fieldNames Names of the bundle metadata fields whose data is to be removed.
//! @param fieldCount Number of the bundle metadata fields to be removed.
//! @param removedCount Number of bundle metadata fields successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeBundleMetadata(const omni::graph::core::NameToken* const fieldNames,
size_t fieldCount,
size_t* const removedCount) noexcept;
//! @brief Search for read write field handles in the attribute by using field names.
//!
//! @copydetails IConstBundle2_abi::getConstAttributeMetadataByName_abi
omni::core::Result getAttributeMetadataByName(omni::graph::core::NameToken attribute,
const omni::graph::core::NameToken* const fieldNames,
size_t fieldCount,
omni::graph::core::AttributeDataHandle* const attributeMetadata) noexcept;
//! @brief Create attribute metadata fields.
//!
//! @param attribute Name of the attribute.
//! @param fieldNames Names of new attribute metadata fields.
//! @param fieldTypes Types of new attribute metadata fields.
//! @param elementCount Number of elements in the array, can be `nullptr` if field is not an array.
//! @param fieldCount Size of fieldNames and fieldTypes arrays.
//! @param attributeMetadata Handles to the newly created attribute metadata. Can be `nullptr` if no output is
//! required.
//! @param removedCount Number of attribute metadata fields successfully created.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result createAttributeMetadata(omni::graph::core::NameToken attribute,
const omni::graph::core::NameToken* const fieldNames,
const omni::graph::core::Type* const fieldTypes,
const size_t* const elementCount,
size_t fieldCount,
omni::graph::core::AttributeDataHandle* const attributeMetadata,
size_t* const removedCount) noexcept;
//! @brief Remove attribute metadata fields.
//!
//! @param attribute Name of the attribute.
//! @param fieldNames Names of the attribute metadata fields to be removed.
//! @param fieldCount Size of fieldNames array.
//! @param removedCount Number of attribute metadata fields successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeAttributeMetadata(omni::graph::core::NameToken attribute,
const omni::graph::core::NameToken* const fieldNames,
size_t fieldCount,
size_t* const removedCount) noexcept;
//! @brief Remove all attributes, child bundles and metadata from this bundle, but keep the bundle itself.
//!
//! @param bundleMetadata Clears bundle metadata in this bundle.
//! @param attributes Clears attributes in this bundle.
//! @param childBundles Clears child bundles in this bundle.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result clearContents(bool bundleMetadata, bool attributes, bool childBundles) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::graph::core::BundleHandle omni::core::Generated<omni::graph::core::IBundle2_abi>::getHandle() noexcept
{
return getHandle_abi();
}
inline omni::graph::core::BundleHandle omni::core::Generated<omni::graph::core::IBundle2_abi>::getParentBundle() noexcept
{
return getParentBundle_abi();
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::getAttributes(
omni::graph::core::AttributeDataHandle* const attributes, size_t* const attributeCount) noexcept
{
return getAttributes_abi(attributes, attributeCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::getAttributesByName(
const omni::graph::core::NameToken* const names,
size_t nameCount,
omni::graph::core::AttributeDataHandle* const attributes) noexcept
{
return getAttributesByName_abi(names, nameCount, attributes);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::getChildBundles(
omni::graph::core::BundleHandle* const bundles, size_t* const bundleCount) noexcept
{
return getChildBundles_abi(bundles, bundleCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::getChildBundle(
size_t bundleIndex, omni::graph::core::BundleHandle* const bundle) noexcept
{
return getChildBundle_abi(bundleIndex, bundle);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::getChildBundlesByName(
const omni::graph::core::NameToken* const names,
size_t nameCount,
omni::graph::core::BundleHandle* const foundBundles) noexcept
{
return getChildBundlesByName_abi(names, nameCount, foundBundles);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::copyAttributes(
const omni::graph::core::NameToken* const newNames,
const omni::graph::core::ConstAttributeDataHandle* const sourceAttributes,
size_t attributeCount,
bool overwrite,
omni::graph::core::AttributeDataHandle* const copiedAttributes,
size_t* const copiedCount) noexcept
{
return copyAttributes_abi(newNames, sourceAttributes, attributeCount, overwrite, copiedAttributes, copiedCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::createAttributes(
const omni::graph::core::NameToken* const names,
const omni::graph::core::Type* const types,
const size_t* const elementCount,
size_t attributeCount,
omni::graph::core::AttributeDataHandle* const createdAttributes,
size_t* const createdCount) noexcept
{
return createAttributes_abi(names, types, elementCount, attributeCount, createdAttributes, createdCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::createAttributesLike(
const omni::graph::core::ConstAttributeDataHandle* const patternAttributes,
size_t patternCount,
omni::graph::core::AttributeDataHandle* const createdAttributes,
size_t* const createdCount) noexcept
{
return createAttributesLike_abi(patternAttributes, patternCount, createdAttributes, createdCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::createChildBundles(
const omni::graph::core::NameToken* const names,
size_t nameCount,
omni::graph::core::BundleHandle* const createdBundles,
size_t* const createdCount) noexcept
{
return createChildBundles_abi(names, nameCount, createdBundles, createdCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::linkAttributes(
const omni::graph::core::NameToken* const linkNames,
const omni::graph::core::ConstAttributeDataHandle* const targetAttributes,
size_t attributeCount,
omni::graph::core::AttributeDataHandle* const linkedAttributes,
size_t* const linkedCount) noexcept
{
return linkAttributes_abi(linkNames, targetAttributes, attributeCount, linkedAttributes, linkedCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::copyBundle(
const omni::graph::core::ConstBundleHandle& sourceBundle, bool overwrite) noexcept
{
return copyBundle_abi(sourceBundle, overwrite);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::copyChildBundles(
const omni::graph::core::NameToken* const newNames,
const omni::graph::core::ConstBundleHandle* const sourceBundles,
size_t bundleCount,
bool overwrite,
omni::graph::core::BundleHandle* const copiedBundles,
size_t* const copiedCount) noexcept
{
return copyChildBundles_abi(newNames, sourceBundles, bundleCount, overwrite, copiedBundles, copiedCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::linkBundle(
const omni::graph::core::ConstBundleHandle* const sourceBundle) noexcept
{
return linkBundle_abi(sourceBundle);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::linkChildBundles(
const omni::graph::core::NameToken* const linkNames,
const omni::graph::core::ConstBundleHandle* const targetBundles,
size_t bundleCount,
omni::graph::core::BundleHandle* const linkedBundles,
size_t* const linkedCount) noexcept
{
return linkChildBundles_abi(linkNames, targetBundles, bundleCount, linkedBundles, linkedCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::removeAttributes(
const omni::graph::core::ConstAttributeDataHandle* const attributes,
size_t attributeCount,
size_t* const removedCount) noexcept
{
return removeAttributes_abi(attributes, attributeCount, removedCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::removeAttributesByName(
const omni::graph::core::NameToken* const names, size_t nameCount, size_t* const removedCount) noexcept
{
return removeAttributesByName_abi(names, nameCount, removedCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::removeChildBundles(
const omni::graph::core::ConstBundleHandle* const childHandles, size_t childCount, size_t* const removedCount) noexcept
{
return removeChildBundles_abi(childHandles, childCount, removedCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::removeChildBundlesByName(
const omni::graph::core::NameToken* const names, size_t nameCount, size_t* const removedCount) noexcept
{
return removeChildBundlesByName_abi(names, nameCount, removedCount);
}
inline omni::graph::core::BundleHandle omni::core::Generated<omni::graph::core::IBundle2_abi>::getMetadataStorage() noexcept
{
return getMetadataStorage_abi();
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::getBundleMetadataByName(
const omni::graph::core::NameToken* const fieldNames,
size_t fieldCount,
omni::graph::core::AttributeDataHandle* const bundleMetadata) noexcept
{
return getBundleMetadataByName_abi(fieldNames, fieldCount, bundleMetadata);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::createBundleMetadata(
const omni::graph::core::NameToken* const fieldNames,
const omni::graph::core::Type* const fieldTypes,
const size_t* const elementCount,
size_t fieldCount,
omni::graph::core::AttributeDataHandle* const bundleMetadata,
size_t* const createdCount) noexcept
{
return createBundleMetadata_abi(fieldNames, fieldTypes, elementCount, fieldCount, bundleMetadata, createdCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::removeBundleMetadata(
const omni::graph::core::NameToken* const fieldNames, size_t fieldCount, size_t* const removedCount) noexcept
{
return removeBundleMetadata_abi(fieldNames, fieldCount, removedCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::getAttributeMetadataByName(
omni::graph::core::NameToken attribute,
const omni::graph::core::NameToken* const fieldNames,
size_t fieldCount,
omni::graph::core::AttributeDataHandle* const attributeMetadata) noexcept
{
return getAttributeMetadataByName_abi(attribute, fieldNames, fieldCount, attributeMetadata);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::createAttributeMetadata(
omni::graph::core::NameToken attribute,
const omni::graph::core::NameToken* const fieldNames,
const omni::graph::core::Type* const fieldTypes,
const size_t* const elementCount,
size_t fieldCount,
omni::graph::core::AttributeDataHandle* const attributeMetadata,
size_t* const removedCount) noexcept
{
return createAttributeMetadata_abi(
attribute, fieldNames, fieldTypes, elementCount, fieldCount, attributeMetadata, removedCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::removeAttributeMetadata(
omni::graph::core::NameToken attribute,
const omni::graph::core::NameToken* const fieldNames,
size_t fieldCount,
size_t* const removedCount) noexcept
{
return removeAttributeMetadata_abi(attribute, fieldNames, fieldCount, removedCount);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundle2_abi>::clearContents(bool bundleMetadata,
bool attributes,
bool childBundles) noexcept
{
return clearContents_abi(bundleMetadata, attributes, childBundles);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 32,728 | C | 52.30456 | 124 | 0.670466 |
omniverse-code/kit/include/omni/graph/core/IDataModel.h | // 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.
//
#pragma once
#include "Handle.h"
#include <carb/Interface.h>
namespace omni
{
namespace graph
{
namespace core
{
/**
* Interface to the underlying data access for OmniGraph
*/
struct IDataModel
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::IDataModel", 1, 1);
// This shouldn't exist...all data model changes should be implemented via data model interface
// until this is done, we expose a way to protect edits to data model...like ones in PrimCommon
/**
* @return Allocate and return new scoped lock for read or write.
*/
void* (CARB_ABI* enterEditScope)(bool writer);
/**
* @param[in] scope Free scoped lock
*/
void (CARB_ABI* exitEditScope)(void* scope);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IDataModel, exitEditScope, 1)
//! Scoping object to enter and exist editing mode for the DataModel
class DataModelEditScope
{
public:
//! Constructor to enter the edit scope, optionally with write mode enabled
DataModelEditScope(bool write)
{
static const IDataModel& iDataModel = *carb::getCachedInterface<IDataModel>();
m_scope = iDataModel.enterEditScope(write);
}
//! Destructor that exits the DataModel edit scope
~DataModelEditScope()
{
static const IDataModel& iDataModel = *carb::getCachedInterface<IDataModel>();
iDataModel.exitEditScope(m_scope);
}
private:
void* m_scope{nullptr};
};
}
}
}
| 2,002 | C | 28.028985 | 107 | 0.715285 |
omniverse-code/kit/include/omni/graph/core/TemplateUtils.h | // Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <utility>
#include <type_traits>
// ======================================================================
// Implementation of the C++20 feature to detect whether a type is a bounded array (e.g. int[2], float[3]...)
template<class T> struct is_bounded_array: std::false_type {};
template<class T, std::size_t N> struct is_bounded_array<T[N]> : std::true_type {};
// ======================================================================
// When we move to C++17 we can replace and_ with std::conjunction
// Recursively applies std::conditional to all of the template arguments.
template <typename... Conds>
struct and_ : std::true_type
{
};
template <typename Cond, typename... Conds>
struct and_<Cond, Conds...> : std::conditional<Cond::value, and_<Conds...>, std::false_type>::type
{
};
// ======================================================================
// When we move to C++17 we can replace "fold" with C++ fold expression
// Ex: args && ...
// Recursively applies provided functor to all of the template arguments.
// Ex: fold(std::logical_and<>(), args...)
template <class F, class A0>
auto fold(F&&, A0&& a0)
{
return std::forward<A0>(a0);
}
template <class F, class A0, class... As>
auto fold(F&& f, A0&& a0, As&&... as)
{
return f(std::forward<A0>(a0), fold(f, std::forward<As>(as)...));
}
// ======================================================================
// Removes const& qualifier on a type
template <typename T>
using remove_const_ref = std::remove_const<typename std::remove_reference<T>::type>;
// ======================================================================
// Check to see if a list of types are all of the named type
template <typename MembersAreThisType, typename... MemberType>
using areTypeT = and_<std::is_same<MembersAreThisType, MemberType>...>;
// ======================================================================
// Templatized version of void
template <typename... Ts>
using void_t = void;
// ======================================================================
// This set of templates is used to define a metaprogram "is_detected" that derives from
// std::true_type if the declared templated function exists and std::false_type if not
// (for use in compile-time overload selection, described below).
namespace detail
{
// Matches a call with any type, any templated type, and a variable length list of any types.
// There has to be a typename as the first parameter because another template can't be one.
// Using the void_t<> type defined above allows this parameter to be used for SFINAE selection.
template <typename, template <typename...> class, typename...>
struct is_detected : std::false_type
{
};
// This specialization of detail::is_detected triggers only when the Operation can be instantiated
// with the Arguments. For method checks the "has_X" templates above will be legal types when the
// class mentioned as the first member of "Arguments" implements the method "X". This in turn will
// make void_t<Operation<Arguments...>>> a legal type. In those situations this specialization will
// succeed and is_detected<> will be a std::true_type.
template <template <class...> class Operation, typename... Arguments>
struct is_detected<void_t<Operation<Arguments...>>, Operation, Arguments...> : std::true_type
{
};
}
// This is used only to hide the implementation detail of using the void_t<> template argument to
// guide the SFINAE substitution which detects method overrides. That way the templates below can
// use this more natural pattern:
// is_detected<has_X, NodeTypeClass>()
// instead of this:
// detail::is_detected<void_t<>, has_X, NodeTypeClass>()
template <template <class...> class Operation, typename... Arguments>
using is_detected = ::detail::is_detected<void_t<>, Operation, Arguments...>;
| 4,283 | C | 43.164948 | 109 | 0.636937 |
omniverse-code/kit/include/omni/graph/core/ISchedulingHints.h | // 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.
//
#pragma once
#include <omni/core/IObject.h>
#include <omni/core/Omni.h>
#include <omni/inspect/IInspector.h>
namespace omni
{
namespace graph
{
namespace core
{
//! How does the node access the data described by the enum eAccessLocation
enum class eAccessType
{
//! There is no access to data of the associated type
eNone,
//! There is only read access to data of the associated type
eRead,
//! There is only write access to data of the associated type
eWrite,
//! There is both read and write access to data of the associated type
eReadWrite
};
//! What type of non-attribute data does this node access
enum class eAccessLocation
{
//! Accesses the USD stage data
eUsd,
//! Accesses data that is not part of the node or node type
eGlobal,
//! Accesses data that is shared by every instance of a particular node type
eStatic,
//! Accesses information on the topology of the graph to which the node belongs
eTopology
};
//! How thread safe is the node during evaluation
enum class eThreadSafety
{
//! Nodes can be evaluated in multiple threads safely
eSafe,
//! Nodes cannot be evaluated in multiple threads safely
eUnsafe,
//! The thread safety status of the node type is unknown
eUnknown
};
//! How the node is allowed to be computed
enum class eComputeRule
{
//! Nodes are computed according to the default evaluator rules
eDefault,
//! The evaluator may skip computing this node until explicitly requested with INode::requestCompute
eOnRequest
};
//! Declare the ISchedulingHints interface definition
OMNI_DECLARE_INTERFACE(ISchedulingHints);
//! Interface to the list of scheduling hints that can be applied to a node type
class ISchedulingHints_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.ISchedulingHints")>
{
protected:
/**
* Get the threadSafety status (i.e. can be run in parallel with other nodes)
*
* @returns Is the node compute threadsafe?
*/
virtual eThreadSafety getThreadSafety_abi() noexcept = 0;
/**
* Set the flag indicating if a node is threadsafe or not.
*
* @param[in] newThreadSafety New value of the threadsafe flag
*/
virtual void setThreadSafety_abi(eThreadSafety newThreadSafety) noexcept = 0;
/**
* Get the type of access the node has for a given data type
*
* @param[in] dataType Type of data for which access type is being modified
* @returns Value of the access type flag
*/
virtual eAccessType getDataAccess_abi(eAccessLocation dataType) noexcept = 0;
/**
* Set the flag describing how a node accesses particular data in its compute _abi (defaults to no access).
* Setting any of these flags will, in most cases, automatically mark the node as "not threadsafe".
* One current exception to this is allowing a node to be both threadsafe and a writer to USD, since
* such behavior can be achieved if delayed writebacks (e.g. "registerForUSDWriteBack") are utilized
* in the node's compute method.
*
* @param[in] dataType Type of data for which access type is being modified
* @param[in] newAccessType New value of the access type flag
*/
virtual void setDataAccess_abi(eAccessLocation dataType, eAccessType newAccessType) noexcept = 0;
/**
* Get the flag describing the compute rule which may be followed by the evaluator.
*
* @returns Value of the ComputeRule flag
*/
virtual eComputeRule getComputeRule_abi() noexcept = 0;
/**
* Set the flag describing the compute rule which may be followed by the evaluator.
*
* @param[in] newComputeRule New value of the ComputeRule flag
*/
virtual void setComputeRule_abi(eComputeRule newComputeRule) noexcept = 0;
/**
* Runs the inspector on the scheduling hints.
*
* @param[in] inspector The inspector class
* @return true if the inspection ran successfully, false if the inspection type is not supported
*/
virtual bool inspect_abi(omni::inspect::IInspector* inspector) noexcept = 0;
};
} // namespace core
} // namespace graph
} // namespace omni
#include "ISchedulingHints.gen.h"
| 4,687 | C | 33.218978 | 111 | 0.711756 |
omniverse-code/kit/include/omni/graph/core/CppWrappers.h | // 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.
//
#pragma once
#include "TemplateUtils.h"
#include <carb/Defines.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/CudaUtils.h>
#include <string>
#include <tuple>
#include <type_traits>
#include <vector>
#include <gsl/span>
namespace omni
{
namespace graph
{
namespace core
{
// The templates for extracting data do not like double pointers so use this type for assigning strings
using CString = char*;
// NOTE: This file is a work in progress, for assessing possible interfaces, not yet for use.
// -Wall will warn about these inline functions not being used
#if defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
using Path = omni::fabric::Path;
using Token = omni::fabric::Token;
// ----------------------------------------------------------------------------
// Accessors for accessing attributes by name
static ConstAttributeDataHandle getAttributeR(GraphContextObj const& contextObj,
ConstBundleHandle bundleHandle,
fabric::TokenC name)
{
ConstAttributeDataHandle out;
contextObj.iBundle->getAttributesByNameR(&out, contextObj, bundleHandle, &name, 1);
return out;
}
static ConstAttributeDataHandle getAttributeR(GraphContextObj const& contextObj,
ConstBundleHandle bundleHandle,
Token const& name)
{
NameToken nameToken = name;
return getAttributeR(contextObj, bundleHandle, nameToken);
}
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getAttributesR(const GraphContextObj& contextObj,
ConstBundleHandle& primHandle,
std::tuple<NameTypes...> names)
{
// Check that size(out)==len(names) and that every element of names has type size_t
const size_t inCount = std::tuple_size<std::tuple<NameTypes...>>::value;
const size_t outCount = std::tuple_size<std::tuple<Types...>>::value;
static_assert(inCount == outCount, "Input and output tuples must be of same length");
static_assert(areTypeT<NameToken, NameTypes...>::value || areTypeT<Token, NameTypes...>::value,
"Attribute names must have type NameToken or Token");
static_assert(areTypeT<ConstAttributeDataHandle, Types...>::value, "Outputs must have type ConstAttributeDataHandle");
std::tuple<Types...> out;
// Cast to C-ABI compatible types
std::tuple<Types...>* outTuplePtr = &out;
ConstAttributeDataHandle* outPtr = reinterpret_cast<ConstAttributeDataHandle*>(outTuplePtr);
std::tuple<NameTypes...>* inTuplePtr = &names;
NameToken* namesPtr = reinterpret_cast<NameToken*>(inTuplePtr);
// Call C-ABI version of method
contextObj.iBundle->getAttributesByNameR(outPtr, contextObj, primHandle, namesPtr, inCount);
return out;
}
static AttributeDataHandle getAttributeW(const GraphContextObj& contextObj, BundleHandle& primHandle, const Token& name)
{
AttributeDataHandle out;
NameToken nameToken = name;
contextObj.iBundle->getAttributesByNameW(&out, contextObj, primHandle, &nameToken, 1);
return out;
}
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getAttributesW(const GraphContextObj& contextObj,
BundleHandle& primHandle,
std::tuple<NameTypes...> names)
{
// Check that size(out)==len(names) and that every element of names has type size_t
const size_t inCount = std::tuple_size<std::tuple<NameTypes...>>::value;
const size_t outCount = std::tuple_size<std::tuple<Types...>>::value;
static_assert(inCount == outCount, "Input and output tuples must be of same length");
static_assert(areTypeT<NameToken, NameTypes...>::value || areTypeT<Token, NameTypes...>::value,
"Attribute names must have type NameToken or Token");
static_assert(areTypeT<AttributeDataHandle, Types...>::value, "Outputs must have type AttributeDataHandle");
std::tuple<Types...> out;
// Cast to C-ABI compatible types
std::tuple<Types...>* outTuplePtr = &out;
AttributeDataHandle* outPtr = reinterpret_cast<AttributeDataHandle*>(outTuplePtr);
std::tuple<NameTypes...>* inTuplePtr = &names;
HandleInt* namesPtr = reinterpret_cast<HandleInt*>(inTuplePtr);
// Call C-ABI version of method
contextObj.iBundle->getAttributesByNameW(outPtr, contextObj, primHandle, namesPtr, inCount);
return out;
}
// ----------------------------------------------------------------------------
// Accessors for accessing attributes by AttributeDataHandle
// Specialization for the read-only data of a single attribute. Get a single attribute handle from getAttributeR
// to pass in as the second parameter.
// auto constHandle = getAttributeR(contextObj, node, Token("myAttribute"))
// // Note that the template parameter for the special case is the data type, not a pointer type
// const auto dataPtr = getDataR<float>(contextObj, constHandle);
template <typename T>
const T* getDataR(const GraphContextObj& contextObj, const ConstAttributeDataHandle& attrHandle)
{
const T* out;
const void** outPtr = reinterpret_cast<const void**>(&out);
contextObj.iAttributeData->getDataR(outPtr, contextObj, &attrHandle, 1);
return out;
}
// Get the read-only data for an arbitrary list of attributes. Get a tuple attribute handle from getAttributesR
// to pass in as the second parameter.
// auto constHandles = getAttributesR<ConstAttributeDataHandle, ConstAttributeDataHandle>(contextObj, node,
// std::make_tuple(Token("a"), Token("b")))
// const float* a_value{nullptr};
// const float* b_value{nullptr};
// // Note that the template parameters for the general case are pointers to the data type
// std::tie(a_value, b_value) = getDataR<float*, float*>(contextObj, constHandles);
template <typename... Types, typename... HandleTypes>
std::tuple<Types...> getDataR(const GraphContextObj& contextObj, std::tuple<HandleTypes...> handles)
{
// Check that size(out)==len(names) and that every element of names has type size_t
const size_t inCount = std::tuple_size<std::tuple<HandleTypes...>>::value;
const size_t outCount = std::tuple_size<std::tuple<Types...>>::value;
static_assert(inCount == outCount, "Input and output tuples must be of same length");
static_assert(areTypeT<ConstAttributeDataHandle, HandleTypes...>::value,
"Attribute handles must have type ConstAttributeDataHandle");
std::tuple<Types...> out;
// Cast to C-ABI compatible types
std::tuple<Types...>* outTuplePtr = &out;
const void** outPtr = reinterpret_cast<const void**>(outTuplePtr);
std::tuple<HandleTypes...>* inTuplePtr = &handles;
ConstAttributeDataHandle* handlesPtr = reinterpret_cast<ConstAttributeDataHandle*>(inTuplePtr);
// Call C-ABI version of method
contextObj.iAttributeData->getDataR(outPtr, contextObj, handlesPtr, inCount);
return out;
}
// Specialization for the read-only GPU data of a single attribute. Get a single attribute handle from getAttributeR
// to pass in as the second parameter.
// auto handle = getAttributeR(contextObj, node, Token("myAttribute"))
// // Note that the template parameter for the special case is the data type, not a pointer type
// const auto gpuData = getDataRGPU<float>(contextObj, handle);
// If you wish to get CPU pointers to GPU data for arrays then use the alternative version:
// const auto gpuData = getDataRGPUOnCPU<float>(contextObj, handle);
template <typename T>
const T* getDataRGpuAt(const GraphContextObj& contextObj, const ConstAttributeDataHandle& attrHandle, omni::fabric::PtrToPtrKind where)
{
const T* out;
const void** outPtr = reinterpret_cast<const void**>(&out);
contextObj.iAttributeData->getDataRGpuAt(outPtr, contextObj, &attrHandle, 1, where);
return out;
}
// Syntactic sugar
template <typename T>
const T* getDataRGPU(const GraphContextObj& contextObj, const ConstAttributeDataHandle& attrHandle)
{
return getDataRGpuAt<T>(contextObj, attrHandle, omni::fabric::PtrToPtrKind::eGpuPtrToGpuPtr);
}
template <typename T>
const T* getDataRGPUOnCPU(const GraphContextObj& contextObj, const ConstAttributeDataHandle& attrHandle)
{
return getDataRGpuAt<T>(contextObj, attrHandle, omni::fabric::PtrToPtrKind::eCpuPtrToGpuPtr);
}
// Get the read-only GPU data for an arbitrary list of attributes. Get a tuple attribute handle from getAttributesR
// to pass in as the second parameter.
// auto handles = getAttributesR<ConstAttributeDataHandle, ConstAttributeDataHandle>(contextObj, node,
// std::make_tuple(Token("a"), Token("b")))
// const float* a_gpu_value{nullptr};
// const float* b_gpu_value{nullptr};
// // Note that the template parameters for the general case are pointers to the data type
// std::tie(a_gpu_value, b_gpu_value) = getDataRGPU<float*, float*>(contextObj, handles);
// If you wish to get CPU pointers to GPU data for arrays then use the alternative version:
// std::tie(a_gpu_value, b_gpu_value) = getDataRGPUOnCPU<float*, float*>(contextObj, handles);
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getDataRGpuAt(const GraphContextObj& contextObj, std::tuple<NameTypes...> handles, omni::fabric::PtrToPtrKind where)
{
// Check that size(out)==len(names) and that every element of names has type size_t
const size_t inCount = std::tuple_size<std::tuple<NameTypes...>>::value;
const size_t outCount = std::tuple_size<std::tuple<Types...>>::value;
static_assert(inCount == outCount, "Input and output tuples must be of same length");
static_assert(areTypeT<ConstAttributeDataHandle, NameTypes...>::value,
"Attribute handles must have type ConstAttributeDataHandle");
std::tuple<Types...> out;
// Cast to C-ABI compatible types
std::tuple<Types...>* outTuplePtr = &out;
const void** outPtr = reinterpret_cast<const void**>(outTuplePtr);
std::tuple<NameTypes...>* inTuplePtr = &handles;
ConstAttributeDataHandle* handlesPtr = reinterpret_cast<ConstAttributeDataHandle*>(inTuplePtr);
// Call C-ABI version of method
contextObj.iAttributeData->getDataRGpuAt(outPtr, contextObj, handlesPtr, inCount, where);
return out;
}
// Syntactic sugar
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getDataRGPU(const GraphContextObj& contextObj, std::tuple<NameTypes...> handles)
{
return getDataRGpuAt<Types...>(contextObj, handles, omni::fabric::PtrToPtrKind::eGpuPtrToGpuPtr);
}
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getDataRGPUOnCPU(const GraphContextObj& contextObj, std::tuple<NameTypes...> handles)
{
return getDataRGpuAt<Types...>(contextObj, handles, omni::fabric::PtrToPtrKind::eCpuPtrToGpuPtr);
}
// Specialization for the writable data of a single attribute. Get a single attribute handle from getAttributeW
// to pass in as the second parameter.
// auto handle = getAttributeW(contextObj, node, Token("myAttribute"))
// // Note that the template parameter for the special case is the data type, not a pointer type
// auto dataPtr = getDataW<float>(contextObj, handle);
template <typename T>
T* getDataW(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle)
{
T* out;
void** outPtr = reinterpret_cast<void**>(&out);
contextObj.iAttributeData->getDataW(outPtr, contextObj, &attrHandle, 1);
return out;
}
// Get the writable data for an arbitrary list of attributes. Get a tuple attribute handle from getAttributesW
// to pass in as the second parameter.
// auto handles = getAttributesW<AttributeDataHandle, AttributeDataHandle>(contextObj, node,
// std::make_tuple(Token("a"), Token("b")))
// float* a_value{nullptr};
// float* b_value{nullptr};
// // Note that the template parameters for the general case are pointers to the data type
// std::tie(a_value, b_value) = getDataW<float*, float*>(contextObj, handles);
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getDataW(const GraphContextObj& contextObj, std::tuple<NameTypes...> handles)
{
// Check that size(out)==len(names) and that every element of names has type size_t
const size_t inCount = std::tuple_size<std::tuple<NameTypes...>>::value;
const size_t outCount = std::tuple_size<std::tuple<Types...>>::value;
static_assert(inCount == outCount, "Input and output tuples must be of same length");
static_assert(
areTypeT<AttributeDataHandle, NameTypes...>::value, "Attribute handles must have type AttributeDataHandle");
std::tuple<Types...> out;
// Cast to C-ABI compatible types
std::tuple<Types...>* outTuplePtr = &out;
void** outPtr = reinterpret_cast<void**>(outTuplePtr);
std::tuple<NameTypes...>* inTuplePtr = &handles;
AttributeDataHandle* handlesPtr = reinterpret_cast<AttributeDataHandle*>(inTuplePtr);
// Call C-ABI version of method
contextObj.iAttributeData->getDataW(outPtr, contextObj, handlesPtr, inCount);
return out;
}
// Specialization for the writable GPU data of a single attribute. Get a single attribute handle from getAttributeW
// to pass in as the second parameter.
// auto handle = getAttributeW(contextObj, node, Token("myAttribute"))
// // Note that the template parameter for the special case is the data type, not a pointer type
// auto gpuData = getDataWGPU<float>(contextObj, handle);
// If you wish to get CPU pointers to GPU data for arrays then use the alternative version:
// auto gpuData = getDataWGPUOnCPU<float>(contextObj, handle);
template <typename T>
T* getDataWGpuAt(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle, omni::fabric::PtrToPtrKind whereGpuPtrs)
{
T* out;
void** outPtr = reinterpret_cast<void**>(&out);
contextObj.iAttributeData->getDataWGpuAt(outPtr, contextObj, &attrHandle, 1, whereGpuPtrs);
return out;
}
// Syntactic sugar
template <typename T>
T* getDataWGPU(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle)
{
return getDataWGpuAt<T>(contextObj, attrHandle, omni::fabric::PtrToPtrKind::eGpuPtrToGpuPtr);
}
template <typename T>
T* getDataWGPUOnCPU(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle)
{
return getDataWGpuAt<T>(contextObj, attrHandle, omni::fabric::PtrToPtrKind::eCpuPtrToGpuPtr);
}
// Get the writable GPU data for an arbitrary list of attributes. Get a tuple attribute handle from getAttributesW
// to pass in as the second parameter.
// auto handles = getAttributesW<AttributeDataHandle, AttributeDataHandle>(contextObj, node,
// std::make_tuple(Token("a"), Token("b")))
// float* a_gpu_value{nullptr};
// float* b_gpu_value{nullptr};
// // Note that the template parameters for the general case are pointers to the data type
// std::tie(a_gpu_value, b_gpu_value) = getDataWGPU<float*, float*>(contextObj, handles);
// If you wish to get CPU pointers to GPU data for arrays then use the alternative version:
// std::tie(a_gpu_value, b_gpu_value) = getDataWGPUOnCPU<float*, float*>(contextObj, handles);
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getDataWGpuAt(const GraphContextObj& contextObj, std::tuple<NameTypes...> handles, omni::fabric::PtrToPtrKind whereGpuPtrs)
{
// Check that size(out)==len(names) and that every element of names has type size_t
const size_t inCount = std::tuple_size<std::tuple<NameTypes...>>::value;
const size_t outCount = std::tuple_size<std::tuple<Types...>>::value;
static_assert(inCount == outCount, "Input and output tuples must be of same length");
static_assert(
areTypeT<AttributeDataHandle, NameTypes...>::value, "Attribute handles must have type AttributeDataHandle");
std::tuple<Types...> out;
// Cast to C-ABI compatible types
std::tuple<Types...>* outTuplePtr = &out;
void** outPtr = reinterpret_cast<void**>(outTuplePtr);
std::tuple<NameTypes...>* inTuplePtr = &handles;
AttributeDataHandle* handlesPtr = reinterpret_cast<AttributeDataHandle*>(inTuplePtr);
// Call C-ABI version of method
contextObj.iAttributeData->getDataWGpuAt(outPtr, contextObj, handlesPtr, inCount, whereGpuPtrs);
return out;
}
// Syntactic sugar
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getDataWGPU(const GraphContextObj& contextObj, std::tuple<NameTypes...> handles)
{
return getDataWGpuAt<Types...>(contextObj, handles, omni::fabric::PtrToPtrKind::eGpuPtrToGpuPtr);
}
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getDataWGPUOnCPU(const GraphContextObj& contextObj, std::tuple<NameTypes...> handles)
{
return getDataWGpuAt<Types...>(contextObj, handles, omni::fabric::PtrToPtrKind::eCpuPtrToGpuPtr);
}
static size_t getElementCount(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle)
{
size_t out;
ConstAttributeDataHandle constAttrHandle = attrHandle;
contextObj.iAttributeData->getElementCount(&out, contextObj, &constAttrHandle, 1);
return out;
}
static size_t getElementCount(const GraphContextObj& contextObj, ConstAttributeDataHandle const& attrHandle)
{
size_t out;
contextObj.iAttributeData->getElementCount(&out, contextObj, &attrHandle, 1);
return out;
}
template <typename... Types, typename... HandleTypes>
std::tuple<Types...> getElementCount(const GraphContextObj& contextObj, std::tuple<HandleTypes...> handles)
{
// Check that size(out)==len(names) and that every element of names has type size_t
const size_t inCount = std::tuple_size<std::tuple<HandleTypes...>>::value;
const size_t outCount = std::tuple_size<std::tuple<Types...>>::value;
static_assert(inCount == outCount, "Input and output tuples must be of same length");
static_assert(areTypeT<ConstAttributeDataHandle, HandleTypes...>::value ||
areTypeT<AttributeDataHandle, HandleTypes...>::value,
"Attribute handles must have type ConstAttributeDataHandle or AttributeDataHandle");
static_assert(areTypeT<size_t, Types...>::value, "Outputs must have type size_t");
std::tuple<Types...> out;
// Cast to C-ABI compatible types
std::tuple<Types...>* outTuplePtr = &out;
size_t* outPtr = reinterpret_cast<size_t*>(outTuplePtr);
std::tuple<HandleTypes...>* inTuplePtr = &handles;
ConstAttributeDataHandle* handlesPtr = reinterpret_cast<ConstAttributeDataHandle*>(inTuplePtr);
// Call C-ABI version of method
contextObj.iAttributeData->getElementCount(outPtr, contextObj, handlesPtr, inCount);
return out;
}
//-----------------------------------------------------------------------------
static std::vector<ConstAttributeDataHandle> getAttributes(const GraphContextObj& contextObj, ConstBundleHandle bundle)
{
size_t count = contextObj.iBundle->getAttributesCount(contextObj, bundle);
std::vector<ConstAttributeDataHandle> attrsOut(count);
contextObj.iBundle->getAttributesR(attrsOut.data(), contextObj, bundle, count);
return attrsOut;
}
static std::vector<AttributeDataHandle> getAttributes(const GraphContextObj& contextObj, BundleHandle bundle)
{
size_t count = contextObj.iBundle->getAttributesCount(contextObj, bundle);
std::vector<AttributeDataHandle> attrsOut(count);
contextObj.iBundle->getAttributesW(attrsOut.data(), contextObj, bundle, count);
return attrsOut;
}
static void getAttributesByName(ConstAttributeDataHandle* attrsOut,
const GraphContextObj& contextObj,
ConstBundleHandle prim,
const Token* attrNames,
size_t count)
{
const NameToken* nameTokens = reinterpret_cast<const NameToken*>(attrNames);
contextObj.iBundle->getAttributesByNameR(attrsOut, contextObj, prim, nameTokens, count);
}
static void getAttributesByName(AttributeDataHandle* attrsOut,
const GraphContextObj& contextObj,
BundleHandle prim,
const Token* attrNames,
size_t count)
{
const NameToken* nameTokens = reinterpret_cast<const NameToken*>(attrNames);
contextObj.iBundle->getAttributesByNameW(attrsOut, contextObj, prim, nameTokens, count);
}
// ======================================================================
// Context wrappers
// getAttributeR is to be used in conjunction with the single item getDataR specialization to extract read-only data
// from a single attribute. If you have more than one attribute it is best to use getAttributesR, to minimize the calls
// across the ABI boundary. See the getDataR description for more information.
static ConstAttributeDataHandle getAttributeR(const GraphContextObj& contextObj,
NodeContextHandle node,
const Token& name,
InstanceIndex instanceIndex)
{
ConstAttributeDataHandle out;
NameToken nameToken = name;
contextObj.iContext->getAttributesByNameR(&out, contextObj, node, &nameToken, 1, instanceIndex);
return out;
}
// getAttributesR is to be used in conjunction with the general version of getDataR to extract read-only data from an
// arbitrary list of attributes. It uses variadic templates to gather all arguments into a single ABI call. See the
// getDataR description for more information. Sample usage:
// std::tie(a, b, c) = getAttributesR(contextObj, node, std::make_tuple(Token("a"), Token("b"), Token("c")), instanceIndex)
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getAttributesR(const GraphContextObj& contextObj,
NodeContextHandle node,
std::tuple<NameTypes...> names,
InstanceIndex instanceIndex)
{
// Check that size(out)==len(names) and that every element of names has type size_t
const size_t inCount = std::tuple_size<std::tuple<NameTypes...>>::value;
const size_t outCount = std::tuple_size<std::tuple<Types...>>::value;
static_assert(inCount == outCount, "Input and output tuples must be of same length");
static_assert(areTypeT<NameToken, NameTypes...>::value || areTypeT<Token, NameTypes...>::value,
"Attribute names must have type NameToken or Token");
static_assert(areTypeT<ConstAttributeDataHandle, Types...>::value, "Outputs must have type ConstAttributeDataHandle");
std::tuple<Types...> out;
// Cast to C-ABI compatible types
std::tuple<Types...>* outTuplePtr = &out;
ConstAttributeDataHandle* outPtr = reinterpret_cast<ConstAttributeDataHandle*>(outTuplePtr);
std::tuple<NameTypes...>* inTuplePtr = &names;
NameToken* namesPtr = reinterpret_cast<NameToken*>(inTuplePtr);
// Call C-ABI version of method
contextObj.iContext->getAttributesByNameR(outPtr, contextObj, node, namesPtr, inCount, instanceIndex);
return out;
}
// getAttributeW is to be used in conjunction with the single item getDataW specialization to extract writable data
// from a single attribute. If you have more than one attribute it is best to use getAttributesW, to minimize the calls
// across the ABI boundary. See the getDataW description for more information.
static AttributeDataHandle getAttributeW(const GraphContextObj& contextObj,
NodeContextHandle node,
const Token& name,
InstanceIndex instanceIndex)
{
AttributeDataHandle out;
NameToken nameToken = name;
contextObj.iContext->getAttributesByNameW(&out, contextObj, node, &nameToken, 1, instanceIndex);
return out;
}
// getAttributesW is to be used in conjunction with the general version of getDataW to extract read-only data from an
// arbitrary list of attributes. It uses variadic templates to gather all arguments into a single ABI call. See the
// getDataW description for more information. Sample usage:
// std::tie(a, b, c) = getAttributesW(contextObj, node, std::make_tuple(Token("a"), Token("b"), Token("c")), instanceIndex)
template <typename... Types, typename... NameTypes>
std::tuple<Types...> getAttributesW(const GraphContextObj& contextObj,
NodeContextHandle node,
std::tuple<NameTypes...> names,
InstanceIndex instanceIndex)
{
// Check that size(out)==len(names) and that every element of names has type size_t
const size_t inCount = std::tuple_size<std::tuple<NameTypes...>>::value;
const size_t outCount = std::tuple_size<std::tuple<Types...>>::value;
static_assert(inCount == outCount, "Input and output tuples must be of same length");
static_assert(areTypeT<NameToken, NameTypes...>::value || areTypeT<Token, NameTypes...>::value,
"Attribute names must have type NameToken or Token");
static_assert(areTypeT<AttributeDataHandle, Types...>::value, "Outputs must have type AttributeDataHandle");
std::tuple<Types...> out;
// Cast to C-ABI compatible types
std::tuple<Types...>* outTuplePtr = &out;
AttributeDataHandle* outPtr = reinterpret_cast<AttributeDataHandle*>(outTuplePtr);
std::tuple<NameTypes...>* inTuplePtr = &names;
NameToken* namesPtr = reinterpret_cast<NameToken*>(inTuplePtr);
// Call C-ABI version of method
contextObj.iContext->getAttributesByNameW(outPtr, contextObj, node, namesPtr, inCount, instanceIndex);
return out;
}
#if defined(__GNUC__)
# pragma GCC diagnostic pop
#endif
}
}
}
| 26,594 | C | 46.746858 | 144 | 0.692976 |
omniverse-code/kit/include/omni/graph/core/IVariable2.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
/**
* @brief Interface extension for IVariable that adds the ability to set a variable type
*/
template <>
class omni::core::Generated<omni::graph::core::IVariable2_abi> : public omni::graph::core::IVariable2_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::IVariable2")
/**
* Sets the type of the variable.
*
* @param[in] type New type for the variable
*
* @return True if the type is able to be set, false otherwise
*/
bool setType(omni::graph::core::Type type) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline bool omni::core::Generated<omni::graph::core::IVariable2_abi>::setType(omni::graph::core::Type type) noexcept
{
return setType_abi(type);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 1,610 | C | 26.305084 | 116 | 0.714907 |
omniverse-code/kit/include/omni/graph/core/IVariable.h | // 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.
//
#pragma once
#include <omni/core/IObject.h>
#include <omni/graph/core/Type.h>
#include <omni/graph/core/Handle.h>
namespace omni
{
namespace graph
{
namespace core
{
/**
* Scope in which the variable has been made available
*/
enum class eVariableScope
{
/** Variable is accessible only to its graph */
ePrivate = 0,
/** Variable can be read by other graphs */
eReadOnly = 1,
/** Variable can be read/written by other graphs */
ePublic = 2,
};
//! Declare the IVariable interface definition
OMNI_DECLARE_INTERFACE(IVariable);
//! Data type to use for a reference to an IVariable interface definition
using IVariablePtr = omni::core::ObjectPtr<IVariable>;
/**
* Object that contains a value that is local to a graph, available from anywhere in the graph
*/
class IVariable_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.IVariable")>
{
protected:
/**
* Returns the name of the variable object. The name is derived by
* removing any variable specific prefixes from the underlying attribute.
*
* @return The name of the variable.
*/
virtual const char* getName_abi() noexcept = 0;
/**
* Returns the full path to the variables underlying attribute
*
* @return The full usd path of the variable
*/
virtual const char* getSourcePath_abi() noexcept = 0;
/**
* Returns the type of the variable
*
* @return The type of the variable
*/
virtual OMNI_ATTR("no_py") Type getType_abi() noexcept = 0;
/**
* Returns the category of the variable
*
* @return The category of the variable, or an empty string if it is not set.
*/
virtual const char* getCategory_abi() noexcept = 0;
/**
* Sets the category of the variable
*
* @param[in] category A string representing the variable category
*/
virtual void setCategory_abi(OMNI_ATTR("c_str, in, not_null") const char* category) noexcept = 0;
/**
* Gets the display name of the variable. By default the display name is the same
* as the variable name.
*
* @return The display name of the variable, or an empty string if it is not set.
*/
virtual const char* getDisplayName_abi() noexcept = 0;
/**
* Set the display name of the variable.
*
* @param[in] displayName A string to set the display name to
*/
virtual void setDisplayName_abi(OMNI_ATTR("c_str, in, not_null") const char* displayName) noexcept = 0;
/**
* Get the tooltip used for the variable.
*
* @return The tooltip of the variable, or an emtpy string if none is set.
*/
virtual const char* getTooltip_abi() noexcept = 0;
/**
* Set the tooltip used for the variable
*
* @param[in] toolTip A description used as a tooltip.
*/
virtual void setTooltip_abi(OMNI_ATTR("c_str, in, not_null") const char* toolTip) noexcept = 0;
/**
* Get the scope of the variable. The scope determines which graphs can read and write the value.
*
* @return The scope of the variable.
*/
virtual eVariableScope getScope_abi() noexcept = 0;
/**
* Sets the scope of the variable.
*
* @param[in] scope The scope to set on the variable.
*/
virtual void setScope_abi(eVariableScope scope) noexcept = 0;
/**
* Returns whether this variable is valid
*
* @return True if the variable is valid, false otherwise
*/
virtual bool isValid_abi() noexcept = 0;
};
} // namespace core
} // namespace graph
} // namespace omni
#include "IVariable.gen.h"
//! @cond Doxygen_Suppress
//!
//! API part of the variable interface
//! @copydoc omni::graph::core::IVariable_abi
OMNI_DEFINE_INTERFACE_API(omni::graph::core::IVariable)
//! @endcond
{
public:
/**
* Changes the type of the variable.
*
* @param[in] type The type to change the variable to
* @returns True if the type was successfully changed, False otherwise. Setting the type
* can fail if the backing USD change is on a layer with a weaker opinion.
*/
inline bool setType(omni::graph::core::Type type) noexcept;
};
| 4,637 | C | 27.807453 | 107 | 0.664007 |
omniverse-code/kit/include/omni/graph/core/PyISchedulingHints.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
#pragma once
#include <omni/core/ITypeFactory.h>
#include <omni/python/PyBind.h>
#include <omni/python/PyString.h>
#include <omni/python/PyVec.h>
#include <sstream>
auto bindeAccessType(py::module& m)
{
py::enum_<omni::graph::core::eAccessType> e(
m, "eAccessType",
R"OMNI_BIND_RAW_(How does the node access the data described by the enum eAccessLocation)OMNI_BIND_RAW_");
e.value("E_NONE", omni::graph::core::eAccessType::eNone,
R"OMNI_BIND_RAW_(There is no access to data of the associated type)OMNI_BIND_RAW_");
e.value("E_READ", omni::graph::core::eAccessType::eRead,
R"OMNI_BIND_RAW_(There is only read access to data of the associated type)OMNI_BIND_RAW_");
e.value("E_WRITE", omni::graph::core::eAccessType::eWrite,
R"OMNI_BIND_RAW_(There is only write access to data of the associated type)OMNI_BIND_RAW_");
e.value("E_READ_WRITE", omni::graph::core::eAccessType::eReadWrite,
R"OMNI_BIND_RAW_(There is both read and write access to data of the associated type)OMNI_BIND_RAW_");
return e;
}
auto bindeAccessLocation(py::module& m)
{
py::enum_<omni::graph::core::eAccessLocation> e(
m, "eAccessLocation", R"OMNI_BIND_RAW_(What type of non-attribute data does this node access)OMNI_BIND_RAW_");
e.value("E_USD", omni::graph::core::eAccessLocation::eUsd,
R"OMNI_BIND_RAW_(Accesses the USD stage data)OMNI_BIND_RAW_");
e.value("E_GLOBAL", omni::graph::core::eAccessLocation::eGlobal,
R"OMNI_BIND_RAW_(Accesses data that is not part of the node or node type)OMNI_BIND_RAW_");
e.value("E_STATIC", omni::graph::core::eAccessLocation::eStatic,
R"OMNI_BIND_RAW_(Accesses data that is shared by every instance of a particular node type)OMNI_BIND_RAW_");
e.value("E_TOPOLOGY", omni::graph::core::eAccessLocation::eTopology,
R"OMNI_BIND_RAW_(Accesses information on the topology of the graph to which the node belongs)OMNI_BIND_RAW_");
return e;
}
auto bindeThreadSafety(py::module& m)
{
py::enum_<omni::graph::core::eThreadSafety> e(
m, "eThreadSafety", R"OMNI_BIND_RAW_(How thread safe is the node during evaluation)OMNI_BIND_RAW_");
e.value("E_SAFE", omni::graph::core::eThreadSafety::eSafe,
R"OMNI_BIND_RAW_(Nodes can be evaluated in multiple threads safely)OMNI_BIND_RAW_");
e.value("E_UNSAFE", omni::graph::core::eThreadSafety::eUnsafe,
R"OMNI_BIND_RAW_(Nodes cannot be evaluated in multiple threads safely)OMNI_BIND_RAW_");
e.value("E_UNKNOWN", omni::graph::core::eThreadSafety::eUnknown,
R"OMNI_BIND_RAW_(The thread safety status of the node type is unknown)OMNI_BIND_RAW_");
return e;
}
auto bindeComputeRule(py::module& m)
{
py::enum_<omni::graph::core::eComputeRule> e(
m, "eComputeRule", R"OMNI_BIND_RAW_(How the node is allowed to be computed)OMNI_BIND_RAW_");
e.value("E_DEFAULT", omni::graph::core::eComputeRule::eDefault,
R"OMNI_BIND_RAW_(Nodes are computed according to the default evaluator rules)OMNI_BIND_RAW_");
e.value(
"E_ON_REQUEST", omni::graph::core::eComputeRule::eOnRequest,
R"OMNI_BIND_RAW_(The evaluator may skip computing this node until explicitly requested with INode::requestCompute)OMNI_BIND_RAW_");
return e;
}
auto bindISchedulingHints(py::module& m)
{
// hack around pybind11 issues with C++17
// - https://github.com/pybind/pybind11/issues/2234
// - https://github.com/pybind/pybind11/issues/2666
// - https://github.com/pybind/pybind11/issues/2856
py::class_<omni::core::Generated<omni::graph::core::ISchedulingHints_abi>,
omni::python::detail::PyObjectPtr<omni::core::Generated<omni::graph::core::ISchedulingHints_abi>>,
omni::core::IObject>
clsParent(m, "_ISchedulingHints");
py::class_<omni::graph::core::ISchedulingHints, omni::core::Generated<omni::graph::core::ISchedulingHints_abi>,
omni::python::detail::PyObjectPtr<omni::graph::core::ISchedulingHints>, omni::core::IObject>
cls(m, "ISchedulingHints",
R"OMNI_BIND_RAW_(Interface to the list of scheduling hints that can be applied to a node type)OMNI_BIND_RAW_");
cls.def(py::init(
[](const omni::core::ObjectPtr<omni::core::IObject>& obj)
{
auto tmp = omni::core::cast<omni::graph::core::ISchedulingHints>(obj.get());
if (!tmp)
{
throw std::runtime_error("invalid type conversion");
}
return tmp;
}));
cls.def(py::init(
[]()
{
auto tmp = omni::core::createType<omni::graph::core::ISchedulingHints>();
if (!tmp)
{
throw std::runtime_error("unable to create omni::graph::core::ISchedulingHints instantiation");
}
return tmp;
}));
cls.def_property("thread_safety", &omni::graph::core::ISchedulingHints::getThreadSafety,
&omni::graph::core::ISchedulingHints::setThreadSafety);
cls.def_property("compute_rule", &omni::graph::core::ISchedulingHints::getComputeRule,
&omni::graph::core::ISchedulingHints::setComputeRule);
cls.def("get_data_access", &omni::graph::core::ISchedulingHints::getDataAccess,
R"OMNI_BIND_RAW_(Get the type of access the node has for a given data type
@param[in] dataType Type of data for which access type is being modified
@returns Value of the access type flag)OMNI_BIND_RAW_",
py::arg("data_type"));
cls.def("set_data_access", &omni::graph::core::ISchedulingHints::setDataAccess,
R"OMNI_BIND_RAW_(Set the flag describing how a node accesses particular data in its compute _abi (defaults to no access).
Setting any of these flags will, in most cases, automatically mark the node as "not threadsafe".
One current exception to this is allowing a node to be both threadsafe and a writer to USD, since
such behavior can be achieved if delayed writebacks (e.g. "registerForUSDWriteBack") are utilized
in the node's compute method.
@param[in] dataType Type of data for which access type is being modified
@param[in] newAccessType New value of the access type flag)OMNI_BIND_RAW_",
py::arg("data_type"), py::arg("new_access_type"));
cls.def("inspect",
[](omni::graph::core::ISchedulingHints* self, omni::inspect::IInspector* inspector)
{
auto return_value = self->inspect(inspector);
return return_value;
},
R"OMNI_BIND_RAW_(Runs the inspector on the scheduling hints.
@param[in] inspector The inspector class
@return true if the inspection ran successfully, false if the inspection type is not supported)OMNI_BIND_RAW_",
py::arg("inspector"));
return omni::python::PyBind<omni::graph::core::ISchedulingHints>::bind(cls);
}
| 7,462 | C | 49.425675 | 139 | 0.664969 |
omniverse-code/kit/include/omni/graph/core/ConstBundlePrimsImpl.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "ConstBundlePrims.h"
#include <omni/graph/core/CppWrappers.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/ComputeGraph.h>
#include <algorithm>
namespace omni
{
namespace graph
{
namespace core
{
// ====================================================================================================
//
// Const Bundle Primitive
//
// ====================================================================================================
inline ConstBundlePrim::ConstBundlePrim(ConstBundlePrims& bundlePrims, omni::core::ObjectPtr<IConstBundle2> bundle)
: m_bundlePrims{ &bundlePrims }, m_bundle{ std::move(bundle) }
{
// Read and cache all non internal attributes.
readAndCacheAttributes();
const detail::AttrDefinition& primIndexDef = detail::getPrimIndexDefinition();
m_primIndexAttr = getConstBundlePtr()->getConstBundleMetadataByName(primIndexDef.token);
}
inline ConstBundleHandle ConstBundlePrim::getConstHandle() noexcept
{
return m_bundle->getConstHandle();
}
inline void ConstBundlePrim::readAndCacheAttributes() noexcept
{
IConstBundle2* bundle = getConstBundlePtr();
GraphContextObj const& context = getConstBundlePrims()->context();
std::vector<ConstAttributeDataHandle> attrHandles(bundle->getAttributeCount());
bundle->getConstAttributes(attrHandles.data(), attrHandles.size());
auto& attrs = getAttributes();
for(ConstAttributeDataHandle& attrHandle : attrHandles)
{
if(!attrHandle.isValid())
continue;
NameToken attrName = context.iAttributeData->getName(context, attrHandle);
attrs.insert(std::make_pair(attrName, std::make_unique<BundleAttrib>(*this, attrName)));
}
}
inline BundleAttrib const* ConstBundlePrim::getConstAttr(core::NameToken attrName) noexcept
{
// Try to find cached attributes
auto& attrMap = getAttributes();
auto it = attrMap.find(attrName);
if (it != attrMap.end())
{
return it->second.get();
}
// Try to find attribute in this bundle.
IConstBundle2* bundle = getConstBundlePtr();
ConstAttributeDataHandle attributeHandle = bundle->getConstAttributeByName(attrName);
if (!attributeHandle.isValid())
{
// attribute is not found, ensure entry is removed from the cache.
auto it = attrMap.find(attrName);
if (it != attrMap.end())
{
attrMap.erase(it);
}
return nullptr;
}
// Check if attribute in the bundle is stale
auto newPrimAttribute = new BundleAttrib{ *this, attrName};
std::unique_ptr<BundleAttrib> primAttributePtr{ newPrimAttribute };
attrMap.emplace(attrName, std::move(primAttributePtr));
return newPrimAttribute;
}
inline BundleAttrib const* ConstBundlePrim::getAttr(NameToken attrName) const noexcept
{
return const_cast<ConstBundlePrim*>(this)->getConstAttr(attrName);
}
inline size_t ConstBundlePrim::attrCount() noexcept
{
return getAttributes().size();
}
inline BundlePrimIndex ConstBundlePrim::primIndex() noexcept
{
if (m_primIndexAttr.isValid())
{
ConstBundlePrims* bundlePrims = getConstBundlePrims();
return *getDataR<BundlePrimIndex>(bundlePrims->context(), m_primIndexAttr);
}
return kInvalidBundlePrimIndex;
}
inline NameToken ConstBundlePrim::path() noexcept
{
if (!m_pathAttr.isValid())
{
const detail::AttrDefinition& attrDef = detail::getPrimPathDefinition();
m_pathAttr = getConstBundlePtr()->getConstAttributeByName(attrDef.token);
}
NameToken result = omni::fabric::kUninitializedToken;
if (m_pathAttr.isValid())
{
ConstBundlePrims* bundlePrims = getConstBundlePrims();
result = *getDataR<NameToken>(bundlePrims->context(), m_pathAttr);
}
return result;
}
inline NameToken ConstBundlePrim::path() const noexcept
{
return const_cast<ConstBundlePrim*>(this)->path();
}
inline NameToken ConstBundlePrim::type() noexcept
{
if (!m_typeAttr.isValid())
{
const detail::AttrDefinition& attrDef = detail::getPrimTypeDefinition();
m_typeAttr = getConstBundlePtr()->getConstAttributeByName(attrDef.token);
}
NameToken result = omni::fabric::kUninitializedToken;
if (m_typeAttr.isValid())
{
ConstBundlePrims* bundlePrims = getConstBundlePrims();
result = *getDataR<NameToken>(bundlePrims->context(), m_typeAttr);
}
return result;
}
inline NameToken ConstBundlePrim::type() const noexcept
{
return const_cast<ConstBundlePrim*>(this)->type();
}
inline DirtyIDType ConstBundlePrim::dirtyID() noexcept
{
auto id = carb::getCachedInterface<ComputeGraph>()->getDirtyIDInterfacePtr(m_bundle->getContext());
return id->getForBundle(m_bundle->getConstHandle());
}
inline DirtyIDType ConstBundlePrim::dirtyID() const noexcept
{
CARB_IGNOREWARNING_MSC_WITH_PUSH(4996)
CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Wdeprecated-declarations")
return const_cast<ConstBundlePrim*>(this)->dirtyID();
CARB_IGNOREWARNING_GNUC_POP
CARB_IGNOREWARNING_MSC_POP
}
inline ConstBundlePrims* ConstBundlePrim::getConstBundlePrims() noexcept
{
return m_bundlePrims;
}
inline ConstBundlePrimAttrIterator ConstBundlePrim::begin() noexcept
{
return ConstBundlePrimAttrIterator(*this, getAttributes().begin());
}
inline ConstBundlePrimAttrIterator ConstBundlePrim::end() noexcept
{
return ConstBundlePrimAttrIterator(*this, getAttributes().end());
}
inline ConstBundlePrimAttrIterator ConstBundlePrim::begin() const noexcept
{
ConstBundlePrim& thisPrim = const_cast<ConstBundlePrim&>(*this);
return ConstBundlePrimAttrIterator(thisPrim, thisPrim.getAttributes().begin());
}
inline ConstBundlePrimAttrIterator ConstBundlePrim::end() const noexcept
{
ConstBundlePrim& thisPrim = const_cast<ConstBundlePrim&>(*this);
return ConstBundlePrimAttrIterator(thisPrim, thisPrim.getAttributes().end());
}
inline IConstBundle2* ConstBundlePrim::getConstBundlePtr() noexcept
{
return m_bundle.get();
}
inline ConstBundlePrim::BundleAttributeMap& ConstBundlePrim::getAttributes() noexcept
{
return m_attributes;
}
// ====================================================================================================
//
// Const Bundle Primitives
//
// ====================================================================================================
inline ConstBundlePrims::ConstBundlePrims()
{
}
inline ConstBundlePrims::ConstBundlePrims(GraphContextObj const& context,
ConstBundleHandle const& bundle)
: ConstBundlePrims()
{
attach(context, bundle);
}
inline void ConstBundlePrims::detach() noexcept
{
m_primitives.clear();
m_commonAttributes.reset();
m_context = GraphContextObj{};
m_bundle.release();
m_factory.release();
}
inline ConstBundlePrims::BundlePrimArray& ConstBundlePrims::getPrimitives() noexcept
{
return m_primitives;
}
inline ConstBundleHandle ConstBundlePrims::getConstHandle() noexcept
{
return m_bundle->getConstHandle();
}
template <typename FUNC>
ConstBundlePrim* ConstBundlePrims::getConstPrim(BundlePrimIndex primIndex, FUNC createSortedBundlePrims) noexcept
{
// Return invalid const bundle prim if out of bounds.
size_t const bundlePrimCount = getPrimCount();
if (primIndex >= bundlePrimCount)
{
return nullptr;
}
auto& prims = getPrimitives();
// HDC_TODO: we need a clear signal to be sure when creation and resorting is required.
if (prims.size() != bundlePrimCount)
{
prims = std::move(createSortedBundlePrims());
CARB_ASSERT(bundlePrimCount == (size_t)std::count_if(prims.cbegin(), prims.cend(), [](const auto& p) { return p.get(); }));
}
return prims[primIndex].get();
}
inline ConstBundlePrim* ConstBundlePrims::getPrim(BundlePrimIndex primIndex) noexcept
{
return getConstPrim(primIndex);
}
inline ConstBundlePrim* ConstBundlePrims::getConstPrim(BundlePrimIndex primIndex) noexcept
{
auto createSortedBundlePrims = [this, &bundlePrims = *this]() -> BundlePrimArray
{
const size_t childBundleCount = getConstBundlePtr()->getChildBundleCount();
std::vector<ConstBundleHandle> handles(childBundleCount);
getConstBundlePtr()->getConstChildBundles(handles.data(), handles.size());
const GraphContextObj& graphContext = context();
BundlePrimArray prims(childBundleCount);
BundlePrimArray nonIndexedPrims;
for (ConstBundleHandle& handle : handles)
{
auto childBundle = getBundleFactoryPtr()->getConstBundle(graphContext, handle);
ConstBundlePrim* prim = new ConstBundlePrim(bundlePrims, childBundle);
BundlePrimIndex index = prim->primIndex();
CARB_ASSERT(index < childBundleCount || index == kInvalidBundlePrimIndex);
if (index < childBundleCount)
{
prims[index].reset(prim);
}
else
{
nonIndexedPrims.emplace_back(prim);
}
}
// Merge non-indexed prims into the sorted array.
if (!nonIndexedPrims.empty())
{
BundlePrimIndex index = 0;
for (ConstBundlePrimPtr& nonIndexedPrim : nonIndexedPrims)
{
while (index < childBundleCount)
{
ConstBundlePrimPtr& prim = prims[index++];
if (!prim)
{
prim = std::move(nonIndexedPrim);
break;
}
}
}
}
return prims;
};
return getConstPrim(primIndex, createSortedBundlePrims);
}
inline DirtyIDType ConstBundlePrims::getBundleDirtyID() noexcept
{
CARB_IGNOREWARNING_MSC_WITH_PUSH(4996)
CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Wdeprecated-declarations")
return getCommonAttrs().dirtyID();
CARB_IGNOREWARNING_GNUC_POP
CARB_IGNOREWARNING_MSC_POP
}
inline ConstBundlePrim& ConstBundlePrims::getConstCommonAttrs() noexcept
{
return *m_commonAttributes;
}
inline GraphContextObj const& ConstBundlePrims::context() noexcept
{
if (m_bundle)
{
m_context = m_bundle->getContext();
}
else
{
m_context = GraphContextObj{};
}
return m_context;
}
inline void ConstBundlePrims::attach(GraphContextObj const& context,
ConstBundleHandle const& bundleHandle) noexcept
{
ComputeGraph* computeGraph = carb::getCachedInterface<ComputeGraph>();
omni::core::ObjectPtr<IBundleFactory> factory = computeGraph->getBundleFactoryInterfacePtr();
omni::core::ObjectPtr<IConstBundle2> bundle = factory->getConstBundle(context, bundleHandle);
attach(std::move(factory), std::move(bundle));
}
inline void ConstBundlePrims::attach(omni::core::ObjectPtr<IBundleFactory>&& factoryPtr,
omni::core::ObjectPtr<IConstBundle2>&& bundlePtr) noexcept
{
// Initialize members
m_factory = std::move(factoryPtr);
m_bundle = std::move(bundlePtr);
// Initialize common attributes to provide access to ConstBundlePrims attributes.
m_commonAttributes.reset(new ConstBundlePrim(*this, m_bundle));
if (!m_bundle->isValid())
{
return;
}
// TODO: Following code is necessary for backward compatibility.
IConstBundle2* bundle = getConstBundlePtr();
GraphContextObj const& context = this->context();
}
inline IBundleFactory* ConstBundlePrims::getBundleFactoryPtr() noexcept
{
return m_factory.get();
}
inline IConstBundle2* ConstBundlePrims::getConstBundlePtr() noexcept
{
return m_bundle.get();
}
inline size_t ConstBundlePrims::getPrimCount() noexcept
{
if (IConstBundle2* bundle = getConstBundlePtr())
{
return bundle->getChildBundleCount();
}
return 0;
}
inline ConstBundlePrimIterator ConstBundlePrims::begin() noexcept
{
return ConstBundlePrimIterator(*this);
}
inline ConstBundlePrimIterator ConstBundlePrims::end() noexcept
{
return ConstBundlePrimIterator(*this, getPrimCount());
}
/***********************************************************************************************
*
* TODO: Following methods might be deprecated in the future, but are kept for backward compatibility.
* In the next iteration when real interface starts to emerge, we can retire those methods.
*
***********************************************************************************************/
inline ConstBundlePrim& ConstBundlePrims::getCommonAttrs() noexcept
{
return getConstCommonAttrs();
}
inline ConstBundleHandle ConstBundlePrims::handle() noexcept
{
return m_bundle->getConstHandle();
}
inline void ConstBundlePrims::separateAttrs() noexcept
{
// There is nothing to separate. This function is deprecated.
}
inline void ConstBundlePrims::ensurePrimAttrsCached(BundlePrimIndex primIndex) noexcept
{
// Responsibility of caching attributes was moved to Bundle Prim.
}
// ====================================================================================================
//
// Const Bundle Primitive Iterator
//
// ====================================================================================================
inline ConstBundlePrimIterator::ConstBundlePrimIterator(ConstBundlePrims& bundlePrims, BundlePrimIndex primIndex) noexcept
: m_bundlePrims(&bundlePrims), m_primIndex(primIndex)
{
}
inline bool ConstBundlePrimIterator::operator==(ConstBundlePrimIterator const& that) const noexcept
{
return m_bundlePrims == that.m_bundlePrims && m_primIndex == that.m_primIndex;
}
inline bool ConstBundlePrimIterator::operator!=(ConstBundlePrimIterator const& that) const noexcept
{
return !(*this == that);
}
inline ConstBundlePrim& ConstBundlePrimIterator::operator*() noexcept
{
return *(m_bundlePrims->getConstPrim(m_primIndex));
}
inline ConstBundlePrim* ConstBundlePrimIterator::operator->() noexcept
{
return m_bundlePrims->getConstPrim(m_primIndex);
}
inline ConstBundlePrimIterator& ConstBundlePrimIterator::operator++() noexcept
{
++m_primIndex;
return *this;
}
// ====================================================================================================
//
// Const Bundle Primitive Attribute Iterator
//
// ====================================================================================================
inline ConstBundlePrimAttrIterator::ConstBundlePrimAttrIterator(ConstBundlePrim& bundlePrim, ConstBundlePrim::AttrMapIteratorType attrIter) noexcept
: m_bundlePrim(&bundlePrim), m_attrIter(attrIter)
{
}
inline bool ConstBundlePrimAttrIterator::operator==(ConstBundlePrimAttrIterator const& that) const noexcept
{
return m_bundlePrim == that.m_bundlePrim && m_attrIter == that.m_attrIter;
}
inline bool ConstBundlePrimAttrIterator::operator!=(ConstBundlePrimAttrIterator const& that) const noexcept
{
return !(*this == that);
}
inline BundleAttrib const& ConstBundlePrimAttrIterator::operator*() const noexcept
{
CARB_ASSERT(m_attrIter->second);
return *(m_attrIter->second);
}
inline BundleAttrib const*ConstBundlePrimAttrIterator:: operator->() const noexcept
{
CARB_ASSERT(m_attrIter->second);
return m_attrIter->second.get();
}
inline ConstBundlePrimAttrIterator& ConstBundlePrimAttrIterator::operator++() noexcept
{
++m_attrIter;
return *this;
}
} // namespace core
} // namespace graph
} // namespace omni
| 16,127 | C | 29.545454 | 148 | 0.655671 |
omniverse-code/kit/include/omni/graph/core/IGatherPrototype.h | // 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.
//
#pragma once
#include <carb/flatcache/IFlatcache.h>
#include <omni/graph/core/iComputeGraph.h>
#include <tuple>
namespace carb
{
namespace flatcache
{
using ArrayIndex = size_t;
}
}
namespace omni {
namespace graph {
namespace core {
// ====================================================================================================
// This is a temporary ABI interface used for prototyping the use of improved Gather. Some of these functions
// may move to other interfaces once the prototyping is complete. For now, none of them should be used outside
// of the prototyping efforts.
/* _____ _ _ _ _ _
| __ \ | \ | | | | | | | |
| | | | ___ | \| | ___ | |_ | | | |___ ___
| | | |/ _ \ | . ` |/ _ \| __| | | | / __|/ _ \
| |__| | (_) | | |\ | (_) | |_ | |__| \__ \ __/
|_____/ \___/ |_| \_|\___/ \__| \____/|___/\___|
*/
using PathBucketIndex = std::tuple<carb::flatcache::PathC, carb::flatcache::BucketId, carb::flatcache::ArrayIndex>;
using GatherId = uint64_t;
static constexpr GatherId kInvalidGatherId = 0;
/**
* Gathered attributes can be automatically converted and copied to Hydra fast-path attributes
*/
enum class GatherAddTransformsMode
{
eNone, ///< do not add any attributes
eLocal, ///< _localTransform
eWorld ///< _worldPosition, _worldOrientation, _worldScale
};
struct IGatherPrototype
{
CARB_PLUGIN_INTERFACE("omni::graph::core::IGatherPrototype", 2, 0);
/**
* Adds the given paths to FC and updates the FC sync filter for this Graph. The prims may be tagged to ensure
* the buckets do not contain unrelated prims. The returned GatherId identifies the FC buckets.
*
* After this call, the given paths will be present in FC, in a set of buckets which contain only these paths. This
* is necessary to allow vectorized access to an attribute.
*
* @note The order of the paths supplied to this function may not be the order of the same paths in the Gather. Use
* getGatheredPaths() to get the gather-order of gathered prims.
*
* @note The returned GatherId can become invalidated if the underlying flatcache data changes, use isGatherValid()
* to check.
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] paths array of prim paths to add
* @param[in] numPaths number of elements in paths
* @param[in] allAttributes when true, all USD attributes will be gathered. When false, the "attributes" parameter
* is used.
* @param[in] attributes array of attribute names to add to FC, when allAttributes is false
* @param[in] numAttributes number of elements in attributes array
* @param[in] addTransformsMode The transform attributes to create if any
* @param[in] shouldWriteBack Flag to request to write back cached data to USD
* @param[in] forceExportToHistory when true, all gathered paths will be tagged for being exported into the history
*
* @return The gather id corresponding to the gathered buckets, or kInvalidGatherId on failure.
*/
GatherId(CARB_ABI* gatherPaths)(const GraphContextObj&,
const carb::flatcache::PathC* paths,
size_t numPaths,
bool allAttributes,
NameToken const* attributes,
size_t numAttributes,
GatherAddTransformsMode addTransformsMode,
bool shouldWriteBack,
bool forceExportToHistory);
/**
* Gets the array of paths in the given Gather, in gather order.
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] gatherId The Gather id returned from gatherPaths()
* @param[out] refToPaths reference to the array of prim paths, in gather-order. This pointer is volatile, do not
* save. It can become invalid the next time something changes in flatcache.
* @param[out] refToSize number of elements in refToPaths
*
* @return true if the Gather was found, false if it was not
*/
bool (CARB_ABI*getGatheredPaths)(const GraphContextObj&, GatherId gatherId,
carb::flatcache::PathC const*& refToPaths, size_t& refToSize);
/**
* Gets the array of buckets in the given Gather, in gather order.
* For example if the gathered paths are P1,P2,P3,P4 which spans bucket B1, B2, we know that the sum of the
* sizes of B1 and B2 must be 4. If B1 has 2 entries we know where the paths are located:
*
* B1
* row 0: P1
* row 1: P2
*
* B2
* row 0: P3
* row 1: P4
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] gatherId The Gather id returned from gatherPaths()
* @param[out] refToBucketArray reference to the array of BucketIds, in gather-order. This pointer is volatile, do not
* save. It can become invalid the next time something changes in flatcache.
* @param[out] refToSize number of elements in refToBucketArray
*
* @return true if the Gather was found, false if it was not
*/
bool(CARB_ABI* getGatheredBuckets)(const GraphContextObj&,
GatherId gatherId,
BucketId const*& refToBucketArray,
size_t& refToSize);
/**
* Gets the size information for the given gathered attribute name.
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] gatherId The Gather id returned from gatherPaths()
* @param[in] attributeName name of the gathered attribute
* @param[out] type The type information
* @param[out] baseSizeBytes The size of the base elements of the Type
* FIXME: Should be accessible from flatcache ABI?
* @return true if the attribute was found, false if it was not
*/
bool(CARB_ABI* getGatheredType)(const GraphContextObj&, GatherId gatherId, NameToken attributeName, Type& type, size_t& baseSizeBytes);
// ==============================================================================================================
// The functions below here are temporary replacements for the same functions removed from IGraphContext. They
// were being modified to use attributes, causing a breaking change, and since they were going to be changed anyway
// they were moved to this prototype for easier update later.
// ==============================================================================================================
/**
* Given an attribute connected to a gather node, retrieves the attribute value in system memory
* Deprecated: to be replaced with the 2.0 API soon
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] attrObj The attribute structure to which the operation applies
* @param[in] flags The data access flags indicating whether the data is to be R, W, or RW
* @return the void pointer to the data
*/
void*(CARB_ABI* getGatherArray)(const GraphContextObj& context, const AttributeObj& attrObj, DataAccessFlags flags);
/**
* Given an attribute connected to a gather node, retrieves the attribute value in GPU memory
* Deprecated: to be replaced with the 2.0 API soon
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] attrObj The attribute structure to which the operation applies
* @param[in] flags The data access flags indicating whether the data is to be R, W, or RW
* @return the void pointer to the data
*/
void*(CARB_ABI* getGatherArrayGPU)(const GraphContextObj& context, const AttributeObj& attrObj, DataAccessFlags flags);
/**
* Given an attribute connected to a gather node, retrieves the array of the paths it has gathered
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] attrObj The source attribute structure. This can be any of the gather node's attributes.
* @return the pointer to the path array, encoded as uint64_t. These integers can be cast to SdfPaths.
*/
const uint64_t*(CARB_ABI* getGatherPathArray)(const GraphContextObj& context, const AttributeObj& attrObj);
/**
* Given an array attribute in a gather node, retrieves an array of the array sizes in CPU memory
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] attrObj The source attribute structure.
* @param[in] flags The data access flags indicating whether the data is to be R, W, or RW
* @return the pointer to the array
*/
size_t*(CARB_ABI* getGatherArrayAttributeSizes)(const GraphContextObj& context,
const AttributeObj& attrObj,
DataAccessFlags flags);
/**
* Given an array attribute in a gather node, retrieves an array of the array sizes in GPU memory
* Deprecated: to be replaced with the 2.0 API soon
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] attrObj The source attribute structure.
* @param[in] flags The data access flags indicating whether the data is to be R, W, or RW
* @return the pointer to the array
*/
size_t*(CARB_ABI* getGatherArrayAttributeSizesGPU)(const GraphContextObj& context,
const AttributeObj& attrObj,
DataAccessFlags flags);
/**
* Given a gather node attribute, retrieves the number of elements
* Deprecated: to be replaced with the 2.0 API soon
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] attrObj The attribute structure to which the operation applies
* @return the number of elements gathered, -1 if operation is unsuccessful
*/
size_t(CARB_ABI* getElementCount)(const GraphContextObj& context, const AttributeObj& attrObj);
/**
* Gets the array of repeated paths and where to find its data in the given Gather.
* Each element in the array will have the path of the prim, the bucket id of it's data, and the index of its position inside the bucket
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] gatherId The Gather id returned from gatherPaths()
* @param[out] refToRepeatedPathsArray reference to the array of PathBucketIndex which outlines the location of the
* data for repeated paths in the gater. This pointer is volatile, do not
* save. It can become invalid the next time something changes in flatcache.
* @param[out] refToSize number of elements in refToRepeatedPathsArray
*
* @return true if the Gather was found, false if it was not
*/
bool(CARB_ABI* getGatheredRepeatedPaths)(const GraphContextObj&,
GatherId gatherId,
PathBucketIndex const*& refToRepeatedPathsArray,
size_t& refToSize);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IGatherPrototype, getGatheredRepeatedPaths, 10)
} // namespace core
} // namespace graph
} // namespace omni
| 12,354 | C | 50.053719 | 140 | 0.635017 |
omniverse-code/kit/include/omni/graph/core/CudaUtils.h | // 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.
//
#pragma once
// This file contains support for CUDA or CUDA/C++ common code
// TODO: find out how to assert in CUDA
#ifndef __CUDACC__
# define CUDA_SAFE_ASSERT(cond, ...) CARB_ASSERT(cond, ##__VA_ARGS__)
# define CUDA_CALLABLE
#else
# define CUDA_SAFE_ASSERT(cond, ...)
# define CUDA_CALLABLE __device__ __host__
#endif
| 770 | C | 35.714284 | 77 | 0.735065 |
omniverse-code/kit/include/omni/graph/core/NodeTypeRegistrar.h | // 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.
//
#pragma once
#include "iComputeGraph.h"
#include <carb/Framework.h>
#include <iostream>
#include <type_traits>
//====================================================================================================
//
// Node type registration is handled through this set of classes. The implementation is geared towards simplifying
// the registration process as much as possible. All of this is support code for the macro "REGISTER_OGN_NODE()",
// which you place at the bottom of your .ogn file.
//
//====================================================================================================
namespace omni
{
namespace graph
{
namespace core
{
// If a node type version is not specified then it gets this value.
// Keep in sync with DEFAULT_NODE_TYPE_VERSION_DEFAULT in omni.graph.core/python/tests/omnigraph_test_utils.py
static constexpr int kDefaultNodeTypeVersion = 1;
// See this file for how to handle new methods added to the iNodeType interface.
#define NODE_TYPE_REGISTRY // For inclusion protection
#include "NodeTypeRegistryTemplates.h"
// Scoped node registration helper class. Used by the NodeTypeRegistrar to pass in node methods for the
// INodeType ABI, keeping the node type registered for the lifetime of the instantiated object. Only one
// registration object can exist per node type so copy methods are deleted in favour of their move equivalents.
class NodeTypeRegistration
{
public:
// Direct access to the interface, for the manual registration modes
const INodeType& nodeTypeInterface() const
{
return m_interface;
}
// Direct access to the version, for the manual registration modes
const int nodeTypeVersion() const
{
return m_versionNumber;
}
// Move constructor allows passing of registration information through return values without double
// register/unregister
NodeTypeRegistration(NodeTypeRegistration&& rhs) noexcept
{
m_interface = rhs.m_interface;
m_versionNumber = rhs.m_versionNumber;
rhs.m_interface = INodeType{};
rhs.m_versionNumber = kDefaultNodeTypeVersion;
}
// Move operator allows passing of registration information through return values without double register/unregister
NodeTypeRegistration& operator=(NodeTypeRegistration&& rhs) noexcept
{
m_interface = rhs.m_interface;
m_versionNumber = rhs.m_versionNumber;
rhs.m_interface = INodeType{};
rhs.m_versionNumber = kDefaultNodeTypeVersion;
return *this;
}
// Only available constructor takes in the four methods required by the INodeType API and registers
// the node type using that interface. Only the name function is remembered for later unregistration.
NodeTypeRegistration(GetNodeTypeFunction nameFn,
ComputeFunction computeFn,
InitializeFunction initializeFn,
ReleaseFunction releaseFn,
InitializeTypeFunction initializeTypeFn,
UpdateNodeVersionFunction updateNodeVersionFn,
AddInputFunction addInputFn,
AddExtendedInputFunction addExtendedInputFn,
AddOutputFunction addOutputFn,
AddExtendedOutputFunction addExtendedOutputFn,
AddStateFunction addStateFn,
AddExtendedStateFunction addExtendedStateFn,
HasStateFunction hasStateFn,
RegisterTasksFunction registerTasksFn,
GetAllMetadataFunction getAllMetadataFn,
GetMetadataFunction getMetadataFn,
GetMetadataCountFunction getMetadataCountFn,
SetMetadataFunction setMetadataFn,
GetScheduleNodeCountFunction getScheduleNodeCountFn,
GetScheduleNodesFunction getScheduleNodesFn,
OnConnectionTypeResolveFunction onConnectionTypeResolveFn,
InspectFunction inspectFn,
ComputeVectorizedFunction computeVectorized,
ReleaseInstanceFunction releaseInstance,
int versionNumber)
{
m_versionNumber = versionNumber;
m_interface.addInput = addInputFn;
m_interface.addExtendedInput = addExtendedInputFn;
m_interface.addOutput = addOutputFn;
m_interface.addExtendedOutput = addExtendedOutputFn;
m_interface.addState = addStateFn;
m_interface.addExtendedState = addExtendedStateFn;
m_interface.compute = computeFn;
m_interface.getNodeType = nameFn;
m_interface.getScheduleNodes = getScheduleNodesFn;
m_interface.getScheduleNodeCount = getScheduleNodeCountFn;
m_interface.hasState = hasStateFn;
m_interface.initialize = initializeFn;
m_interface.initializeType = initializeTypeFn;
m_interface.registerTasks = registerTasksFn;
m_interface.getAllMetadata = getAllMetadataFn;
m_interface.getMetadata = getMetadataFn;
m_interface.getMetadataCount = getMetadataCountFn;
m_interface.setMetadata = setMetadataFn;
m_interface.release = releaseFn;
m_interface.updateNodeVersion = updateNodeVersionFn;
m_interface.onConnectionTypeResolve = onConnectionTypeResolveFn;
m_interface.inspect = inspectFn;
m_interface.computeVectorized = computeVectorized;
m_interface.releaseInstance = releaseInstance;
m_interface.getCarbABIVersion = []() { return INodeType::getInterfaceDesc().version; };
}
// Node registrations must be unique
NodeTypeRegistration() = delete;
NodeTypeRegistration(const NodeTypeRegistration&) = delete;
NodeTypeRegistration& operator=(const NodeTypeRegistration&) = delete;
private:
INodeType m_interface = {}; // Interface created for this node type
int m_versionNumber{ kDefaultNodeTypeVersion }; // Node type's registered version number
};
// Template class from which nodes can derive to automate their registration.
//
template <typename T>
class NodeTypeRegistrar
{
static const char* s_nodeTypeName; // Name used if the node does not have a getNodeTypeName method
public:
// Register the node type, returning a scoped registration object. Your node type will be registered and
// available for the lifetime of the returned object.
static NodeTypeRegistration registerNode(const char* name,
int versionNumber,
InitializeTypeFunction initializeTypeOverride)
{
s_nodeTypeName = name;
auto nodeTypeNameGetter = getNodeTypeFunction<T>();
if (!nodeTypeNameGetter)
{
nodeTypeNameGetter = &getNodeTypeName;
}
return std::move(NodeTypeRegistration(
nodeTypeNameGetter, computeFunction<T>(), initializeFunction<T>(), releaseFunction<T>(),
initializeTypeOverride ? initializeTypeOverride : initializeTypeFunction<T>(),
updateNodeVersionFunction<T>(), addInputFunction<T>(), addExtendedInputFunction<T>(),
addOutputFunction<T>(), addExtendedOutputFunction<T>(), addStateFunction<T>(), addExtendedStateFunction<T>(),
hasStateFunction<T>(), registerTasksFunction<T>(), getAllMetadataFunction<T>(), getMetadataFunction<T>(),
getMetadataCountFunction<T>(), setMetadataFunction<T>(), getScheduleNodeCountFunction<T>(), getScheduleNodesFunction<T>(),
onConnectionTypeResolveFunction<T>(), inspectFunction<T>(), computeVectorizedFunction<T>(), releaseInstanceFunction<T>(),
versionNumber));
}
static const char* getNodeTypeName()
{
return s_nodeTypeName;
}
};
// When the template instantiates the class it will also instantiate this static member
template <typename NodeType>
const char* NodeTypeRegistrar<NodeType>::s_nodeTypeName{ nullptr };
// Macro that simplifies the syntax of node registration, creating a scoped object for automatic register/unregister
// that can be accessed through the consistently named method "nodeTypeRegistrationMYNODENAME" to call its
// registerNodeType and unregisterNodeType methods at the appropriate time.
#define REGISTER_NODE_TYPE(NODE_CLASS, NODE_TYPE_NAME, NODE_TYPE_VERSION) \
const omni::graph::core::NodeTypeRegistration& nodeTypeRegistration##NODE_CLASS() \
{ \
static omni::graph::core::NodeTypeRegistration s_nodeRegistration{ \
omni::graph::core::NodeTypeRegistrar<NODE_CLASS>::registerNode(NODE_TYPE_NAME, NODE_TYPE_VERSION, nullptr) \
}; \
return s_nodeRegistration; \
}
}
}
}
#define REGISTER_NAMESPACED_NODE_TYPE(NODE_CLASS, NAMESPACE, NODE_TYPE_NAME, NODE_TYPE_VERSION) \
const omni::graph::core::NodeTypeRegistration& nodeTypeRegistration##NODE_CLASS() \
{ \
static omni::graph::core::NodeTypeRegistration s_nodeRegistration{ \
omni::graph::core::NodeTypeRegistrar<NAMESPACE ::NODE_CLASS>::registerNode( \
NODE_TYPE_NAME, NODE_TYPE_VERSION, nullptr) \
}; \
return s_nodeRegistration; \
}
| 10,672 | C | 50.810679 | 134 | 0.619097 |
omniverse-code/kit/include/omni/graph/core/IBundleFactory.gen.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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
template <>
class omni::core::Generated<omni::graph::core::IBundleFactory_abi> : public omni::graph::core::IBundleFactory_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::IBundleFactory")
/**
* Create bundles at given paths and acquire instances of IBundle2 interface.
*
* @param[in] contextObj The context where bundles are created.
* @param[in] paths Locations for new bundles.
* @param[in] pathCount Length of paths array.
* @param[out] createdBundles Output instances of IBundle2 interface.
* @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
* invalid.
*/
omni::core::Result createBundles(const omni::graph::core::GraphContextObj* const contextObj,
const carb::flatcache::PathC* const paths,
size_t pathCount,
omni::graph::core::IBundle2** const createdBundles) noexcept;
/**
* Acquire instances of IConstBundle2 interface from const bundle handles.
*
* @param[in] contextObj The context where bundles belong to.
* @param[in] bundleHandles The bundle handles.
* @param[in] bundleCount Length of bundleHandles array.
* @param[out] bundles Output instances of IConstBundle2 interface.
* @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
* invalid.
*/
omni::core::Result getConstBundles(const omni::graph::core::GraphContextObj* const contextObj,
const omni::graph::core::ConstBundleHandle* const bundleHandles,
size_t bundleCount,
omni::graph::core::IConstBundle2** const bundles) noexcept;
/**
* Acquire instances of IBundle2 interface from bundle handles.
*
* @param[in] contextObj The context where bundles belong to.
* @param[in] bundleHandles The bundle handles.
* @param[in] bundleCount Length of bundleHandles array.
* @param[out] bundles Output instances of IConstBundle2 interface.
* @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
* invalid.
*/
omni::core::Result getBundles(const omni::graph::core::GraphContextObj* const contextObj,
const omni::graph::core::BundleHandle* const bundleHandles,
size_t bundleCount,
omni::graph::core::IBundle2** const bundles) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundleFactory_abi>::createBundles(
const omni::graph::core::GraphContextObj* const contextObj,
const carb::flatcache::PathC* const paths,
size_t pathCount,
omni::graph::core::IBundle2** const createdBundles) noexcept
{
return createBundles_abi(contextObj, paths, pathCount, createdBundles);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundleFactory_abi>::getConstBundles(
const omni::graph::core::GraphContextObj* const contextObj,
const omni::graph::core::ConstBundleHandle* const bundleHandles,
size_t bundleCount,
omni::graph::core::IConstBundle2** const bundles) noexcept
{
return getConstBundles_abi(contextObj, bundleHandles, bundleCount, bundles);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundleFactory_abi>::getBundles(
const omni::graph::core::GraphContextObj* const contextObj,
const omni::graph::core::BundleHandle* const bundleHandles,
size_t bundleCount,
omni::graph::core::IBundle2** const bundles) noexcept
{
return getBundles_abi(contextObj, bundleHandles, bundleCount, bundles);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 4,743 | C | 40.982301 | 114 | 0.684166 |
omniverse-code/kit/include/omni/graph/core/INodeCategories.h | // 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.
//
#pragma once
#include <omni/core/IObject.h>
namespace omni {
namespace graph {
namespace core {
//! Declare the INodeCategories interface definition
OMNI_DECLARE_INTERFACE(INodeCategories);
/** Interface to the list of categories that a node type can belong to */
class INodeCategories_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.INodeCategories")>
{
protected:
/**
* Get the number of categories available
*
* @returns Count of fixed category types
*/
virtual size_t getCategoryCount_abi() noexcept = 0;
/**
* Get the list of available categories and their descriptions.
*
* The caller is responsible for allocating and destroying buffers large enough to hold "bufferSize" results.
* If bufferSize > getCategoryCount() then the entries at the ends of the buffers will be filled with nullptr.
*
* @param[in] categoryNameBuffer List of category names
* @param[in] categoryDescriptionBuffer List of category descriptions corresponding to the names
* @param[in] bufferSize Number of entries to fill in the buffers
*
* @return true if the category buffer was successfully filled and the bufferSize matched the category count
*/
virtual OMNI_ATTR("no_py") bool getCategories_abi(
OMNI_ATTR("*c_str, out, not_null, count=bufferSize") char const** categoryNameBuffer,
OMNI_ATTR("*c_str, out, not_null, count=bufferSize") char const** categoryDescriptionBuffer,
size_t bufferSize
) noexcept = 0;
/**
* Define a new category
*
* @param[in] categoryName Name of the new category
* @param[in] categoryDescription Description of the category
*
* @return false if there was already a category with the given name
*/
virtual bool defineCategory_abi(
OMNI_ATTR("c_str, in, not_null") char const* categoryName,
OMNI_ATTR("c_str, in, not_null") char const* categoryDescription
) noexcept = 0;
/**
* Remove an existing category, mainly to manage the ones created by a node type for itself
*
* @param[in] categoryName Name of the category to remove
*
* @return false if there was no category with the given name
*/
virtual bool removeCategory_abi(
OMNI_ATTR("c_str, in, not_null") char const* categoryName
) noexcept = 0;
};
} // namespace core
} // namespace graph
} // namespace omni
#include "INodeCategories.gen.h" // generated file
| 2,946 | C | 35.382716 | 114 | 0.70095 |
omniverse-code/kit/include/omni/graph/core/iComputeGraph.h | // Copyright (c) 2019-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.
//
#pragma once
#include <carb/events/IEvents.h>
#include <carb/Defines.h>
#include <carb/Interface.h>
#include <carb/Types.h>
#include <omni/fabric/Enums.h>
#include <omni/fabric/IPath.h>
#include <omni/fabric/IToken.h>
#include <omni/graph/core/Type.h>
#include <omni/graph/core/Handle.h>
#include <omni/graph/core/ISchedulingHints2.h>
#include <omni/graph/core/ogn/Types.h>
#include <omni/graph/core/IVariable2.h>
#include <omni/graph/core/iAttributeData.h>
#include <omni/graph/exec/unstable/Stamp.h>
#include <omni/graph/core/bundle/IBundle1.h>
#include <omni/inspect/IInspector.h>
#include <cstddef>
// Interfaces pulled out of this file but which are still referenced through it
#include "IGraphRegistry.h"
#ifdef __CUDA_ARCH__
#error iComputeGraph.h cannot be included from a .cu file due to a compiler problem. You probably want Handle.h.
#endif
namespace omni
{
namespace graph
{
namespace core
{
//! If 1 then extra logging is enabled (which affects performance)
#define COMPUTE_GRAPH_VERBOSE_LOGGING 0
// ==============================================================================================================
/** Encapsulates the information required to define a file format version number */
struct FileFormatVersion
{
int majorVersion; //!< Major version, for which changes mean incompatible formats
int minorVersion; //!< Minor version, for which changes mean compatible formats, possibly with auto-upgrades
/**
* @brief Equality operator for the file format version object
*
* @param rhs Version number to compare against
* @return true The version number is not equal to @p rhs
* @return false The version number is equal to @p rhs
*/
bool operator==(const FileFormatVersion& rhs) const
{
return rhs.majorVersion == majorVersion && rhs.minorVersion == minorVersion;
}
/**
* @brief Inequality operator for the file format version object
*
* @param rhs Version number to compare against
* @return true The version number is not equal to @p rhs
* @return false The version number is equal to @p rhs
*/
bool operator!=(const FileFormatVersion& rhs) const
{
return !(*this==rhs);
}
/**
* @brief Less-than operator for the file format version object
*
* @param rhs Version number to compare against
* @return true The version number is less than @p rhs
* @return false The version number is greater than or equal to @p rhs
*/
bool operator<(const FileFormatVersion& rhs) const
{
return majorVersion < rhs.majorVersion || ((majorVersion == rhs.majorVersion) && (minorVersion < rhs.minorVersion));
}
/**
* @brief Greater-than operator for the file format version object
*
* @param rhs Version number to compare against
* @return true The version number is greater than @p rhs
* @return false The version number is less than or equal to @p rhs
*/
bool operator>(const FileFormatVersion& rhs) const
{
return majorVersion > rhs.majorVersion || ((majorVersion == rhs.majorVersion) && (minorVersion > rhs.minorVersion));
}
};
struct GraphObj;
// ==============================================================================================================
/** Callback object to instantiate for use as a callback when an older version of an OmniGraph file is read */
struct FileFormatUpgrade
{
/**
* Callback function definition. Parameters are
*
* - oldVersion Version of the file being read
* - newVersion Current version of the file format
* - userData User data to pass to the callback
*/
void(*fileFormatUpgradeCallback)(const FileFormatVersion& oldVersion,
const FileFormatVersion& newVersion,
GraphObj& graphObj,
void* userData);
/** User data to pass to the callback function */
void* userData;
/**
* @brief Equality operator for the file format upgrade callback object
*
* @param rhs Callback object to compare against
* @return true The callback object is equal to @p rhs
* @return false The callback object is not equal to @p rhs
*/
bool operator==(const FileFormatUpgrade& rhs) const
{
return rhs.fileFormatUpgradeCallback == fileFormatUpgradeCallback &&
rhs.userData == userData;
}
/**
* @brief Inequality operator for the file format upgrade callback object
*
* @param rhs Callback object to compare against
* @return true The callback object is not equal to @p rhs
* @return false The callback object is equal to @p rhs
*/
bool operator!=(const FileFormatUpgrade& rhs) const
{
return !(*this == rhs);
}
};
// ==============================================================================================================
/**
* @brief Encapsulation of a callback that happens when a node's error status changes
*
*/
struct ErrorStatusChangeCallback
{
/**
* Callback function definition. Parameters are
*
* - nodeList List of nodes whose error status changed since the last compute
* - graphObj Graph to which the nodes belong
* - userData User data to pass to the callback
*/
void (*errorStatusChangeCallback)(const std::vector<NodeObj>& nodeList, GraphObj& graphObj, void* userData);
/** User data to pass to the callback function */
void* userData;
/**
* @brief Equality operator for the error status change callback object
*
* @param rhs Callback object to compare against
* @return true The callback object is equal to @p rhs
* @return false The callback object is not equal to @p rhs
*/
bool operator==(const ErrorStatusChangeCallback& rhs) const
{
return rhs.errorStatusChangeCallback == errorStatusChangeCallback &&
rhs.userData == userData;
}
/**
* @brief Inequality operator for the error status change callback object
*
* @param rhs Callback object to compare against
* @return true The callback object is not equal to @p rhs
* @return false The callback object is equal to @p rhs
*/
bool operator!=(const ErrorStatusChangeCallback& rhs) const
{
return !(*this == rhs);
}
};
// ==============================================================================================================
/** Type of connection between two attributes */
enum ConnectionType
{
kConnectionType_Regular = 0, //!< Normal attribute to attribute evaluation connection
kConnectionType_DataOnly = 1, //!< Data only connection, not implying evaluation
kConnectionType_Execution = 2, //!< Execution type connection, for execution type attributes
kConnectionType_Bundle = 3, //!< Bundle to bundle connections
kConnectionType_PureRelationship = 4 //!< Only establish a relationship, no execution or data passed
};
// ==============================================================================================================
/** Extended type of an attribute */
enum ExtendedAttributeType
{
kExtendedAttributeType_Regular = 0, //!< No extended type, just a normal strongly typed attribute
kExtendedAttributeType_Union = 1, //!< An attribute that could be any one of a specific list of types
kExtendedAttributeType_Any = 2 //!< An attribute that can be any legal type
};
// ==============================================================================================================
/** Port type of an attribute */
enum AttributePortType
{
kAttributePortType_Input = 0, //!< The attribute is an input
kAttributePortType_Output = 1, //!< The attribute is an output
kAttributePortType_State = 2, //!< The attribute holds state information
kAttributePortType_Unknown = 3 //!< The port type is currently unknown
};
// ==============================================================================================================
/**
* The kind of backing for the graph - can be one of FC shared, with history
* or without history. The shared FC means the orchestration graph (the graph
* containing all other graphs as nodes) has a stage with history, and all
* other global level graphs (which are nodes in this orchestration graph) share
* this stage with history FC. The shared FC also applies to subgraphs that share
* the same FC as their parent graph. The stage with history setting is self explanatory
* but note there can only be 1 stage with history currently. The stage without
* history uses a separate FC to house the data for the graph
* The "None" backing type are for orchestration graphs (graphs that hold other graphs
* as nodes) that don't necessarily need a cache to hold "real" data`
*/
enum GraphBackingType
{
kGraphBackingType_FabricShared = 0, //!< Graph backing is a shared copy of Fabric
kGraphBackingType_FabricWithHistory = 1, //!< Use the Fabric instantiation that has history
kGraphBackingType_FabricWithoutHistory = 2, //!< Use the Fabric instantiation that has no retained history
kGraphBackingType_Unknown = 3, //!< Backing type is currently unknown
kGraphBackingType_None = 4, //!< There is no backing for the OmniGraph data
kGraphBackingType_FlatCacheShared = 0, //!< @private Deprecated, use kGraphBackingType_FabricShared
kGraphBackingType_FlatCacheWithHistory = 1, //!< @private Deprecated, use kGraphBackingType_FabricWithHistory
kGraphBackingType_FlatCacheWithoutHistory = 2, //!< @private Deprecated, use kGraphBackingType_FabricWithoutHistory
};
// ==============================================================================================================
/**
* The pipeline stage defines where this graph is going to be used - as part of
* simulation (before rendering), pre-rendering (after sim but before render), or
* post-rendering. Each pipeline stage will have a set of graphs that will
* be run there. We use larger numbers for the enums with spaces in between
* so that other stages can be inserted in the future. The custom pipeline stage
* allows for graphs that can be run at any unknown time.
*/
enum GraphPipelineStage
{
kGraphPipelineStage_Simulation = 10, //!< The simulation phase, a.k.a. normal evaluation
kGraphPipelineStage_PreRender = 20, //!< The preRender phase, run just before Hydra takes over
kGraphPipelineStage_PostRender = 30, //!< The postRender phase, run after Hydra finishes
kGraphPipelineStage_Unknown = 100, //!< The phase is currently unknown
kGraphPipelineStage_OnDemand = 200, //!< The graph evaluates only on demand, not as part of the pipeline
kGraphPipelineStage_Count = 4 //!< The number of existing pipelines
};
// ==============================================================================================================
/**
* The graph evaluation mode specifies whether a graph is intended to self-evaluate,
* or if represents an asset to by evaluated on behalf of a different Prim.
*/
enum class GraphEvaluationMode
{
//! In Automatic mode, the graph is evaluated as Standalone, unless an OmniGraphAPI interface has a relationship to it,
//! in which case it is evaluated as Instanced mode.
Automatic = 0,
//! In Standalone mode, the graph is evaluated once, with itself as the graph target
Standalone = 1,
//! In Instanced mode, the graph is evaluated once for each OmniGraphAPI interface with a relationship to the graph Prim
//! Graphs that are used as assets should use this mode to prevent standalone execution.
Instanced = 2
};
// ==============================================================================================================
/** Information passed to define the opposite end of a connection */
struct ConnectionInfo
{
AttributeObj attrObj; //!< Attribute at the opposite end
ConnectionType connectionType; //!< Type of connection being made
};
// ==============================================================================================================
/** Callback object used when a connection is made or broken between two attributes */
struct ConnectionCallback
{
/**
* Callback function definition. Parameters are
*
* - srcAttr Source end of the connection that changed
* - dstAttr Destination end of the connection that changed
* - userData User data to pass to the callback
*/
void(*connectionCallback)(const AttributeObj& srcAttr, const AttributeObj& dstAttr, void* userData);
/** User data to pass to the callback function */
void* userData;
/**
* @brief Equality operator for the connection/disconnection callback object
*
* @param rhs Callback object to compare against
* @return true The callback object is equal to @p rhs
* @return false The callback object is not equal to @p rhs
*/
bool operator==(const ConnectionCallback& rhs) const
{
return rhs.connectionCallback == connectionCallback &&
rhs.userData == userData;
}
/**
* @brief Inequality operator for the connection/disconnection callback object
*
* @param rhs Callback object to compare against
* @return true The callback object is not equal to @p rhs
* @return false The callback object is equal to @p rhs
*/
bool operator!=(const ConnectionCallback& rhs) const
{
return !(*this == rhs);
}
};
// ==============================================================================================================
/** Callback object used when a path has changed, requiring a path attribute update */
struct PathChangedCallback
{
/**
* Callback function definition. Parameters are
*
* - paths Array of paths that have changed
* - numPaths Number of paths in the array
* - userData User data to pass to the callback
*/
void(*pathChangedCallback)(const omni::fabric::PathC* paths, const size_t numPaths, void* userData);
/** User data to pass to the callback function */
void* userData;
/**
* @brief Equality operator for the path change callback object
*
* @param rhs Callback object to compare against
* @return true The callback object is equal to @p rhs
* @return false The callback object is not equal to @p rhs
*/
bool operator==(const PathChangedCallback& rhs) const
{
return rhs.pathChangedCallback == pathChangedCallback &&
rhs.userData == userData;
}
/**
* @brief Inequality operator for the path change callback object
*
* @param rhs Callback object to compare against
* @return true The callback object is not equal to @p rhs
* @return false The callback object is equal to @p rhs
*/
bool operator!=(const PathChangedCallback& rhs) const
{
return !(*this == rhs);
}
};
namespace ogn
{
class OmniGraphDatabase;
}
/**
* A callback allocate, initialize, and returns an OGN database for a given node
*/
using CreateDbFunc = ogn::OmniGraphDatabase* (*)(GraphContextObj const*, NodeObj const*, size_t);
/**
* Parameters for IGraph::CreateGraphAsNode
*/
struct CreateGraphAsNodeOptions
{
static const uint8_t kCurrentVersion = 1; //!< Version number of this structure
//! The version of this structure.
const uint8_t version{ CreateGraphAsNodeOptions::kCurrentVersion };
//! The name of the node that wraps the graph
const char* nodeName{ "" };
//! The path to where the graph that the node will wrap will be added
const char* graphPath{ "" };
//! The evaluator to use for the new graph
const char* evaluatorName{ "" };
//! Whether this graph is a top level global graph
bool isGlobalGraph{ true };
//! Whether to back this graph by USD
bool backByUSD{ true };
//! What kind of FC backs this graph
GraphBackingType backingType{ kGraphBackingType_FabricShared };
//! What pipeline stage this graph occupies
GraphPipelineStage pipelineStage{ kGraphPipelineStage_Simulation };
//! The evaluation mode for the graph
GraphEvaluationMode evaluationMode{ GraphEvaluationMode::Automatic };
};
/**
* @brief Possible values to be set for Attributes of type "execution"
* @private Deprecated. See omni::graph::action::IActionGraph.
*/
enum ExecutionAttributeState : uint32_t
{
kExecutionAttributeStateDisabled, //!< Output attribute connection is disabled
kExecutionAttributeStateEnabled, //!< Output attribute connection is enabled
//! Output attribute connection is enabled and the node is pushed to the evaluation stack
kExecutionAttributeStateEnabledAndPush,
//! Push this node as a latent event for the current entry point
kExecutionAttributeStateLatentPush,
// Output attribute connection is enabled and the latent state is finished for this node
kExecutionAttributeStateLatentFinish
};
/**
* The attribute name prefix used for attributes which hold the concrete value of resolved extended attributes.
*/
#define RESOLVED_ATTRIBUTE_PREFIX "__resolved_"
/**
* The path used to identify the targeted prim, when graph instancing is used. At runtime this token will be
* replaced with the absolute path to the targeted prim.
*/
static constexpr char kInstancingGraphTargetPath[] = "_OMNI_GRAPH_TARGET";
/**
* The value of an uninitialized attribute for a type (eg: tuple_count, array_depth)
*/
constexpr uint8_t kUninitializedTypeCount = UINT8_MAX;
/**
* Value representing an instance
*/
struct InstanceIndex
{
/** Returns true iff this InstanceIndex is equal to the @p other */
bool const operator==(InstanceIndex const& other) const
{ return index == other.index; }
/** Returns true iff this InstanceIndex is not equal to the @p other */
bool const operator!=(InstanceIndex const& other) const
{ return index != other.index; }
/** Returns true iff this InstanceIndex is less than the @p other */
bool const operator<(InstanceIndex const& other) const
{ return index < other.index; }
/** Returns true iff this InstanceIndex is less than or equal to the @p other */
bool const operator<=(InstanceIndex const& other) const
{ return index <= other.index; }
/** Returns true iff this InstanceIndex is greater than the @p other */
bool const operator>(InstanceIndex const& other) const
{ return index > other.index; }
/** Returns true iff this InstanceIndex is greater than or equal to the @p other */
bool const operator>=(InstanceIndex const& other) const
{ return index >= other.index; }
/** Returns the sum of this instance index and that of the @p other */
InstanceIndex operator+(InstanceIndex other) const
{ return { index + other.index }; }
/** Returns the sum of this instance index and @p idx */
InstanceIndex operator+(size_t idx) const
{ return { index + idx }; }
/** Increments the instance index by the index amount contained in @p other */
InstanceIndex& operator+=(InstanceIndex other)
{ index += other.index; return *this; }
/** Increments the index value */
InstanceIndex& operator++()
{ index++; return *this; }
size_t index{ 0 }; //!< Index value for the instance
};
/**
* Some default instance value
*/
static constexpr InstanceIndex kAuthoringGraphIndex{ size_t(-1) }; //!< Special index for the authoring graph original
static constexpr InstanceIndex kAccordingToContextIndex{ size_t(-2) }; //!< Special index for a context
static constexpr InstanceIndex kInvalidInstanceIndex{ size_t(-3) }; //!< Special index indicating an invalid instance
// ======================================================================
/** Interface to provide functionality to access and modify properties of an OmniGraph attribute.
*/
struct IAttribute
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::IAttribute", 1, 12);
/**
* Returns the name of the attribute
*
* @param[in] attr Reference to the AttributeObj struct representing the attribute object
* @return The name of the attribute
*/
const char*(CARB_ABI* getName)(const AttributeObj& attr);
/**
* Returns the type name of the attribute
*
* @param[in] attr Reference to the AttributeObj struct representing the attribute object
* @return The type name of the attribute
*/
const char*(CARB_ABI* getTypeName)(const AttributeObj& attr);
/**
* Returns the extended type, if any, of the attribute. Extended types are things like "union" and
* "any" types that aren't in the explicit list of types in USD. kExtendedAttributeType_Regular
* means that the attribute is not one of these extended types.
*
* @param[in] attr Reference to the AttributeObj struct representing the attribute object
* @return The extended type of the attribute
*/
ExtendedAttributeType(CARB_ABI* getExtendedType)(const AttributeObj& attr);
/**
* Returns the resolved type an extended type like union actually turns out to be, by
* inferring it from the connection. If the type is still not resolved, the BaseDataType of
* the returned type will have eNone as its value.
*
* If the attribute type is just a Regular one then this method will return its permanent type.
*
* @param[in] attr Reference to the AttributeObj struct representing the attribute object
* @return The resolved type of the attribute, based on the connection
*/
Type(CARB_ABI* getResolvedType)(const AttributeObj& attr);
/**
* Returns whether the attribute is an array
*
* @param[in] attr Reference to the AttributeObj struct representing the attribute object
* @return Whether or not the attribute is an array
*/
bool(CARB_ABI* isArray)(const AttributeObj& attr);
/**
* Connects an attribute using a relationship to some other prim. This could be for a bundle connection
* or a pure relationship to a prim. In the case of a pure relationship to a prim, some meta-data will
* be added to mark the relationship as not being used for a bundle
*
* @param[in] attrObj The attr that represents the relationship
* @param[in] pathToPrim The path to the prim to connect to
* @param[in] modifyInUsd Whether the connection is also modified in the underlying USD representation
* @param[in] isBundleConnection Whether the connection is to be used for bundles or just a pure relationship to a prim
* @return true if connection is successful, false otherwise
*/
bool(CARB_ABI* connectPrim)(const AttributeObj& attrObj, const char* pathToPrim, bool modifyInUsd, bool isBundleConnection);
/**
* Disconnects an attribute using a relationship to some other prim. This could be for a bundle connection
* or a pure relationship to a prim.
*
* @param[in] attrObj The attr that represents the relationship
* @param[in] pathToPrim The path to the prim to disconnect
* @param[in] modifyInUsd Whether the connection is also modified in the underlying USD representation
* @param[in] isBundleConnection Whether the connection is to be used for bundles or just a pure relationship to a prim
* @return true if disconnection is successful, false otherwise
*/
bool(CARB_ABI* disconnectPrim)(const AttributeObj& attrObj, const char* pathToPrim, bool modifyInUsd, bool isBundleConnection);
/**
* Connects two attributes together to add an edge to the graph. This is a legacy version of the
* connection API. Calling this is equivalent to setting kConnectionType_Regular type connections.
* Please use connectAttrsEx to have fuller control over the kind of connections created.
*
* @param[in] srcAttr The attr that is the source of the directed connection
* @param[in] destAttr The attr that is the destination of the directed connection
* @param[in] modifyInUsd Whether the connection is also modified in the underlying USD representation
* @return true if connection is successful, false otherwise
*/
bool(CARB_ABI* connectAttrs)(const AttributeObj& srcAttr, const AttributeObj& destAttr, bool modifyInUsd);
/**
* Connects two attributes together to add an edge to the graph. This is an extended version with
* more information about the connection, such as the type of connection.
*
* @param[in] srcAttr The attr that is the source of the directed connection
* @param[in] destAttrInfo A ConnectionInfo struct describing the connection
* @param[in] modifyInUsd Whether the connection is also modified in the underlying USD representation
* @return true if connection is successful, false otherwise
*/
bool(CARB_ABI* connectAttrsEx)(const AttributeObj& srcAttr, const ConnectionInfo& destAttr, bool modifyInUsd);
/**
* Disconnects two attributes that are connected
*
* @param[in] srcAttr The attribute that is the source of the directed connection
* @param[in] destAttr The attribute that is the destination of the directed connection
* @param[in] modifyInUsd Whether the connection is also modified in the underlying USD representation
* @return true if connection is successfully broken, false otherwise (if no connections existed)
*/
bool(CARB_ABI* disconnectAttrs)(const AttributeObj& srcAttr, const AttributeObj& destAttr, bool modifyInUsd);
/**
* Queries whether two attributes are connected
*
* @param[in] srcAttr The attribute that is the source of the directed connection
* @param[in] destAttr The attribute that is the destination of the directed connection
* @return true if the two attributes are connected, false otherwise
*/
bool(CARB_ABI* areAttrsConnected)(const AttributeObj& srcAttr, const AttributeObj& destAttr);
/**
* Queries whether two attributes are connection compatible
*
* @param[in] srcAttr The attribute that would be the source of the directed connection
* @param[in] destAttr The attribute that would be the destination of the directed connection
* @return true if the two attributes are compatible, false otherwise
*/
bool(CARB_ABI* areAttrsCompatible)(const AttributeObj& srcAttr, const AttributeObj& destAttr);
/**
* Retrieves the number of upstream connections to the attribute of a node
*
* @param[in] attrObj The attribute object for which to retrieve the connection count
* @return The number of upstream connections to that attribute
*/
size_t(CARB_ABI* getUpstreamConnectionCount)(const AttributeObj& attrObj);
/**
* Retrieves the upstream connections of the attribute of a node
*
* @param[in] attrObj The attribute object for which to retrieve the connections
* @param[out] attrsBuf Buffer to hold the return AttributeObj
* @param[in] bufferSize the number of AttributeObj structures the buffer is able to hold
* @return true on success, false on failure
*/
bool(CARB_ABI* getUpstreamConnections)(const AttributeObj& attrObj, AttributeObj* attrsBuf, size_t bufferSize);
/**
* Retrieves the detailed upstream connection info of an attribute. Includes information like type of
* connections.
*
* @param[in] attrObj The attribute object for which to retrieve the connections
* @param[out] connectionInfoBif Buffer to hold the return ConnectionInfo
* @param[in] bufferSize the number of AttributeObj structures the buffer is able to hold
* @return true on success, false on failure
*/
bool(CARB_ABI* getUpstreamConnectionsInfo)(const AttributeObj& attrObj,
ConnectionInfo* connectionInfoBuf,
size_t bufferSize);
/**
* Retrieves the number of downstream connections to the attribute of a node
*
* @param[in] attrObj The attribute object for which to retrieve the connection count
* @return The number of downstream connections to that attribute
*/
size_t(CARB_ABI* getDownstreamConnectionCount)(const AttributeObj& attrObj);
/**
* Retrieves the down connections of the attribute of a node
*
* @param[in] attrObj The attribute object for which to retrieve the connections
* @param[out] attrsBuf Buffer to hold the return AttributeObj
* @param[in] bufferSize the number of AttributeObj structures the buffer is able to hold
* @return true on success, false on failure
*/
bool(CARB_ABI* getDownstreamConnections)(const AttributeObj& attrObj, AttributeObj* attrsBuf, size_t bufferSize);
/**
* Retrieves the detailed upstream connection info of an attribute. Includes information like type of
* connections.
*
* @param[in] attrObj The attribute object for which to retrieve the connections
* @param[out] connectionInfoBif Buffer to hold the return ConnectionInfo
* @param[in] bufferSize the number of AttributeObj structures the buffer is able to hold
* @return true on success, false on failure
*/
bool(CARB_ABI* getDownstreamConnectionsInfo)(const AttributeObj& attrObj,
ConnectionInfo* connectionInfoBuf,
size_t bufferSize);
/**
* Retrieves the node associated with this attribute
*
* @param[in] attrObj The attribute object for which to retrieve the node
* @return The NodeObj representing the node. In case of failure, the node handle
* will be kInvalidNodeHandle
*/
NodeObj(CARB_ABI* getNode)(const AttributeObj& attrObj);
/**
* Ensures the attribute's value is updated, before reading it. For push graphs this does nothing, as the
* push graph is always evaluating and considered up to date.
* For pull graphs, this generates the true "pull" on the attribute, that will cause whatever is upstream
* and is dirty to evaluate.
*
* @param[in] attrObj The attribute object for which to update the value for
* @param[in] updateImmediately Whether to cause the graph to update immediately (synchronously)
* @return Whether the update was successful
*/
bool(CARB_ABI* updateAttributeValue)(const AttributeObj& attrObj, bool updateImmediately);
/** @private Deprecated - do not use */
AttributeDataHandle(CARB_ABI* deprecated_0)(const AttributeObj&);
/** @private Deprecated - do not use */
ConstAttributeDataHandle(CARB_ABI* deprecated_1)(const AttributeObj&);
/**
* Registers a callback to be invoked when the value of the current attribute changes
*
* An attribute only permits a single callback and when called, the previously set callback
* is replaced. Passing nullptr as the callback will remove any existing callback.
*
* @param[in] thisAttribute Reference to the AttributeObj struct representing the current attribute object
* @param[in] onValueChanged The callback to trigger. Parameters are the attribute involved, and the new value
* @param[in] triggerOnConnected Whether to trigger the callback on connected attributes.
*/
void(CARB_ABI* registerValueChangedCallback)(const AttributeObj& attrObj,
void (*onValueChanged)(const AttributeObj& attr, const void* value),
bool triggerOnConnected);
/**
* Returns the set of all metadata on this attribute.
*
* The keyBuf and valueBuf arrays preallocated by the caller, and contain at least "getMetadataCount()"
* entries in them.
* All returned strings are owned by the node type and not to be destroyed.
* The returned keyBuf and valueBuf must have exactly the same size with corresponding index values; that is
* keyBuf[i] is the metadata name for the string in valueBuf[i].
*
* @param[in] thisAttribute Reference to the AttributeObj struct representing the current attribute object
* @param[out] keyBuf Buffer in which to put the list of metadata keys
* @param[out] valueBuf Buffer in which to put the list of metadata values
* @param[in] bufferSize the number of strings each of the two buffers is able to hold
* @return Number of metadata items successfully populated
*/
size_t(CARB_ABI* getAllMetadata)(const AttributeObj& thisAttribute,
const char** keyBuf,
const char** valueBuf,
size_t bufferSize);
/**
* Retrieves a metadata value from this attribute
*
* @param[in] thisAttribute Reference to the AttributeObj struct representing the current attribute object
* @param[in] key The name of the metadata to be retrieved
* @return The value of the metadata, or nullptr if the named metadata was not set on this attribute
*/
const char*(CARB_ABI* getMetadata)(const AttributeObj& thisAttribute, const char* key);
/**
* Returns the number of metadata entries on this attribute
*
* @param[in] thisAttribute Reference to the AttributeObj struct representing the current attribute object
* @return the number of metadata key/value pairs on this attribute
*/
size_t(CARB_ABI* getMetadataCount)(const AttributeObj& thisAttribute);
/**
* Sets a metadata value on this attribute.
*
* Certain metadata keywords have special meaning internally:
* uiName: The name of the attribute in a longer, human-readable format
*
* Note: The main way for metadata to be set is through the .ogn format files. If you call this directly the
* metadata will not persist across sessions. If you wish to define metadata outside of the .ogn file
* the best method is to override the initializeType() method in your attribute definition and set it there.
*
* @param[in] attrObj Reference to the AttributeObj struct representing the current attribute object
* @param[in] key The keyword, used as the name of the metadata
* @param[in] value The value of the metadata. Metadata can be parsed later if non-string values are desired.
*/
void(CARB_ABI* setMetadata)(const AttributeObj& attrObj, const char* key, const char* value);
/**
* Where we have dynamic scheduling, downstream nodes can have their execution disabled by turning on the flag
* in the upstream attribute. Note you also have to call setDynamicDownstreamControl on the node to enable
* this feature. See setDynamicDownstreamControl on INode for further information.
*
* @param[in] attrObj Reference to the AttributeObj struct representing the current attribute object
* @return Whether downstream nodes connected to this attribute should be disabled from further work
*/
bool (CARB_ABI* getDisableDynamicDownstreamWork)(const AttributeObj& attrObj);
/**
* Where we have dynamic scheduling, downstream nodes can have their execution disabled by turning on the flag
* in the upstream attribute. Note you also have to call setDynamicDownstreamControl on the node to enable
* this feature. This function allows you to set the flag on the attribute that will disable the downstream
* node. See setDynamicDownstreamControl on INode for further information.
*
* @param[in] attrObj Reference to the AttributeObj struct representing the current attribute object
* @param[in] value Whether to disable the downstream connected nodes or not.
*/
void (CARB_ABI* setDisableDynamicDownstreamWork)(const AttributeObj& attrObj, bool value);
/**
* Sets the resolved type of an extended type. This should be called by a node from the
* *onConnectionTypeResolve()* callback when it determines that an extended-type attribute
* can be resolved to a specific type. For example a generic 2-input "Add" node could resolve input B and its
* output attribute type to float when input A is connected to a float. Passing @ref omni::fabric::Type() will
* reset the attribute type to "unresolved".
*
* @note This operation is asynchronous because it is considered as part of a whole-graph type resolution
* algorithm. It also may not succeed because there could be constraints in the graph that
* prevent the type from being resolved as requested.
*
* @param[in] attr Reference to the AttributeObj struct representing the attribute object
* @param[in] type The new type of the attribute
*/
void(CARB_ABI* setResolvedType)(const AttributeObj& attr, const Type& type);
/**
* Retrieves the port type (such as input, output, state) associated with this attribute
*
* @param[in] attrObj The attribute object for which to retrieve the connections
* @return the AttributePortType of this attribute
*/
AttributePortType(CARB_ABI* getPortType)(const AttributeObj& attrObj);
/**
* Returns whether the attribute is a dynamic attribute (not in the node definition) or not
*
* @param[in] attrObj The attribute object for which to query
* @return Whether the attribute is a dynamic one
*/
bool(CARB_ABI* isDynamic)(const AttributeObj& attrObj);
/**
* Returns the full path to the attribute, including the node path
*
* @param[in] attr Reference to the AttributeObj struct representing the attribute object
* @return The full path to the attribute
*/
const char*(CARB_ABI* getPath)(const AttributeObj& attrObj);
/**
* @return The string representing the extended union types, nullptr if the attribute is not a union type
*/
const char*(CARB_ABI* getUnionTypes)(const AttributeObj& attribute);
/**
* Returns whether the attribute is still valid or not
*
* @param[in] attrObj The attribute object for which to query
* @return Whether the attribute is still valid
*/
bool(CARB_ABI* isValid)(const AttributeObj& attrObj);
/**
* Return the attribute name with the port type prepended if it isn't already present.
*
* @param[in] name The attribute name, with or without the port prefix
* @param[in] portType The port type of the attribute
* @param[in] isBundle true if the attribute name is to be used in a bundle. Note that colon is an illegal character
* in bundled attributes so an underscore is used instead.
* @return The name with the proper prefix for the given port type
*/
NameToken(CARB_ABI* ensurePortTypeInName)(NameToken name, AttributePortType portType, bool isBundle);
/**
* Parse the port type from the given attribute name if present. The port type is indicated by a prefix seperated by
* a colon or underscore in the case of bundled attributes.
*
* @param[in] name The attribute name
* @return The port type indicated by the attribute prefix if present. AttributePortType::kAttributePortType_Unknown
* if there is no recognized prefix.
*/
AttributePortType(CARB_ABI* getPortTypeFromName)(NameToken name);
/**
* Return the attribute name with the port type removed if it is present. For example "inputs:attr" becomes "attr"
*
* @param[in] name The attribute name, with or without the port prefix
* @param[in] isBundle true if the attribute name is to be used in a bundle. Note that colon is an illegal character
* in bundled attributes so an underscore is used instead.
* @return The name with the port type prefix removed
*/
NameToken(CARB_ABI* removePortTypeFromName)(NameToken name, bool isBundle);
/**
* Get the optional compute flag from the attribute. When true this flag indicates that the attribute does not
* need to be valid in order for the compute() function to be called.
* Note that "valid" does not necessarily mean the attribute data is up to date, it only means that everything
* required to locate the attribute data is available and valid (otherwise outputs would always be invalid).
*
* @param[in] attrObj The attribute object being queried
* @return True if the attribute is optional for compute
*/
bool(CARB_ABI* getIsOptionalForCompute)(const AttributeObj& attrObj);
/**
* Set whether the attribute is optional for compute or not; mostly used by generated code.
* This flag would be set on attributes that the compute() method may not look at. It would then be up to the
* compute() method to check validity if it ends up requiring the attribute's value. You might use this when an
* attribute value is not used in all compute paths, like a "choice" node that selects exactly one of its inputs
* to send to the output - only the selected input would need to be valid for compute to succeed.
*
* @param[in] attrObj The attribute object being modified
* @param[in] isOptional New value for the optional flag on the attribute
*/
void(CARB_ABI* setIsOptionalForCompute)(const AttributeObj& attrObj, bool isOptional);
/**
* Returns an AttributeDataHandle to access the default data on this input attribute.
*
* @param[in] attrObj The input attribute object for which to update the default value for
* @return The AttributeDataHandle associated with the default value of this attribute, to mutate data in the FC
*/
AttributeDataHandle(CARB_ABI* getDefaultValueAttributeDataHandle)(const AttributeObj& attrObj);
/**
* Get the deprecated flag from the attribute. When true this flag indicates that the attribute has been
* deprecated and will be removed in a future version of the node.
*
* @param[in] attrObj The attribute object being queried
* @return True if the attribute is deprecated
*/
bool(CARB_ABI* isDeprecated)(const AttributeObj& attrObj);
/**
* Return the deprecation message for an attribute.
*
* @param[in] attributeObj Attribute to which this function applies
* @return String containing the attribute deprecation message (nullptr if the attribute is not deprecated)
*/
char const*(CARB_ABI* deprecationMessage)(const AttributeObj& attributeObj);
/**
* Returns an AttributeDataHandle to access the data on this attribute.
*
* @param[in] attrObj The attribute object for which to retrieve the data accessor
* @param[in] instanceIdx The instance index relative to the current active instance for which you want to retrieve the data.
* @return The AttributeDataHandle associated with this attribute, to mutate data in the FC
*/
AttributeDataHandle(CARB_ABI* getAttributeDataHandle)(const AttributeObj& attrObj, InstanceIndex instanceIdx);
/**
* Returns a ConstAttributeDataHandle to access the data on this attribute.
*
* @param[in] attrObj The attribute object for which to retrieve the data accessor
* @param[in] instanceIdx The instance index relative to the current active instance for which you want to retrieve the data.
* @return The ConstAttributeDataHandle associated with this attribute, to read data in the FC
*/
ConstAttributeDataHandle(CARB_ABI* getConstAttributeDataHandle)(const AttributeObj& attrObj, InstanceIndex instanceIdx);
/**
* Returns whether or not this attribute is a runtime constant or not.
* Runtime constant will keep the same value every frame, for every instances
* This property can be taken advantage in vectorized compute
*
* @param[in] attrObj The attribute object to query
*
* @return true if the attribute is a runtime constant, false otherwise
*/
bool(CARB_ABI* isRuntimeConstant)(const AttributeObj& attrObj);
/**
* Warn the framework that writing to the provided attributes is done, so it can trigger callbacks attached to them
*
* @param[in] attrObjs A pointer to an array of attribute objects for which to call change callbacks
* @param[in] attrObjCount The number of object(s) in that array
*/
void(CARB_ABI* writeComplete)(const AttributeObj* attrObjs, size_t attrObjCount);
/**
* Returns the name of the attribute as a token
*
* @param[in] attr Reference to the AttributeObj struct representing the attribute object
* @return The name of the attribute as a token
*/
NameToken(CARB_ABI* getNameToken)(const AttributeObj& attr);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IAttribute, getNameToken, 47)
// ======================================================================
/** Each node type in a plugin must implement this interface */
struct INodeType
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::INodeType", 1, 12);
/**
* Return node type name - this is used by 'node:type' schema in Node prim.
* For retrieving the node type name of a known NodeTypeObj use getTypeName().
*
* @return The node type name
*/
const char*(CARB_ABI* getNodeType)();
/**
* Implementation of compute, see above GraphContext for functions to pull/push data with other nodes
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] node Reference to the NodeObj struct representing the node object
* @return true if compute is successful, false otherwise
*/
bool(CARB_ABI* compute)(const GraphContextObj& context, const NodeObj& node);
// functions below are optional
/**
* This allows each node to define custom data for each node instance
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] node Reference to the NodeObj struct representing the node object pointer
*/
void(CARB_ABI* initialize)(const GraphContextObj& context, const NodeObj& node);
/**
* Release memory created by initialize function above
*
* @param[in] node Reference to the NodeObj struct representing the node object
* pointer
*/
void(CARB_ABI* release)(const NodeObj& node);
/**
* This allows each node to be upgraded/downgraded for each node instance
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] oldVersion int specifying the old version (of the node)
* @param[in] newVersion int specifying the new version (of the node type)
* @return true if the node was modified, false otherwise
*/
bool(CARB_ABI* updateNodeVersion)(const GraphContextObj& context,
const NodeObj& node,
int oldVersion,
int newVersion);
/**
* This allows each node type to specify its inputs and outputs in order to build up a description
* of the node type. This is done by calling the provided implementations of addInput and addOuput to
* add the requisite inputs and outputs respectively.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
*/
void(CARB_ABI* initializeType)(const NodeTypeObj& nodeType);
/**
* Adds an input for the node type. This is intended to be called from initializeType when specifying
* the inputs for the node type.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @param[in] name Name of the input
* @param[in] typeName Typename of the input
* @param[in] required Whether or not the input is required
* @param[in] defaultValuePtr Pointer to the location containing the default value of the input
* @param[in] defaultElemCountPtr Number of elements in the default value -- nullptr if the input is a scalar
*/
void(CARB_ABI* addInput)(const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr);
/**
* Adds an output for the node type. This is intended to be called from initializeType when specifying
* the outputs for the node type.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @param[in] name Name of the output
* @param[in] typeName Typename of the output
* @param[in] required Whether or not the output is required
* @param[in] defaultValuePtr Pointer to the location containing the default value of the output
* @param[in] defaultElemCountPtr Number of elements in the default value -- nullptr if the output is a scalar
*/
void(CARB_ABI* addOutput)(const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr);
/**
* Adds a state attribute for the node type. This is intended to be called from initializeType when specifying
* the state information for the node type. State attributes differ from inputs and outputs in that they will
* never leave the node (i.e. they cannot be connected). The node is responsible for ensuring that their contents
* are consistent with the current evaluation.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @param[in] name Name of the input
* @param[in] typeName Typename of the input
* @param[in] required Whether or not the input is required
* @param[in] defaultValuePtr Pointer to the location containing the default value of the input
* @param[in] defaultElemCountPtr Number of elements in the default value -- nullptr if the input is a scalar
*/
void(CARB_ABI* addState)(const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr);
/**
* Adds an extended input (not one of the usual data types) for the node type, for example, a union type.
* This is intended to be called from initializeType when specifying the inputs for the node type.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @param[in] name Name of the input
* @param[in] typeInfo A buffer holding extra information about the type
* @param[in] required Whether or not the input is required
* @param[in] extendedAttrType Whether the attribute is an extended type, like a union or any
*/
void(CARB_ABI* addExtendedInput)(const NodeTypeObj& nodeType,
const char* name,
const char* typeInfo,
bool required,
ExtendedAttributeType extendedAttrType);
/**
* Adds an extended output (not one of the usual data types) for the node type, for example, a union type.
* This is intended to be called from initializeType when specifying the inputs for the node type.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @param[in] name Name of the input
* @param[in] typeInfo A buffer holding extra information about the type
* @param[in] required Whether or not the input is required
* @param[in] extendedAttrType Whether the attribute is an extended type, like a union or any
*/
void(CARB_ABI* addExtendedOutput)(const NodeTypeObj& nodeType,
const char* name,
const char* typeInfo,
bool required,
ExtendedAttributeType extendedAttrType);
/**
* Adds an extended state (not one of the usual data types) for the node type, for example, a union type.
* This is intended to be called from initializeType when specifying the inputs for the node type.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @param[in] name Name of the input
* @param[in] typeInfo A buffer holding extra information about the type
* @param[in] required Whether or not the input is required
* @param[in] extendedAttrType Whether the attribute is an extended type, like a union or any
*/
void(CARB_ABI* addExtendedState)(const NodeTypeObj& nodeType,
const char* name,
const char* typeInfo,
bool required,
ExtendedAttributeType extendedAttrType);
/**
* Return whether state information exists on the node. This is mainly used for determining how nodes can be
* safely scheduled for execution.
*
* Internal state information is data maintained on the node that is unique to the node's evaluation instance.
* As this is somewhat equivalent to member data it cannot be accessed in parallel on the same node. For example,
* a node with internal state data cannot be scheduled as part of a parallel graph loop.
*
* @return True if this node type manages its own internal state information
*/
bool(CARB_ABI* hasState)(const NodeTypeObj& nodeType);
/**
* Sets a flag that indications state information exists on the node. This is mainly used for determining how
* nodes can be safely scheduled for execution.
*
* @param[in] nodeHasState New value for the flag indicating if the node has state information
*/
void(CARB_ABI* setHasState)(const NodeTypeObj& nodeType, bool nodeHasState);
/**
* Returns the path to this node type object, so that nodes could be created under this path in the case
* of compound nodes
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @return path to the nodeTypeObj
*/
const char*(CARB_ABI* getPath)(const NodeTypeObj& nodeType);
/**
* Registers task functions that the node intends to schedule via Realm. This is called once for each node type
* during the lifetime of the process after the Realm runtime has been initialized.
*
*/
void(CARB_ABI* registerTasks)();
/**
* Returns the set of all metadata on this node.
*
* The keyBuf and valueBuf arrays preallocated by the caller, and contain at least "getMetadataCount()"
* entries in them.
* All returned strings are owned by the node type and not to be destroyed.
* The returned keyBuf and valueBuf must have exactly the same size with corresponding index values; that is
* keyBuf[i] is the metadata name for the string in valueBuf[i].
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the current node type object
* @param[out] keyBuf Buffer in which to put the list of metadata keys
* @param[out] valueBuf Buffer in which to put the list of metadata values
* @param[in] bufferSize the number of strings each of the two buffers is able to hold
* @return Number of metadata items successfully populated
*/
size_t(CARB_ABI* getAllMetadata)(const NodeTypeObj& nodeType,
const char** keyBuf,
const char** valueBuf,
size_t bufferSize);
/**
* Retrieves a metadata value from this node type
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the current node type object
* @param[in] key The name of the metadata to be retrieved
* @return The value of the metadata, or nullptr if the named metadata was not set on this node type
*/
const char*(CARB_ABI* getMetadata)(const NodeTypeObj& nodeType, const char* key);
/**
* Returns the number of metadata entries on this node
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the current node type object
* @return the number of metadata key/value pairs on this node
*/
size_t(CARB_ABI* getMetadataCount)(const NodeTypeObj& nodeType);
/**
* Sets a metadata value on this node type.
*
* Certain metadata keywords have special meaning internally:
* _extension_: The name of the extension from which the node type was loaded
* uiName: The name of the node type in a longer, human-readable format
*
* Note: The main way for metadata to be set is through the .ogn format files. If you call this directly the
* metadata will not persist across sessions. If you wish to define metadata outside of the .ogn file
* the best method is to override the initializeType() method in your node definition and set it there.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the current node type object
* @param[in] key The keyword, used as the name of the metadata
* @param[in] value The value of the metadata. Metadata can be parsed later if non-string values are desired.
* @return true if the keyword was successfully set
*/
void(CARB_ABI* setMetadata)(const NodeTypeObj& nodeType, const char* key, const char* value);
/**
* Adds a sub-nodetype to an existing node type. This is used for Python and Compounds, where there
* is a global type that houses all the type information for all the nodes registered in the system.
* Each of those specific node types is a sub-nodetype to the bigger container node type
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the current node type object
* @param[in] subNodeTypeName Name of the sub-nodeType
* @param[in] subNodeType Reference to the NodeTypeObj struct representing the sub-nodetype object
*/
void(CARB_ABI* addSubNodeType)(const NodeTypeObj& nodeType,
const char* subNodeTypeName,
const NodeTypeObj& subNodeType);
/**
* Retrieves a sub-nodetype to an existing node type. This is mainly used for Python nodes, where there is a
* global PythonNode type that houses all the type information for all the python nodes registered in the
* system. Each of those specific python node types is a sub-nodetype to the bigger python node type
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the current node type object
* @param[in] subNodeTypeName Name of the sub-nodeType
* @return The NodeTypeObj of sub-nodetype
*/
NodeTypeObj(CARB_ABI* getSubNodeType)(const NodeTypeObj& nodeType, const char* subNodeTypeName);
/**
* Creates a new nodeType, but without the interface portion. It only contains the "handle" portion
* of the NodeTypeObj - that is, a handle to an underlying object that can store the inputs/outputs of
* a node type. This is currently mainly used for Python types, where the functions are stored not in
* INodeType struct as other types, but elsewhere.
*
* @param[in] the name of the new node type to be created.
* @param[in] the version of the new node type to be created.
* @return The NodeTypeObj created without the INodeType portion.
*/
NodeTypeObj(CARB_ABI* createNodeType)(const char* nodeTypeName, int version);
/**
* Gets the number of scheduled instances for the node type object so that an internal buffer of the appropriate
* size can be created. The number of scheduled instances should match the number created in getScheduleNode.
*
* This function is called as the graph is evaluated and a list of upstream nodes is provided such that the
* number of scheduled instances for the node can be dependent on the results of upstream evaluations.
*
* Currently, we only support either zero or one scheduled instances.
*
* Deprecated: Use action graph for conditional scheduling
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] upstreamScheduleNodesBuf pointer to an array of upstream schedule nodes
* @param[in] upstreamBufferSize size of the upstream schedule node buffer
* @return The number of scheduled instances expected for the node
*/
size_t(CARB_ABI* getScheduleNodeCount)(const GraphContextObj& context,
const NodeObj& node,
const ScheduleNodeObj* upstreamScheduleNodesBuf,
size_t upstreamBufferSize);
/**
* Gets/Creates the scheduled instances for the node type object. The number of scheduled instances should match the
* return value of getScheduleNodeCount.
*
* This function is called as the graph is evaluated and a list of upstream nodes is provided such that the
* scheduled instances for the node can be dependent on the results of upstream evaluations.
*
* Currently, we only support either zero or one scheduled instances.
*
* Deprecated: Use action graph for conditional scheduling
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] upstreamScheduleNodesBuf pointer to an array of upstream schedule nodes
* @param[in] upstreamBufferSize size of the upstream schedule node buffer
* @param[out] scheduleNodesBuf pointer to an output array of schedule nodes for this node
* @param[out] upstreamBufferSize size of the output schedule node buffer
* @param[in] bufferSize size of scheduleNodesBuf array
*/
void(CARB_ABI* getScheduleNodes)(const GraphContextObj& context,
const NodeObj& node,
const ScheduleNodeObj* upstreamScheduleNodesBuf,
size_t upstreamBufferSize,
ScheduleNodeObj* scheduleNodesBuf,
size_t bufferSize);
/**
* This function is called when an extended type attribute has been resolved due to a connection change. The node
* can then choose to call IAttribute::setResolvedType() on extended type attributes according to its
* internal logic.
*
* @param[in] node Reference to the NodeObj struct representing the node object
*/
void(CARB_ABI* onConnectionTypeResolve)(const NodeObj& node);
/**
* Return whether this node type is a singleton (only 1 instance allowed per graph instance, and its subgraphs)
*
* A node type can be made to be singleton, in which case only 1 instance of that type of Node will be allowed
* per graph.
*
* @return True if this node type is a singleton
*/
bool(CARB_ABI* isSingleton)(const NodeTypeObj& nodeType);
/**
* Runs the inspector on the data in the given node type.
*
* @param[in] nodeTypeObj The node type on which the inspector runs
* @param[in] inspector The inspector class
* @return true if the inspection ran successfully, false if the inspection type is not supported
*/
bool(CARB_ABI* inspect)(const NodeTypeObj& nodeTypeObj, inspect::IInspector* inspector);
/**
* Returns the number of subnode types on this node type.
*
* @param[in] nodeType Reference to node type object for which subnode types are to be found
* @return the number of subnode types owned by this node type
*/
size_t(CARB_ABI* getSubNodeTypeCount)(const NodeTypeObj& nodeType) ;
/**
* Returns the set of all subnode types of this node type.
*
* The subNodeTypeBuf array must be preallocated by the caller, and contain at least "bufferSize" entries.
* The contents of both buffers are owned by the interface and should not be freed by the caller.
*
* @param[in] nodeType Reference to node type object for which subnode types are to be found
* @param[out] subNodeTypeNameBuf Buffer in which to put the list of subnode type names
* @param[out] subNodeTypeBuf Buffer in which to put the list of subnode type definitions
* @param[in] bufferSize the number of strings each of the two buffers is able to hold
* @return Number of subnode types successfully populated
*/
size_t(CARB_ABI* getAllSubNodeTypes)(const NodeTypeObj& nodeType,
const char** subNodeTypeNameBuf,
NodeTypeObj* subNodeTypeBuf,
size_t bufferSize);
/**
* Removes a sub-nodetype from an existing node type. This is mainly used for Python nodes, where there is a
* global PythonNode type that houses all the type information for all the python nodes registered in the
* system. Each of those specific python node types is a sub-nodetype to the bigger python node type. When a
* Python module is unloaded it should be removing any sub-nodetypes it has added.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @param[in] subNodeTypeName Name of the sub-nodeType to be removed
* @return True if the removal succeeded, false if not (most likely because the sub-nodetype did not exist)
*/
bool(CARB_ABI* removeSubNodeType)(const NodeTypeObj& nodeType,
const char* subNodeTypeName);
/**
* Get the currently defined scheduling hints for this node type.
* Call the inline function unless you want to manage your own reference counts.
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @return Scheduling hints pertaining to scheduling for this node type.
*/
ISchedulingHints*(CARB_ABI* getSchedulingHints)(const NodeTypeObj& nodeType);
/**
* Get a pointer to the currently defined scheduling hints for this node type.
* This version lets you manage your own reference counts.
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @return Scheduling hints pertaining to scheduling for this node type.
*/
inline omni::core::ObjectPtr<ISchedulingHints> getSchedulingHintsPtr(const NodeTypeObj& nodeType) const
{
return omni::core::steal(getSchedulingHints(nodeType));
}
/**
* Set the scheduling hints for this node type.
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @param[in] newSchedulingHints Scheduling hints pertaining to scheduling for this node type.
*/
void(CARB_ABI* setSchedulingHints)(const NodeTypeObj& nodeType, ISchedulingHints* newSchedulingHints);
/**
* Returns the name of the node type
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the node type object
* @return The name of the node type
*/
const char*(CARB_ABI* getTypeName)(const NodeTypeObj& nodeType);
/**
* Destroys a node type object, including any sub-nodetype objects attached to it.
*
* @param[in] The nodeType to destroy
* @return true if the node type is destroyed, false otherwise
*/
bool(CARB_ABI* destroyNodeType)(const NodeTypeObj& nodeType);
/**
* Retrieves a sub-nodetype to an existing node type by it's SdfPath. This is mainly used for compound
* nodes where subnode types that are stored have a backing Prim on the stage.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the current node type object
* @param[in] pathToSubNodeType Stage path to the subnode type
* @return The NodeTypeObj of sub-nodetype
*/
NodeTypeObj(CARB_ABI* getSubNodeTypeByPath)(const NodeTypeObj& nodeType, const char* pathToSubNodeType);
/**
* Determines if the node type is a compound node type. A compound node type is a node type that references
* an OmniGraph to define the computation.
*
* @param[in] nodeType Reference to the NodeTypeObj struct representing the current node type object
* @return True if the node type is a compound node, false otherwise
*/
bool(CARB_ABI* isCompoundNodeType)(const NodeTypeObj& nodeType);
/**
* Implementation of computeVectorized, see above GraphContext for functions to pull/push data with other nodes
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] count The number of vectorized instances available for compute
* @return true if compute is successful, false otherwise
*/
size_t(CARB_ABI* computeVectorized)(const GraphContextObj& context, const NodeObj& node, size_t count);
/**
* Called whenever a graph instance is being removed form the stage.
* This is an opportunity to release any memory allocated specifically for this instance
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] instanceID The instanceID as would be returned by INode::getGraphInstanceID
*/
void (CARB_ABI* releaseInstance)(const NodeObj& node, NameToken instanceID);
/**
* Called by the framework when an OGN database previously created by the provided callback in INode::getOgnDatabase
* needs to be destroyed
*
* @param[in] node Reference to the NodeObj struct representing the node object previously used to create the DB
* @param[in] db An OGN database previously created by provided callback in INode::getOgnDatabase
*/
void(CARB_ABI* destroyDB)(const NodeObj& node, ogn::OmniGraphDatabase* db);
/**
* Called by the framework in order to notify an OGN database previously created by the provided callback in
* INode::getOgnDatabase that a type resolution event has happened on an attribute
*
* @param[in] attrib Reference to the AttributeObj struct representing the attribute object that just (un)resolved its type
* @param[in] db An OGN database previously created by provided callback in INode::getOgnDatabase
*/
void(CARB_ABI* notifyTypeResolution)(AttributeObj const& attrib, ogn::OmniGraphDatabase* db);
/**
* Called by the framework in order to notify an OGN database that some dynamic attributes been added or removed.
*
* @param[in] db An OGN database previously created by provided callback in INode::getOgnDatabase
* @param[in] attrib The attribute that is created or removed
* @param[in] isAttributeCreated If true, the attribute is newly created, otherwise it is going to be removed
*/
void(CARB_ABI* notifyDynamicAttributeChanged)(ogn::OmniGraphDatabase* db, AttributeObj const& attrib, bool isAttributeCreated);
/**
* Returns the ABI version against which the extension has been built
*/
carb::Version(CARB_ABI* getCarbABIVersion)();
//////////////////////////////////////////////////////////////////////////////////////
// REMINDER REMINDER REMINDER REMINDER REMINDER REMINDER
//////////////////////////////////////////////////////////////////////////////////////
// Any change made in this ABI should come with a change in either (or both of):
// - OmniGraphNode_ABI::populateNodeTypeInterface()
// - NodeTypeRegistration::NodeTypeRegistration()
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(INodeType, getCarbABIVersion, 42)//Check the reminder above
// ======================================================================
/** Interface to a single node in a graph */
struct INode
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::INode", 4, 7);
/**
* Returns the number of attributes on this node
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @return the number of attributes on this node
*/
size_t(CARB_ABI* getAttributeCount)(const NodeObj& node);
/**
* Returns the attributes on this node
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[out] attrsBuf Buffer to hold the return attribute objects
* @param[in] bufferSize the number of AttributeObj structures the buffer is able to hold
* @return true if successful, false otherwise
*/
bool(CARB_ABI* getAttributes)(const NodeObj& node, AttributeObj* attrsBuf, size_t bufferSize);
/**
* Retrieves whether the attribute in question exists or not
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] attrName Name of the attribute on the node
* @return true if the attribute exists on the node, false if not
*/
bool(CARB_ABI* getAttributeExists)(const NodeObj& node, const char* attrName);
/** @private Retired - do not use */
void (CARB_ABI* retired_1)(NodeObj&);
/**
* Retrieves an attribute that points to the attribute on the current node.
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] attrName Name of the attribute on the node
* @return the attribute object requested
*/
AttributeObj(CARB_ABI* getAttribute)(const NodeObj& node, const char* attrName);
/**
* Retrieves an attribute that points to the attribute on the current node.
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] attrName Name of the attribute on the node
* @return the attribute object requested
*/
AttributeObj(CARB_ABI* getAttributeByToken)(const NodeObj& node, NameToken attrName);
/**
* Retrieves the prim path to the node
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @return the prim path to the node
*/
const char*(CARB_ABI* getPrimPath)(const NodeObj& node);
/**
* Retrieves the user data set on the node
*
* @param[in] node Reference to the NodeObj struct representing the node object
*/
void*(CARB_ABI* getUserData)(const NodeObj& node);
/**
* Retrieves the user data set on the node
*
* @param[in] node Reference to the NodeObj struct representing the node object
*/
void(CARB_ABI* setUserData)(const NodeObj& node, void* userData);
/** @private Retired - do not use */
void (CARB_ABI* retired_2)(NodeObj&);
/** @private Retired - do not use */
bool (CARB_ABI* retired_3)(NodeObj&);
/** @private Retired - do not use */
void (CARB_ABI* retired_4)(NodeObj&);
/**
* Returns the graph that this node belongs to
* @param[in] node Reference to the NodeObj struct representing the node object
* @return GraphObj structure containing the graph this node belongs to
*/
GraphObj(CARB_ABI* getGraph)(const NodeObj& node);
/** @private Deprecated - do not use */
CARB_DEPRECATED("Deprecated - use getNodeTypeObj")
INodeType(CARB_ABI* getNodeType)(const NodeObj&);
/** @private Deprecated - do not use */
CARB_DEPRECATED("Deprecated - use getNodeTypeObj().getTypeName()")
const char*(CARB_ABI* getPythonNodeType)(const NodeObj&);
/**
* Returns the node is disabled
* @param[in] node Reference to the NodeObj struct representing the node object
* @return true if disabled, false otherwise
*/
bool(CARB_ABI* isDisabled)(const NodeObj& node);
/**
* Sets the disabled state on the node
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] disable Whether to disable the node
*/
void(CARB_ABI* setDisabled)(const NodeObj& node, bool disable);
/**
* Lets the evaluation system know that the compute for this node is complete for this frame but not completed
* overall. For example, once an animation is triggered, we want the animation to play until completion - on
* a particular frame, the animation for that frame may be complete, but we're not done until the overall
* animation is completed. This method is only meaningful for evaluators that implement standard flow graph
* semantics.
*
* @param[in] node Reference to the NodeObj struct representing the node object
*
*/
void(CARB_ABI* setComputeIncomplete)(const NodeObj& node);
/**
* Returns whether the node has an USD representation on the stage.
* @param[in] node Reference to the NodeObj struct representing the node object
* @return true if the node is backed by USD, false otherwise
*/
bool(CARB_ABI* isBackedByUsd)(const NodeObj& node);
/**
* Creates a dynamic attribute on the node.
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] name Name of the attribute
* @param[in] attributeType The Type of the attribute. Extended attributes are Token types.
* @param[in] value Pointer to the location containing the initial value of the attribute
* @param[in] elemCount Number of elements in the attribute -- nullptr if the attribute is a scalar
* @param[in] portType Whether this attribute is an input, output, or state
* @param[in] extendedAttrType The type of extended attribute to create, if any (see definition of
* ExtendedAttributeType)
* @param[in] unionTypes In case the extendedAttrType is union, unionTypes is a comma separated
* string that lists the allowable concrete types in the union
* @return true if the attribute was created, false otherwise
*/
bool(CARB_ABI* createAttribute)(const NodeObj& node,
const char* name,
Type attributeType,
const void* value,
const size_t* elemCount,
AttributePortType portType,
ExtendedAttributeType extendedAttrType,
const char* unionTypes);
/**
* Removes a dynamic attribute from the node
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] name Name of the attribute
* @return true if the attribute was removed, false if the attribute was not found
*/
bool(CARB_ABI* removeAttribute)(const NodeObj& node, const char* name);
/** @private Deprecated - do not use */
CARB_DEPRECATED("Use EF Framework to customize task generation by nodes")
ScheduleNodeObj(CARB_ABI* createScheduleNode)(const NodeObj& node);
/**
* Registers a callback to be invoked when any attribute of the current node is connected
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] connectionCallback The struct containing the callback to trigger, and a piece of user data.
* The parameters are the attributes of this and the other node being connected, and a void* of user data
* @return true for success, false for failure
*/
bool(CARB_ABI* registerConnectedCallback)(const NodeObj& node,
ConnectionCallback connectionCallback);
/**
* Registers a callback to be invoked when any attribute of the current node is disconnected
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] connectionCallback The struct containing the callback to trigger, and a piece of user data.
* The parameters are the attributes of this and the other node being disconnected, and a void* of user data
* @return true for success, false for failure
*/
bool(CARB_ABI* registerDisconnectedCallback)(const NodeObj& node,
ConnectionCallback connectionCallback);
/**
* Deregisters the callback to be invoked when any attribute of the current node is connected
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] connectionCallback The struct containing the callback to trigger, and a piece of user data.
*/
void(CARB_ABI* deregisterConnectedCallback)(const NodeObj& node, ConnectionCallback connectionCallback);
/**
* Deregisters the callback to be invoked when any attribute of the current node is disconnected
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] connectionCallback The struct containing the callback to trigger, and a piece of user data.
*/
void(CARB_ABI* deregisterDisconnectedCallback)(const NodeObj& node, ConnectionCallback connectionCallback);
/**
* When we are using dynamic scheduling (where the exact amount of work is not known upfront), a node may
* try to suppress downstream nodes from executing based on runtime execution information. To do this,
* it needs to turn on dynamic downstream control. This function returns whether the node is participating
* in this scheme. A good use case for this feature is where we have a lot of prim nodes ticking
* unnecessarily, consuming cycles. We can turn them off using this feature with information available
* at compute time.
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @return Whether this node is setup to participate in dynamic scheduling by dynamically controlling the
* scheduling of downstream nodes.
*/
bool(CARB_ABI* getDynamicDownstreamControl)(const NodeObj& node);
/**
* When we are using dynamic scheduling (where the exact amount of work is not known upfront), nodes may
* try to suppress downstream nodes from executing based on runtime execution information. To do this,
* it needs to turn on dynamic downstream control. This function sets whether the node is participating
* in this scheme. You need to call this function on the upstream node that is suppressing downstream
* activity.
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] value Whether to turn the flag on or off on the node
* @return Whether this node is setup to participate in dynamic scheduling by dynamically controlling the
* scheduling of downstream nodes.
*/
void(CARB_ABI* setDynamicDownstreamControl)(const NodeObj& node, bool value);
/**
* Returns the NodeTypeObj structure associated with this node.
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @return NodeTypeObj encapsulating the node type from which this node was created
*/
NodeTypeObj(CARB_ABI* getNodeTypeObj)(const NodeObj& node);
/**
* Resolves attribute types given a set of attributes which are fully type coupled.
* For example if node 'Increment' has one input attribute 'a' and one output attribute 'b'
* and the types of 'a' and 'b' should always match. If the input is resolved then this function will
* resolve the output to the same type.
* It will also take into consideration available conversions on the input side.
* The type of the first (resolved) provided attribute will be used to resolve others or select appropriate conversions
*
* Note that input attribute types are never inferred from output attribute types.
*
* This function should only be called from the INodeType function `onConnectionTypeResolve`
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[out] attrsBuf Buffer that holds the attributes to be resolved as a coupled group
* @param[in] bufferSize the number of AttributeObj structures the buffer is able to hold
* @return true if successful, false otherwise, usually due to mismatched or missing resolved types
*/
bool(CARB_ABI* resolveCoupledAttributes)(const NodeObj& node, AttributeObj* attrsBuf, size_t bufferSize);
/**
* Resolves attribute types given a set of attributes, that can have differing tuple counts and/or array depth,
* and differing but convertible base data type.
* The three input buffers are tied together, holding the attribute, the tuple
* count, and the array depth of the types to be coupled.
* This function will solve base type conversion by targeting the first provided type in the list,
* for all other ones that require it.
*
* For example if node 'makeTuple2' has two input attributes 'a' and 'b' and one output 'c' and we want to resolve
* any float connection to the types 'a':float, 'b':float, 'c':float[2] (convertible base types and different tuple counts)
* then the input buffers would contain:
* attrsBuf = [a, b, c]
* tuplesBuf = [1, 1, 2]
* arrayDepthsBuf = [0, 0, 0]
* rolesBuf = [AttributeRole::eNone, AttributeRole::eNone, AttributeRole::eNone]
*
* This is worth noting that 'b' could be of any type convertible to float. But since the first provided
* attribute is 'a', the type of 'a' will be used to propagate the type resolution.
*
* Note that input attribute types are never inferred from output attribute types.
*
* This function should only be called from the INodeType function `onConnectionTypeResolve`
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] attrsBuf Buffer that holds the attributes to be resolved as a coupled group
* @param[in] tuplesBuf Buffer that holds the tuple count desired for each corresponding attribute. Any value
* of kUninitializedTypeCount indicates the found tuple count is to be used when resolving.
* @param[in] arrayDepthsBuf Buffer that holds the array depth desired for each corresponding attribute. Any value
* of kUninitializedTypeCount indicates the found array depth is to be used when resolving.
* @param[in] rolesBuf Buffer that holds the role desired for each corresponding attribute. Any value of
* AttributeRole::eUnknown indicates the found role is to be used when resolving.
* @param[in] bufferSize the number of AttributeObj structures the buffer is able to hold
* @return true if successful, false otherwise, usually due to mismatched or missing resolved types
*/
bool(CARB_ABI* resolvePartiallyCoupledAttributes)(const NodeObj& node,
const AttributeObj* attrsBuf,
const uint8_t* tuplesBuf,
const uint8_t* arrayDepthsBuf,
const AttributeRole* rolesBuf,
size_t bufferSize);
/** @private Deprecated - do not use */
CARB_DEPRECATED("Use USD notice handling to monitor changes")
bool(CARB_ABI* registerPathChangedCallback)(const NodeObj&, PathChangedCallback);
/** @private Deprecated - do not use */
CARB_DEPRECATED("Use USD notice handling to monitor changes")
void(CARB_ABI* deregisterPathChangedCallback)(const NodeObj& node, PathChangedCallback pathChangedCallback);
/**
* Returns the graph wrapped by this node, if any (as opposed to the graph this node belongs to)
* @param[in] node Reference to the NodeObj struct representing the node object
* @return GraphObj structure containing the graph wrapped by this node
*/
GraphObj(CARB_ABI* getWrappedGraph)(const NodeObj& node);
/**
* Returns the interface for the event stream generated by changes to this node.
* @return The IEventStreamPtr that pumps events when node changes happen
*/
carb::events::IEventStreamPtr(CARB_ABI* getEventStream)(const NodeObj& node);
/**
* Returns whether the NodeObj's handle is still valid
* @param[in] node Reference to the NodeObj struct representing the node object
* @return true if valid, false otherwise
*/
bool (CARB_ABI* isValid)(const NodeObj& node);
/**
* Requests that the given node be computed at the next graph evaluation. This is for use with nodes that are
* marked as being RequestDrivenCompute.
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @return true if the request was successful, false if there was an error
*/
bool(CARB_ABI* requestCompute)(const NodeObj& node);
/**
* Returns a NobeObj for the given NodeHandle if the referenced node is valid.
*
* @param[in] nodeHandle The NodeHandle for the compute node
* @return The NodeObj representing the node. In case of failure, the node handle
* will be kInvalidNodeHandle
*/
NodeObj(CARB_ABI* getNodeFromHandle)(const NodeHandle nodeHandle);
/**
* Returns the number of times compute() has been called on this node since the
* counter last rolled over to 0.
*
* @param[in] node Reference to the NodeObj struct representing the node object.
* @return The count.
*/
size_t (CARB_ABI* getComputeCount)(const NodeObj& node);
/** @private Deprecated - do not use */
CARB_DEPRECATED("Use increaseComputeCount instead")
size_t (CARB_ABI* incrementComputeCount)(const NodeObj& node);
/** @private Deprecated - do not use */
CARB_DEPRECATED("Use logComputeMessageOnInstance instead")
bool (CARB_ABI* logComputeMessage)(const NodeObj& node, ogn::Severity severity, const char* message);
/**
* Returns the number of compute messages of the given severity logged for the node.
*
* Compute messages are cleared at the start of each evaluation, so the count will be
* only for the most recent evaluation.
*
* @param[in] node Reference to the NodeObj struct representing the node object.
* @param[in] severity Severity level of the messages.
* @return The number of compute messages of the specified severity.
*/
size_t (CARB_ABI* getComputeMessageCount)(const NodeObj& node, ogn::Severity severity);
/**
* Returns a specified compute message of the given severity logged for the node.
*
* Use getComputeMessageCount() to determine the number of messages currently available.
*
* @param[in] node Reference to the NodeObj struct representing the node object.
* @param[in] severity Severity level of the message to return.
* @param[in] index Index of the message to return, starting at 0.
* @return The requested message or nullptr if 'index' was out of range.
*/
const char* (CARB_ABI* getComputeMessage)(const NodeObj& node, ogn::Severity severity, size_t index);
/**
* Clears all compute messages logged for the node prior to its most recent evaluation.
* Messages from its most recent evaluation are left untouched.
*
* @param[in] node Reference to the NodeObj struct representing the node object.
* @return The number of messages that were deleted.
*/
size_t (CARB_ABI* clearOldComputeMessages)(const NodeObj& node);
/**
* Retrieve the OGN database for the current active instance of this node. The DB is maintained up2date internally by the framework.
* If it does not exists the provided ognCreate callback will be invoked to instantiate it
*
* @param[in] node Reference to the NodeObj struct representing the node object.
* @param[in] ognCreate A callback that allocates and returns the DB associated to the current active instance of this node. Ownership is transfered to the node
*/
ogn::OmniGraphDatabase*(CARB_ABI* getOgnDatabase)(const NodeObj& node, CreateDbFunc ognCreate);
/**
* Returns whether this node is a compound node. A compound node is a node whose node type is defined by a subgraph instead
* of a built-in type.
*
* @param[in] node Reference to the NodeObj struct representing the node object.
* @returns True if the provided node is a compound node, false otherwise
*/
bool(CARB_ABI* isCompoundNode)(const NodeObj& node);
/**
* Retrieve a persistent ID for the current active graph associated to this node, optionally offseted
*
* @param[in] node Handle representing the node object.
* @param[in] instanceOffset: In vectorized context, the instance index relative to the currently targeted graph
* @return A unique and process-persistent ID that represents the current active instance of this node
*/
NameToken (CARB_ABI* getGraphInstanceID)(NodeHandle node, InstanceIndex instanceOffset);
/**
* Returns a Stamp that is incremented any time an input or state attribute is changed outside of graph evaluation.
* For example, interactively or through a script.
*
* @param[in] node Reference to the NodeObj struct representing the node object.
* @returns The stamp value
*/
exec::unstable::Stamp(CARB_ABI* getAttributeChangeStamp)(const NodeObj& node);
/**
* Returns a handle to the associated sub-graph, if the given node is a compound node.
*
* @param[in] node Handle representing the node object.
* @return The GraphObj representing the graph. In case of failure, the graph handle
* will be kInvalidGraphHandle.
*/
GraphObj (CARB_ABI* getCompoundGraphInstance)(const NodeObj& node);
/**
* Query all the node and context handles that the provided node emulate when used in an auto instancing scenario.
*
* @param[in] node Handle representing the "master" node object, the one that handle the execution.
* @param[out] graphContexts A pointer reference that will be set to an array of all the emulated auto-instanced graph contexts
* @param[out] nodeObjects A pointer reference that will be set to an array of all the emulated auto-instanced nodes
* @return The number of elements in the returned arrays, 1 if there is not auto instancing associated to the provided node (itself)
*/
size_t(CARB_ABI* getAutoInstances)(const NodeObj& node, GraphContextObj const*& graphContexts, NodeObj const*& nodeObjects);
/** @private Retired - do not use */
bool (CARB_ABI* retired_5)(const NodeObj& nodeObj);
/**
* Logs a compute message of a given severity for the node.
*
* This method is intended to be used from within the compute() method of a
* node to alert the user to any problems or issues with the node's most recent
* evaluation. They are accumulated until the start of the next compute,
* at which point they are cleared.
*
* If duplicate messages are logged, with the same severity level, only one is
* stored.
*
* @param[in] node Reference to the NodeObj struct representing the node object.
* @param[in] inst In vectorized context, the instance index relative to the currently targeted graph
* @param[in] severity Severity level of the message.
* @param[in] message The message.
* @return Returns true if the message has already been logged, false otherwise.
*/
bool(CARB_ABI* logComputeMessageOnInstance)(const NodeObj& node, InstanceIndex inst, ogn::Severity severity, const char* message);
/**
* Increase the node's compute counter by the provided amount.
*
* This method is provided primarily for debugging and experimental uses and
* should not normally be used by end-users.
*
* @param[in] node Reference to the NodeObj struct representing the node object
* @param[in] count the number to be added to the compute count.
* @return The new count.
*/
size_t(CARB_ABI* increaseComputeCount)(const NodeObj& node, size_t count);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(INode, increaseComputeCount, 52)
/**
* Defines the node event types.
*/
enum class INodeEvent
{
eCreateAttribute, //!< Dynamic attribute added to a node
eRemoveAttribute, //!< Dynamic attribute removed from a node
eAttributeTypeResolve //!< Extended-type attribute resolution has changed
};
/**
* Defines the graph event types
*/
enum class IGraphEvent
{
eCreateVariable, ///< Variable has been added to the graph
eRemoveVariable, ///< Variable has been removed from the graph
eClosing, ///< Stage is closing
eComputeRequested, ///< INode::requestCompute was called on a contained node
eNodeAttributeChange,///< An input or state attribute changed outside of graph evaluation
eVariableTypeChange ///< A variable in the graph had its type changed
};
// ======================================================================
/** Interface to an OmniGraph, several of which may be present in a scene */
struct IGraph
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::IGraph", 3, 13);
/**
* Returns the number of nodes in the graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return The number of nodes in the graph
*/
size_t(CARB_ABI* getNodeCount)(const GraphObj& graphObj);
/**
* Get the nodes in the graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[out] nodesBuf Buffer to hold the return NodeObjs
* @param[in] bufferSize the number of NodeObj structures the buffer is able to hold
* @return true on success, false on failure
*/
bool(CARB_ABI* getNodes)(const GraphObj& graphObj, NodeObj* nodesBuf, size_t bufferSize);
/**
* Returns the number of subgraphs in the graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return The number of subgraphs in the graph
*/
size_t(CARB_ABI* getSubgraphCount)(const GraphObj& graphObj);
/**
* Get the subgraphs in the graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[out] graphsBuf Buffer to hold the return GraphObjs
* @param[in] bufferSize the number of GraphObjs structures the buffer is able to hold
* @return true on success, false on failure
*/
bool(CARB_ABI* getSubgraphs)(const GraphObj& graphObj, GraphObj* graphsBuf, size_t bufferSize);
/**
* Get a particular subgraph in the graph given its path
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] subgraphPath the path to the subgraph in question
* @return The GraphObj representing the graph. In case of failure, the graph handle
* will be kInvalidGraphHandle
*/
GraphObj(CARB_ABI* getSubgraph)(const GraphObj& graphObj, const char* subgraphPath);
/**
* Returns the path to the graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return The path to the graph (may be empty)
*/
const char*(CARB_ABI* getPathToGraph)(const GraphObj& graphObj);
/**
* Returns whether the current graph is disabled
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return true if the current graph is disabled false otherwise
*/
bool(CARB_ABI* isDisabled)(const GraphObj& graphObj);
/**
* Sets the disabled state of the graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] disable Whether or not to disable the current graph
*/
void(CARB_ABI* setDisabled)(const GraphObj& graphObj, bool disable);
/**
* Get the default graph context associated with the graph. Each graph has a default
* context - it's usually one that gives you evaluation of the graph on the current
* time, for example.
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return The GraphContextObj representing the default graph context associated with
* the node.
*/
GraphContextObj(CARB_ABI* getDefaultGraphContext)(const GraphObj& graphObj);
/**
* Get a particular node in the graph given its path
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] nodePath the path to the node in question
* @return The NodeObj representing the node. In case of failure, the node handle
* will be kInvalidNodeHandle
*/
NodeObj(CARB_ABI* getNode)(const GraphObj& graphObj, const char* nodePath);
/**
* Create a node in the graph at a given path with a given type
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] nodePath the path to where the node will be added
* @param[in] nodeType the type name of the node to add
* @param[in] createUsd Whether to create USD backing for the node being created
* @return The NodeObj representing the node. In case of failure, the node handle
* will be kInvalidNodeHandle
*/
NodeObj(CARB_ABI* createNode)(GraphObj& graphObj, const char* nodePath, const char* nodeType, bool createUsd);
/**
* Destroy the node in the graph at a given path
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] nodePath the path of the node to destroy
* @param[in] destroyUsd Whether to destroy USD backing for the node being destroyed
* @return True, if the node was successfully destroyed. False otherwise.
*/
bool(CARB_ABI* destroyNode)(GraphObj& graphObj, const char* nodePath, bool destroyUsd);
/**
* Rename the node in the graph at a given path
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] nodePath the path of the node to rename
* @param[in] newPath the new path of the node
* @return True, if the node was successfully renamed. False otherwise.
*/
bool(CARB_ABI* renameNode)(GraphObj& graphObj, const char* oldPath, const char* newPath);
/**
* Create a subgraph in the graph at a given path with a given type
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] subgraphPath the path to where the subgraph will be added
* @param[in] evaluator the evaluator type to use for the subgraph being created
* @param[in] createUsd whether to create USD backing for the subgraph being created
* @return The GraphObj representing the subgraph. In case of failure, the graph handle
* will be kInvalidGraphHandle
*/
GraphObj(CARB_ABI* createSubgraph)(GraphObj& graphObj, const char* subgraphPath, const char* evaluator, bool createUsd);
/**
* reload the graph settings based on ComputeGraphSettings
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
*/
void(CARB_ABI* reloadGraphSettings)(GraphObj& graphObj);
/**
* Rename the subgraph in the graph at a given path
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] subgraphPath the path of the subgraph to rename
* @param[in] newPath the new path of the subgraph
* @return True, if the subgraph was successfully renamed. False otherwise.
*/
bool(CARB_ABI* renameSubgraph)(GraphObj& graphObj, const char* oldPath, const char* newPath);
/**
* Notifies the graph that some attribute has changed on a node. This will trigger
* updates from things like lazy evaluation graphs, for example.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] Reference to the AttributeObj struct representing the attribute object
*/
void(CARB_ABI* onAttributeChanged)(const GraphObj& graphObj, const AttributeObj& attrObj);
/** @private Deprecated - do not use */
CARB_DEPRECATED("Will be removed in next major version, please use IGraph::inspect instead")
void(CARB_ABI* printDiagnostic)(const GraphObj&);
/**
* Register a callback to be invoked when a legacy file with an older file format version
* is detected. This callback is invoked before stage attach happens.
*
* @param[in] fileFormatUpgrade - structure containing the callback and a piece of user data to
* be passed back to the callback when invoked.
*/
void (CARB_ABI* registerPreLoadFileFormatUpgradeCallback)(FileFormatUpgrade fileFormatUpgrade);
/**
* Register a callback to be invoked when a legacy file with an older file format version
* is detected. This callback is invoked after stage attach happens.
*
* @param[in] fileFormatUpgrade - structure containing the callback and a piece of user data to
* be passed back to the callback when invoked.
*/
void (CARB_ABI* registerPostLoadFileFormatUpgradeCallback)(FileFormatUpgrade fileFormatUpgrade);
/**
* Deregisters the pre-load callback to be invoked when a legacy file with an older
* file format version is detected.
*
* @param[in] fileFormatUpgrade - structure containing the callback and a piece of user data to
* be passed back to the callback when invoked.
*
*/
void (CARB_ABI* deregisterPreLoadFileFormatUpgradeCallback)(FileFormatUpgrade fileFormatUpgrade);
/**
* Deregisters the post-load callback to be invoked when a legacy file with an older
* file format version is detected.
*
* @param[in] fileFormatUpgrade - structure containing the callback and a piece of user data to
* be passed back to the callback when invoked.
*/
void (CARB_ABI* deregisterPostLoadFileFormatUpgradeCallback)(FileFormatUpgrade fileFormatUpgrade);
/**
* Returns whether USD notice handling is enabled for the graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return true if the current graph has USD notice handling enabled
*/
bool(CARB_ABI* usdNoticeHandlingEnabled)(const GraphObj& graphObj);
/**
* Sets whether the USD notice handling is enabled for this graph. This is an
* advanced operation - do not use this method unless you know what you're doing.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] enable Whether or not to enable USD notice handling for this graph
*/
void(CARB_ABI* setUSDNoticeHandlingEnabled)(const GraphObj& graphObj, bool enable);
/**
* Runs the inspector on the data in the given graph.
*
* @param[in] graphObj The graph on which the inspector runs
* @param[in] inspector The inspector class
* @return true if the inspection ran successfully, false if the inspection type is not supported
*/
bool(CARB_ABI* inspect)(const GraphObj& graphObj, inspect::IInspector* inspector);
/**
* Create a new graph, wrapped as a node, at the given location.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] nodeName the name of the node that wraps the graph
* @param[in] graphPath the path to where the graph that the node will wrap will be added
* @param[in] evaluatorName the evaluator to use for the new graph
* @param[in] isGlobalGraph Whether this graph is a top level global graph
* @param[in] backByUSD Whether to back this graph by USD
* @param[in] backingType What kind of FC backs this graph
* @param[in] graphPipelineStage What pipeline stage this graph occupies
* @return The NodeObj representing the node that wraps the graph. The newly created graph can be
* retrieved from the node. In case of failure, the NodeObj will contain kInvalidNodeHandle
*/
NodeObj(CARB_ABI* createGraphAsNode)(GraphObj& graphObj,
const char* nodeName,
const char* graphPath,
const char* evaluatorName,
bool isGlobalGraph,
bool backByUSD,
GraphBackingType backingType,
GraphPipelineStage graphPipelineStage);
/**
* Reloads the graph from the stage by deleting the current graph and creating a new one to attach
* to the stage. Note: this is a complete reset - any stateful nodes will lose their state.
*
* @param[in] graphObj The graph to reload
*/
void(CARB_ABI* reloadFromStage)(const GraphObj& graphObj);
/**
* Returns the Fabric backing type for this graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return Fabric backing type. See GraphBackingType definition for details.
*/
GraphBackingType(CARB_ABI* getGraphBackingType)(const GraphObj& graphObj);
/**
* Returns the graph pipeline stage (eg. simulation, pre-render, post-render) for this graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return Graph pipeline stage. See GraphPipelineStage definition for details.
*/
GraphPipelineStage(CARB_ABI* getPipelineStage)(const GraphObj& graphObj);
/**
* Returns whether the GraphObj's handle is still valid
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return true if valid, false otherwise
*/
bool(CARB_ABI* isValid)(const GraphObj& graphObj);
/**
* Returns the FabricId for this Graph. This id can be used with the Fabric API, but should only
* be required for advanced use cases.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[out] fabricId The output user id
* @return true on success, false on failure
*/
bool(CARB_ABI* getFabricId)(const GraphObj& graphObj, omni::fabric::FabricId& fabricId);
/**
* Warning: this is an advanced function - do not call unless you know exactly what is involved here.
*
* This allows a graph to be "ticked" independently of the normal graph evaluation process, where
* graphs are ordered into different pipeline stages (simulation, pre-render, post-render), and all
* graphs of each stage are evaluated according to the order described in the orchestration graph in
* each stage.
*
* Instead, this function allows graphs in the custom pipeline stage to be evaluated on its own.
* If this function is being called from a different thread, it is the caller's responsibility to ensure
* that the Fabric backing the graph is independent (stage without history), otherwise data races
* will ensue. If this function is being called from the simulation / main thread, the the Fabric
* backing the graph may be a shared one.
*
* It is illegal to call this function for any graph other than those setup with the custom pipeline
* stage.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
*/
void (CARB_ABI* evaluate)(const GraphObj& graphObj);
/**
* Returns the parent of this graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return The parent graph (may be invalid)
*/
GraphObj(CARB_ABI* getParentGraph)(const GraphObj& graphObj);
/**
* Returns whether the path points to a top level graph prim.
*
* @param[in] path to the prim in question
* @return True if the path points to a prim that is a top level graph
*/
bool(CARB_ABI* isGlobalGraphPrim)(const char* path);
/**
* Registers a callback to be invoked at the end of graph evaluation for all of the nodes
* whose error status changed during that evaluation.
*
* This is provided primarily for UI purposes. E.g. highlighting nodes with compute errors
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] errorStatusChangeCallback - structure containing the callback and a piece of user data to
* be passed back to the callback when invoked.
*/
void (CARB_ABI* registerErrorStatusChangeCallback)(const GraphObj& graphObj, ErrorStatusChangeCallback errorStatusChangeCallback);
/**
* Deregisters a callback to be invoked at the end of graph evaluation for all of the nodes
* whose error status changed during that evaluation.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] errorStatusChangeCallback - structure containing the callback and a piece of user data to
* be passed back to the callback when invoked.
*
*/
void (CARB_ABI* deregisterErrorStatusChangeCallback)(const GraphObj& graphObj, ErrorStatusChangeCallback errorStatusChangeCallback);
/** @private deprecated - do not use */
CARB_DEPRECATED("Will be retired in next major version: this call is not necessary anymore and can be safely removed")
void(CARB_ABI* nodeErrorStatusChanged)(const GraphObj& graphObj, const NodeObj& nodeObj);
/**
* Returns the number of variables in the graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return The number of variables in the graph.
*/
size_t(CARB_ABI* getVariableCount)(const GraphObj& graphObj);
/**
* Get the variables defined in the graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[out] variableBuf Buffer to hold the returned IVariable objects
* @param[in] bufferSize The number of IVariable objects the buffer is able to hold
* @return true on success, false on failure
*/
bool(CARB_ABI* getVariables)(const GraphObj& graphObj, IVariablePtr* variableBuf, size_t bufferSize);
/**
* Create a new variable on the graph with the given name. The name must be unique
* among variables on the graph, even if the type is different.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] name The name to give the variable.
* @param[in] variableType the data type used to create the variable.
* @return The newly created variable, or null if the variable could not be created.
*/
IVariablePtr(CARB_ABI* createVariable)(const GraphObj& graphObj, const char* name, Type variableType);
/**
* Removes the given variable from the graph.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] variable The variable to remove from the graph.
* @return True if the variable was successfully removed, false otherwise.
*/
bool(CARB_ABI* removeVariable)(const GraphObj& graphObj, const IVariablePtr& variable);
/**
* Retrieves a variable with the given name.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] name The name of the variable to search for.
* @return The variable with the given name on the graph, or null if the variable does
* not exist.
*/
IVariablePtr(CARB_ABI* findVariable)(const GraphObj& graphObj, const char* name);
/**
* Change the pipeline stage (eg. simulation, pre-render, post-render) that this graph is in
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] newPipelineStage The new pipeline stage that this graph will be moved into
*/
void (CARB_ABI* changePipelineStage)(const GraphObj& graphObj, GraphPipelineStage newPipelineStage);
/**
* Returns the interface for the event stream generated by changes to this graph.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return The IEventStreamPtr that pumps events when graph changes happen
*/
carb::events::IEventStreamPtr(CARB_ABI* getEventStream)(const GraphObj& graphObj);
/**
* Returns the evaluation mode of the graph. The evaluation mode determines how the graph
* will be evaluated standalone or when referenced from an OmniGraphAPI component.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return The evaluation mode of the graph
*/
GraphEvaluationMode(CARB_ABI* getEvaluationMode)(const GraphObj& graphObj);
/**
* Sets the evaluation mode of the graph. The evaluation mode determines if the graph
* will be evaluated standalone or when referenced from an OmniGraphAPI component.
*
* @param[in] graphObj Reference to the graph object
* @param[in] evaluationMode the evaluation mode of the graph to set
*/
void(CARB_ABI* setEvaluationMode)(const GraphObj& graphObj, GraphEvaluationMode evaluationMode);
/**
* Create a new graph, wrapped as a node, at the given location.
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @param[in] options Options relating to creating a graph as a node.
* @return The NodeObj representing the node that wraps the graph. The newly created graph can be
* retrieved from the node. In case of failure, the NodeObj will contain kInvalidNodeHandle
*/
NodeObj(CARB_ABI* createGraphAsNodeV2)(GraphObj& graphObj, const CreateGraphAsNodeOptions& options);
/**
* Returns the name of the evaluator for the specified graph
*
* @param[in] graphObj Reference to the GraphObj struct representing the graph object
* @return The name of the evaluator, or the empty string if it isn't set.
*/
const char*(CARB_ABI* getEvaluatorName)(const GraphObj& graphObj);
/**
* Returns whether this graph is a compound graph instance. A compound graph is a subgraph that
* is parented to a compound node
*
* @return True if this graph is a compound graph, false otherwise.
*/
bool(CARB_ABI* isCompoundGraph)(const GraphObj& graphObj);
/**
* Returns the number of instance currently allocated for this graph
*
* @return The number of instances registered in the graph, 0 if the graph is standalone
*/
size_t(CARB_ABI* getInstanceCount)(const GraphObj& graphObj);
/**
* Returns whether this graph is an auto instance. An auto instance is a graph that got merged as an instance
* with all other similar graphs in the stage.
*
* @return True if this graph is an auto instance, false otherwise.
*/
bool(CARB_ABI* isAutoInstanced)(const GraphObj& graphObj);
/**
* Set whether or not this graph can be candidate for auto-instance merging (true by default)
*
* @return The old value of the allowed flag
*/
bool(CARB_ABI* setAutoInstancingAllowed)(const GraphObj& graphObj, bool allowed);
/**
* Returns the compound node for which this graph is the compound subgraph of.
*
* @return If this graph is a compound graph, the owning compound node. Otherwise, an invalid node is returned.
*/
NodeObj(CARB_ABI* getOwningCompoundNode)(const GraphObj& graphObj);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IGraph, getOwningCompoundNode, 52)
using DataAccessFlags = uint32_t; //!< Data type for specifying read/write access abilities
static constexpr DataAccessFlags kReadAndWrite = 0; //!< Data is accessible for both read and write
static constexpr DataAccessFlags kReadOnly = 1; //!< Data is only accessible for reading
static constexpr DataAccessFlags kWriteOnly = 2; //!< Data is only accessible for writing
// ======================================================================
/** Use this interface to pull data for compute node, and also push data to compute graph/cache */
struct IGraphContext
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::IGraphContext", 3, 7);
/**
* Returns the stage id the context is currently attached to
* @param[in] context structure containing both the interface and underlying object
* @return the USD stage id
*/
long int(CARB_ABI* getStageId)(const GraphContextObj& contextObj);
//---------------------------------------------------------------------------------------------
// wrappers for fabric
/** @private Retired - do not use */
void (CARB_ABI* retired_1)();
/** @private Retired - do not use */
void (CARB_ABI* retired_2)();
/** @private Deprecated - do not use */
size_t*(CARB_ABI* deprecated_12)(const GraphContextObj&, const AttributeObj&, DataAccessFlags);
/** @private Deprecated - do not use */
size_t*(CARB_ABI* deprecated_13)(const GraphContextObj&, const AttributeObj&, DataAccessFlags);
/** @private Retired - do not use */
void (CARB_ABI* retired_3)();
/** @private Retired - do not use */
void (CARB_ABI* retired_4)();
/** @private Retired - do not use */
void (CARB_ABI* retired_5)();
/** @private Retired - do not use */
void (CARB_ABI* retired_6)();
/** @private Retired - do not use */
void (CARB_ABI* retired_7)();
/** @private Retired - do not use */
void (CARB_ABI* retired_8)();
/**
* Returns the graph associated with this context
* @param[in] context structure containing both the interface and underlying object
* @return GraphObj structure containing the graph
*/
GraphObj(CARB_ABI* getGraph)(const GraphContextObj& context);
/**
* Returns the time between last evaluation of the graph and "now"
* @param[in] context structure containing both the interface and underlying object
* @return the elapsed time
*/
float(CARB_ABI* getElapsedTime)(const GraphContextObj& contextObj);
/**
* Returns the global playback time
* @param[in] context structure containing both the interface and underlying object
* @return the global playback time in seconds
*/
float(CARB_ABI* getTime)(const GraphContextObj& contextObj);
/**
* Returns the time between last evaluation of the graph and "now", in NS.
* Note this will only return valid values if the update loop is using the
* void updateSimStep(int64_t timeNS, carb::tasking::Counter* counter, bool) interface
* As of this writing, this is limited to the DS project
*
* @param[in] context structure containing both the interface and underlying object
* @return the elapsed time in nano seconds
*/
int64_t(CARB_ABI* getElapsedTimeNS)(const GraphContextObj& contextObj);
/**
* Returns the global time in NS.
* Note this will only return valid values if the update loop is using the
* void updateSimStep(int64_t timeNS, carb::tasking::Counter* counter, bool) interface
* As of this writing, this is limited to the DS project
*
* @param[in] context structure containing both the interface and underlying object
* @return the global time in nano seconds
*/
int64_t(CARB_ABI* getTimeNS)(const GraphContextObj& contextObj);
/**
* Given an attribute, retrieves the default attribute value in system memory
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] attrObj The attribute object for which to retrieve the default value
* @return the const void pointer to the data
*/
const void*(CARB_ABI* getDefault)(const GraphContextObj& context, const AttributeObj& attrObj);
/** @private Deprecated - do not use */
ConstBundleHandle(CARB_ABI* deprecated_4)(const GraphContextObj&, NodeContextHandle, NameToken);
/** @private Deprecated - do not use */
size_t (CARB_ABI* deprecated_5)(const GraphContextObj&, NodeContextHandle, NameToken);
/** @private Deprecated - do not use */
void (CARB_ABI* deprecated_6)(const GraphContextObj&,NodeContextHandle,NameToken,ConstBundleHandle*);
/** @private Deprecated - do not use */
BundleHandle (CARB_ABI* deprecated_3)(const GraphContextObj& , NodeContextHandle, NameToken);
/** @private Deprecated - do not use */
void(CARB_ABI* deprecated_7)(
ConstAttributeDataHandle*, const GraphContextObj&, NodeContextHandle, const NameToken*, size_t);
/** @private Deprecated - do not use */
void(CARB_ABI* deprecated_8)(AttributeDataHandle*, const GraphContextObj&, NodeContextHandle, const NameToken*, size_t);
/**
* Retrieve the number of attributes that a given node has
*
* @param[in] contextObj: Structure containing both the interface and underlying object
* @param[in] node The node to query the attribute count from
* @return the number of attributes the queried node has
*/
size_t (CARB_ABI* getAttributesCount)(const GraphContextObj& contextObj, NodeContextHandle node);
/** @private Deprecated - do not use */
void(CARB_ABI* deprecated_9)(ConstAttributeDataHandle*, const GraphContextObj&, NodeContextHandle, size_t);
/** @private Deprecated - do not use */
void(CARB_ABI* deprecated_10)(AttributeDataHandle*, const GraphContextObj&, NodeContextHandle, size_t);
/** @private Deprecated - do not use */
BundleHandle(CARB_ABI* deprecated_11)(const GraphContextObj&, NodeContextHandle, NameToken, ConstBundleHandle);
/** @private Deprecated - do not use */
[[deprecated("Use copyBundleContentsInto")]] void (CARB_ABI* copyPrimContentsInto)(const GraphContextObj& contextObj,
BundleHandle destBundleHandle,
ConstBundleHandle sourceBundleHandle);
/** @private Retired - do not use */
void(CARB_ABI* retired_10)();
/** @private Deprecated - do not use */
[[deprecated("Use clearBundleContents")]] void(CARB_ABI* clearPrimContents)(const GraphContextObj& contextObj, BundleHandle bundleHandle);
/** @private Retired - do not use */
void(CARB_ABI* retired_9)();
/**
* Returns the global playback time in frames
* @param[in] context structure containing both the interface and underlying object
* @return the global playback time in frames
*/
float(CARB_ABI* getFrame)(const GraphContextObj& contextObj);
/**
* Returns the state of global playback
* @param[in] context structure containing both the interface and underlying object
* @return true if playback has started, false is playback is stopped
*/
bool(CARB_ABI* getIsPlaying)(const GraphContextObj& contextObj);
/**
* Runs the inspector on the data in the given graph context.
*
* @param[in] contextObj The graph context on which the inspector runs
* @param[in] inspector The inspector class
* @return true if the inspection ran successfully, false if the inspection type is not supported
*/
bool(CARB_ABI* inspect)(const GraphContextObj& contextObj, inspect::IInspector* inspector);
/**
* Returns the time since the App started
* @param[in] context structure containing both the interface and underlying object
* @return the global time since the app started in seconds
*/
double(CARB_ABI* getTimeSinceStart)(const GraphContextObj& contextObj);
/**
* Returns whether the graph context object is still valid or not
*
* @param[in] contextObj The context object for which to query
* @return Whether the context is still valid
*/
bool(CARB_ABI* isValid)(const GraphContextObj& contextObj);
/** @private Deprecated - do not use */
AttributeDataHandle (CARB_ABI* deprecated_0)(const GraphContextObj&, const IVariablePtr&);
/** @private Deprecated - do not use */
ConstAttributeDataHandle(CARB_ABI* deprecated_1)(const GraphContextObj&, const IVariablePtr&);
/**
* Returns the accumulated total of elapsed times between rendered frames
* @param[in] contextObj structure containing both the interface and underlying object
* @return the accumulated total of elapsed times between rendered frames
*/
double(CARB_ABI* getAbsoluteSimTime)(const GraphContextObj& contextObj);
/** @private Deprecated - do not use */
NameToken(CARB_ABI* deprecated_2)(const GraphContextObj&);
/** Deprecated - do not use - removal scheduled for 106 **/
[[deprecated("Use registerForUSDWriteBacks")]]
void(CARB_ABI* registerForUSDWriteBack)(const GraphContextObj& contextObj, BundleHandle bundle, NameToken attrib);
/**
* Given a variable and an instance path, returns a handle to access its data.
*
* @param[in] contextObj The context object used to find the variable data
* @param[in] variable The variable to retrieve the data from
* @param[in] Path to the prim holding an instance of this graph
*
* @returns An attribute data handle that can be used to access the variable data.
* If the given prim does not contain an instance of the graph, the data handle
* returned will be invalid.
*/
AttributeDataHandle(CARB_ABI* getVariableInstanceDataHandle)(const GraphContextObj& contextObj,
const IVariablePtr& variable,
const char* instancePrimPath);
/**
* Given a variable and an instance path, returns a constant handle to access its data as readonly.
*
* @param[in] contextObj The context object used to find the variable data
* @param[in] variable The variable to retrieve the data from
* @param[in] Path to the prim holding an instance of this graph
*
* @returns An constant attribute data handle that can be used to access the variable data.
* If the given prim does not contain an instance of the graph, the data handle
* returned will be invalid.
*/
ConstAttributeDataHandle(CARB_ABI* getVariableInstanceConstDataHandle)(const GraphContextObj& contextObj,
const IVariablePtr& variable,
const char* instancePrimPath);
/**
* Get the Prim path of the graph target.
*
* The graph target is defined as the parent Prim of the compute graph, except during
* instancing - where OmniGraph executes a graph once for each Prim. In the case
* of instancing, the graph target will change at each execution to be the path of the instance.
* If this is called outside of graph execution, the path of the graph Prim is returned, or an empty
* token if the graph does not have a Prim associated with it.
*
* @param[in] contextObj The context object used to find the data.
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*
* @returns a token representing the path of the graph target primitive.
*/
NameToken const&(CARB_ABI* getGraphTarget)(const GraphContextObj& contextObj, InstanceIndex instanceIndex);
/**
* Given a variable, returns a handle to access its data.
*
* @param[in] contextObj The context object used to find the variable data
* @param[in] variable The variable to retrieve the data from
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*
* @returns An attribute data handle that can be used to access the variable data.
*/
AttributeDataHandle(CARB_ABI* getVariableDataHandle)(const GraphContextObj& contextObj,
const IVariablePtr& variable,
InstanceIndex instanceIndex);
/**
* Given a variable, returns a constant handle to access its data as readonly.
*
* @param[in] contextObj The context object used to find the variable data
* @param[in] variable The variable to retrieve the data from
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*
* @returns A constant attribute data handle that can be used to access the variable data.
*/
ConstAttributeDataHandle(CARB_ABI* getVariableConstDataHandle)(const GraphContextObj& contextObj,
const IVariablePtr& variable,
InstanceIndex instanceIndex);
/** @private Deprecated - do not use */
[[deprecated("Use getOutputBundle!")]] BundleHandle(CARB_ABI* getOutputPrim)(const GraphContextObj& contextObj,
NodeContextHandle node,
NameToken bundleName,
InstanceIndex instanceIndex);
/** @private Deprecated - do not use */
[[deprecated("Use getInputTarget!")]] ConstBundleHandle(CARB_ABI* getInputPrim)(const GraphContextObj& contextObj,
NodeContextHandle node,
NameToken bundleName,
InstanceIndex instanceIndex);
/** @private Deprecated - do not use */
[[deprecated("Use getInputTargetCount!")]] size_t(CARB_ABI* getInputPrimCount)(const GraphContextObj& contextObj,
NodeContextHandle node,
NameToken relName,
InstanceIndex instanceIndex);
/** @private Deprecated - do not use */
[[deprecated("Use getInputTargets!")]] void(CARB_ABI* getInputPrims)(const GraphContextObj& contextObj,
NodeContextHandle node,
NameToken relName,
ConstBundleHandle* bundleHandles,
InstanceIndex instanceIndex);
/**
* Requests some input attributes of the specified compute node in the specified context.
*
* If no input attribute with the given name exists on the node, the returned handle
* will return false from its isValid() function.
*
*
* @param[in/out] attrsOut A pre-allocated array that will be filled with the requested handles
* @param[in] contextObj The context object used to find the data
* @param[in] node The node object to retrieve the data from
* @param[in] attrNames An array of names of attributes on the given node to retrieve a data handle for
* @param[in] count The size of the provided arrays (attrName and attrsOut)
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*/
void(CARB_ABI* getAttributesByNameR)(ConstAttributeDataHandle* attrsOut,
const GraphContextObj& contextObj,
NodeContextHandle node,
const NameToken* attrNames,
size_t count,
InstanceIndex instanceIndex);
/**
* Requests some output attributes of the specified compute node in the specified context.
*
* If no input attribute with the given name exists on the node, the returned handle
* will return false from its isValid() function.
*
*
* @param[in/out] attrsOut A pre-allocated array that will be filled with the requested handles
* @param[in] contextObj The context object used to find the data
* @param[in] node The node object to retrieve the data from
* @param[in] attrNames An array of names of attributes on the given node to retrieve a data handle for
* @param[in] count The size of the provided arrays (attrName and attrsOut)
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*/
void(CARB_ABI* getAttributesByNameW)(AttributeDataHandle* attrsOut,
const GraphContextObj& contextObj,
NodeContextHandle node,
const NameToken* attrNames,
size_t count,
InstanceIndex instanceIndex);
/**
* Requests all input attributes of the specified compute node in the specified context.
*
*
* @param[in/out] attrsOut A pre-allocated array that will be filled with the requested handles
* @param[in] contextObj The context object used to find the data
* @param[in] node The node object to retrieve the data from
* @param[in] count The size of the attrsOut array
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*/
void(CARB_ABI* getAttributesR)(ConstAttributeDataHandle* attrsOut,
const GraphContextObj& contextObj,
NodeContextHandle node,
size_t count,
InstanceIndex instanceIndex);
/**
* Requests all output attributes of the specified compute node in the specified context.
*
*
* @param[in/out] attrsOut A pre-allocated array that will be filled with the requested handles
* @param[in] contextObj The context object used to find the data
* @param[in] node The node object to retrieve the data from
* @param[in] count The size of the attrsOut array
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*/
void(CARB_ABI* getAttributesW)(AttributeDataHandle* attrsOut,
const GraphContextObj& contextObj,
NodeContextHandle node,
size_t count,
InstanceIndex instanceIndex);
/** @private Deprecated - do not use */
[[deprecated("use copyBundleContentsIntoOutput")]] BundleHandle(CARB_ABI* copyPrimContentsIntoOutput)(
const GraphContextObj& contextObj,
NodeContextHandle node,
NameToken outBundleName,
ConstBundleHandle sourceBundleHandle,
InstanceIndex instanceIndex);
/**
* Given an attribute of array type, return a pointer to the number of elements in the array
* If flags is kWriteOnly or kReadAndWrite then writing to the dereferenced pointer resizes the
* array the next time it is accessed on CPU or GPU
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] attrObj The attribute object for which to retrieve the array size
* @param[in] flags The data access flags indicating whether the array size is to be R, W, or RW
* @return the pointer to the array size
*/
size_t*(CARB_ABI* getArrayAttributeSize)(const GraphContextObj& context,
const AttributeObj& attrObj,
DataAccessFlags flags,
InstanceIndex instanceIndex);
/**
* Given an attribute of array type, return a GPU pointer to the number of elements in the array
* Flags must be kReadOnly, because currently we don't allow GPU code to resize GPU arrays
* This restriction may be relaxed in the future
* If you want to resize a GPU array you can do it on the CPU using getArrayAttributeSize
*
* @param[in] context structure containing both the interface and underlying object
* @param[in] attrObj The attribute object for which to retrieve the array size
* @param[in] flags The data access flags indicating whether the array size is to be R, W, or RW
* @return the pointer to the array size
*/
size_t*(CARB_ABI* getArrayAttributeSizeGPU)(const GraphContextObj& context,
const AttributeObj& attrObj,
DataAccessFlags flags,
InstanceIndex instanceIndex);
/**
* Requests an output bundle of the specified compute node in the specified context.
*
* If no output bundle with the given name exists on the node, the returned handle
* will return false from its isValid() function.
*
* @param[in] contextObj The context object used to find the data
* @param[in] node The node object to retrieve the data from
* @param[in] outputName The name of the attribute on the given node that represent the output bundle
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*
* @returns A handle to the requested prim
*/
BundleHandle(CARB_ABI* getOutputBundle)(const GraphContextObj& contextObj,
NodeContextHandle node,
NameToken outputName,
InstanceIndex instanceIndex);
/**
* Requests an input target path of the specified compute node in the specified context.
*
* If no input target path with the given name exists on the node, the returned path
* will return uninitialized path.
*
* @param[in] contextObj The context object used to find the data
* @param[in] node The node object to retrieve the data from
* @param[in] inputName The name of the attribute on the given node that represent the input bundle
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*
* @returns A path to the requested target
*/
omni::fabric::PathC(CARB_ABI* getInputTarget)(const GraphContextObj& contextObj,
NodeContextHandle node,
NameToken inputName,
InstanceIndex instanceIndex);
/**
* Requests the number of input targets in the relationship with the given name on the
* specified compute node in the specified context.
*
* This returns 0 if no relationship with the given name exists on the node
* or the relationship is empty.
*
* @param[in] contextObj The context object used to find the data
* @param[in] node The node object to retrieve the data from
* @param[in] inputName The name of the relationship attribute on the given node that represent the input targets
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*
* @returns The number of input targets under the provided relationship
*/
size_t(CARB_ABI* getInputTargetCount)(const GraphContextObj& contextObj,
NodeContextHandle node,
NameToken inputName,
InstanceIndex instanceIndex);
/**
* Fills in the provided targets array with paths to all of the input targets(bundles or primitives)
* in the relationship with the given name on the specified compute node in the specified context.
*
* The caller *must* first call getInputTargetCount to ensure that the targets array will be
* sufficiently large to receive all of the paths.
*
* @param[in] contextObj The context object used to find the data
* @param[in] node The node object to retrieve the data from
* @param[in] inputName The name of the relationship attribute on the given node that represent the input targets
* @param[in,out] targets A pre-sized array that will be filled with the requested paths
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*/
void(CARB_ABI* getInputTargets)(const GraphContextObj& contextObj,
NodeContextHandle node,
NameToken inputName,
omni::fabric::PathC* targets,
InstanceIndex instanceIndex);
/**
* Creates copies of all attributes from sourceBundleHandle in the output bundle
* with the specified name on the specified node.
*
* This function is equivalent to:
* BundleHandle retBundle = iContext.getOutputBundle(context, node, outBundleName);
* iContext.copyBundleContentsInto(context, retBundle, sourceBundleHandle);
* return retBundle;
* but with a single function pointer call, instead of two.
*
* @param[in] contextObj The context object used to find the data
* @param[in] node The node object to retrieve the data from
* @param[in] outBundleName The name of the attribute on the given node that represent the output bundle to write to
* @param[in] sourceBundleHandle A handle to a bundle to copy content from
* @param[in] instanceIndex In vectorized context, the instance index relative to the currently targeted graph
*
* @returns An handle to the targeted output bundle
*/
BundleHandle(CARB_ABI* copyBundleContentsIntoOutput)(const GraphContextObj& contextObj,
NodeContextHandle node,
NameToken outBundleName,
ConstBundleHandle sourceBundleHandle,
InstanceIndex instanceIndex);
/**
* Creates copies of all attributes from sourceBundleHandle in the bundle corresponding with destBundleHandle.
*
* @param contextObj The context object used to find the data
* @param destBundleHandle A handle to a bundle to copy content to
* @param sourceBundleHandle A handle to a bundle to copy content from
*/
void(CARB_ABI* copyBundleContentsInto)(const GraphContextObj& contextObj,
BundleHandle destBundleHandle,
ConstBundleHandle sourceBundleHandle);
/**
* Removes all attributes from the prim corresponding with bundleHandle,
* but keeps the bundle itself.
*
* @param contextObj The context object used to find the data
* @param bundleHandle A handle to a bundle to clear content from
*/
void(CARB_ABI* clearBundleContents)(const GraphContextObj& contextObj, BundleHandle bundleHandle);
/**
* Register provided attributes for USD write back at the end of the current frame
*
*
* @param[in] contextObj The context object used to find the data.
* @param[in] handles An array of handles of the attributes that should be written back to usd
* @param[in] count The size of the provided array
*/
void(CARB_ABI* registerForUSDWriteBacks)(const GraphContextObj& contextObj, AttributeDataHandle const* handles, size_t count);
/**
* Register provided attributes for USD write back at the end of the current frame to a specific layer
*
*
* @param[in] contextObj The context object used to find the data.
* @param[in] handles An array of handles of the attributes that should be written back to usd
* @param[in] count The size of the provided array
* @param[in] layerIdentifier The unique name for the layer to be written
*/
void(CARB_ABI* registerForUSDWriteBacksToLayer)(const GraphContextObj& contextObj,
AttributeDataHandle const* handles,
size_t count,
NameToken layerIdentifier);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IGraphContext, registerForUSDWriteBacksToLayer, 65)
// ==============================================================================================================
/** The underlying schedule node represents the scheduled task(s) corresponding to the representational node in the
* graph. As OmniGraph evolves, the schedule node will be extended to store the results of the instance(s)/task(s)
* corresponding to the representational node.
*/
struct IScheduleNode
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::IScheduleNode", 1, 0);
//! @private Deprecated: Task generation is the responsibility of the execution framework
NodeObj(CARB_ABI* getNode)(const ScheduleNodeObj& scheduleNodeObj);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IScheduleNode, getNode, 0)
// ==============================================================================================================
//! @private Retired prototype
struct IDataStealingPrototype
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::IDataStealingPrototype", 1, 1);
/** @private Retired - do not use */
bool(CARB_ABI* __retired_0)(const GraphContextObj&,ConstAttributeDataHandle,ConstAttributeDataHandle);
/** @private Retired - do not use */
AttributeDataHandle(CARB_ABI* __retired_1)(const GraphContextObj&,ConstAttributeDataHandle );
/** @private Retired - do not use */
bool(CARB_ABI* __retired_2)(const GraphContextObj&,ConstBundleHandle,ConstBundleHandle);
/** @private Retired - do not use */
BundleHandle(CARB_ABI* __retired_3)(const GraphContextObj&, ConstBundleHandle);
bool(CARB_ABI* enabled)(const GraphContextObj&);//always false
/** @private Retired - do not use */
void(CARB_ABI* __retired_4)(const GraphContextObj&, bool);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IDataStealingPrototype, __retired_4, 5)
} // namespace core
} // namespace graph
} // namespace omni
| 153,550 | C | 47.438801 | 164 | 0.671136 |
omniverse-code/kit/include/omni/graph/core/PostUsdInclude.h | // 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.
//
// This file should be included in conjunction with PreUsdInclude.h when including any of the individual USD
// definition files. This file restores the warnings that were disabled for the inclusion of USD files.
//
// It includes a special ifdef detection to prevent inclusion of this file without PreUsdInclude.h as that
// would have unpredictable effects on the compiler. The usual "#pragma once" is omitted, so that the mechanism works
// correctly even with multiple uses. It is not legal to include anything other than USD headers between these two.
//
// Here is an example of how you use this mechanism to include the definition of the USD type pxr::GfHalf:
//
// #include <omni/graph/core/PreUsdInclude.h>
// #include <pxr/base/gf/half.h>
// #include <omni/graph/core/PostUsdInclude.h>
//
#ifdef _MSC_VER
# pragma warning(pop)
# undef NOMINMAX
#elif defined(__GNUC__)
# pragma GCC diagnostic pop
# ifdef OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS
# define __DEPRECATED
# undef OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS
# endif
#endif
#ifdef __USD_INCLUDE_PROTECTION__
# undef __USD_INCLUDE_PROTECTION__
#else
# error "You must include PreUsdInclude.h before including PostUsdInclude.h"
#endif
| 1,669 | C | 41.820512 | 117 | 0.75734 |
omniverse-code/kit/include/omni/graph/core/IGraphRegistry.h | // 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.
//
#pragma once
#include <carb/events/IEvents.h>
#include <carb/Interface.h>
#include <omni/graph/core/Handle.h>
#include <omni/inspect/IInspector.h>
namespace omni {
namespace graph {
namespace core {
/**
* An event that occurs on the graph registry
*/
enum class IGraphRegistryEvent
{
//! Node type has been added to the registry. Event payloads are:
//! "node_type" (std::string): Name of new node type
eNodeTypeAdded,
//! Node type has been removed from the registry. Event payloads are:
//! "node_type" (std::string): Name of removed node type
eNodeTypeRemoved,
//! Node type has had its namespace changed. Event payloads are:
//! "node_type" (std::string): New namespace
//! "prev_type" (std::string): Previous namespace
eNodeTypeNamespaceChanged,
//! Node type has had its category changed. Event payloads are:
//! "node_type" (std::string): Node type whose category changed
//! "prev_value" (std::string): Previous category value
eNodeTypeCategoryChanged
};
// ======================================================================
//! Interface that manages the registration and deregistration of node types
struct IGraphRegistry
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::IGraphRegistry", 1, 5);
/**
* Returns the number of registered types in the graph. This includes C++ types only.
*
* @return The number of subgraphs in the graph
*/
size_t(CARB_ABI* getRegisteredTypesCount)();
/**
* Gets the list of the registered types in the graph. This includes C++ types only.
*
* @param[out] typesBuf Buffer to hold the return array of node type objects
* @param[in] bufferSize the number of NodeTypeObj structures the buffer is able to hold
* @return true on success, false on failure
*/
bool(CARB_ABI* getRegisteredTypes)(NodeTypeObj* typesBuf, size_t bufferSize);
/**
* Gets the version of the registered node type. This includes both C++ and Python types.
*
* @param[in] nodeType the name of the node type in question.
* @return the version number of the currently registered type. If the type is not found
* returns the default version number, which is 0
*/
int(CARB_ABI* getNodeTypeVersion)(const char* nodeType);
/**
* Registers a node type as defined above with the system
* Deprecated. Use registerNodeTypeInterface instead.
*
* @param[in] desc Reference to the node type interface (the underlying object is not yet available here)
* @param[in] version Version of the node interface to be registered
*/
CARB_DEPRECATED("Will be removed in next major version, use IGraphRegistry::registerNodeTypeInterface instead")
void(CARB_ABI* registerNodeType)(const INodeType& desc, int version);
/**
* Unregisters a node type interface as defined above with the system
*
* @param[in] nodeType Name of the node type to be unregistered
*/
void(CARB_ABI* unregisterNodeType)(const char* nodeType);
/**
* Registers an alias by which a node type can be referred to. Useful for backward compatibility in files.
*
* @param[in] desc Reference to the node type interface
* @param[in] alias Alternate name that can be used to refer to the node type when creating
*/
CARB_DEPRECATED("Will be removed in next major version, use INodeTypeForwarding instead")
void(CARB_ABI* registerNodeTypeAlias)(const INodeType& desc, const char* alias);
/**
* Runs the inspector on the contents of the graph registry.
*
* @param[in] inspector The inspector class
* @return true if the inspection ran successfully, false if the inspection type is not supported
*/
bool(CARB_ABI* inspect)(inspect::IInspector* inspector);
/**
* Gets the node type information corresponding to the node type name. This includes aliases.
*
* @param[in] bufferSize the number of NodeTypeObj structures the buffer is able to hold
* @return true on success, false on failure
*/
NodeTypeObj(CARB_ABI* getRegisteredType)(const char* nodeTypeName);
/**
* Returns the interface for the event stream for the changes on the graph registry
*
* The events that are raised are specified by IGraphRegistryEvent
*
* @return the event stream interface that pumps events
*/
carb::events::IEventStreamPtr(CARB_ABI* getEventStream)();
/**
* Registers a node type as defined above with the system
*
* @param[in] desc Reference to the node type interface (the underlying object is not yet available here)
* @param[in] version Version of the node interface to be registered
* @param[in] The size of the INodeType struct being passed. Use sizeof(INodeType).
*
*/
void(CARB_ABI* registerNodeTypeInterface)(const INodeType& desc, int version, size_t nodeTypeStructSize);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IGraphRegistry, registerNodeTypeInterface, 9)
} // namespace core
} // namespace graph
} // namespace omni
| 5,671 | C | 39.514285 | 115 | 0.693176 |
omniverse-code/kit/include/omni/graph/core/ISchedulingHints.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Interface to the list of scheduling hints that can be applied to a node type
template <>
class omni::core::Generated<omni::graph::core::ISchedulingHints_abi> : public omni::graph::core::ISchedulingHints_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::ISchedulingHints")
/**
* Get the threadSafety status (i.e. can be run in parallel with other nodes)
*
* @returns Is the node compute threadsafe?
*/
omni::graph::core::eThreadSafety getThreadSafety() noexcept;
/**
* Set the flag indicating if a node is threadsafe or not.
*
* @param[in] newThreadSafety New value of the threadsafe flag
*/
void setThreadSafety(omni::graph::core::eThreadSafety newThreadSafety) noexcept;
/**
* Get the type of access the node has for a given data type
*
* @param[in] dataType Type of data for which access type is being modified
* @returns Value of the access type flag
*/
omni::graph::core::eAccessType getDataAccess(omni::graph::core::eAccessLocation dataType) noexcept;
/**
* Set the flag describing how a node accesses particular data in its compute _abi (defaults to no access).
* Setting any of these flags will, in most cases, automatically mark the node as "not threadsafe".
* One current exception to this is allowing a node to be both threadsafe and a writer to USD, since
* such behavior can be achieved if delayed writebacks (e.g. "registerForUSDWriteBack") are utilized
* in the node's compute method.
*
* @param[in] dataType Type of data for which access type is being modified
* @param[in] newAccessType New value of the access type flag
*/
void setDataAccess(omni::graph::core::eAccessLocation dataType, omni::graph::core::eAccessType newAccessType) noexcept;
/**
* Get the flag describing the compute rule which may be followed by the evaluator.
*
* @returns Value of the ComputeRule flag
*/
omni::graph::core::eComputeRule getComputeRule() noexcept;
/**
* Set the flag describing the compute rule which may be followed by the evaluator.
*
* @param[in] newComputeRule New value of the ComputeRule flag
*/
void setComputeRule(omni::graph::core::eComputeRule newComputeRule) noexcept;
/**
* Runs the inspector on the scheduling hints.
*
* @param[in] inspector The inspector class
* @return true if the inspection ran successfully, false if the inspection type is not supported
*/
bool inspect(omni::core::ObjectParam<omni::inspect::IInspector> inspector) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::graph::core::eThreadSafety omni::core::Generated<omni::graph::core::ISchedulingHints_abi>::getThreadSafety() noexcept
{
return getThreadSafety_abi();
}
inline void omni::core::Generated<omni::graph::core::ISchedulingHints_abi>::setThreadSafety(
omni::graph::core::eThreadSafety newThreadSafety) noexcept
{
setThreadSafety_abi(newThreadSafety);
}
inline omni::graph::core::eAccessType omni::core::Generated<omni::graph::core::ISchedulingHints_abi>::getDataAccess(
omni::graph::core::eAccessLocation dataType) noexcept
{
return getDataAccess_abi(dataType);
}
inline void omni::core::Generated<omni::graph::core::ISchedulingHints_abi>::setDataAccess(
omni::graph::core::eAccessLocation dataType, omni::graph::core::eAccessType newAccessType) noexcept
{
setDataAccess_abi(dataType, newAccessType);
}
inline omni::graph::core::eComputeRule omni::core::Generated<omni::graph::core::ISchedulingHints_abi>::getComputeRule() noexcept
{
return getComputeRule_abi();
}
inline void omni::core::Generated<omni::graph::core::ISchedulingHints_abi>::setComputeRule(
omni::graph::core::eComputeRule newComputeRule) noexcept
{
setComputeRule_abi(newComputeRule);
}
inline bool omni::core::Generated<omni::graph::core::ISchedulingHints_abi>::inspect(
omni::core::ObjectParam<omni::inspect::IInspector> inspector) noexcept
{
return inspect_abi(inspector.get());
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 4,965 | C | 34.726618 | 130 | 0.720846 |
omniverse-code/kit/include/omni/graph/core/OgnHelpers.h | // 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.
//
#pragma once
// This file contains helper functions used by the generated .ogn file code.
// You shouldn't normally have to look in here.
#include <omni/graph/core/ogn/Types.h>
#include <omni/graph/core/ogn/State.h>
#include <omni/graph/core/ogn/Database.h>
#include <omni/graph/core/ogn/AttributeInitializer.h>
#include <omni/graph/core/ogn/Registration.h>
// The fabric namespace usage is somewhat more targetted though so it can be explicit
using omni::fabric::IToken;
using omni::fabric::IPath; | 941 | C | 41.81818 | 85 | 0.781084 |
omniverse-code/kit/include/omni/graph/core/IAttributeType.h | // 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.
//
#pragma once
#include <omni/graph/core/iComputeGraph.h>
#include <carb/Defines.h>
#include <carb/Interface.h>
#include <carb/Types.h>
#include <omni/graph/core/Handle.h>
#include <omni/graph/core/Type.h>
#include <omni/inspect/IInspector.h>
namespace omni {
namespace graph {
namespace core {
// ======================================================================
/**
* @brief Interface class managing various features of attribute types
*
*/
struct IAttributeType
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::IAttributeType", 1, 4);
/**
* @brief Returns an attribute type object corresponding to the OGN-style type name
*
* The type name is assumed to contain no whitespace for efficiency, so prune it before calling if necessary.
*
* @param[in] ognTypeName Attribute type name in the format used by the .ogn files
* @return The attribute type description corresponding to the type name
*/
Type (CARB_ABI* typeFromOgnTypeName)(const char* ognTypeName);
/**
* @brief Returns an attribute type object corresponding to the Sdf-style type name.
*
* The type name is assumed to contain no whitespace for efficiency, so prune it before calling if necessary.
* Note that some types cannot be expressed in this form (e.g. the extended types such as "union" and "any", and
* OGn-only types such as "bundle") so where possible use the typeFromOgnTypeName() method.
*
* @param[in] sdfTypeName Attribute type name in the format used by pxr::SdfValueTypeNames
* @return The attribute type description corresponding to the type name
*/
Type (CARB_ABI* typeFromSdfTypeName)(const char* sdfTypeName);
/**
* @brief Returns the size of the base data (without tuples or array counts) for the given attribute type
*
* @param[in] type Attribute type whose size is to be returned
* @return Size of the base data stored by the attribute type, 0 if none is stored
*/
size_t (CARB_ABI* baseDataSize)(Type const& type);
/**
* @brief Runs the inspector on the attribute data with the given type.
*
* @param[in] type The attribute type of the raw data
* @param[in] data Pointer to the raw data of the given type.
* @param[in] elementCount Number of array elements in the data (1 if not an array)
* @param[in] inspector The inspector class
* @return true if the inspection ran successfully, false if the inspection type is not supported
*/
bool(CARB_ABI* inspect)(Type const& type, void const* data, size_t arrayElementCount, inspect::IInspector* inspector);
/**
* @brief Returns the SdfValueTypeName corresponding to the given type.
*
* @note Not all OGN Types are fully represented in the Sdf schema since they have additional semantics in OGN
* which do not exist in USD. In that case the SdfValueTypeName of the base type will be returned, which is
* what is used to serialize the attribute.
*
* For example Type(BaseDataType::UInt64, 1, 0, AttributeRole::eObjectId) is an OGN "objectId" which will
* return just "uint64" from this function.
*
* @param[in] type The Type in question
* @return The token of the corresponding SdfTypeName
*/
NameToken(CARB_ABI* sdfTypeNameFromType)(Type const& type);
/**
* @brief Checks to see if the Type passed in corresponds to a legal OGN type.
*
* @param[in] type Type to be checked
* @return true if the Type can be fully represented by OGN
* @return false if the Type does not correspond exactly to an OGN type
*
*/
bool(CARB_ABI* isLegalOgnType)(Type const& type);
/**
* @brief Retreives the number of attribute unions.
*
* @return The number of attribute union types.
*/
size_t(CARB_ABI* getUnionTypeCount)();
/**
* @brief Retrieves the name of the available union types
*
* @param[in] buffer The array of pointers to fill in with names of the union types.
* The values returned are only valid while the list of unions is not changing.
* @param[in] bufferSize The number of entries to retreive. Use getUnionTypeCount to retrieve the number
* available.
* @return The number of entries written to buffer.
*
*/
size_t(CARB_ABI* getUnionTypes)(const char** buffer, size_t bufferSize);
/**
* @brief Retrieves the number of entries for the attribute union of the given name
*
* @param[in] unionType The name of the attribute union to retrieve.
* @return The number of entries associated with unionType. If unionType is not valid, 0 is returned.
*
*/
size_t(CARB_ABI* getUnionTypeEntryCount)(const char* unionType);
/**
* @brief Gets the list of ogn type names associated with an attribute union.
*
* The list of returned types is fully expanded. This means if an attribute union is defined in terms
* of other attributes unions, the entries returned will have recursively expanded each entry and the
* final list will only contain ogn type names and not other attribute unions names.
*
* @param[in] unionType The name of the attribute union to retrieve.
* @param[in] buffer The array of pointers to fill in with names of the ogn types names.
* The values returned are only valid while the list of unions is not changing.
* @param[in] bufferSize The number of entries to retrieve. Use getUnionTypeEntryCount to find the maximum available.
* @return The number of items written to buffer. If unionType is not valid, 0 is returned.
*
*/
size_t(CARB_ABI* getUnionTypeEntries)(const char* unionType, const char** buffer, size_t bufferSize);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IAttributeType, getUnionTypeEntries, 9)
} // namespace core
} // namespace graph
} // namespace omni
| 6,566 | C | 42.490066 | 122 | 0.683673 |
omniverse-code/kit/include/omni/graph/core/GpuArray.h | // 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.
//
#pragma once
#include <stddef.h>
#include <stdint.h>
namespace omni
{
namespace graph
{
namespace core
{
template <typename T>
struct GpuArray
{
// GPU pointer to data
T* const* gpuData;
// GPU pointer to elem count
const size_t* elemCount;
#ifdef __CUDACC__
__device__ T* data()
{
return *gpuData;
}
__device__ size_t size() const
{
return *elemCount;
}
#endif
};
template <typename T>
struct ArrayOfGpuArray
{
// GPU array of GPU data pointers
T* const* gpuData;
// GPU array of elem counts
const size_t* elemCount;
#ifdef __CUDACC__
__device__ T* data(size_t i) const
{
return gpuData[i];
}
__device__ size_t size(size_t i) const
{
return elemCount[i];
}
#endif
};
template <typename T>
struct ConstGpuArray
{
// GPU pointer to data
const T* const* gpuData;
// GPU pointer to elem count
const size_t* elemCount;
#ifdef __CUDACC__
__device__ const T* data() const
{
return *gpuData;
}
__device__ size_t size() const
{
return *elemCount;
}
#endif
};
template <typename T>
struct ArrayOfConstGpuArray
{
// GPU array of GPU data pointers
const T* const* gpuData;
// GPU array of elem counts
const size_t* elemCount;
#ifdef __CUDACC__
__device__ const T* data(size_t i) const
{
return gpuData[i];
}
__device__ size_t size(size_t i) const
{
return elemCount[i];
}
#endif
};
}
}
}
| 1,955 | C | 16.464286 | 77 | 0.627621 |
omniverse-code/kit/include/omni/graph/core/ComputeGraph.h | // Copyright (c) 2019-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.
//
#pragma once
#include "iComputeGraph.h"
#include "INodeCategories.h"
#include "unstable/INodeTypeForwarding.h"
#include "IBundleFactory.h"
#include "IDirtyID.h"
#include "IBundleChanges.h"
#include <carb/Interface.h>
#include <carb/tasking/TaskingTypes.h>
#include <omni/core/IObject.h>
namespace rtx
{
namespace resourcemanager
{
class RpResource;
typedef uint32_t SyncScopeId;
}
}
namespace carb
{
namespace graphics
{
struct Semaphore;
}
}
namespace gpu
{
namespace rendergraph
{
//! Declare the IRenderGraph interface definition
OMNI_DECLARE_INTERFACE(IRenderGraph);
using RenderGraph = omni::core::ObjectPtr<gpu::rendergraph::IRenderGraph>;
}
enum class GfResult: int32_t;
}
namespace omni
{
namespace usd
{
class IUsdMutex;
using PathH = uint64_t;
namespace hydra
{
struct ViewportHydraRenderResults;
}
}
namespace kit
{
struct StageUpdateSettings;
}
namespace graph
{
namespace core
{
/** used only by kit - do not use this interface in plugins */
struct ComputeGraph
{
CARB_PLUGIN_INTERFACE("omni::graph::core::ComputeGraph", 2, 8)
/**
* Returns the number of global orchestration graphs for all stages of the graph pipelines
*
* Note: from version 2.3 on, the semantics of this call has changed, even if the interface has not.
* There is now a orchestration graph which has nodes that each wrap either a graph or an extension to be run
* This function will now return the number of such orchestration graphs. The non-orchestration global graphs
* can be retrieved by iterating over the nodes of the orchestration graph and calling getWrappedGraph
*
* @return the number of graphs in the system, regardless of pipeline stage
*/
size_t(CARB_ABI* getGraphCount)();
/**
* Fills the buffer with global orchestration graph objects that occupy all pipeline stages
*
* Note: From version 2.3 on, see note above about the global orchestration graph with nodes that
* wrap previous global graphs
*
* @param[out] graphObjs The buffer of graphs to fill
* @param[in] bufSize The size of the buffer in terms of the number of GraphObj it has room for
* @return true on success, false on failure
*/
bool(CARB_ABI* getGraphs)(GraphObj* contextBuf, size_t bufSize);
/**
* Returns the number of graph contexts for all pipeline stages
*
* Note: From version 2.3 on, see note above about the global orchestration graph with nodes that
* wrap previous global graphs
*
* @return the number of graph contexts in the whole system, regardless of pipeline stage
*/
size_t(CARB_ABI* getGraphContextCount)();
/**
* Fills the buffer with graph context objects that occupy all pipeline stages
*
* Note: From version 2.3 on, see note above about the global orchestration graph with nodes
* that wrap previous global graphs
*
* @param[out] contextBuf The buffer of graph contexts to fill
* @param[in] bufSize The size of the buffer in terms of the number of GraphContextObj it has room for
* @return true on success, false on failure
*/
bool(CARB_ABI* getGraphContexts)(GraphContextObj* contextBuf, size_t bufSize);
/**
* @brief Shut down all of the compute graph infrastructure
*
* The functionality in this method was originally introduced because we didn't have carbOnPluginShutdown working
* properly (it's not being called for some reason), but later we decided to keep it because DS needs more control
* over OG's startup and shutdown.
*/
void(CARB_ABI* shutdownComputeGraph)();
/**
* @brief Start up all of the compute graph infrastructure
*
* Needed by DS to have more control over OG startup / shutdown mechanism
*/
void(CARB_ABI* startupComputeGraph)();
/**
* @brief Attach OmniGraph to the given stage
*
* @param[in] stageId ID of the stage to which OmniGraph should attach
* @param[in] metersPerUnit Length units of the stage
* @param[in] userData Extra raw data to use for and identify the attachment
*
*/
void(CARB_ABI* attach)(long int stageId, double metersPerUnit, void* userData);
/**
* @brief Detach OmniGraph using the information in the @p userData
*
* @param[in] userData Extra raw data to use for and identify the detachment
*
*/
void(CARB_ABI* detach)(void* userData);
/**
* @deprecated This version is deprecated and will be removed in a future version.
* Use updateV2() instead.
*/
void(CARB_ABI* update)(float currentTime,
float elapsedSecs,
const omni::kit::StageUpdateSettings* updateSettings,
void* userData);
/**
* @deprecated This version is deprecated and will be removed in a future version.
* Use updateSimStepWithUsd() instead.
*/
void(CARB_ABI* updateSimStep)(int64_t timeNS, carb::tasking::Counter*);
/**
* @brief Enable of disable the attachment of OmniGraph to the Kit update looop
*
* Currently there is a dependency in SimStageWithHistory on OG, so we cannot shutdown the graph
* when it needs to be ticked from external process, such as DS2's ISimStep.
* Using this method we can block (or unblock) OG from reacting to Kit's update loop.
*
* @param[in] state Whether the Kit update loop should be respected or not
*/
void(CARB_ABI* considerKitUpdateLoop)(bool state);
/**
* @brief postRenderBegin is called after IHydraEngine::render() after the postRender starts
* in order to tick graphs in the postRender pipeline stage.
*
* @param[in] syncScope ID for the resource manager's sync scope
* @param[in] renderGraph Graph that will be processed in the postRender
*/
void(CARB_ABI* postRenderBegin)(rtx::resourcemanager::SyncScopeId syncScope,
gpu::rendergraph::RenderGraph renderGraph);
/**
* @brief postRenderBegin is called after IHydraEngine::render() during the postRender update
* in order to tick graphs in the postRender pipeline stage.
*
* @param[in] syncScope ID for the resource manager's sync scope
* @param[in] renderResults Return value from IHydraEngine::render()
* @param[in] renderProductPrimPath Prim path of the RenderProduct for this view
* @param[in] simTime Kit's simulation time that's passed to ComputeGraphImpl::updateV2()
* @param[in] hydraTime The current time value of the USD Stage
*/
void(CARB_ABI* postRenderUpdate)(rtx::resourcemanager::SyncScopeId syncScope,
omni::usd::hydra::ViewportHydraRenderResults* renderResults,
omni::usd::PathH renderProductPrimPath,
double simTime,
double hydraTime);
/**
* @brief postRenderBegin is called after IHydraEngine::render() after the postRender ends
* in order to tick graphs in the postRender pipeline stage.
*
* @param[in] syncScope ID for the resource manager's sync scope
* @return The status of the postRender
*/
gpu::GfResult(CARB_ABI* postRenderEnd)(rtx::resourcemanager::SyncScopeId syncScope);
/**
* Returns the number of global orchestration graphs given a particular graph pipeline stage.
*
* @param[in] pipelineStage The stage of the pipeline (simulation, pre-render, post-render)
* @return the number of graphs in that pipeline stage
*/
size_t(CARB_ABI* getGraphCountInPipelineStage)(GraphPipelineStage pipelineStage);
/**
* Fills the buffer with global orchestration graph objects that occupy a particular pipeline stage
*
* @param[out] graphObjs The buffer of graphs to fill
* @param[in] bufSize The size of the buffer in terms of the number of GraphObj it has room for
* @param[in] pipelineStage The stage of the pipeline (simulation, pre-render, post-render)
* @return true on success, false on failure
*/
bool(CARB_ABI* getGraphsInPipelineStage)(GraphObj* graphObjs, size_t bufSize, GraphPipelineStage pipelineStage);
/**
* @brief This update function is used by DriveSim's ISimStep interface to tick the graph
*
* @param[in] timeNS Simulation time, in nanoseconds
* @param[in] counter Tasking counter
* @param[in] disableUsdUpdates Turn off USD updates while the simulation step is happening
*/
void(CARB_ABI* updateSimStepUsd)(int64_t timeNS, carb::tasking::Counter* counter, bool disableUsdUpdates);
/**
* @brief Gets the interface object handling the node categories
*
* @return Raw object that implements the node category interface
*/
INodeCategories*(CARB_ABI* getNodeCategoriesInterface)();
/**
* @brief Gets an ONI object for the interface handling the node categories
*
* @return Shared object that implements the node category interface
*/
inline omni::core::ObjectPtr<INodeCategories> getNodeCategoriesInterfacePtr() const
{
return omni::core::steal(getNodeCategoriesInterface());
}
/**
* @brief Sets the test failure state. This is for test failures that cannot be caught by conventional means.
*
* @param[in] hasFailed If true then increment the test failure count, otherwise reset it to 0.
*/
void (CARB_ABI* setTestFailure)(bool hasFailed);
/**
* @return Returns the current test failure count since it was last cleared.
*/
size_t (CARB_ABI* testFailureCount)();
/**
* @brief Gets an ONI object for the interface handling the bundle factory
*
* @return Shared object that implements the bundle factory interface
*/
IBundleFactory*(CARB_ABI* getBundleFactoryInterface)();
/**
* @brief Gets an ONI object for the interface handling the bundle factory
*
* @return Shared object that implements the bundle factory interface
*/
inline omni::core::ObjectPtr<IBundleFactory> getBundleFactoryInterfacePtr() const
{
return omni::core::steal(getBundleFactoryInterface());
}
/**
* @brief Updates the graphs
*
* @param[in] currentTime Time at which the graphs are being updated
* @param[in] elapsedSecs Amount of time elapsed in overall graph updates
* @param[in] absoluteSimTime Time at which the simulation graph updates
* @param[in] updateSettings Any settings required by the update
* @param[in] userData Raw user data to pass to the update
*/
void(CARB_ABI* updateV2)(double currentTime,
float elapsedSecs,
double absoluteSimTime,
const omni::kit::StageUpdateSettings* updateSettings,
void* userData);
/**
* @brief preRenderBegin is called before IHydraEngine::render() before the preRender starts
* in order to tick graphs in the prerender pipeline stage.
*
* @param[in] renderGraph Render graph that is about to be ticked
*/
void(CARB_ABI* preRenderBegin)(gpu::rendergraph::RenderGraph renderGraph);
/**
* @brief preRenderUpdate is called before IHydraEngine::render() when the preRender updates
* in order to tick graphs in the prerender pipeline stage.
*
* @param[in] simTime Time at which the render graph is being updated according to the simulation graph
* @param[in] hydraTime Time at which the render graph is being updated according to Hydra
* @param[in] mutex Mutex for locking USD while updating
*/
void(CARB_ABI* preRenderUpdate)(double simTime,
double hydraTime,
omni::usd::IUsdMutex& mutex);
/**
* @brief preRenderEnd is called before IHydraEngine::render() after the preRender is done
* in order to tick graphs in the prerender pipeline stage.
*/
void(CARB_ABI* preRenderEnd)();
/**
* Flushes any pending USD changes from the fabric scene delegate.
*/
void(CARB_ABI* flushUsd)();
/**
* @brief Gets the interface object handling the node type forwarding
*
* @return Shared object that implements the node type forwarding interface
*/
unstable::INodeTypeForwarding*(CARB_ABI* getNodeTypeForwardingInterface)();
inline omni::core::ObjectPtr<unstable::INodeTypeForwarding> getNodeTypeForwardingInterfacePtr() const
{
return omni::core::steal(getNodeTypeForwardingInterface());
}
unstable::IDirtyID2*(CARB_ABI* getDirtyIDInterface)(GraphContextObj const& context);
omni::core::ObjectPtr<unstable::IDirtyID2> getDirtyIDInterfacePtr(GraphContextObj const& context) const
{
return omni::core::steal(getDirtyIDInterface(context));
}
IBundleChanges*(CARB_ABI* getBundleChangesInterface)(GraphContextObj const& context);
omni::core::ObjectPtr<IBundleChanges> getBundleChangesInterfacePtr(GraphContextObj const& context) const
{
return omni::core::steal(getBundleChangesInterface(context));
}
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(ComputeGraph, getBundleChangesInterface, 28)
}
}
}
| 13,885 | C | 36.52973 | 118 | 0.684048 |
omniverse-code/kit/include/omni/graph/core/PreUsdInclude.h | // 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.
//
// This file should be included in conjunction with PostUsdInclude.h when including any of the individual USD
// definition files. They have a number of warnings that are triggered by our default build configuration that these
// files silence as being third party includes we can't fix them ourselves.
//
// It includes a special ifdef detection to prevent inclusion of this file without PostUsdInclude.h as that
// would have unpredictable effects on the compiler. The usual "#pragma once" is omitted, so that the mechanism works
// correctly even with multiple uses. It is not legal to include anything other than USD headers between these two.
//
// Here is an example of how you use this mechanism to include the definition of the USD type pxr::GfHalf:
//
// #include <omni/graph/core/PreUsdInclude.h>
// #include <pxr/base/gf/half.h>
// #include <omni/graph/core/PostUsdInclude.h>
//
// NOTE: At some point when USD is upgraded these might no longer be required; at that time they can be deprecated
//
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4244) // = Conversion from double to float / int to float
# pragma warning(disable : 4267) // conversion from size_t to int
# pragma warning(disable : 4305) // argument truncation from double to float
# pragma warning(disable : 4800) // int to bool
# pragma warning(disable : 4996) // call to std::copy with parameters that may be unsafe
# pragma warning(disable : 4003) // not enough arguments for function-like macro invocation
# define NOMINMAX // Make sure nobody #defines min or max
#elif defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
# pragma GCC diagnostic ignored "-Wunused-local-typedefs"
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wunused-variable"
// This suppresses deprecated header warnings, which is impossible with pragmas.
// Alternative is to specify -Wno-deprecated build option, but that disables other useful warnings too.
# ifdef __DEPRECATED
# define OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS
# undef __DEPRECATED
# endif
#endif
#ifdef __USD_INCLUDE_PROTECTION__
# error "You must include PostUsdInclude.h after including PreUsdInclude.h"
#else
# define __USD_INCLUDE_PROTECTION__
#endif
| 2,789 | C | 50.666666 | 117 | 0.752599 |
omniverse-code/kit/include/omni/graph/core/PyINodeCategories.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
#pragma once
#include <omni/core/ITypeFactory.h>
#include <omni/python/PyBind.h>
#include <omni/python/PyString.h>
#include <omni/python/PyVec.h>
#include <sstream>
auto bindINodeCategories(py::module& m)
{
// hack around pybind11 issues with C++17
// - https://github.com/pybind/pybind11/issues/2234
// - https://github.com/pybind/pybind11/issues/2666
// - https://github.com/pybind/pybind11/issues/2856
py::class_<omni::core::Generated<omni::graph::core::INodeCategories_abi>,
omni::python::detail::PyObjectPtr<omni::core::Generated<omni::graph::core::INodeCategories_abi>>,
omni::core::IObject>
clsParent(m, "_INodeCategories");
py::class_<omni::graph::core::INodeCategories, omni::core::Generated<omni::graph::core::INodeCategories_abi>,
omni::python::detail::PyObjectPtr<omni::graph::core::INodeCategories>, omni::core::IObject>
cls(m, "INodeCategories",
R"OMNI_BIND_RAW_(Interface to the list of categories that a node type can belong to )OMNI_BIND_RAW_");
cls.def(py::init(
[](const omni::core::ObjectPtr<omni::core::IObject>& obj)
{
auto tmp = omni::core::cast<omni::graph::core::INodeCategories>(obj.get());
if (!tmp)
{
throw std::runtime_error("invalid type conversion");
}
return tmp;
}));
cls.def(py::init(
[]()
{
auto tmp = omni::core::createType<omni::graph::core::INodeCategories>();
if (!tmp)
{
throw std::runtime_error("unable to create omni::graph::core::INodeCategories instantiation");
}
return tmp;
}));
cls.def_property_readonly("category_count", &omni::graph::core::INodeCategories::getCategoryCount);
cls.def("define_category",
[](omni::graph::core::INodeCategories* self, const char* categoryName, const char* categoryDescription)
{
auto return_value = self->defineCategory(categoryName, categoryDescription);
return return_value;
},
R"OMNI_BIND_RAW_(Define a new category
@param[in] categoryName Name of the new category
@param[in] categoryDescription Description of the category
@return false if there was already a category with the given name)OMNI_BIND_RAW_",
py::arg("category_name"), py::arg("category_description"));
cls.def("remove_category",
[](omni::graph::core::INodeCategories* self, const char* categoryName)
{
auto return_value = self->removeCategory(categoryName);
return return_value;
},
R"OMNI_BIND_RAW_(Remove an existing category, mainly to manage the ones created by a node type for itself
@param[in] categoryName Name of the category to remove
@return false if there was no category with the given name)OMNI_BIND_RAW_",
py::arg("category_name"));
return omni::python::PyBind<omni::graph::core::INodeCategories>::bind(cls);
}
| 3,605 | C | 41.928571 | 117 | 0.638835 |
omniverse-code/kit/include/omni/graph/core/SlangScript.h | // Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Framework.h>
#include <carb/graphics/Graphics.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/base/tf/token.h>
#include <pxr/base/tf/type.h>
#include <pxr/usd/sdf/path.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <slang/slang.h>
#include <slang/slang-com-ptr.h>
#define SLANG_PRELUDE_NAMESPACE CPPPrelude
#include <string>
#include <vector>
#include <slang/prelude/slang-cpp-types.h>
namespace omni
{
namespace graph
{
namespace core
{
struct SlangScript
{
// A ResizeSpec allows the user to set (using USD) the size of an output
// array to the size of an input array
struct ResizeSpec
{
std::string outputArray;
std::string inputArray;
};
std::vector<ResizeSpec> resizeSpec;
// Whether to run on CPU or GPU
gpucompute::Target target;
// Compiler output
gpucompute::Shader* shader = nullptr;
gpucompute::ComputeCompiler* compiler = nullptr;
SlangScript(const char* codeString,
gpucompute::Target target,
const std::vector<ResizeSpec>& resizeSpec,
carb::graphics::Device* device);
~SlangScript()
{
if (shader)
compiler->destroyShader(*shader);
}
};
}
}
}
| 1,703 | C | 23.342857 | 77 | 0.696418 |
omniverse-code/kit/include/omni/graph/core/Handle.h | // 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.
//
#pragma once
#include <omni/fabric/IPath.h>
#include <omni/fabric/IToken.h>
#include <omni/fabric/IFabric.h>
#include <omni/graph/core/TemplateUtils.h>
// Support for generic handles for interface objects.
// Ideally each of the handle types would be put into interface files for their corresponding types. In the
// current scheme they are too intertwined to separate them cleanly. Having this file provides a way for code
// to have access to handles for passing around without pulling in all of the unrelated interfaces.
namespace omni {
namespace graph {
namespace core {
/**
* Macro to validate the structure of the interface definitions. New functions must be added at the end,
* and the struct itself must be a standard layout POD, as per Carbonite requirements.
* @param[in] StructName Name of the structure being validated
* @param[in] LastFunction Name of the last function declared in the structure
* @param[in] NumberOfFunctions Total number of functions declared in the structure
*/
#define STRUCT_INTEGRITY_CHECK(StructName, LastFunction, NumberOfFunctions) \
static_assert(offsetof(StructName, LastFunction) == NumberOfFunctions * sizeof(void(*)()), \
"New " # StructName " ABI methods must be added at the end"); \
static_assert(std::is_trivial<StructName>::value, # StructName " must be a POD"); \
static_assert(std::is_standard_layout<StructName>::value, # StructName " must have std layout"); \
static_assert(sizeof(StructName) == (NumberOfFunctions+1) * sizeof(void (*)()), \
"Please update the integrity check macro to point to the last method of " #StructName);
// ==============================================================================================================
/**
* @brief Template class for defining handles to various OmniGraph data types
*
* @tparam T The underlying type of the handle being defined
* @tparam SUBCLASS The handle subclass being defined
*/
template <typename T, typename SUBCLASS>
class HandleBase
{
public:
//! Default constructor, gives an invalid handle
HandleBase() = default;
//! Default copy constructor, bitwise copy of handle data
HandleBase(const HandleBase&) = default;
//! Construct a handle from the underlying data it represents
explicit HandleBase(const T& h) : handle(h)
{
}
//! Default assignment operator, bitwise copy of the handle data
HandleBase& operator=(const HandleBase&) = default;
//! Cast to the underlying data type of the handle
explicit operator T() const
{
return handle;
}
//! Returns true if the handle is currently valid
bool isValid() const
{
return (handle != SUBCLASS::invalidValue());
}
//! Equality operator - only identical handles are equal
bool operator==(HandleBase rhs) const
{
return handle == rhs.handle;
}
//! Inequality operator - only identical handles are equal
bool operator!=(HandleBase rhs) const
{
return !(handle == rhs.handle);
}
//! Constant representing a unique invalid handle for this instantiation
static constexpr SUBCLASS invalidHandle()
{
return static_cast<SUBCLASS>(SUBCLASS::invalidValue());
}
protected:
T handle; //!< Instantiation of the underlying type of the handle
};
//! Underlying data type for a handle being represented as an integer
using HandleInt = uint64_t;
//! Representation of a string that is referenced via a unique token. Note that although this token is
//! reference counted this is the raw value which is not. Use ogn::Token at the high level to get that
//! reference counting if you intend to hang on to copies of the token.
using NameToken = omni::fabric::TokenC;
//! Representation of a path. Note that although this path is reference counted this is the raw value
//! which is not. Use ogn::Path at the high level to get that reference counting if you intend to hang
//! on to copies of the path.
using TargetPath = omni::fabric::PathC;
//! Location of rows of data in Fabric
using BucketId = omni::fabric::BucketId;
//! Representation of an internal type used by AutoNode
using ObjectId = HandleInt;
// NOTE: Due to Linux debug linking pre-C++17 not liking constexpr static variables,
// other than built-in integer types, being passed by const reference,
// invalid values for handles are now constructed via inline functions, instead
// of using constexpr static variables. Just to play it safe, we're using a macro
// here, in case it also has an issue with built-in integer types being referenced
// from an inline function at compile-time. Note that the link errors don't show
// up until *runtime*, since they appear to be handled via dynamic linking.
//! Representation of an invalid handle as an integer
#define OG_INVALID_HANDLE_INT_VALUE (~HandleInt(0))
//! Representation of an invalid handle as an integer
constexpr static HandleInt kInvalidHandleIntValue = OG_INVALID_HANDLE_INT_VALUE;
// ==============================================================================================================
//! Handle type representing attributes, which require two parts to be valid
using AttrKey = std::pair<HandleInt, HandleInt>;
//! This is here so we can use AttrKey and ConstAttributeDataHandle as a key to std::unordered_map.
//! There is another below in ConstAttributeDataHandleHash, intentionally the same as they represent the same data.
//!
//! See https://www.techiedelight.com/use-std-pair-key-std-unordered_map-cpp/ for a full discussion.
struct AttrKeyHash
{
//! Return a hash value for the underlying handle data
std::size_t operator()(const AttrKey& attrKey) const
{
return std::hash<HandleInt>()(attrKey.first) ^ std::hash<HandleInt>()(attrKey.second);
}
};
// ==============================================================================================================
//! Object representing a handle to an AttributeData type
class ConstAttributeDataHandle : public HandleBase<AttrKey, ConstAttributeDataHandle>
{
public:
using HandleBase<AttrKey, ConstAttributeDataHandle>::HandleBase;
//! Path to the prim or bundle of the attribute, e.g. in "/world/cube.size", this returns "/world/cube"
omni::fabric::PathC path() const noexcept { return handle.first; }
//! Name of the attribute, e.g. in "/world/cube.size", this would be "size"
omni::fabric::TokenC name() const noexcept { return handle.second; }
//! Returns an invalid AttributeData handle value
static constexpr AttrKey invalidValue()
{
return std::make_pair(HandleInt(omni::fabric::kUninitializedPath.path),
HandleInt(omni::fabric::kUninitializedToken.token));
}
};
// --------------------------------------------------------------------------------------------------------------
//! Hash definition so that AttributeDataHandle can be used in a map
struct ConstAttributeDataHandleHash
{
//! Returns a hash value unique for AttributeData handles
std::size_t operator()(const ConstAttributeDataHandle& attrDataHandle) const
{
AttrKey attrKey(attrDataHandle);
return AttrKeyHash()(attrKey);
}
};
// --------------------------------------------------------------------------------------------------------------
//! Object representing a handle to a variable AttributeData type
class AttributeDataHandle : public HandleBase<AttrKey, AttributeDataHandle>
{
public:
using HandleBase<AttrKey, AttributeDataHandle>::HandleBase;
//! Returns an invalid AttributeData handle value
static constexpr AttrKey invalidValue()
{
return std::make_pair(HandleInt(omni::fabric::kUninitializedPath.path),
HandleInt(omni::fabric::kUninitializedToken.token));
}
//! Path to the prim or bundle of the attribute, e.g. in "/world/cube.size", this returns "/world/cube"
omni::fabric::PathC path() const noexcept { return handle.first; }
//! Name of the attribute, e.g. in "/world/cube.size", this would be "size"
omni::fabric::TokenC name() const noexcept { return handle.second; }
//! Returns a constant AttributeDataHandle pointing to the same AttributeData as this variable one
operator ConstAttributeDataHandle() const
{
return ConstAttributeDataHandle(AttrKey(*this));
}
};
// ==============================================================================================================
//! Object representing a handle to a constant OmniGraph Bundle
class ConstBundleHandle : public HandleBase<HandleInt, ConstBundleHandle>
{
public:
using HandleBase<HandleInt, ConstBundleHandle>::HandleBase;
//! Returns an invalid Bundle handle value
static constexpr HandleInt invalidValue()
{
return omni::fabric::kUninitializedPath.path;
}
};
// --------------------------------------------------------------------------------------------------------------
//! Hash definition so that BundleHandle can be used in a map
struct ConstBundleHandleHash
{
//! Returns a hash value unique for Bundle handles
std::size_t operator()(const ConstBundleHandle& handle) const
{
return std::hash<HandleInt>()(HandleInt(handle));
}
};
// --------------------------------------------------------------------------------------------------------------
//! Object representing a handle to an OmniGraph Bundle
class BundleHandle : public HandleBase<HandleInt, BundleHandle>
{
public:
using HandleBase<HandleInt, BundleHandle>::HandleBase;
//! Returns an invalid Bundle handle value
static constexpr HandleInt invalidValue()
{
return omni::fabric::kUninitializedPath.path;
}
//! Returns a constant BundleHandle pointing to the same Bundle as this variable one
operator ConstBundleHandle() const
{
return ConstBundleHandle(HandleInt(*this));
}
};
//! Deprecated - for backward compatibility only
using ConstPrimHandle [[deprecated("Use ConstBundleHandle!")]] = ConstBundleHandle;
//! Deprecated - for backward compatibility only
using ConstPrimHandleHash [[deprecated("Use ConstBundleHandleHash!")]] = ConstBundleHandleHash;
//! Deprecated - for backward compatibility only
using PrimHandle [[deprecated("Use BundleHandle!")]] = BundleHandle;
// ==============================================================================================================
//! Object representing a handle to an OmniGraph NodeContext
class NodeContextHandle : public HandleBase<HandleInt, NodeContextHandle>
{
public:
using HandleBase<HandleInt, NodeContextHandle>::HandleBase;
//! Returns an invalid NodeContext handle value
static constexpr HandleInt invalidValue()
{
return kInvalidHandleIntValue;
}
};
// ======================================================================
// Support for attributes
using AttributeHandle = uint64_t; //!< Handle to an OmniGraph Attribute
using AttributeHash = uint64_t; //!< Hash value type for OmniGraph Attributes
static constexpr AttributeHandle kInvalidAttributeHandle = 0; //!< Constant representing an invalid attribute handle
struct IAttribute;
//! Object representing an OmniGraph Attribute
struct AttributeObj
{
const IAttribute* iAttribute; //!< Interface to functionality on the attribute
AttributeHandle attributeHandle; //!< Opaque handle to actual underlying attribute
//! Returns true if this object refers to a valid attribute
bool isValid() const
{
return (attributeHandle != kInvalidAttributeHandle);
}
};
// ======================================================================
// Support for node types
using NodeTypeHandle = uint64_t; //!< Handle to an OmniGraph NodeType
static constexpr NodeTypeHandle kInvalidNodeTypeHandle = 0; //!< Constant representing an invalid node type handle
struct INodeType;
//! Object representing an OmniGraph NodeType
struct NodeTypeObj
{
const INodeType* iNodeType; //!< Interface to functionality on the node type
NodeTypeHandle nodeTypeHandle; //!< Opaque handle to actual underlying node type - managed by OmniGraph
//! Returns true if this object refers to a valid node type
bool isValid() const
{
return (nodeTypeHandle != kInvalidNodeTypeHandle);
}
};
// ======================================================================
// Support for evaluation contexts
struct IGraphContext;
struct IBundle;
struct IAttributeData;
using GraphContextHandle = uint64_t; //!< Handle to an OmniGraph GraphContext
static constexpr GraphContextHandle kInvalidGraphContextHandle = 0; //!< Constant representing an invalid graph context handle
/**
* @brief Object representing an OmniGraph GraphContext
*/
struct GraphContextObj
{
const IGraphContext* iContext; //!< Interfaces to functionality on the context
// Convenience location for commonly used interfaces
const IBundle* iBundle; //!< Cached ABI interface pointer
const IAttributeData* iAttributeData; //!< Cached ABI interface pointer
const omni::fabric::IToken* iToken; //!< Cached ABI interface pointer
const omni::fabric::IPath* iPath; //!< Cached ABI interface pointer
GraphContextHandle contextHandle; //!< Opaque handle to actual underlying graph context
//! Returns true if this object refers to a valid graph context
bool isValid() const
{
return (contextHandle != kInvalidGraphContextHandle);
}
};
// ======================================================================
// Support for nodes
using NodeHandle = uint64_t;
static constexpr NodeHandle kInvalidNodeHandle = 0; //!< Constant representing an invalid node handle
struct INode;
//! Object representing an OmniGraph Node
struct NodeObj
{
//! Interface to functionality on the node
const INode* iNode{ nullptr };
//! Opaque handle to actual underlying node - managed by compute graph system
NodeHandle nodeHandle{ kInvalidNodeHandle };
//! handle used to retrieve data on the node - every node has a NodeContextHandle, but not the other way around
NodeContextHandle nodeContextHandle{ NodeContextHandle::invalidValue() };
//! Returns true if this object refers to a valid node
bool isValid() const
{
return (nodeHandle != kInvalidNodeHandle);
}
};
// ======================================================================
// Support for graphs
using GraphHandle = uint64_t;
static constexpr GraphHandle kInvalidGraphHandle = 0; //!< Constant representing an invalid graph handle
struct IGraph;
//! Object representing an OmniGraph Graph
struct GraphObj
{
IGraph* iGraph; //!< Interface to functionality on the graph
GraphHandle graphHandle; //!< Opaque handle to actual underlying graph
//! Returns true if this object refers to a valid graph
bool isValid() const
{
return (graphHandle != kInvalidGraphHandle);
}
};
// ======================================================================
// Support for schedule nodes
using ScheduleNodeHandle = uint64_t; //!< Handle to an OmniGraph ScheduleNode
static constexpr ScheduleNodeHandle kInvalidScheduleNodeHandle = 0; //!< Constant representing an invalid schedule node handle
struct IScheduleNode;
//! Object representing an OmniGraph ScheduleNode
struct ScheduleNodeObj
{
const IScheduleNode* iScheduleNode; //!< Interface to functionality on the schedule node
ScheduleNodeHandle scheduleNodeHandle; //!< Opaque handle to actual underlying schedule node
//! Returns true if this object refers to a valid schedule node
bool isValid() const
{
return (scheduleNodeHandle != kInvalidScheduleNodeHandle);
}
};
// ======================================================================
/**
* SFINAE function that will call setContext on an object if it exists as "void setContext(GraphContextObj&)".
* This allows setting a context in the wrapper functions to percolate down to the member implementations
* when appropriate.
*
* Usage:
* OptionalMethod::setContext<ClassType>(classMember, context);
*/
template <class NodeTypeClass>
using has_setContext = typename std::is_same<void,
decltype(std::declval<NodeTypeClass&>().setContext(
std::declval<const GraphContextObj&>()))>::value_type;
/**
* SFINAE function that will call setHandle on an object if it exists as "void setHandle(GraphContextObj&)".
* This allows setting a handle in the wrapper functions to percolate down to the member implementations
* when appropriate.
*
* Usage:
* OptionalMethod::setHandle<ClassType, HandleType>(classMember, handle);
*/
template <class NodeTypeClass, typename HandleType>
using has_setHandle = typename std::is_same<void,
decltype(std::declval<NodeTypeClass&>().setHandle(
std::declval<HandleType>()))>::value_type;
//! Helper struct to make it easy to reference methods on a class that may or may not be defined.
struct OptionalMethod
{
private:
template <typename ClassToSet, typename HandleType>
static void call_setHandle(ClassToSet& member, HandleType handle, std::true_type)
{
member.setHandle(handle);
}
template <typename ClassToSet, typename HandleType>
static void call_setHandle(ClassToSet& member, HandleType handle, std::false_type)
{
}
template <typename ClassToSet>
static void call_setContext(ClassToSet& member, const GraphContextObj& context, std::true_type)
{
member.setContext(context);
}
template <typename ClassToSet>
static void call_setContext(ClassToSet& member, const GraphContextObj& context, std::false_type)
{
}
public:
/**
* @brief Set the Handle object
*
* @tparam ClassToSet Object class on which to set the handle
* @tparam HandleType Handle class that is the object class member containing the handle
* @param member Object on which the handle is to be set
* @param handle Handle to be set on the object
*/
template <typename ClassToSet, typename HandleType>
static void setHandle(ClassToSet& member, HandleType handle)
{
call_setHandle(member, handle, is_detected<has_setHandle, ClassToSet, HandleType>());
}
/**
* @brief Set the Context object, if an implementation exists
*
* @tparam ClassToSet Object class on which to set the context
* @param member Object on which the context is to be set
* @param context Context to be set on the object
*/
template <typename ClassToSet>
static void setContext(ClassToSet& member, const GraphContextObj& context)
{
call_setContext(member, context, is_detected<has_setContext, ClassToSet>());
}
};
/*
_____ _ _
| __ \ | | | |
| | | | ___ _ __ _ __ ___ ___ __ _| |_ ___ __| |
| | | |/ _ \ '_ \| '__/ _ \/ __/ _` | __/ _ \/ _` |
| |__| | __/ |_) | | | __/ (_| (_| | || __/ (_| |
|_____/ \___| .__/|_| \___|\___\__,_|\__\___|\__,_|
| |
|_|
May go away at any time - what you should use are in the comments
*/
//! Deprecated - use kInvalidTokenValue
constexpr static HandleInt INVALID_TOKEN_VALUE = ~HandleInt(0);
} // namespace core
} // namespace graph
} // namespace omni
| 19,883 | C | 40.167702 | 126 | 0.653724 |
omniverse-code/kit/include/omni/graph/core/Accessors.h | // 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.
//
#pragma once
#include <omni/graph/core/CppWrappers.h>
#include <omni/graph/core/CudaUtils.h>
#include <omni/graph/core/Type.h>
#include <omni/graph/core/tuple.h>
#include <omni/graph/core/Handle.h>
namespace omni
{
namespace graph
{
namespace core
{
/**
* Retrieves the Nth upstream connected attribute, invalid object if it isn't there. This is a utility function
* that lets callers avoid the hassle of going through the allocation/deallocation required for ABI access.
*
* @template N Index of the upstream attribute
* @param[in] attrObj The attribute object for which to retrieve the connection
* @return Nth upstream attribute, or invalid if there is none
*/
template <int Count>
AttributeObj getNthUpstreamAttribute(const AttributeObj& attrObj)
{
size_t connectionCount = attrObj.iAttribute->getUpstreamConnectionCount(attrObj);
if (connectionCount > Count)
{
AttributeObj* attrObjs = reinterpret_cast<AttributeObj*>(alloca(sizeof(AttributeObj) * connectionCount));
attrObj.iAttribute->getUpstreamConnections(attrObj, attrObjs, connectionCount);
AttributeObj toReturn = attrObjs[Count];
return toReturn;
}
return AttributeObj{nullptr, kInvalidAttributeHandle};
}
/**
* Retrieves the Nth upstream attribute if it exists, or the passed-in attribute if not.
*
* @template N Index of the upstream attribute
* @param[in] attrObj The attribute object for which to retrieve the connection
* @return Nth upstream attribute, or the passed-in attribute if there is none
*/
template <int Count>
AttributeObj getNthUpstreamAttributeOrSelf(const AttributeObj& attrObj)
{
AttributeObj nth = getNthUpstreamAttribute<Count>(attrObj);
return nth.iAttribute ? nth : attrObj;
}
template <typename T>
constexpr BaseDataType baseDataTypeForType()
{
using Type = typename std::remove_cv<T>::type;
if (std::is_same<Type, int>::value)
{
return BaseDataType::eInt;
}
if (std::is_same<Type, int64_t>::value)
{
return BaseDataType::eInt64;
}
if (std::is_same<Type, float>::value)
{
return BaseDataType::eFloat;
}
if (std::is_same<Type, double>::value)
{
return BaseDataType::eDouble;
}
CUDA_SAFE_ASSERT("Type not implemented");
return BaseDataType::eUnknown;
}
constexpr bool isNumericBaseType(BaseDataType type)
{
switch (type)
{
case BaseDataType::eInt:
case BaseDataType::eInt64:
case BaseDataType::eFloat:
case BaseDataType::eDouble:
return true;
default:
return false;
}
}
// Scalar numeric attribute accessor.
template <typename T>
class NumericAccessor
{
public:
static constexpr BaseDataType expectedType = baseDataTypeForType<T>();
static constexpr bool readOnly = std::is_const<T>::value;
using RawType = typename std::remove_cv<T>::type;
using HandleType = typename std::conditional<readOnly, ConstAttributeDataHandle, AttributeDataHandle>::type;
NumericAccessor() : attributeType(BaseDataType::eUnknown), data(nullptr), componentCount(0), elementCount(0)
{
}
NumericAccessor(const NumericAccessor&) = default;
NumericAccessor& operator=(const NumericAccessor&) = default;
#if 0
// The enable_if makes this valid only if T is const, since a non-const accessor can't
// be initialized with a const attribute handle, but a const accessor can be initialized
// from a const or non-const attribute handle.
template <typename HANDLE_TYPE,
typename IGNORED = typename std::enable_if<readOnly && (std::is_same<HANDLE_TYPE, ConstAttributeDataHandle>::value ||
std::is_same<HANDLE_TYPE, AttributeDataHandle>::value),
int>::type>
NumericAccessor(const GraphContextObj& context,
HANDLE_TYPE attributeHandle,
IGNORED = 0)
: NumericAccessor()
{
if (!attributeHandle.isValid())
return;
Type type = context.iAttributeData->getType(context, attributeHandle);
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
attributeType = baseType;
const void* pData;
context.iAttributeData->getDataR(&pData, context, &attributeHandle, 1);
data = (depth == 0) ? pData : (*(const void* const*)pData);
componentCount = type.componentCount;
elementCount = omni::graph::core::getElementCount(context, attributeHandle);
}
}
}
// The enable_if makes this valid only if T is non-const, since a non-const accessor can
// only be initialized with a non-const attribute handle.
template <typename IGNORED = typename std::enable_if<!readOnly, int>::type>
NumericAccessor(const GraphContextObj& context,
AttributeDataHandle attributeHandle,
IGNORED = 0)
: NumericAccessor()
{
if (!attributeHandle.isValid())
return;
Type type = context.iAttributeData->getType(context, attributeHandle);
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
attributeType = baseType;
void* pData;
context.iAttributeData->getDataW(&pData, context, &attributeHandle, 1);
data = (depth == 0) ? pData : (*(void* const*)pData);
componentCount = type.componentCount;
elementCount = omni::graph::core::getElementCount(context, attributeHandle);
}
}
}
// Construct a NumericAccessor by prim and attribute name.
//
// The enable_if makes this valid only if T is const, since a non-const accessor can't
// be initialized with a const attribute handle, but a const accessor can be initialized
// from a const or non-const attribute handle.
template <typename HANDLE_TYPE,
typename IGNORED = typename std::enable_if<readOnly && (std::is_same<HANDLE_TYPE, ConstBundleHandle>::value ||
std::is_same<HANDLE_TYPE, BundleHandle>::value),
int>::type>
NumericAccessor(const GraphContextObj& context,
HANDLE_TYPE primHandle,
Token attributeName,
IGNORED = 0)
: NumericAccessor()
{
if (!primHandle.isValid())
return;
ConstAttributeDataHandle attributeHandle;
NameToken nameToken(attributeName);
context.iBundle->getAttributesByNameR(&attributeHandle, context, primHandle, &nameToken, 1);
*this = NumericAccessor(context, attributeHandle);
}
// Construct a NumericAccessor by non-const prim and attribute name.
//
// The enable_if makes this valid only if T is non-const, since a non-const accessor can
// only be initialized with a non-const attribute handle.
template <typename IGNORED = typename std::enable_if<!readOnly, int>::type>
NumericAccessor(const GraphContextObj& context,
BundleHandle primHandle,
NameToken attributeName,
IGNORED = 0)
: NumericAccessor()
{
if (!primHandle.isValid())
return;
AttributeDataHandle attributeHandle;
context.iBundle->getAttributesByNameW(&attributeHandle, context, primHandle, &attributeName, 1);
*this = NumericAccessor(context, attributeHandle);
}
#endif
bool isValid() const
{
return (data != nullptr);
}
size_t getComponentCount() const
{
return componentCount;
}
size_t getElementCount() const
{
return elementCount;
}
// Returns a pointer to the data if it's a perfect type match, else nullptr.
T* getPerfectMatch() const
{
return reinterpret_cast<T*>((attributeType == expectedType) ? data : nullptr);
}
CUDA_CALLABLE
RawType get(size_t i = 0) const
{
CUDA_SAFE_ASSERT(data != nullptr);
CUDA_SAFE_ASSERT(i < componentCount * elementCount);
if (attributeType == expectedType)
{
return reinterpret_cast<const RawType*>(data)[i];
}
switch (attributeType)
{
case BaseDataType::eInt:
return RawType(reinterpret_cast<const int*>(data)[i]);
case BaseDataType::eInt64:
return RawType(reinterpret_cast<const int64_t*>(data)[i]);
case BaseDataType::eFloat:
return RawType(reinterpret_cast<const float*>(data)[i]);
case BaseDataType::eDouble:
return RawType(reinterpret_cast<const double*>(data)[i]);
}
CUDA_SAFE_ASSERT(0);
return RawType(0);
}
// The enable_if makes this valid only if T is non-const.
template <bool IsEnabled = true, typename std::enable_if<(IsEnabled && !readOnly), int>::type = 0>
CUDA_CALLABLE void set(RawType value, size_t i = 0) const
{
CUDA_SAFE_ASSERT(data != nullptr);
CUDA_SAFE_ASSERT(i < componentCount * elementCount);
if (attributeType == expectedType)
{
reinterpret_cast<RawType*>(data)[i] = value;
}
else
{
switch (attributeType)
{
case BaseDataType::eInt:
reinterpret_cast<int*>(data)[i] = int(value);
break;
case BaseDataType::eInt64:
reinterpret_cast<int64_t*>(data)[i] = int64_t(value);
break;
case BaseDataType::eFloat:
reinterpret_cast<float*>(data)[i] = float(value);
break;
case BaseDataType::eDouble:
reinterpret_cast<double*>(data)[i] = double(value);
break;
default:
CUDA_SAFE_ASSERT(0);
break;
}
}
}
// TODO: make getNumericAccessor functions be friends of this class and make data private again
// private:
BaseDataType attributeType;
using VoidType = typename std::conditional<readOnly, const void, void>::type;
VoidType* data;
size_t componentCount;
size_t elementCount;
};
// CPU accessors
// When the dest is const, source can either be ConstBundleHandle or BundleHandle
template <typename T,
typename HANDLE_TYPE,
typename IGNORED =
typename std::enable_if<std::is_const<T>::value && (std::is_same<HANDLE_TYPE, ConstBundleHandle>::value ||
std::is_same<HANDLE_TYPE, BundleHandle>::value),
int>::type>
NumericAccessor<T> getNumericAccessor(const GraphContextObj& context,
HANDLE_TYPE primHandle,
Token attributeName,
IGNORED = 0)
{
NumericAccessor<T> accessor;
if (!primHandle.isValid())
return accessor;
ConstAttributeDataHandle attributeHandle;
NameToken nameToken(attributeName);
context.iBundle->getAttributesByNameR(&attributeHandle, context, primHandle, &nameToken, 1);
if (!attributeHandle.isValid())
return accessor;
Type type = context.iAttributeData->getType(context, attributeHandle);
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
accessor.attributeType = baseType;
const void* pData;
context.iAttributeData->getDataR(&pData, context, &attributeHandle, 1);
accessor.data = (depth == 0) ? pData : (*(const void* const*)pData);
accessor.componentCount = type.componentCount;
accessor.elementCount = omni::graph::core::getElementCount(context, attributeHandle);
}
}
return accessor;
}
// When the dest is non-const, source can only be BundleHandle
template <typename T, typename IGNORED = typename std::enable_if<!std::is_const<T>::value, int>::type>
NumericAccessor<T> getNumericAccessor(const GraphContextObj& context,
BundleHandle primHandle,
Token attributeName,
IGNORED = 0)
{
NumericAccessor<T> accessor;
if (!primHandle.isValid())
return accessor;
AttributeDataHandle attributeHandle;
NameToken nameToken(attributeName);
context.iBundle->getAttributesByNameW(&attributeHandle, context, primHandle, &nameToken, 1);
if (!attributeHandle.isValid())
return accessor;
Type type = context.iAttributeData->getType(context, attributeHandle);
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
accessor.attributeType = baseType;
void* pData;
context.iAttributeData->getDataW(&pData, context, &attributeHandle, 1);
accessor.data = (depth == 0) ? pData : (*(void* const*)pData);
accessor.componentCount = type.componentCount;
accessor.elementCount = omni::graph::core::getElementCount(context, attributeHandle);
}
}
return accessor;
}
// GPU accessors
// When the dest is const, source can either be ConstBundleHandle or BundleHandle
template <typename T,
typename HANDLE_TYPE,
typename IGNORED =
typename std::enable_if<std::is_const<T>::value && (std::is_same<HANDLE_TYPE, ConstBundleHandle>::value ||
std::is_same<HANDLE_TYPE, BundleHandle>::value),
int>::type>
NumericAccessor<T> getNumericAccessorGPU(const GraphContextObj& context, HANDLE_TYPE primHandle, Token attributeName)
{
NumericAccessor<T> accessor;
if (!primHandle.isValid())
return accessor;
ConstAttributeDataHandle attributeHandle;
NameToken nameToken(attributeName);
context.iBundle->getAttributesByNameR(&attributeHandle, context, primHandle, &nameToken, 1);
if (!attributeHandle.isValid())
return accessor;
Type type = context.iAttributeData->getType(context, attributeHandle);
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
accessor.attributeType = baseType;
const void* pData;
context.iAttributeData->getDataRGPU(&pData, context, &attributeHandle, 1);
accessor.data = (depth == 0) ? pData : (*(const void* const*)pData);
accessor.componentCount = type.componentCount;
accessor.elementCount = omni::graph::core::getElementCount(context, attributeHandle);
}
}
return accessor;
}
// When the dest is non-const, source can only be BundleHandle
template <typename T, typename IGNORED = typename std::enable_if<!std::is_const<T>::value, int>::type>
NumericAccessor<T> getNumericAccessorGPU(const GraphContextObj& context,
BundleHandle primHandle,
Token attributeName,
IGNORED = 0)
{
NumericAccessor<T> accessor;
if (!primHandle.isValid())
return accessor;
AttributeDataHandle attributeHandle;
NameToken nameToken(attributeName);
context.iBundle->getAttributesByNameW(&attributeHandle, context, primHandle, &nameToken, 1);
if (!attributeHandle.isValid())
return accessor;
Type type = context.iAttributeData->getType(context, attributeHandle);
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
accessor.attributeType = baseType;
void* pData;
context.iAttributeData->getDataWGPU(&pData, context, &attributeHandle, 1);
accessor.data = (depth == 0) ? pData : (*(void* const*)pData);
accessor.componentCount = type.componentCount;
accessor.elementCount = omni::graph::core::getElementCount(context, attributeHandle);
}
}
return accessor;
}
template <typename T, size_t N>
class VectorAccessor
{
public:
static constexpr BaseDataType expectedType = baseDataTypeForType<T>();
static constexpr size_t componentCount = N;
static constexpr bool readOnly = std::is_const<T>::value;
using RawBaseType = typename std::remove_cv<T>::type;
using RawVectorType = tuple<RawBaseType, N>;
using VectorType = typename std::conditional<readOnly, const tuple<RawBaseType, N>, tuple<RawBaseType, N>>::type;
using VoidType = typename std::conditional<readOnly, const void, void>::type;
using HandleType = typename std::conditional<readOnly, ConstAttributeDataHandle, AttributeDataHandle>::type;
VectorAccessor() : attributeType(BaseDataType::eUnknown), data(nullptr), elementCount(0)
{
}
VectorAccessor(const VectorAccessor&) = default;
VectorAccessor& operator=(const VectorAccessor&) = default;
// The enable_if makes this valid only if T is const, since a non-const accessor can't
// be initialized with a const attribute handle, but a const accessor can be initialized
// from a const or non-const attribute handle.
template <typename HANDLE_TYPE,
typename IGNORED = typename std::enable_if<readOnly && (std::is_same<HANDLE_TYPE, ConstAttributeDataHandle>::value ||
std::is_same<HANDLE_TYPE, AttributeDataHandle>::value),
int>::type>
VectorAccessor(const GraphContextObj& context, HANDLE_TYPE attributeHandle, IGNORED = 0) : VectorAccessor()
{
if (!attributeHandle.isValid())
return;
Type type = context.iAttributeData->getType(context, attributeHandle);
size_t componentCount = type.componentCount;
if (componentCount == N)
{
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
attributeType = baseType;
const void* pData;
context.iAttributeData->getDataR(&pData, context, &attributeHandle, 1);
data = (depth == 0) ? pData : (*(const void* const*)pData);
elementCount = omni::graph::core::getElementCount(context, attributeHandle);
}
}
}
}
// The enable_if makes this valid only if T is non-const, since a non-const accessor can
// only be initialized with a non-const attribute handle.
template <typename IGNORED = typename std::enable_if<!readOnly, int>::type>
VectorAccessor(const GraphContextObj& context, AttributeDataHandle attributeHandle, IGNORED = 0) : VectorAccessor()
{
if (!attributeHandle.isValid())
return;
Type type = context.iAttributeData->getType(context, attributeHandle);
size_t componentCount = type.componentCount;
if (componentCount == N)
{
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
attributeType = baseType;
void* pData;
context.iAttributeData->getDataW(&pData, context, &attributeHandle, 1);
data = (depth == 0) ? pData : (*(void* const*)pData);
elementCount = omni::graph::core::getElementCount(context, attributeHandle);
}
}
}
}
// Construct a VectorAccessor by prim and attribute name.
//
// The enable_if makes this valid only if T is const, since a non-const accessor can't
// be initialized with a const attribute handle, but a const accessor can be initialized
// from a const or non-const attribute handle.
template <typename HANDLE_TYPE,
typename IGNORED = typename std::enable_if<readOnly && (std::is_same<HANDLE_TYPE, ConstBundleHandle>::value ||
std::is_same<HANDLE_TYPE, BundleHandle>::value),
int>::type>
VectorAccessor(const GraphContextObj& context, HANDLE_TYPE primHandle, NameToken attributeName, IGNORED = 0)
: VectorAccessor()
{
if (!primHandle.isValid())
return;
ConstAttributeDataHandle attributeHandle;
context.iBundle->getAttributesByNameR(&attributeHandle, context, primHandle, &attributeName, 1);
*this = VectorAccessor(context, attributeHandle);
}
// Construct a VectorAccessor by non-const prim and attribute name.
//
// The enable_if makes this valid only if T is non-const, since a non-const accessor can
// only be initialized with a non-const attribute handle.
template <typename IGNORED = typename std::enable_if<!readOnly, int>::type>
VectorAccessor(const GraphContextObj& context, BundleHandle primHandle, NameToken attributeName, IGNORED = 0)
: VectorAccessor()
{
if (!primHandle.isValid())
return;
AttributeDataHandle attributeHandle;
context.iBundle->getAttributesByNameW(&attributeHandle, context, primHandle, &attributeName, 1);
*this = VectorAccessor(context, attributeHandle);
}
bool isValid() const
{
return (data != nullptr);
}
size_t getElementCount() const
{
return elementCount;
}
// Returns a pointer to the data if it's a perfect type match, else nullptr.
VectorType* getPerfectMatch() const
{
return reinterpret_cast<VectorType*>((attributeType == expectedType) ? data : nullptr);
}
RawVectorType get(size_t i = 0) const
{
CUDA_SAFE_ASSERT(data != nullptr);
CUDA_SAFE_ASSERT(i < elementCount);
if (attributeType == expectedType)
{
return reinterpret_cast<const RawVectorType*>(data)[i];
}
switch (attributeType)
{
case BaseDataType::eInt:
return RawVectorType(reinterpret_cast<const tuple<int, N>*>(data)[i]);
case BaseDataType::eInt64:
return RawVectorType(reinterpret_cast<const tuple<int64_t, N>*>(data)[i]);
case BaseDataType::eFloat:
return RawVectorType(reinterpret_cast<const tuple<float, N>*>(data)[i]);
case BaseDataType::eDouble:
return RawVectorType(reinterpret_cast<const tuple<double, N>*>(data)[i]);
}
CUDA_SAFE_ASSERT(0);
return RawVectorType(T(0));
}
// The enable_if makes this valid only if T is non-const.
template <typename IGNORED = typename std::enable_if<!readOnly, int>::type>
void set(const RawVectorType& value, size_t i = 0, IGNORED = 0) const
{
CUDA_SAFE_ASSERT(data != nullptr);
CUDA_SAFE_ASSERT(i < componentCount * elementCount);
if (attributeType == expectedType)
{
reinterpret_cast<RawVectorType*>(data)[i] = value;
}
else
{
switch (attributeType)
{
case BaseDataType::eInt:
reinterpret_cast<tuple<int, N>*>(data)[i] = tuple<int, N>(value);
break;
case BaseDataType::eInt64:
reinterpret_cast<tuple<int64_t, N>*>(data)[i] = tuple<int64_t, N>(value);
break;
case BaseDataType::eFloat:
reinterpret_cast<tuple<float, N>*>(data)[i] = tuple<float, N>(value);
break;
case BaseDataType::eDouble:
reinterpret_cast<tuple<double, N>*>(data)[i] = tuple<double, N>(value);
break;
default:
CUDA_SAFE_ASSERT(0);
break;
}
}
}
private:
BaseDataType attributeType;
VoidType* data;
size_t elementCount;
};
// Bulk scalar numeric array attribute accessor (non-const implementation).
template <typename T>
class BulkNumericAccessor
{
public:
static constexpr BaseDataType expectedType = baseDataTypeForType<T>();
static constexpr bool readOnly = false;
using RawType = typename std::remove_cv<T>::type;
using HandleType = AttributeDataHandle;
BulkNumericAccessor()
: attributeType(BaseDataType::eUnknown), data(nullptr), matchingData(nullptr), componentCount(0), elementCount(0)
{
}
BulkNumericAccessor(BulkNumericAccessor&& that)
{
attributeType = that.attributeType;
data = that.data;
matchingData = that.matchingData;
componentCount = that.componentCount;
elementCount = that.elementCount;
that.attributeType = BaseDataType::eUnknown;
that.data = nullptr;
that.matchingData = nullptr;
that.componentCount = 0;
that.elementCount = 0;
}
BulkNumericAccessor& operator=(BulkNumericAccessor&& that)
{
attributeType = that.attributeType;
data = that.data;
matchingData = that.matchingData;
componentCount = that.componentCount;
elementCount = that.elementCount;
that.attributeType = BaseDataType::eUnknown;
that.data = nullptr;
that.matchingData = nullptr;
that.componentCount = 0;
that.elementCount = 0;
return *this;
}
BulkNumericAccessor(const BulkNumericAccessor& that) = delete;
BulkNumericAccessor& operator=(const BulkNumericAccessor& that) = delete;
// This is valid only if T is non-const, since a non-const accessor can
// only be initialized with a non-const attribute handle.
BulkNumericAccessor(const GraphContextObj& context, AttributeDataHandle attributeHandle) : BulkNumericAccessor()
{
if (!attributeHandle.isValid())
return;
Type type = context.iAttributeData->getType(context, attributeHandle);
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
attributeType = baseType;
void* pData;
context.iAttributeData->getDataW(&pData, context, &attributeHandle, 1);
data = (depth == 0) ? pData : (*(void* const*)pData);
componentCount = type.componentCount;
elementCount = omni::graph::core::getElementCount(context, attributeHandle);
if (attributeType != expectedType)
{
size_t fullCount = componentCount * elementCount;
RawType* converted = new RawType[fullCount];
convertToMatching(converted, fullCount);
matchingData = converted;
}
else
{
matchingData = reinterpret_cast<T*>(data);
}
}
}
}
// Construct a BulkNumericAccessor by non-const prim and attribute name.
//
// This is valid only if T is non-const, since a non-const accessor can
// only be initialized with a non-const attribute handle.
BulkNumericAccessor(const GraphContextObj& context, BundleHandle primHandle, NameToken attributeName)
: BulkNumericAccessor()
{
if (!primHandle.isValid())
return;
AttributeDataHandle attributeHandle;
context.iBundle->getAttributesByNameW(&attributeHandle, context, primHandle, &attributeName, 1);
*this = BulkNumericAccessor(context, attributeHandle);
}
~BulkNumericAccessor()
{
if (attributeType != expectedType && matchingData != nullptr)
{
flushInternal(matchingData);
delete[] matchingData;
}
}
bool isValid() const
{
return (data != nullptr);
}
size_t getComponentCount() const
{
return componentCount;
}
size_t getElementCount() const
{
return elementCount;
}
// Returns a pointer to the data if it's convertible, else nullptr.
T* getData() const
{
return matchingData;
}
// Returns a pointer to the data if it's convertible, else nullptr.
// Convertible types are always treated as a perfect match for bulk conversion.
// This function is just provided for compatibility with the NumericAccessor
// and VectorAccessor classes above.
T* getPerfectMatch() const
{
return matchingData;
}
void flush()
{
flushInternal(matchingData);
}
private:
void flushInternal(RawType* matchData)
{
CUDA_SAFE_ASSERT(data != nullptr);
if (attributeType == expectedType)
{
return;
}
const size_t fullCount = componentCount * elementCount;
switch (attributeType)
{
case BaseDataType::eInt:
{
int* source = reinterpret_cast<int*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
source[i] = int(matchData[i]);
}
break;
}
case BaseDataType::eInt64:
{
int64_t* source = reinterpret_cast<int64_t*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
source[i] = int64_t(matchData[i]);
}
break;
}
case BaseDataType::eFloat:
{
float* source = reinterpret_cast<float*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
source[i] = float(matchData[i]);
}
break;
}
case BaseDataType::eDouble:
{
double* source = reinterpret_cast<double*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
source[i] = double(matchData[i]);
}
break;
}
default:
CUDA_SAFE_ASSERT(0);
break;
}
}
void convertToMatching(RawType* converted, const size_t fullCount)
{
switch (attributeType)
{
case BaseDataType::eInt:
{
const int* source = reinterpret_cast<const int*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawType(source[i]);
}
break;
}
case BaseDataType::eInt64:
{
const int64_t* source = reinterpret_cast<const int64_t*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawType(source[i]);
}
break;
}
case BaseDataType::eFloat:
{
const float* source = reinterpret_cast<const float*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawType(source[i]);
}
break;
}
case BaseDataType::eDouble:
{
const double* source = reinterpret_cast<const double*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawType(source[i]);
}
break;
}
default:
CUDA_SAFE_ASSERT(0);
break;
}
}
BaseDataType attributeType;
using VoidType = void;
VoidType* data;
T* matchingData;
size_t componentCount;
size_t elementCount;
};
// Bulk scalar numeric array attribute accessor (const implementation).
template <typename T>
class BulkNumericAccessor<const T>
{
public:
static constexpr BaseDataType expectedType = baseDataTypeForType<T>();
static constexpr bool readOnly = true;
using RawType = typename std::remove_cv<T>::type;
using HandleType = ConstAttributeDataHandle;
BulkNumericAccessor()
: attributeType(BaseDataType::eUnknown), data(nullptr), matchingData(nullptr), componentCount(0), elementCount(0)
{
}
BulkNumericAccessor(BulkNumericAccessor&& that)
{
attributeType = that.attributeType;
data = that.data;
matchingData = that.matchingData;
componentCount = that.componentCount;
elementCount = that.elementCount;
that.attributeType = BaseDataType::eUnknown;
that.data = nullptr;
that.matchingData = nullptr;
that.componentCount = 0;
that.elementCount = 0;
}
BulkNumericAccessor& operator=(BulkNumericAccessor&& that)
{
attributeType = that.attributeType;
data = that.data;
matchingData = that.matchingData;
componentCount = that.componentCount;
elementCount = that.elementCount;
that.attributeType = BaseDataType::eUnknown;
that.data = nullptr;
that.matchingData = nullptr;
that.componentCount = 0;
that.elementCount = 0;
return *this;
}
BulkNumericAccessor(const BulkNumericAccessor& that) = delete;
BulkNumericAccessor& operator=(const BulkNumericAccessor& that) = delete;
// HANDLE_TYPE can be ConstAttributeDataHandle or AttributeDataHandle.
template <typename HANDLE_TYPE>
BulkNumericAccessor(const GraphContextObj& context, HANDLE_TYPE attributeHandle) : BulkNumericAccessor()
{
if (!attributeHandle.isValid())
return;
Type type = context.iAttributeData->getType(context, attributeHandle);
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
attributeType = baseType;
const void* pData;
context.iAttributeData->getDataR(&pData, context, &attributeHandle, 1);
data = (depth == 0) ? pData : (*(const void* const*)pData);
componentCount = type.componentCount;
elementCount = omni::graph::core::getElementCount(context, attributeHandle);
if (attributeType != expectedType)
{
size_t fullCount = componentCount * elementCount;
RawType* converted = new RawType[fullCount];
convertToMatching(converted, fullCount);
matchingData = converted;
}
else
{
matchingData = reinterpret_cast<const T*>(data);
}
}
}
}
// Construct a BulkNumericAccessor by prim and attribute name.
//
// HANDLE_TYPE can be ConstAttributeDataHandle or AttributeDataHandle.
template <typename HANDLE_TYPE>
BulkNumericAccessor(const GraphContextObj& context, HANDLE_TYPE primHandle, NameToken attributeName)
: BulkNumericAccessor()
{
if (!primHandle.isValid())
return;
ConstAttributeDataHandle attributeHandle;
context.iBundle->getAttributesByNameR(&attributeHandle, context, primHandle, &attributeName, 1);
*this = BulkNumericAccessor(context, attributeHandle);
}
~BulkNumericAccessor()
{
}
bool isValid() const
{
return (data != nullptr);
}
size_t getComponentCount() const
{
return componentCount;
}
size_t getElementCount() const
{
return elementCount;
}
// Returns a pointer to the data if it's convertible, else nullptr.
const T* getData() const
{
return matchingData;
}
// Returns a pointer to the data if it's convertible, else nullptr.
// Convertible types are always treated as a perfect match for bulk conversion.
// This function is just provided for compatibility with the NumericAccessor
// and VectorAccessor classes above.
const T* getPerfectMatch() const
{
return matchingData;
}
private:
void convertToMatching(RawType* converted, const size_t fullCount)
{
switch (attributeType)
{
case BaseDataType::eInt:
{
const int* source = reinterpret_cast<const int*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawType(source[i]);
}
break;
}
case BaseDataType::eInt64:
{
const int64_t* source = reinterpret_cast<const int64_t*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawType(source[i]);
}
break;
}
case BaseDataType::eFloat:
{
const float* source = reinterpret_cast<const float*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawType(source[i]);
}
break;
}
case BaseDataType::eDouble:
{
const double* source = reinterpret_cast<const double*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawType(source[i]);
}
break;
}
default:
CUDA_SAFE_ASSERT(0);
break;
}
}
BaseDataType attributeType;
using VoidType = const void;
VoidType* data;
const T* matchingData;
size_t componentCount;
size_t elementCount;
};
// Bulk vector numeric array attribute accessor (non-const implementation).
template <typename T, size_t N>
class BulkVectorAccessor
{
public:
static constexpr BaseDataType expectedType = baseDataTypeForType<T>();
static constexpr size_t componentCount = N;
static constexpr bool readOnly = false;
using RawBaseType = typename std::remove_cv<T>::type;
using RawVectorType = tuple<RawBaseType, N>;
using VectorType = tuple<RawBaseType, N>;
using HandleType = AttributeDataHandle;
BulkVectorAccessor() : attributeType(BaseDataType::eUnknown), data(nullptr), matchingData(nullptr), elementCount(0)
{
}
BulkVectorAccessor(BulkVectorAccessor&& that)
{
attributeType = that.attributeType;
data = that.data;
matchingData = that.matchingData;
elementCount = that.elementCount;
that.attributeType = BaseDataType::eUnknown;
that.data = nullptr;
that.matchingData = nullptr;
that.elementCount = 0;
}
BulkVectorAccessor& operator=(BulkVectorAccessor&& that)
{
attributeType = that.attributeType;
data = that.data;
matchingData = that.matchingData;
elementCount = that.elementCount;
that.attributeType = BaseDataType::eUnknown;
that.data = nullptr;
that.matchingData = nullptr;
that.elementCount = 0;
return *this;
}
BulkVectorAccessor(const BulkVectorAccessor& that) = delete;
BulkVectorAccessor& operator=(const BulkVectorAccessor& that) = delete;
// A non-const accessor can only be initialized with a non-const attribute handle.
BulkVectorAccessor(const GraphContextObj& context, AttributeDataHandle attributeHandle) : BulkVectorAccessor()
{
if (!attributeHandle.isValid())
return;
Type type = context.iAttributeData->getType(context, attributeHandle);
size_t componentCount = type.componentCount;
if (componentCount == N)
{
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
void* pData;
context.iAttributeData->getDataW(&pData, context, &attributeHandle, 1);
data = (depth == 0) ? pData : (*(void* const*)pData);
attributeType = baseType;
elementCount = omni::graph::core::getElementCount(context, attributeHandle);
if (attributeType != expectedType)
{
size_t fullCount = componentCount * elementCount;
RawVectorType* converted = new RawVectorType[fullCount];
convertToMatching(converted, fullCount);
matchingData = converted;
}
else
{
matchingData = reinterpret_cast<VectorType*>(data);
}
}
}
}
}
// A non-const accessor can only be initialized with a non-const attribute handle.
BulkVectorAccessor(const GraphContextObj& context, BundleHandle bundleHandle, Token attributeName)
: BulkVectorAccessor()
{
if (!bundleHandle.isValid())
return;
AttributeDataHandle attributeHandle;
NameToken attributeNameToken(attributeName);
context.iBundle->getAttributesByNameW(&attributeHandle, context, bundleHandle, &attributeNameToken, 1);
*this = BulkVectorAccessor(context, attributeHandle);
}
~BulkVectorAccessor()
{
if (attributeType != expectedType && matchingData != nullptr)
{
flushInternal(matchingData);
delete[] matchingData;
}
}
bool isValid() const
{
return (data != nullptr);
}
size_t getElementCount() const
{
return elementCount;
}
// Returns a pointer to the data if it's convertible, else nullptr.
VectorType* getData() const
{
return matchingData;
}
// Returns a pointer to the data if it's convertible, else nullptr.
// Convertible types are always treated as a perfect match for bulk conversion.
// This function is just provided for compatibility with the NumericAccessor
// and VectorAccessor classes above.
VectorType* getPerfectMatch() const
{
return matchingData;
}
void flush()
{
flushInternal(matchingData);
}
private:
void flushInternal(RawVectorType* matchData)
{
CUDA_SAFE_ASSERT(data != nullptr);
if (attributeType == expectedType)
{
return;
}
const size_t fullCount = componentCount * elementCount;
switch (attributeType)
{
case BaseDataType::eInt:
{
tuple<int, N>* source = reinterpret_cast<tuple<int, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
source[i] = tuple<int, N>(matchData[i]);
}
break;
}
case BaseDataType::eInt64:
{
tuple<int64_t, N>* source = reinterpret_cast<tuple<int64_t, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
source[i] = tuple<int64_t, N>(matchData[i]);
}
break;
}
case BaseDataType::eFloat:
{
tuple<float, N>* source = reinterpret_cast<tuple<float, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
source[i] = tuple<float, N>(matchData[i]);
}
break;
}
case BaseDataType::eDouble:
{
tuple<double, N>* source = reinterpret_cast<tuple<double, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
source[i] = tuple<double, N>(matchData[i]);
}
break;
}
default:
CUDA_SAFE_ASSERT(0);
break;
}
}
void flushInternal(const RawVectorType* matchData)
{
// Does nothing. This signature is just for compiling purposes.
}
void convertToMatching(RawVectorType* converted, const size_t fullCount)
{
switch (attributeType)
{
case BaseDataType::eInt:
{
const tuple<int, N>* source = reinterpret_cast<const tuple<int, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawVectorType(source[i]);
}
break;
}
case BaseDataType::eInt64:
{
const tuple<int64_t, N>* source = reinterpret_cast<const tuple<int64_t, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawVectorType(source[i]);
}
break;
}
case BaseDataType::eFloat:
{
const tuple<float, N>* source = reinterpret_cast<const tuple<float, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawVectorType(source[i]);
}
break;
}
case BaseDataType::eDouble:
{
const tuple<double, N>* source = reinterpret_cast<const tuple<double, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawVectorType(source[i]);
}
break;
}
default:
CUDA_SAFE_ASSERT(0);
break;
}
}
BaseDataType attributeType;
using VoidType = void;
VoidType* data;
VectorType* matchingData;
size_t elementCount;
};
// Bulk vector numeric array attribute accessor (const implementation).
template <typename T, size_t N>
class BulkVectorAccessor<const T, N>
{
public:
static constexpr BaseDataType expectedType = baseDataTypeForType<T>();
static constexpr size_t componentCount = N;
static constexpr bool readOnly = true;
using RawBaseType = typename std::remove_cv<T>::type;
using RawVectorType = tuple<RawBaseType, N>;
using VectorType = const tuple<RawBaseType, N>;
using HandleType = ConstAttributeDataHandle;
BulkVectorAccessor() : attributeType(BaseDataType::eUnknown), data(nullptr), matchingData(nullptr), elementCount(0)
{
}
BulkVectorAccessor(BulkVectorAccessor&& that)
{
attributeType = that.attributeType;
data = that.data;
matchingData = that.matchingData;
elementCount = that.elementCount;
that.attributeType = BaseDataType::eUnknown;
that.data = nullptr;
that.matchingData = nullptr;
that.elementCount = 0;
}
BulkVectorAccessor& operator=(BulkVectorAccessor&& that)
{
attributeType = that.attributeType;
data = that.data;
matchingData = that.matchingData;
elementCount = that.elementCount;
that.attributeType = BaseDataType::eUnknown;
that.data = nullptr;
that.matchingData = nullptr;
that.elementCount = 0;
return *this;
}
BulkVectorAccessor(const BulkVectorAccessor& that) = delete;
BulkVectorAccessor& operator=(const BulkVectorAccessor& that) = delete;
// A const accessor can be initialized from a const or non-const attribute handle.
template <typename HANDLE_TYPE>
BulkVectorAccessor(const GraphContextObj& context, HANDLE_TYPE attributeHandle) : BulkVectorAccessor()
{
if (!attributeHandle.isValid())
return;
Type type = context.iAttributeData->getType(context, attributeHandle);
size_t componentCount = type.componentCount;
if (componentCount == N)
{
BaseDataType baseType = type.baseType;
if (isNumericBaseType(baseType))
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
attributeType = baseType;
const void* pData;
context.iAttributeData->getDataR(&pData, context, &attributeHandle, 1);
data = (depth == 0) ? pData : (*(const void* const*)pData);
elementCount = omni::graph::core::getElementCount(context, attributeHandle);
if (attributeType != expectedType)
{
size_t fullCount = componentCount * elementCount;
RawVectorType* converted = new RawVectorType[fullCount];
convertToMatching(converted, fullCount);
matchingData = converted;
}
else
{
matchingData = reinterpret_cast<VectorType*>(data);
}
}
}
}
}
// A const accessor can be initialized from a const or non-const attribute handle.
template <typename HANDLE_TYPE>
BulkVectorAccessor(const GraphContextObj& context, HANDLE_TYPE primHandle, Token attributeName)
: BulkVectorAccessor()
{
if (!primHandle.isValid())
return;
ConstAttributeDataHandle attributeHandle;
NameToken attributeNameToken(attributeName);
context.iBundle->getAttributesByNameR(&attributeHandle, context, primHandle, &attributeNameToken, 1);
*this = BulkVectorAccessor(context, attributeHandle);
}
~BulkVectorAccessor()
{
if (attributeType != expectedType && matchingData != nullptr)
{
delete[] matchingData;
}
}
bool isValid() const
{
return (data != nullptr);
}
size_t getElementCount() const
{
return elementCount;
}
// Returns a pointer to the data if it's convertible, else nullptr.
VectorType* getData() const
{
return matchingData;
}
// Returns a pointer to the data if it's convertible, else nullptr.
// Convertible types are always treated as a perfect match for bulk conversion.
// This function is just provided for compatibility with the NumericAccessor
// and VectorAccessor classes above.
VectorType* getPerfectMatch() const
{
return matchingData;
}
private:
void convertToMatching(RawVectorType* converted, const size_t fullCount)
{
switch (attributeType)
{
case BaseDataType::eInt:
{
const tuple<int, N>* source = reinterpret_cast<const tuple<int, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawVectorType(source[i]);
}
break;
}
case BaseDataType::eInt64:
{
const tuple<int64_t, N>* source = reinterpret_cast<const tuple<int64_t, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawVectorType(source[i]);
}
break;
}
case BaseDataType::eFloat:
{
const tuple<float, N>* source = reinterpret_cast<const tuple<float, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawVectorType(source[i]);
}
break;
}
case BaseDataType::eDouble:
{
const tuple<double, N>* source = reinterpret_cast<const tuple<double, N>*>(data);
for (size_t i = 0; i < fullCount; ++i)
{
converted[i] = RawVectorType(source[i]);
}
break;
}
default:
CUDA_SAFE_ASSERT(0);
break;
}
}
BaseDataType attributeType;
using VoidType = const void;
VoidType* data;
VectorType* matchingData;
size_t elementCount;
};
// Relationship attribute accessor.
// NOTE: This isn't yet supported.
#if 0
template <bool isReadOnly>
class RelationshipAccessor
{
public:
static constexpr BaseDataType expectedType = BaseDataType::eRelationship;
static constexpr bool readOnly = isReadOnly;
using BundleHandleType = typename std::conditional<readOnly, ConstBundleHandle, BundleHandle>::type;
using PrimHandleType [[deprecated("Use BundleHandleType!")]] = BundleHandleType;
using HandleType = typename std::conditional<readOnly, ConstAttributeDataHandle, AttributeDataHandle>::type;
RelationshipAccessor()
: data(nullptr),
elementCount(0),
m_context(nullptr),
m_attributeHandle(AttributeDataHandle::invalidValue()),
m_iAttributeData(nullptr)
{
}
RelationshipAccessor(const RelationshipAccessor&) = default;
RelationshipAccessor& operator=(const RelationshipAccessor&) = default;
RelationshipAccessor(RelationshipAccessor&& that)
{
data = that.data;
elementCount = that.componentCount;
m_context = that.m_context;
m_attributeHandle = that.m_attributeHandle;
m_iAttributeData = that.m_iAttributeData;
that.data = nullptr;
that.elementCount = 0;
that.m_context = nullptr;
that.m_attributeHandle = AttributeDataHandle(AttributeDataHandle::invalidValue());
that.m_iAttributeData = nullptr;
}
RelationshipAccessor& operator=(RelationshipAccessor&& that)
{
data = that.data;
elementCount = that.componentCount;
m_context = that.m_context;
m_attributeHandle = that.m_attributeHandle;
m_iAttributeData = that.m_iAttributeData;
that.data = nullptr;
that.elementCount = 0;
that.m_context = nullptr;
that.m_attributeHandle = AttributeDataHandle(AttributeDataHandle::invalidValue());
that.m_iAttributeData = nullptr;
}
// The enable_if makes this valid only if readOnly is true, since a non-const accessor can't
// be initialized with a const attribute handle, but a const accessor can be initialized
// from a const or non-const attribute handle.
template <typename HANDLE_TYPE,
typename IGNORED = typename std::enable_if<readOnly && (std::is_same<HANDLE_TYPE, ConstAttributeDataHandle>::value ||
std::is_same<HANDLE_TYPE, AttributeDataHandle>::value),
int>::type>
RelationshipAccessor(const GraphContextObj& context, HANDLE_TYPE attributeHandle, IGNORED = 0)
: RelationshipAccessor()
{
if (!attributeHandle.isValid())
return;
Type type = context.iAttributeData->getType(context, attributeHandle);
BaseDataType baseType = type.baseType;
if (baseType == BaseDataType::eRelationship)
{
size_t componentCount = type.componentCount;
if (componentCount == 1)
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
const void* pData;
context.iAttributeData->getDataR(&pData, context, &attributeHandle, 1);
data = (depth == 0) ? pData : (*(const void* const*)pData);
elementCount = omni::graph::core::getElementCount(context, attributeHandle);
}
}
}
}
// The enable_if makes this valid only if readOnly is false, since a non-const accessor can
// only be initialized with a non-const attribute handle.
template <typename IGNORED = typename std::enable_if<!readOnly, int>::type>
RelationshipAccessor(const GraphContextObj& context, AttributeDataHandle attributeHandle, IGNORED = 0)
: RelationshipAccessor()
{
if (!attributeHandle.isValid())
return;
Type type = context.iAttributeData->getType(context, attributeHandle);
BaseDataType baseType = type.baseType;
if (baseType == BaseDataType::eRelationship)
{
size_t componentCount = type.componentCount;
if (componentCount == 1)
{
size_t depth = type.arrayDepth;
if (depth < 2)
{
void* pData;
context.iAttributeData->getDataW(&pData, context, &attributeHandle, 1);
data = (depth == 0) ? pData : (*(void* const*)pData);
elementCount = omni::graph::core::getElementCount(context, attributeHandle);
m_context = context.context;
m_attributeHandle = attributeHandle;
m_iAttributeData = context.iAttributeData;
}
}
}
}
// Construct a RelationshipAccessor by prim and attribute name.
//
// The enable_if makes this valid only if T is const, since a non-const accessor can't
// be initialized with a const attribute handle, but a const accessor can be initialized
// from a const or non-const attribute handle.
template <typename HANDLE_TYPE,
typename IGNORED = typename std::enable_if<readOnly && (std::is_same<HANDLE_TYPE, ConstBundleHandle>::value ||
std::is_same<HANDLE_TYPE, BundleHandle>::value),
int>::type>
RelationshipAccessor(const GraphContextObj& context, HANDLE_TYPE primHandle, NameToken attributeName, IGNORED = 0)
: RelationshipAccessor()
{
if (!primHandle.isValid())
return;
ConstAttributeDataHandle attributeHandle;
context.iBundle->getAttributesByNameR(&attributeHandle, context, primHandle, &attributeName, 1);
*this = RelationshipAccessor(context, attributeHandle);
}
// Construct a RelationshipAccessor by non-const prim and attribute name.
//
// The enable_if makes this valid only if T is non-const, since a non-const accessor can
// only be initialized with a non-const attribute handle.
template <typename IGNORED = typename std::enable_if<!readOnly, int>::type>
RelationshipAccessor(const GraphContextObj& context, BundleHandle primHandle, NameToken attributeName, IGNORED = 0)
: RelationshipAccessor()
{
if (!primHandle.isValid())
return;
AttributeDataHandle attributeHandle;
context.iBundle->getAttributesByNameW(&attributeHandle, context, primHandle, &attributeName, 1);
*this = RelationshipAccessor(context, attributeHandle);
}
~RelationshipAccessor()
{
if (m_context != nullptr && m_iAttributeData != nullptr && m_attributeHandle.isValid())
{
CUDA_SAFE_ASSERT(!readOnly, "Only non-const RelationshipAccessor's should update the reference counts!");
m_iAttributeData->updateRelationshipRefCounts(*m_context, m_attributeHandle);
}
}
bool isValid() const
{
return (data != nullptr);
}
size_t getElementCount() const
{
return elementCount;
}
// Returns a pointer to the data if it's a perfect type match, else nullptr.
BundleHandleType* getData() const
{
return data;
}
BundleHandleType get(size_t i = 0) const
{
CUDA_SAFE_ASSERT(data != nullptr);
CUDA_SAFE_ASSERT(i < elementCount);
return data[i];
}
// The enable_if makes this valid only if T is non-const.
template <typename IGNORED = typename std::enable_if<!readOnly, int>::type>
void set(BundleHandleType value, size_t i = 0, IGNORED = 0) const
{
CUDA_SAFE_ASSERT(data != nullptr);
CUDA_SAFE_ASSERT(i < elementCount);
// FIXME: Does reference counting of the prims need to be updated now, or will it be updated later?
data[i] = value;
}
private:
BundleHandleType* data;
size_t elementCount;
GraphContext* m_context;
AttributeDataHandle m_attributeHandle;
IAttributeData* m_iAttributeData;
};
#endif
}
}
}
| 60,494 | C | 33.948007 | 131 | 0.596274 |
omniverse-code/kit/include/omni/graph/core/tuple.h | // 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.
//
#pragma once
#include <omni/graph/core/CudaUtils.h>
#include <carb/Defines.h>
#include <cmath>
#include <stdint.h>
#include <type_traits>
// Helper to simplify the syntax when selecting different features for PoD types.
template <class T>
struct is_trivial
{
template <class Q = T>
typename std::enable_if<std::is_trivial<Q>::value, bool>::type check()
{
return true;
}
template <class Q = T>
typename std::enable_if<!std::is_trivial<Q>::value, bool>::type check()
{
return false;
}
};
// This is a templated, fixed-component-count (N), vector class, intended to
// have data layout identical to a raw array of type T, so that data interchange
// wrappers can cast a T* to a tuple<T,N>* as appropriate, as long as they
// have ensured that there are at least N elements pointed-to.
//
// It provides a constructor for conversion between different T, but
// intentionally does not allow for conversion between different N.
// Conversion between different T is also explicit, to avoid accidental
// conversions. Some functionality similar to std::array<T,N> is also
// provided, and the data layout should be equivalent.
//
// For example, tuple<float,3> would be a vector of 3 floats.
//
// It also provides some convenience functions that allow for simple operations on the values
// as a single unit such as unary and binary operators.
//
namespace omni
{
namespace graph
{
namespace core
{
template <typename T, size_t N>
class tuple
{
public:
// Some standard types, similar to std::array and std::vector.
using value_type = T;
using size_type = size_t;
using difference_type = ptrdiff_t;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
using iterator = pointer;
using const_iterator = const_pointer;
// static constexpr variable to be able to refer to the tuple size from the type,
// from outside this class definition.
static constexpr size_t tuple_size = N;
// Defaulted default constructor is needed for POD type,
// but it cannot be constexpr, since it leaves v uninitialized.
tuple() noexcept = default;
constexpr tuple(const tuple<T, N>& that) noexcept = default;
constexpr tuple& operator=(const tuple<T, N>& that) noexcept = default;
// constexpr tuple(const tuple<T, N>&& that) noexcept = default;
// constexpr tuple& operator=(const tuple<T, N>&& that) noexcept = default;
// Construct a tuple with all components equal to value.
explicit tuple(const T& value) noexcept
{
for (size_t i = 0; i < N; ++i)
{
v[i] = value;
}
}
// Type conversion constructor is explicit, to avoid unintentional conversions.
// Conversions are done on individual components.
template <typename OTHER_T>
explicit tuple(const tuple<OTHER_T, N>& that) noexcept
{
for (size_t i = 0; i < N; ++i)
{
v[i] = T(that[i]);
}
}
template <typename OTHER_T, typename... Args>
constexpr tuple(OTHER_T a, Args... args) noexcept
{
initHelper<0>(a, args...);
}
// This is a compile-time constant value
static constexpr size_type size() noexcept
{
return N;
}
// Access a single component of this tuple.
constexpr T& operator[](size_t i) noexcept
{
// Ensure that this type is a POD type if T is a POD type.
// This check is unrelated to this operator, but the static_assert
// must be inside some function that is likely to be called.
static_assert(std::is_trivial<tuple<T, N>>::value == std::is_trivial<T>::value,
"tuple<T,N> should be a POD type iff T is a POD type.");
CUDA_SAFE_ASSERT(i < N);
return v[i];
}
constexpr const T& operator[](size_t i) const noexcept
{
CUDA_SAFE_ASSERT(i < N);
return v[i];
}
// Get a pointer to the data of this tuple.
constexpr T* data() noexcept
{
return v;
}
constexpr const T* data() const noexcept
{
return v;
}
// Iterator functions for compatibility with templated code that expects an iterable container.
constexpr iterator begin() noexcept
{
return v;
}
constexpr const_iterator begin() const noexcept
{
return v;
}
constexpr const_iterator cbegin() const noexcept
{
return v;
}
constexpr iterator end() noexcept
{
return v + N;
}
constexpr const_iterator end() const noexcept
{
return v + N;
}
constexpr const_iterator cend() const noexcept
{
return v + N;
}
// Since this is a fixed-component-count vector class,
// it should never be empty, so this should always return false.
// The compiler probably won't allow N to be 0, but if it ever
// does, it would return true in that unlikely case.
static constexpr bool empty() noexcept
{
return N == 0;
}
// Add two of the vectors together
constexpr tuple& operator+=(const tuple<T, N>& that) noexcept
{
for (size_t i = 0; i < N; ++i)
{
v[i] += that[i];
}
return *this;
}
// passing lhs by value helps optimize chained a+b+c
friend tuple<T, N> operator+(tuple<T, N> lhs, const tuple<T, N>& rhs)
{
lhs += rhs;
return lhs;
}
// Subtract another vector from this one
constexpr tuple& operator-=(const tuple<T, N>& that) noexcept
{
for (size_t i = 0; i < N; ++i)
{
v[i] -= that[i];
}
return *this;
}
// passing lhs by value helps optimize chained a-b-c
friend tuple<T, N> operator-(tuple<T, N> lhs, const tuple<T, N>& rhs)
{
lhs -= rhs;
return lhs;
}
// Multiply all elements of the vector by a constant
constexpr tuple& operator*=(const T& multiplier) noexcept
{
for (size_t i = 0; i < N; ++i)
{
v[i] *= multiplier;
}
return *this;
}
// passing lhs by value helps optimize chained (a*b)*c
friend tuple<T, N> operator*(tuple<T, N> lhs, const T& multiplier)
{
lhs *= multiplier;
return lhs;
}
// Divide all elements of the vector by a constant
constexpr tuple& operator/=(const T& divisor) noexcept
{
for (size_t i = 0; i < N; ++i)
{
v[i] /= divisor;
}
return *this;
}
// passing lhs by value helps optimize chained (a/b)/c
friend tuple<T, N> operator/(tuple<T, N> lhs, const T& divisor)
{
lhs /= divisor;
return lhs;
}
// Helper function for PoD types that computes length
constexpr double length() const
{
T myLength{ (T)0 };
for (size_t i = 0; i < N; ++i)
{
myLength += operator[](i) * operator[](i);
}
return std::sqrt(myLength);
}
// Helper function for PoD types that returns a normalized version of the vector
constexpr tuple<T, N> normalized() const
{
tuple<T, N> normalizedVector{ *this };
double vectorLength = length();
// If the length is zero then the vector is zero so it can be returned directly.
if (vectorLength != 0.0)
{
for (size_t i = 0; i < N; ++i)
{
// C-style cast is needed in order to silently handle acceptable precision losses
normalizedVector[i] = T(normalizedVector[i] / vectorLength);
}
}
return normalizedVector;
}
// Uses the elementwise less-than in order from first to last for non-PoD types.
// Should only be called if the elements have that operator.
constexpr bool lessThanByElement(const tuple<T, N>& rhs) const
{
for (size_t i = 0; i < N; ++i)
{
if (operator[](i) < rhs[i])
{
return true;
}
else if (rhs[i] < operator[](i))
{
return false;
}
}
return false;
}
// Algorithm for "<" that uses the vector length for comparison. Does not use the length()
// method because for comparison puposes the expensize sqrt() is not needed.
constexpr bool lessThanByLength(const tuple<T, N>& rhs) const
{
T myLength{ (T)0 };
T rhsLength{ (T)0 };
for (size_t i = 0; i < N; ++i)
{
myLength += operator[](i) * operator[](i);
rhsLength += rhs[i] * rhs[i];
}
return myLength < rhsLength;
}
// Ordering is by vector length for PoDs and by ordering of elements in order if not
constexpr bool operator<(const tuple<T, N>& rhs) const
{
return is_trivial<T>().check() ? lessThanByLength(rhs) : lessThanByElement(rhs);
}
// Uses the elementwise less-than in order from first to last for non-PoD types.
// Should only be called if the elements have that operator.
constexpr bool greaterThanByElement(const tuple<T, N>& rhs) const
{
for (size_t i = 0; i < N; ++i)
{
if (operator[](i) > rhs[i])
{
return true;
}
else if (rhs[i] > operator[](i))
{
return false;
}
}
return false;
}
// Algorithm for "<" that uses the vector length for comparison
constexpr bool greaterThanByLength(const tuple<T, N>& rhs) const
{
T myLength{ (T)0 };
T rhsLength{ (T)0 };
for (size_t i = 0; i < N; ++i)
{
myLength += operator[](i) * operator[](i);
rhsLength += rhs[i] * rhs[i];
}
// No need to take sqrt as only the relative difference is important
return myLength > rhsLength;
}
// Ordering is by vector length for PoDs and by ordering of elements in order if not
constexpr bool operator>(const tuple<T, N>& rhs) const
{
return is_trivial<T>().check() ? greaterThanByLength(rhs) : greaterThanByElement(rhs);
}
// Equality is element-wise
constexpr bool operator==(const tuple<T, N>& rhs) const
{
for (size_t i = 0; i < N; ++i)
{
if (operator[](i) != rhs[i])
{
return false;
}
}
return true;
}
// Derivative operators, where just as efficient as separate implementation
constexpr bool operator!=(const tuple<T, N>& rhs) const
{
return !operator==(rhs);
}
constexpr bool operator>=(const tuple<T, N>& rhs) const
{
return !operator<(rhs);
}
constexpr bool operator<=(const tuple<T, N>& rhs) const
{
return !operator>(rhs);
}
private:
T v[N];
template <size_t i, typename OTHER_T>
constexpr void initHelper(OTHER_T a)
{
static_assert(i == N - 1, "Variadic constructor of tuple<T, N> requires N arguments");
v[i] = T(a);
}
template <size_t i, typename OTHER_T, typename... Args>
constexpr void initHelper(OTHER_T a, Args... args)
{
v[i] = T(a);
initHelper<i + 1>(args...);
}
};
} // namespace core
} // namespace graph
} // namespace omni
| 11,816 | C | 29.145408 | 99 | 0.587847 |
omniverse-code/kit/include/omni/graph/core/Type.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <omni/fabric/IdTypes.h>
#include <omni/fabric/Type.h>
#include <sstream>
#include <string>
// Alias fabric types into omnigraph for backwards compatibility.
// Use omni/fabric/Type.h outside of the omnigraph project
namespace omni
{
namespace graph
{
namespace core
{
//! OmniGraph Type is just an alias for the Fabric Type
using Type = omni::fabric::Type;
//! OmniGraph BaseDataType is just an alias for the Fabric BaseDataType
using BaseDataType = omni::fabric::BaseDataType;
//! OmniGraph AttributeRole is just an alias for the Fabric AttributeRole
using AttributeRole = omni::fabric::AttributeRole;
using BucketId = omni::fabric::BucketId;
// ======================================================================
/**
* @brief Get a string that describes the type role in OGN format
*
* The role name is slightly different here than @ref omni::fabric::getAttributeRoleName for historical reasons
*
* @param r Role whose name is to be returned
* @return std::string OGN-style name of the given role
*/
inline std::string getOgnRoleName(AttributeRole r)
{
static const std::string ognRoleNames[] = { "none",
"vector",
"normal",
"point",
"color",
"texcoord",
"quat",
"transform",
"frame",
"timecode",
"text",
"appliedSchema",
"primTypeName",
"execution",
"matrix",
"objectId",
"bundle",
"path",
"instancedAttribute",
"ancestorPrimTypeName",
"target",
"unknown" };
if (r <= AttributeRole::eUnknown)
{
return ognRoleNames[uint8_t(r)];
}
return std::string();
}
// ======================================================================
/**
* @brief Get a string that describes the type in OGN format
*
* OGN formats the type names slightly differently than @ref omni::fabric::getTypeName
* - the tuples are indexed "float[3]" instead of "float3"
* - the roles replace the actual name "colord[3]" instead of "double3 (color)"
*
* @param t Type definition whose name is to be returned
* @return std::string OGN-style name of the type
*/
inline std::string getOgnTypeName(Type t)
{
std::ostringstream typeName;
if (t.role == AttributeRole::eText)
{
typeName << "string";
return typeName.str();
}
if (t.role == AttributeRole::ePath)
{
typeName << "path";
return typeName.str();
}
if (t.role != AttributeRole::eNone)
{
typeName << getOgnRoleName(t.role);
// For roles with explicit types, add that to the role name
if ((t.role != AttributeRole::eTimeCode) && (t.role != AttributeRole::eTransform) &&
(t.role != AttributeRole::eFrame) && (t.role != AttributeRole::eObjectId) &&
(t.role != AttributeRole::eBundle) && (t.role != AttributeRole::eExecution) &&
(t.role != AttributeRole::eTarget))
{
switch (t.baseType)
{
case BaseDataType::eHalf:
typeName << "h";
break;
case BaseDataType::eFloat:
typeName << "f";
break;
case BaseDataType::eDouble:
typeName << "d";
break;
default:
typeName << t.baseType;
break;
}
}
}
else
{
typeName << t.baseType;
}
if (t.componentCount > 1)
{
typeName << "[" << uint32_t(t.dimension()) << "]";
}
if (t.arrayDepth == 1)
typeName << "[]";
else if (t.arrayDepth == 2)
typeName << "[][]";
return typeName.str();
}
} // namespace core
} // namespace graph
} // namespace omni
| 5,053 | C | 33.855172 | 111 | 0.486246 |
omniverse-code/kit/include/omni/graph/core/IVariable2.h | // 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.
//
#pragma once
#include <omni/core/IObject.h>
#include <omni/graph/core/Type.h>
#include <omni/graph/core/Handle.h>
#include <omni/graph/core/IVariable.h>
namespace omni
{
namespace graph
{
namespace core
{
OMNI_DECLARE_INTERFACE(IVariable2);
/**
* @brief Interface extension for IVariable that adds the ability to set a variable type
*/
class IVariable2_abi :
public omni::core::Inherits<omni::graph::core::IVariable, OMNI_TYPE_ID("omni.graph.core.IVariable2")>
{
protected:
/**
* Sets the type of the variable.
*
* @param[in] type New type for the variable
*
* @return True if the type is able to be set, false otherwise
*/
virtual bool setType_abi(Type type) noexcept = 0;
};
} // namespace core
} // namespace graph
} // namespace omni
#include "IVariable2.gen.h"
/**
* Implementation of IVariable setType method
*/
#ifndef DOXYGEN_BUILD
inline bool omni::graph::core::IVariable::setType(omni::graph::core::Type type) noexcept
{
auto v2 = omni::core::cast<IVariable2>(this);
if (v2)
{
return v2->setType(type);
}
else
{
return false;
}
}
#endif
| 1,585 | C | 23.030303 | 105 | 0.700315 |
omniverse-code/kit/include/omni/graph/core/IInternal.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Defines.h>
#include <carb/Interface.h>
#include <carb/Types.h>
#include <omni/graph/core/unstable/IPrivateNodeGraphDef.h>
#include <omni/graph/core/unstable/IPrivateNodeDef.h>
#include <omni/graph/core/Handle.h>
#include <cstddef>
namespace omni
{
namespace graph
{
namespace core
{
/**
* This class contains functions and member variables that are intended only for internal
* use by the omni.graph.core extension but which, for technical reasons, we are forced to
* expose externally.
*
* This class is explicitly exempt from the usual rules about deprecation and backwards compatibility.
* Members may be added, removed, or changed at any time without notice.
*/
struct IInternal
{
CARB_PLUGIN_INTERFACE("omni::graph::core::IInternal", 1, 2);
// NOTE: In the Python implementation all methods and members should begin with a single underscore (_)
// to further drive home that they are meant for internal use only.
/**
* Mark an attribute as deprecated, meaning that it should no longer be used and will be removed in a future version.
*
* @param[in] attrObj The attribute being deprecated.
* @param[in] message Message explaining what users should do to deal with the deprecation.
*/
void(CARB_ABI* deprecateAttribute)(const AttributeObj& attrObj, const char *message);
/**
* Factory method used to create internal generic graph definition wrapping private class
*
* @param[in] builder Graph builder requesting this construction
* @param[in] definitionName The name associated with this definition. Used by the pass pipeline
* @param[in] graphObj Authoring graph this definition belongs to
* @param[in] isInstanced Is this graph a graph instance
*/
unstable::IPrivateNodeGraphDef* (CARB_ABI* createPrivateGraphDef)(
const GraphObj& graphObj,
bool isInstanced);
/**
* Factory method used to create internal generic node definition wrapping private class
*
* @param[in] nodeObj Authoring node this definition belongs to
*/
unstable::IPrivateNodeDef*(CARB_ABI* createPrivateNodeDef)(const NodeObj& nodeObj);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IInternal, createPrivateNodeDef, 2)
} // namespace core
} // namespace graph
} // namespace omni
| 2,858 | C | 36.618421 | 121 | 0.738279 |
omniverse-code/kit/include/omni/graph/core/ArrayWrapper.h | // 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.
//
#pragma once
#include "GpuArray.h"
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/Accessors.h>
#include <tuple>
namespace omni {
namespace graph {
namespace core {
template <typename T>
struct GpuArray;
template <typename T>
struct ConstGpuArray;
// Convenience function to retrieve an attribute data handle given the attribute. The
// attribute data handle is needed to retrieve the data of the attribute. This is the read only version.
inline ConstAttributeDataHandle getAttributeHandleR(const AttributeObj& attrObj, InstanceIndex instIndex)
{
return attrObj.iAttribute->getConstAttributeDataHandle(attrObj, instIndex);
}
// Convenience function to retrieve an attribute data handle given the attribute. The
// attribute data handle is needed to retrieve the data of the attribute. This is the writable version.
inline AttributeDataHandle getAttributeHandleW(const AttributeObj& attrObj, InstanceIndex instIndex)
{
return attrObj.iAttribute->getAttributeDataHandle(attrObj, instIndex);
}
template <typename T>
class ArrayWrapper
{
const GraphContextObj m_context = {};
const AttributeObj m_attrObj = {};
const InstanceIndex m_instIdx{ kAccordingToContextIndex };
public:
ArrayWrapper(const GraphContextObj& context,
const AttributeObj& attrObj,
InstanceIndex instanceIdx = kAccordingToContextIndex)
: m_context(context), m_attrObj(attrObj), m_instIdx(instanceIdx)
{
}
ArrayWrapper()
{
}
bool isValid(DataAccessFlags access) const
{
if (!m_context.iContext)
return false;
// for outputs it's okay for the size to be 0. So we only check for inputs here.
return access == kReadOnly ? getArrayRd() != nullptr : true;
}
// CPU buffer accessors
T* getArray()
{
return getArrayWr();
}
const T* getArrayRd() const
{
ConstAttributeDataHandle attrDataHandle = getAttributeHandleR(m_attrObj, m_instIdx);
// Technically this is a void*** at this point. Fabric stores arrays as a pointer to the actual
// buffer. The getDataR interface requires a void** , so we are forcing it to be that here.
// At the end of the call, out contains the address to the buffer, which we then dereference to
// get at the array buffer
const void** out = nullptr;
void** outPtr = reinterpret_cast<void**>(&out);
m_context.iAttributeData->getDataR((const void**)outPtr, m_context, &attrDataHandle, 1);
if (out == nullptr)
return nullptr;
return reinterpret_cast<T*>(const_cast<void*>(*out));
}
T* getArrayWr()
{
AttributeDataHandle attrDataHandle = getAttributeHandleW(m_attrObj, m_instIdx);
void** out;
// see note above about void*** forced to void**
void** outPtr = reinterpret_cast<void**>(&out);
m_context.iAttributeData->getDataW(outPtr, m_context, &attrDataHandle, 1);
if (out == nullptr)
return nullptr;
return reinterpret_cast<T*>(*out);
}
void resize(size_t newCount)
{
AttributeDataHandle attrDataHandle = getAttributeHandleW(m_attrObj, m_instIdx);
m_context.iAttributeData->setElementCount(m_context, attrDataHandle, newCount);
}
size_t size() const
{
ConstAttributeDataHandle attrDataHandle = getAttributeHandleR(m_attrObj, m_instIdx);
size_t elemCount = 0;
m_context.iAttributeData->getElementCount(&elemCount, m_context, &attrDataHandle, 1);
return elemCount;
}
bool empty() const
{
return size() == 0;
}
// GPU buffer accessors
GpuArray<T> getArrayGPU()
{
return getArrayWrGPU();
}
ConstGpuArray<T> getArrayRdGPU() const
{
ConstAttributeDataHandle attrDataHandle = getAttributeHandleR(m_attrObj, m_instIdx);
const void** out = nullptr;
void** outPtr = reinterpret_cast<void**>(&out);
m_context.iAttributeData->getDataRGPU((const void**)outPtr, m_context, &attrDataHandle, 1);
auto array = (T* const*)(out);
return ConstGpuArray<T>{ array, sizeGPU() };
}
GpuArray<T> getArrayWrGPU()
{
AttributeDataHandle attrDataHandle = getAttributeHandleW(m_attrObj, m_instIdx);
void** out;
void** outPtr = reinterpret_cast<void**>(&out);
m_context.iAttributeData->getDataWGPU(outPtr, m_context, &attrDataHandle, 1);
auto array = (T* const*)(out);
return GpuArray<T>{ array, sizeGPU() };
}
// GPU size accessor
const size_t* sizeGPU() const
{
// We don't support GPU resizing array
return nullptr;
}
};
}
}
}
| 5,177 | C | 31.566038 | 105 | 0.672204 |
omniverse-code/kit/include/omni/graph/core/NodeTypeRegistryTemplates.h | // 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.
//
#pragma once
#ifndef NODE_TYPE_REGISTRY
# error This file can only be included indirectly from NodeTypeRegistrar.h
#endif
#include "iComputeGraph.h"
#include <type_traits>
//======================================================================
// Template metaprogramming that allows the node registration to figure out at compile time
// which functions a node has that can be registered. Functions come from the INodeType
// interface in iComputeGraph.h.
template <typename>
struct sfinae_true : std::true_type
{
};
template <typename>
struct sfinae_false : std::false_type
{
};
// Template collection to provide a pointer to the static method getNodeType() if it exists
// Usage: auto getNodeTypeFn = getNodeTypeFunction<NodeClass>();
using GetNodeTypeFunction = std::add_pointer<const char*()>::type;
template <typename NodeType>
constexpr auto _checkGetNodeTypeFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkGetNodeTypeFunction(int) -> sfinae_true<decltype(std::declval<const NodeType&>().getNodeType())>;
template <typename NodeType>
struct _hasGetNodeTypeFunction : decltype(_checkGetNodeTypeFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasGetNodeTypeFunction<NodeType>::value, bool>::type = 0>
static inline GetNodeTypeFunction getNodeTypeFunction()
{
return &NodeType::getNodeType;
};
template <typename NodeType, typename std::enable_if<!_hasGetNodeTypeFunction<NodeType>::value, bool>::type = 0>
static inline GetNodeTypeFunction getNodeTypeFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method compute() if it exists
// Usage: auto computeFn = computeFunction<NodeClass>();
using ComputeFunction = std::add_pointer<bool(const GraphContextObj&, const NodeObj&)>::type;
template <typename NodeType>
constexpr auto _checkComputeFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkComputeFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().compute(std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>()))>;
template <typename NodeType>
struct _hasComputeFunction : decltype(_checkComputeFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasComputeFunction<NodeType>::value, bool>::type = 0>
static inline ComputeFunction computeFunction()
{
return &NodeType::compute;
};
template <typename NodeType, typename std::enable_if<!_hasComputeFunction<NodeType>::value, bool>::type = 0>
static inline ComputeFunction computeFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method initialize() if it exists
// Usage: auto initializeFn = initializeFunction<NodeClass>();
using InitializeFunction = std::add_pointer<void(const GraphContextObj&, const NodeObj&)>::type;
template <typename NodeType>
constexpr auto _checkInitializeFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkInitializeFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().initialize(std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>()))>;
template <typename NodeType>
struct _hasInitializeFunction : decltype(_checkInitializeFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasInitializeFunction<NodeType>::value, bool>::type = 0>
static inline InitializeFunction initializeFunction()
{
return &NodeType::initialize;
};
template <typename NodeType, typename std::enable_if<!_hasInitializeFunction<NodeType>::value, bool>::type = 0>
static inline InitializeFunction initializeFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method release() if it exists
// Usage: auto releaseFn = releaseFunction<NodeClass>();
using ReleaseFunction = std::add_pointer<void(const NodeObj&)>::type;
template <typename NodeType>
constexpr auto _checkReleaseFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkReleaseFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().release(std::declval<const NodeObj&>()))>;
template <typename NodeType>
struct _hasReleaseFunction : decltype(_checkReleaseFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasReleaseFunction<NodeType>::value, bool>::type = 0>
static inline ReleaseFunction releaseFunction()
{
return &NodeType::release;
};
template <typename NodeType, typename std::enable_if<!_hasReleaseFunction<NodeType>::value, bool>::type = 0>
static inline ReleaseFunction releaseFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method initializeType() if it exists
// Usage: auto initializeTypeFn = initializeTypeFunction<NodeClass>();
using InitializeTypeFunction = std::add_pointer<void(const NodeTypeObj&)>::type;
template <typename NodeType>
constexpr auto _checkInitializeTypeFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkInitializeTypeFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().initializeType(std::declval<const NodeTypeObj&>()))>;
template <typename NodeType>
struct _hasInitializeTypeFunction : decltype(_checkInitializeTypeFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasInitializeTypeFunction<NodeType>::value, bool>::type = 0>
static inline InitializeTypeFunction initializeTypeFunction()
{
return &NodeType::initializeType;
};
template <typename NodeType, typename std::enable_if<!_hasInitializeTypeFunction<NodeType>::value, bool>::type = 0>
static inline InitializeTypeFunction initializeTypeFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method updateNodeVersion() if it exists
// Usage: auto updateNodeVersionFn = updateNodeVersionFunction<NodeClass>();
using UpdateNodeVersionFunction = std::add_pointer<bool(const GraphContextObj&, const NodeObj&, int, int)>::type;
template <typename NodeType>
constexpr auto _checkUpdateNodeVersionFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkUpdateNodeVersionFunction(int) -> sfinae_true<decltype(std::declval<const NodeType&>().updateNodeVersion(
std::declval<const GraphContextObj&>(), std::declval<const NodeObj&>(), std::declval<int>(), std::declval<int>()))>;
template <typename NodeType>
struct _hasUpdateNodeVersionFunction : decltype(_checkUpdateNodeVersionFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasUpdateNodeVersionFunction<NodeType>::value, bool>::type = 0>
static inline UpdateNodeVersionFunction updateNodeVersionFunction()
{
return &NodeType::updateNodeVersion;
};
template <typename NodeType, typename std::enable_if<!_hasUpdateNodeVersionFunction<NodeType>::value, bool>::type = 0>
static inline UpdateNodeVersionFunction updateNodeVersionFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method addInput() if it exists
// Usage: auto addInputFn = addInputFunction<NodeClass>();
using AddInputFunction =
std::add_pointer<void(const NodeTypeObj&, const char*, const char*, bool, const void*, const size_t*)>::type;
template <typename NodeType>
constexpr auto _checkAddInputFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkAddInputFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().addInput(std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<const void*>(),
std::declval<const size_t*>()))>;
template <typename NodeType>
struct _hasAddInputFunction : decltype(_checkAddInputFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasAddInputFunction<NodeType>::value, bool>::type = 0>
static inline AddInputFunction addInputFunction()
{
return &NodeType::addInput;
};
template <typename NodeType, typename std::enable_if<!_hasAddInputFunction<NodeType>::value, bool>::type = 0>
static inline AddInputFunction addInputFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method addExtendedInput() if it exists
// Usage: auto addExtendedInputFn = addExtendedInputFunction<NodeClass>();
using AddExtendedInputFunction =
std::add_pointer<void(const NodeTypeObj&, const char*, const char*, bool, ExtendedAttributeType)>::type;
template <typename NodeType>
constexpr auto _checkAddExtendedInputFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkAddExtendedInputFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().addExtendedInput(std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<ExtendedAttributeType>()))>;
template <typename NodeType>
struct _hasAddExtendedInputFunction : decltype(_checkAddExtendedInputFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasAddExtendedInputFunction<NodeType>::value, bool>::type = 0>
static inline AddExtendedInputFunction addExtendedInputFunction()
{
return &NodeType::addExtendedInput;
};
template <typename NodeType, typename std::enable_if<!_hasAddExtendedInputFunction<NodeType>::value, bool>::type = 0>
static inline AddExtendedInputFunction addExtendedInputFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method addOutput() if it exists
// Usage: auto addOutputFn = addOutputFunction<NodeClass>();
using AddOutputFunction =
std::add_pointer<void(const NodeTypeObj&, const char*, const char*, bool, const void*, const size_t*)>::type;
template <typename NodeType>
constexpr auto _checkAddOutputFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkAddOutputFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().addOutput(std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<const void*>(),
std::declval<const size_t*>()))>;
template <typename NodeType>
struct _hasAddOutputFunction : decltype(_checkAddOutputFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasAddOutputFunction<NodeType>::value, bool>::type = 0>
static inline AddOutputFunction addOutputFunction()
{
return &NodeType::addOutput;
};
template <typename NodeType, typename std::enable_if<!_hasAddOutputFunction<NodeType>::value, bool>::type = 0>
static inline AddOutputFunction addOutputFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method addExtendedOutput() if it exists
// Usage: auto addExtendedOutputFn = addExtendedOutputFunction<NodeClass>();
using AddExtendedOutputFunction =
std::add_pointer<void(const NodeTypeObj&, const char*, const char*, bool, ExtendedAttributeType)>::type;
template <typename NodeType>
constexpr auto _checkAddExtendedOutputFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkAddExtendedOutputFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().addExtendedOutput(std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<ExtendedAttributeType>()))>;
template <typename NodeType>
struct _hasAddExtendedOutputFunction : decltype(_checkAddExtendedOutputFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasAddExtendedOutputFunction<NodeType>::value, bool>::type = 0>
static inline AddExtendedOutputFunction addExtendedOutputFunction()
{
return &NodeType::addExtendedOutput;
};
template <typename NodeType, typename std::enable_if<!_hasAddExtendedOutputFunction<NodeType>::value, bool>::type = 0>
static inline AddExtendedOutputFunction addExtendedOutputFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method addState() if it exists
// Usage: auto addStateFn = addStateFunction<NodeClass>();
using AddStateFunction =
std::add_pointer<void(const NodeTypeObj&, const char*, const char*, bool, const void*, const size_t*)>::type;
template <typename NodeType>
constexpr auto _checkAddStateFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkAddStateFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().addState(std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<const void*>(),
std::declval<const size_t*>()))>;
template <typename NodeType>
struct _hasAddStateFunction : decltype(_checkAddStateFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasAddStateFunction<NodeType>::value, bool>::type = 0>
static inline AddStateFunction addStateFunction()
{
return &NodeType::addState;
};
template <typename NodeType, typename std::enable_if<!_hasAddStateFunction<NodeType>::value, bool>::type = 0>
static inline AddStateFunction addStateFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method addExtendedState() if it exists
// Usage: auto addExtendedStateFn = addExtendedStateFunction<NodeClass>();
using AddExtendedStateFunction =
std::add_pointer<void(const NodeTypeObj&, const char*, const char*, bool, ExtendedAttributeType)>::type;
template <typename NodeType>
constexpr auto _checkAddExtendedStateFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkAddExtendedStateFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().addExtendedState(std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<ExtendedAttributeType>()))>;
template <typename NodeType>
struct _hasAddExtendedStateFunction : decltype(_checkAddExtendedStateFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasAddExtendedStateFunction<NodeType>::value, bool>::type = 0>
static inline AddExtendedStateFunction addExtendedStateFunction()
{
return &NodeType::addExtendedState;
};
template <typename NodeType, typename std::enable_if<!_hasAddExtendedStateFunction<NodeType>::value, bool>::type = 0>
static inline AddExtendedStateFunction addExtendedStateFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method hasState() if it exists
// Usage: auto hasStateFn = hasStateFunction<NodeClass>();
using HasStateFunction = std::add_pointer<bool(const NodeTypeObj&)>::type;
template <typename NodeType>
constexpr auto _checkHasStateFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkHasStateFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().hasState(std::declval<const NodeTypeObj&>()))>;
template <typename NodeType>
struct _hasHasStateFunction : decltype(_checkHasStateFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasHasStateFunction<NodeType>::value, bool>::type = 0>
static inline HasStateFunction hasStateFunction()
{
return &NodeType::hasState;
};
template <typename NodeType, typename std::enable_if<!_hasHasStateFunction<NodeType>::value, bool>::type = 0>
static inline HasStateFunction hasStateFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method registerTasks() if it exists
// Usage: auto registerTasksFn = registerTasksFunction<NodeClass>();
using RegisterTasksFunction = std::add_pointer<void()>::type;
template <typename NodeType>
constexpr auto _checkRegisterTasksFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkRegisterTasksFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().registerTasks())>;
template <typename NodeType>
struct _hasRegisterTasksFunction : decltype(_checkRegisterTasksFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasRegisterTasksFunction<NodeType>::value, bool>::type = 0>
static inline RegisterTasksFunction registerTasksFunction()
{
return &NodeType::registerTasks;
};
template <typename NodeType, typename std::enable_if<!_hasRegisterTasksFunction<NodeType>::value, bool>::type = 0>
static inline RegisterTasksFunction registerTasksFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method getAllMetadata() if it exists
// Usage: auto getAllMetadataFn = getAllMetadataFunction<NodeClass>();
using GetAllMetadataFunction =
std::add_pointer<size_t(const NodeTypeObj& nodeType, const char**, const char**, size_t)>::type;
template <typename NodeType>
constexpr auto _checkGetAllMetadataFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkGetAllMetadataFunction(int) -> sfinae_true<decltype(std::declval<const NodeType&>().getAllMetadata(
std::declval<const NodeTypeObj&>(), std::declval<const char**>(), std::declval<const char**>(), std::declval<size_t>()))>;
template <typename NodeType>
struct _hasGetAllMetadataFunction : decltype(_checkGetAllMetadataFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasGetAllMetadataFunction<NodeType>::value, bool>::type = 0>
static inline GetAllMetadataFunction getAllMetadataFunction()
{
return &NodeType::getAllMetadata;
};
template <typename NodeType, typename std::enable_if<!_hasGetAllMetadataFunction<NodeType>::value, bool>::type = 0>
static inline GetAllMetadataFunction getAllMetadataFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method getMetadata() if it exists
// Usage: auto getMetadataFn = getMetadataFunction<NodeClass>();
using GetMetadataFunction = std::add_pointer<const char*(const NodeTypeObj& nodeType, const char*)>::type;
template <typename NodeType>
constexpr auto _checkGetMetadataFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkGetMetadataFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().getMetadata(std::declval<const NodeTypeObj&>(),
std::declval<const char*>()))>;
template <typename NodeType>
struct _hasGetMetadataFunction : decltype(_checkGetMetadataFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasGetMetadataFunction<NodeType>::value, bool>::type = 0>
static inline GetMetadataFunction getMetadataFunction()
{
return &NodeType::getMetadata;
};
template <typename NodeType, typename std::enable_if<!_hasGetMetadataFunction<NodeType>::value, bool>::type = 0>
static inline GetMetadataFunction getMetadataFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method getMetadataCount() if it exists
// Usage: auto getMetadataCountFn = getMetadataCountFunction<NodeClass>();
using GetMetadataCountFunction = std::add_pointer<size_t(const NodeTypeObj& nodeType)>::type;
template <typename NodeType>
constexpr auto _checkGetMetadataCountFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkGetMetadataCountFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().getMetadataCount(std::declval<const NodeTypeObj&>()))>;
template <typename NodeType>
struct _hasGetMetadataCountFunction : decltype(_checkGetMetadataCountFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasGetMetadataCountFunction<NodeType>::value, bool>::type = 0>
static inline GetMetadataCountFunction getMetadataCountFunction()
{
return &NodeType::getMetadataCount;
};
template <typename NodeType, typename std::enable_if<!_hasGetMetadataCountFunction<NodeType>::value, bool>::type = 0>
static inline GetMetadataCountFunction getMetadataCountFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method setMetadata() if it exists
// Usage: auto setMetadataFn = setMetadataFunction<NodeClass>();
using SetMetadataFunction = std::add_pointer<void(const NodeTypeObj& nodeType, const char*, const char*)>::type;
template <typename NodeType>
constexpr auto _checkSetMetadataFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkSetMetadataFunction(int) -> sfinae_true<decltype(std::declval<const NodeType&>().setMetadata(
std::declval<const NodeTypeObj&>(), std::declval<const char*>(), std::declval<const char*>()))>;
template <typename NodeType>
struct _hasSetMetadataFunction : decltype(_checkSetMetadataFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasSetMetadataFunction<NodeType>::value, bool>::type = 0>
static inline SetMetadataFunction setMetadataFunction()
{
return &NodeType::setMetadata;
};
template <typename NodeType, typename std::enable_if<!_hasSetMetadataFunction<NodeType>::value, bool>::type = 0>
static inline SetMetadataFunction setMetadataFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method getScheduleNodeCount() if it exists
// Usage: auto getScheduleNodeCountFn = getScheduleNodeCountFunction<NodeClass>();
using GetScheduleNodeCountFunction =
std::add_pointer<size_t(const GraphContextObj&, const NodeObj&, const ScheduleNodeObj*, size_t)>::type;
template <typename NodeType>
constexpr auto _checkGetScheduleNodeCountFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkGetScheduleNodeCountFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().getScheduleNodeCount(std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>(),
std::declval<const ScheduleNodeObj*>(),
std::declval<size_t>()))>;
template <typename NodeType>
struct _hasGetScheduleNodeCountFunction : decltype(_checkGetScheduleNodeCountFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasGetScheduleNodeCountFunction<NodeType>::value, bool>::type = 0>
static inline GetScheduleNodeCountFunction getScheduleNodeCountFunction()
{
return &NodeType::getScheduleNodeCount;
};
template <typename NodeType, typename std::enable_if<!_hasGetScheduleNodeCountFunction<NodeType>::value, bool>::type = 0>
static inline GetScheduleNodeCountFunction getScheduleNodeCountFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method getScheduleNodes() if it exists
// Usage: auto getScheduleNodesFn = getScheduleNodesFunction<NodeClass>();
using GetScheduleNodesFunction = std::add_pointer<void(
const GraphContextObj&, const NodeObj&, const ScheduleNodeObj*, size_t, ScheduleNodeObj*, size_t)>::type;
template <typename NodeType>
constexpr auto _checkGetScheduleNodesFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkGetScheduleNodesFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().getScheduleNodes(std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>(),
std::declval<const ScheduleNodeObj*>(),
std::declval<size_t>(),
std::declval<ScheduleNodeObj*>(),
std::declval<size_t>()))>;
template <typename NodeType>
struct _hasGetScheduleNodesFunction : decltype(_checkGetScheduleNodesFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasGetScheduleNodesFunction<NodeType>::value, bool>::type = 0>
static inline GetScheduleNodesFunction getScheduleNodesFunction()
{
return &NodeType::getScheduleNodes;
};
template <typename NodeType, typename std::enable_if<!_hasGetScheduleNodesFunction<NodeType>::value, bool>::type = 0>
static inline GetScheduleNodesFunction getScheduleNodesFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method onConnectionMade() if it exists
// Usage: auto onConnectionTypeResolveFn = onConnectionTypeResolve<NodeClass>();
using OnConnectionTypeResolveFunction = std::add_pointer<void(const NodeObj&)>::type;
template <typename NodeType>
constexpr auto _checkOnConnectionTypeResolveFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkOnConnectionTypeResolveFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().onConnectionTypeResolve(
std::declval<const NodeObj&>()))>;
template <typename NodeType>
struct _hasOnConnectionTypeResolveFunction : decltype(_checkOnConnectionTypeResolveFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasOnConnectionTypeResolveFunction<NodeType>::value, bool>::type = 0>
static inline OnConnectionTypeResolveFunction onConnectionTypeResolveFunction()
{
return &NodeType::onConnectionTypeResolve;
};
template <typename NodeType, typename std::enable_if<!_hasOnConnectionTypeResolveFunction<NodeType>::value, bool>::type = 0>
static inline OnConnectionTypeResolveFunction onConnectionTypeResolveFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method inspect() if it exists
// Usage: auto inspectFn = inspectFunction<NodeClass>();
using InspectFunction = std::add_pointer<bool(const NodeTypeObj& nodeType, inspect::IInspector*)>::type;
template <typename NodeType>
constexpr auto _checkInspectFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkInspectFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().inspect(std::declval<const NodeTypeObj&>(),
std::declval<inspect::IInspector*>()))>;
template <typename NodeType>
struct _hasInspectFunction : decltype(_checkInspectFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasInspectFunction<NodeType>::value, bool>::type = 0>
static inline InspectFunction inspectFunction()
{
return &NodeType::inspect;
};
template <typename NodeType, typename std::enable_if<!_hasInspectFunction<NodeType>::value, bool>::type = 0>
static inline InspectFunction inspectFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method computeVectorized() if it exists
// Usage: auto computeVectorizedFn = computeVectorizedFunction<NodeClass>();
using ComputeVectorizedFunction = std::add_pointer<size_t(const GraphContextObj&, const NodeObj&, size_t)>::type;
template <typename NodeType>
constexpr auto _checkComputeVectorizedFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkComputeVectorizedFunction(int)
-> sfinae_true<decltype(std::declval<const NodeType&>().computeVectorized(std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>(),
std::declval<size_t>()))>;
template <typename NodeType>
struct _hasComputeVectorizedFunction : decltype(_checkComputeVectorizedFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasComputeVectorizedFunction<NodeType>::value, bool>::type = 0>
static inline ComputeVectorizedFunction computeVectorizedFunction()
{
return &NodeType::computeVectorized;
};
template <typename NodeType, typename std::enable_if<!_hasComputeVectorizedFunction<NodeType>::value, bool>::type = 0>
static inline ComputeVectorizedFunction computeVectorizedFunction()
{
return nullptr;
};
// Template collection to provide a pointer to the static method releaseInstance() if it exists
// Usage: auto releaseInstanceFn = releaseInstanceFunction<NodeClass>();
using ReleaseInstanceFunction = std::add_pointer<void(const NodeObj&, NameToken)>::type;
template <typename NodeType>
constexpr auto _checkReleaseInstanceFunction(long) -> sfinae_false<NodeType>;
template <typename NodeType>
constexpr auto _checkReleaseInstanceFunction(int) -> sfinae_true<decltype(std::declval<const NodeType&>().releaseInstance(
std::declval<const NodeObj&>(), std::declval<NameToken>()))>;
template <typename NodeType>
struct _hasReleaseInstanceFunction : decltype(_checkReleaseInstanceFunction<NodeType>(0))
{
};
template <typename NodeType, typename std::enable_if<_hasReleaseInstanceFunction<NodeType>::value, bool>::type = 0>
static inline ReleaseInstanceFunction releaseInstanceFunction()
{
return &NodeType::releaseInstance;
};
template <typename NodeType, typename std::enable_if<!_hasReleaseInstanceFunction<NodeType>::value, bool>::type = 0>
static inline ReleaseInstanceFunction releaseInstanceFunction()
{
return nullptr;
};
| 31,955 | C | 49.245283 | 126 | 0.704084 |
omniverse-code/kit/include/omni/graph/core/ISchedulingHints2.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Interface extension for ISchedulingHints that adds a new "pure" hint
template <>
class omni::core::Generated<omni::graph::core::ISchedulingHints2_abi> : public omni::graph::core::ISchedulingHints2_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::ISchedulingHints2")
/**
* Get the flag describing the node's purity state.
*
* @returns Value of the PurityStatus flag.
*/
omni::graph::core::ePurityStatus getPurityStatus() noexcept;
/**
* Set the flag describing the node's purity status.
*
* @param[in] newPurityStatus New value of the PurityStatus flag.
*/
void setPurityStatus(omni::graph::core::ePurityStatus newPurityStatus) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::graph::core::ePurityStatus omni::core::Generated<omni::graph::core::ISchedulingHints2_abi>::getPurityStatus() noexcept
{
return getPurityStatus_abi();
}
inline void omni::core::Generated<omni::graph::core::ISchedulingHints2_abi>::setPurityStatus(
omni::graph::core::ePurityStatus newPurityStatus) noexcept
{
setPurityStatus_abi(newPurityStatus);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 2,017 | C | 28.67647 | 131 | 0.730293 |
omniverse-code/kit/include/omni/graph/core/INodeCategories.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
/** Interface to the list of categories that a node type can belong to */
template <>
class omni::core::Generated<omni::graph::core::INodeCategories_abi> : public omni::graph::core::INodeCategories_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::INodeCategories")
/**
* Get the number of categories available
*
* @returns Count of fixed category types
*/
size_t getCategoryCount() noexcept;
/**
* Get the list of available categories and their descriptions.
*
* The caller is responsible for allocating and destroying buffers large enough to hold "bufferSize" results.
* If bufferSize > getCategoryCount() then the entries at the ends of the buffers will be filled with nullptr.
*
* @param[in] categoryNameBuffer List of category names
* @param[in] categoryDescriptionBuffer List of category descriptions corresponding to the names
* @param[in] bufferSize Number of entries to fill in the buffers
*
* @return true if the category buffer was successfully filled and the bufferSize matched the category count
*/
bool getCategories(const char** categoryNameBuffer, const char** categoryDescriptionBuffer, size_t bufferSize) noexcept;
/**
* Define a new category
*
* @param[in] categoryName Name of the new category
* @param[in] categoryDescription Description of the category
*
* @return false if there was already a category with the given name
*/
bool defineCategory(const char* categoryName, const char* categoryDescription) noexcept;
/**
* Remove an existing category, mainly to manage the ones created by a node type for itself
*
* @param[in] categoryName Name of the category to remove
*
* @return false if there was no category with the given name
*/
bool removeCategory(const char* categoryName) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline size_t omni::core::Generated<omni::graph::core::INodeCategories_abi>::getCategoryCount() noexcept
{
return getCategoryCount_abi();
}
inline bool omni::core::Generated<omni::graph::core::INodeCategories_abi>::getCategories(
const char** categoryNameBuffer, const char** categoryDescriptionBuffer, size_t bufferSize) noexcept
{
return getCategories_abi(categoryNameBuffer, categoryDescriptionBuffer, bufferSize);
}
inline bool omni::core::Generated<omni::graph::core::INodeCategories_abi>::defineCategory(
const char* categoryName, const char* categoryDescription) noexcept
{
return defineCategory_abi(categoryName, categoryDescription);
}
inline bool omni::core::Generated<omni::graph::core::INodeCategories_abi>::removeCategory(const char* categoryName) noexcept
{
return removeCategory_abi(categoryName);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 3,679 | C | 34.047619 | 124 | 0.730905 |
omniverse-code/kit/include/omni/graph/core/PyIVariable.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
#pragma once
#include <omni/core/ITypeFactory.h>
#include <omni/python/PyBind.h>
#include <omni/python/PyString.h>
#include <omni/python/PyVec.h>
#include <sstream>
auto bindeVariableScope(py::module& m)
{
py::enum_<omni::graph::core::eVariableScope> e(
m, "eVariableScope", R"OMNI_BIND_RAW_(Scope in which the variable has been made available)OMNI_BIND_RAW_");
e.value("E_PRIVATE", omni::graph::core::eVariableScope::ePrivate,
R"OMNI_BIND_RAW_(Variable is accessible only to its graph )OMNI_BIND_RAW_");
e.value("E_READ_ONLY", omni::graph::core::eVariableScope::eReadOnly,
R"OMNI_BIND_RAW_(Variable can be read by other graphs )OMNI_BIND_RAW_");
e.value("E_PUBLIC", omni::graph::core::eVariableScope::ePublic,
R"OMNI_BIND_RAW_(Variable can be read/written by other graphs )OMNI_BIND_RAW_");
return e;
}
auto bindIVariable(py::module& m)
{
// hack around pybind11 issues with C++17
// - https://github.com/pybind/pybind11/issues/2234
// - https://github.com/pybind/pybind11/issues/2666
// - https://github.com/pybind/pybind11/issues/2856
py::class_<omni::core::Generated<omni::graph::core::IVariable_abi>,
omni::python::detail::PyObjectPtr<omni::core::Generated<omni::graph::core::IVariable_abi>>, omni::core::IObject>
clsParent(m, "_IVariable");
py::class_<omni::graph::core::IVariable, omni::core::Generated<omni::graph::core::IVariable_abi>,
omni::python::detail::PyObjectPtr<omni::graph::core::IVariable>, omni::core::IObject>
cls(m, "IVariable",
R"OMNI_BIND_RAW_(Object that contains a value that is local to a graph, available from anywhere in the graph)OMNI_BIND_RAW_");
cls.def(py::init(
[](const omni::core::ObjectPtr<omni::core::IObject>& obj)
{
auto tmp = omni::core::cast<omni::graph::core::IVariable>(obj.get());
if (!tmp)
{
throw std::runtime_error("invalid type conversion");
}
return tmp;
}));
cls.def(py::init(
[]()
{
auto tmp = omni::core::createType<omni::graph::core::IVariable>();
if (!tmp)
{
throw std::runtime_error("unable to create omni::graph::core::IVariable instantiation");
}
return tmp;
}));
cls.def_property_readonly("name", &omni::graph::core::IVariable::getName);
cls.def_property_readonly("source_path", &omni::graph::core::IVariable::getSourcePath);
cls.def_property("category", &omni::graph::core::IVariable::getCategory,
[](omni::graph::core::IVariable* self, const char* category) { self->setCategory(category); });
cls.def_property("display_name", &omni::graph::core::IVariable::getDisplayName,
[](omni::graph::core::IVariable* self, const char* displayName)
{ self->setDisplayName(displayName); });
cls.def_property("tooltip", &omni::graph::core::IVariable::getTooltip,
[](omni::graph::core::IVariable* self, const char* toolTip) { self->setTooltip(toolTip); });
cls.def_property("scope", &omni::graph::core::IVariable::getScope, &omni::graph::core::IVariable::setScope);
cls.def_property_readonly("valid", &omni::graph::core::IVariable::isValid);
return omni::python::PyBind<omni::graph::core::IVariable>::bind(cls);
}
| 3,955 | C | 48.449999 | 138 | 0.639191 |
omniverse-code/kit/include/omni/graph/core/iAttributeData.h | // Copyright (c) 2019-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.
//
#pragma once
#include <omni/graph/core/Handle.h>
#include <omni/graph/core/Type.h>
namespace omni
{
namespace graph
{
namespace core
{
using RawPtr = uint8_t*; //!< Type for casting byte arrays to actual values
using ConstRawPtr = uint8_t const*; //!< Type for casting const byte arrays to actual values
// ======================================================================
/** Interface to data belonging to a specific attribute */
struct IAttributeData
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::IAttributeData", 1, 6);
/**
* Gets the name of the attribute containing this attribute data.
*
* The attribute data handle may refer to attribute data from an attribute that is upstream
* of the attribute from which the handle was retrieved, in which case, this will
* return the upstream attribute's name.
*
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] handle The handle to the attribute whose name is being requested
* @return A NameToken representing the attribute's name, for which the text can be retrieved
* using IToken::getText
*/
NameToken (CARB_ABI* getName)(const GraphContextObj& contextObj, ConstAttributeDataHandle handle);
/**
* Gets the name of the type of this attribute data. Use getType to get a representation of
* the type that is easier to interpret in code.
*
* The actual attribute data may have a different type than an associated attribute on a node,
* for example, if the upstream source of the data has a different type.
* This function returns the type of the data, not the type of the associated attribute.
*
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] handle The handle to the attribute data whose type name is being requested
* @return A NameToken representing the attribute data's type name, for which the text can be retrieved
* using IToken::getText
*/
NameToken (CARB_ABI* getTypeName)(const GraphContextObj& contextObj, ConstAttributeDataHandle handle);
/**
* Gets the type of this attribute data in a representation that is easily interpreted by code.
*
* The actual attribute data may have a different type than an associated attribute on a node,
* for example, if the upstream source of the data has a different type.
* This function returns the type of the data, not the type of the associated attribute.
*
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] handle The handle to the attribute data whose type is being requested
* @return A Type structure representing the attribute data's type, whose members provide
* information about the type
*/
Type (CARB_ABI* getType)(const GraphContextObj& contextObj, ConstAttributeDataHandle handle);
/**
* Checks whether the type of this attribute data is an array type, i.e. array depth of 1
* (array) or 2 (array of arrays; not yet supported).
*
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] handle The handle to the attribute data to check
* @return true if the attribute data is an array type, else false
*/
bool isArray(const GraphContextObj& contextObj, ConstAttributeDataHandle handle)
{
return (*getType)(contextObj, handle).arrayDepth != 0;
}
/**
deprecated function, do not use
*/
void(CARB_ABI* deprecated_0)(const void**, const GraphContextObj&, const ConstAttributeDataHandle*, size_t);
/**
* Gets GPU pointers to the read-only GPU data of some number of attributes.
*
* Any invalid attributes will have null pointers. Array attributes have an extra level of indirection.
* For example, after requesting int attribute data, attrsOut will effectively be of type
* const int** upon returning, but after requesting int array attribute data, attrsOut will effectively be
* of type const int* const**.
*
* If the attribute data is not on the GPU at the time of this call, but is on the CPU,
* it will be copied to the GPU before returning.
*
* Deprecated: Use getDataRGpuAt
*
* @param[out] attrsOut Array to be filled in with pointers to data of each attribute
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] attrHandles Array of attribute data handles whose data are being requested
* @param[in] attrCount Number of attributes whose data are being requested
*/
void (CARB_ABI* getDataRGPU)(const void** attrsOut,
const GraphContextObj& contextObj,
const ConstAttributeDataHandle* attrHandles,
size_t attrCount);
/**
* Gets CPU pointers to the writable CPU data of some number of attributes.
*
* Any invalid attributes will have null pointers. Array attributes have an extra level of indirection.
* For example, after requesting int attribute data, attrsOut will effectively be of type
* int** upon returning, but after requesting int array attribute data, attrsOut will effectively be
* of type int*const**.
*
* If the attribute data is not on the CPU at the time of this call, but is on the GPU,
* it will be copied to the CPU and invalidated on the GPU before returning.
*
* @param[out] attrsOut Array to be filled in with pointers to data of each attribute
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] attrHandles Array of attribute data handles whose data are being requested
* @param[in] attrCount Number of attributes whose data are being requested
*/
void (CARB_ABI* getDataW)(void** attrsOut,
const GraphContextObj& contextObj,
const AttributeDataHandle* attrHandles,
size_t attrCount);
/**
* Gets GPU pointers to the writable GPU data of some number of attributes.
*
* Any invalid attributes will have null pointers. Array attributes have an extra level of indirection.
* For example, after requesting int attribute data, attrsOut will effectively be of type
* int** upon returning, but after requesting int array attribute data, attrsOut will effectively be
* of type int*const**.
*
* If the attribute data is not on the GPU at the time of this call, but is on the CPU,
* it will be copied to the GPU and invalidated on the CPU before returning.
*
* Deprecated: Use getDataWGpuAt
*
* @param[out] attrsOut Array to be filled in with pointers to data of each attribute
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] attrHandles Array of attribute data handles whose data are being requested
* @param[in] attrCount Number of attributes whose data are being requested
*/
void (CARB_ABI* getDataWGPU)(void** attrsOut,
const GraphContextObj& contextObj,
const AttributeDataHandle* attrHandles,
size_t attrCount);
/**
Deprecated function, do not use
*/
void (CARB_ABI* deprecated_1)(const GraphContextObj&, const AttributeDataHandle*, size_t);
/**
* Gets the number of array elements in each of the specified attributes.
*
* Any invalid attributes will considered to have 0 elements. Attributes that are not
* arrays will be considered to have 1 element. Array of array attributes are not
* yet supported.
*
* @param[out] countOut Array to be filled in with number of elements in each attribute
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] attrHandles Array of attribute data handles whose element counts are being requested
* @param[in] attrCount Number of attributes whose element counts are being requested
*/
void (CARB_ABI* getElementCount)(size_t* countOut,
const GraphContextObj& contextObj,
const ConstAttributeDataHandle* attrHandles,
size_t attrCount);
/**
* Sets the number of array elements in the specified array attribute.
*
* The array attribute's data will not be resized until a pointer to its data is requested.
*
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] handle Attribute data handle referring to an array attribute
* @param[in] count Element count to which the array attribute data should be resized.
*/
void (CARB_ABI* setElementCount)(const GraphContextObj& contextObj, AttributeDataHandle handle, size_t count);
/**
* Copies the data from an existing attribute data value into this one.
* As only data is being copied a name for the destination is not required and will remain unchanged.
*
* @param[in] destination Data location to be overwritten
* @param[in] contextObj Location of both sets of attribute data
* @param[in] source Data being copied
*/
void (CARB_ABI* copyData)(AttributeDataHandle destination,
const GraphContextObj& contextObj,
ConstAttributeDataHandle source);
/**
* Get the location and total number of bytes occupied by the readable attribute data on the CPU.
*
* If the data is not currently valid on the CPU the pointer returned will be nullptr.
*
* @param[in] contextObj Location of both sets of attribute data
* @param[in] attrHandle Handle to the attribute whose size is to be returned
* @param[out] refToData Resulting pointer to the attribute data
* @param[out] refToSize Size of the data being pointed at
*/
void (CARB_ABI* getDataReferenceR)(const ConstAttributeDataHandle attrHandle,
const GraphContextObj& contextObj,
ConstRawPtr& refToData,
size_t& refToSize);
/**
* Get the location and total number of bytes occupied by the readable attribute data on the GPU.
*
* If the data is not currently valid on the GPU the pointer returned will be nullptr.
* If it is then it will point to GPU memory, and should not be dereferenced on the CPU side.
*
* Deprecated: Use getDataReferenceRGpuAt
*
* @param[in] contextObj Location of both sets of attribute data
* @param[in] attrHandle Handle to the attribute whose size is to be returned
* @param[out] refToData Resulting pointer to the attribute data
* @param[out] refToSize Size of the data being pointed at
*/
void (CARB_ABI* getDataReferenceRGpu)(const ConstAttributeDataHandle attrHandle,
const GraphContextObj& contextObj,
ConstRawPtr& refToData,
size_t& refToSize);
/**
* Get the location and total number of bytes occupied by the writable attribute data on the CPU.
*
* If the data is not currently valid on the CPU the pointer returned will be nullptr.
*
* @param[in] contextObj Location of both sets of attribute data
* @param[in] attrHandle Handle to the attribute whose size is to be returned
* @param[out] refToData Resulting pointer to the attribute data
* @param[out] refToSize Size of the data being pointed at
*/
void (CARB_ABI* getDataReferenceW)(const AttributeDataHandle attrHandle,
const GraphContextObj& contextObj,
RawPtr& refToData,
size_t& refToSize);
/**
* Get the location and total number of bytes occupied by the writable attribute data on the GPU.
*
* If the data is not currently valid on the GPU the pointer returned will be nullptr.
* If it is then it will point to GPU memory, and should not be dereferenced on the CPU side.
*
* Deprecated: Use getDataReferenceWGpuAt
*
* @param[in] contextObj Location of both sets of attribute data
* @param[in] attrHandle Handle to the attribute whose size is to be returned
* @param[out] refToData Resulting pointer to the attribute data
* @param[out] refToSize Size of the data being pointed at
*/
void (CARB_ABI* getDataReferenceWGpu)(const AttributeDataHandle attrHandle,
const GraphContextObj& contextObj,
RawPtr& refToData,
size_t& refToSize);
/**
* Check if the cpu data of the given attribute is currently valid
*
* @param[in] contextObj Location of both sets of attribute data
* @param[in] attrHandle Handle to the attribute
*/
bool (CARB_ABI* cpuValid)(const ConstAttributeDataHandle attrHandle, const GraphContextObj& contextObj);
/**
* Check if the gpu data of the given attribute is currently valid
*
* @param[in] contextObj Location of both sets of attribute data
* @param[in] attrHandle Handle to the attribute
*/
bool (CARB_ABI* gpuValid)(const ConstAttributeDataHandle attrHandle, const GraphContextObj& contextObj);
/**
* Gets GPU pointers to the read-only GPU data of some number of attributes.
*
* Any invalid attributes will have null pointers. Array attributes have an extra level of indirection.
* For example, after requesting int attribute data, attrsOut will effectively be of type
* const int** upon returning, but after requesting int array attribute data, attrsOut will effectively be
* of type const int* const**.
*
* If the attribute data is not on the GPU at the time of this call, but is on the CPU,
* it will be copied to the GPU before returning.
*
* @param[out] attrsOut Array to be filled in with pointers to data of each attribute
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] attrHandles Array of attribute data handles whose data are being requested
* @param[in] attrCount Number of attributes whose data are being requested
* @param[in] whereGpuPtrs For array data, the location of the array pointer - either on the CPU or on the GPU
*/
void (CARB_ABI* getDataRGpuAt)(const void** attrsOut,
const GraphContextObj& contextObj,
const ConstAttributeDataHandle* attrHandles,
size_t attrCount,
omni::fabric::PtrToPtrKind whereGpuPtrs);
/**
* Gets GPU pointers to the writable GPU data of some number of attributes.
*
* Any invalid attributes will have null pointers. Array attributes have an extra level of indirection.
* For example, after requesting int attribute data, attrsOut will effectively be of type
* int** upon returning, but after requesting int array attribute data, attrsOut will effectively be
* of type int*const**.
*
* If the attribute data is not on the GPU at the time of this call, but is on the CPU,
* it will be copied to the GPU and invalidated on the CPU before returning.
*
* @param[out] attrsOut Array to be filled in with pointers to data of each attribute
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] attrHandles Array of attribute data handles whose data are being requested
* @param[in] attrCount Number of attributes whose data are being requested
* @param[in] whereGpuPtrs For array data, the location of the array pointer - either on the CPU or on the GPU
*/
void (CARB_ABI* getDataWGpuAt)(void** attrsOut,
const GraphContextObj& contextObj,
const AttributeDataHandle* attrHandles,
size_t attrCount,
omni::fabric::PtrToPtrKind whereGpuPtrs);
/**
* Get the location and total number of bytes occupied by the readable attribute data on the GPU.
*
* If the data is not currently valid on the GPU the pointer returned will be nullptr.
* If it is then it will point to GPU memory, and should not be dereferenced on the CPU side.
*
* @param[in] attrHandle Handle to the attribute whose size is to be returned
* @param[in] contextObj Location of both sets of attribute data
* @param[in] whereGpuPtrs For array data, the location of the array pointer - either on the CPU or on the GPU
* @param[out] refToData Resulting pointer to the attribute data
* @param[out] refToSize Size of the data being pointed at
*/
void (CARB_ABI* getDataReferenceRGpuAt)(const ConstAttributeDataHandle attrHandle,
const GraphContextObj& contextObj,
omni::fabric::PtrToPtrKind whereGpuPtrs,
ConstRawPtr& refToData,
size_t& refToSize);
/**
* Get the location and total number of bytes occupied by the writable attribute data on the GPU.
*
* If the data is not currently valid on the GPU the pointer returned will be nullptr.
* If it is then it will point to GPU memory, and should not be dereferenced on the CPU side.
*
* @param[in] attrHandle Handle to the attribute whose size is to be returned
* @param[in] contextObj Location of both sets of attribute data
* @param[in] whereGpuPtrs For array data, the location of the array pointer - either on the CPU or on the GPU
* @param[out] refToData Resulting pointer to the attribute data
* @param[out] refToSize Size of the data being pointed at
*/
void (CARB_ABI* getDataReferenceWGpuAt)(AttributeDataHandle attrHandle,
const GraphContextObj& contextObj,
omni::fabric::PtrToPtrKind whereGpuPtrs,
RawPtr& refToData,
size_t& refToSize);
/**
* Perform a conversion between 2 data types
*
* The actual attribute data may have a different type than an associated attribute on a node,
* for example, if the upstream source of the data has a different type.
* This function can be used to perform the conversion from the actual attribute data,
* to the provided buffer of the type of the attribute
*
* @param[out] dstDataOut A pointer to the destination buffer to be filled with the result of the conversion
* @param[in] dstType The type the destination buffer
* @param[in] srcDataIn A pointer to the actual attribute data
* @param[in] srcType The type of the attribute data pointer
* @return True if a conversion exists and succeeded, False otherwise.
*/
bool(CARB_ABI* performConversion)(void* dstDataOut, Type dstType, void* srcDataIn, Type srcType);
/**
* Gets CPU pointers to the read-only CPU data of some number of attributes.
*
* Any invalid attributes will have null pointers. Array attributes have an extra level of indirection.
* For example, after requesting int attribute data, attrsOut will effectively be of type
* const int** upon returning, but after requesting int array attribute data, attrsOut will effectively be
* of type const int* const**.
*
* If the attribute data is not on the CPU at the time of this call, but is on the GPU,
* it will be copied to the CPU before returning.
*
* @param[out] attrsOut Array to be filled in with pointers to data of each attribute
* @param[in] contextObj The GraphContextObj containing the attribute data
* @param[in] attrHandles Array of attribute data handles whose data are being requested
* @param[in] attrCount Number of attributes whose data are being requested
*/
void (CARB_ABI* getDataR)(const void** attrsOut,
const GraphContextObj& contextObj,
const ConstAttributeDataHandle* attrHandles,
size_t attrCount);
/**
* In a vectorized context, retrieve the write handle to another instance from a given one
*
* @param[in] contextObj Location of attribute data
* @param[in] attrHandle The source handle to offset
* @param[in] offset An offset to apply to the provided handle. Can be negative.
* @return A handle to the instance located at the provided offset relative to the provided handle
*/
AttributeDataHandle(CARB_ABI* moveToAnotherInstanceW)(const GraphContextObj& contextObj,
AttributeDataHandle attrHandle,
int offset);
/**
* In a vectorized context, retrieve the read handle to another instance from a given one
*
* @param[in] contextObj Location of attribute data
* @param[in] attrHandle The source handle to offset
* @param[in] offset An offset to apply to the provided handle. Can be negative.
* @return A handle to the instance located at the provided offset relative to the provided handle
*/
ConstAttributeDataHandle(CARB_ABI* moveToAnotherInstanceR)(const GraphContextObj& contextObj,
ConstAttributeDataHandle attrHandle,
int offset);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IAttributeData, moveToAnotherInstanceR, 24)
} // namespace core
} // namespace graph
} // namespace omni
| 22,400 | C | 50.496552 | 114 | 0.670179 |
omniverse-code/kit/include/omni/graph/core/ogn/SimpleAttribute.h | // 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.
//
#pragma once
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/CppWrappers.h>
#include <omni/graph/core/ogn/TypeConversion.h>
#include <omni/graph/core/ogn/Types.h>
// =================================================================================================================
// This file contains simple interface classes which wrap data in the OGN database for easier use.
//
// SimpleInput Read-only wrapper for simple (POD and tuple) attribute values on CPU or GPU
// SimpleOutput Writable data wrapper for simple (POD and tuple) attribute values on CPU or GPU
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// ======================================================================
/**
* Wrapper template that handles POD input attribute values.
* Its unowned data points to the real data in the fabric. It provides
* a consistent interface to the data with a isValid() method and an operator(),
* as well as enforcing const-correctness with the values.
*
* Rather than split this into CPU and GPU versions some key methods are enabled by template based
* on the template parameter. This avoids duplication of the common code and reduces clutter.
*
* The data in this class is owned by the OGN generated code, this class only maintains pointers to those references.
* By doing this, those generated references can be updated from fabric and this class will automatically pick up
* the change, avoiding the need for synchronization code.
*/
template <typename DataType, eAttributeType AttributeType, eMemoryType MemoryType = kCpu>
struct SimpleAttribute
{
// Make const-ness aware at compile time so that this class be used in const and non-const contexts
static constexpr bool readOnly = (AttributeType == ogn::kOgnInput);
using data_t = DataType;
using handle_t = std::conditional_t<readOnly, ConstAttributeDataHandle, AttributeDataHandle>;
/**
* Set up the accessor for input attributes with simple data
*
* @param[in] offset: A reference to the instance offset currently pointed by owning database
* @param[in] role Attribute's role
*/
SimpleAttribute(size_t const& offset, AttributeRole role = AttributeRole::eNone) : m_role(role), m_offset(offset)
{
static_assert(readOnly == std::is_const<DataType>::value, "Cannot construct input attributes from non-const types");
}
/**
* Set up the accessor for input attributes with simple data where the data pointer is known at construction time
*
* @param[in] dataPtr Pointer to the attribute's data
* @param[in] role Attribute's role
*/
SimpleAttribute(size_t const& offset, data_t* dataPtr, AttributeRole role = AttributeRole::eNone)
: m_ptrToData{ dataPtr }, m_role(role), m_offset(offset)
{}
/**
* @param[in] idx: For vectorized compute, the instance index/offset relative to the one currently pointed by the owning database
* @return Reference to the raw fabric data extracted for use on the CPU
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type != kCuda>::type>
const DataType& cpu(size_t idx = 0) const
{
// Cast is necessary to generically handle both const and non-const internal data
m_ptrToData = (data_t*)getDataR<DataType>(*m_context, m_handle);
return m_ptrToData[m_offset+idx];
}
/**
* @param[in] idx: For vectorized compute, the instance index/offset relative to the one currently pointed by the owning database
* @return Pointer to the raw fabric data extracted for use on the GPU
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type != kCpu>::type>
const DataType* gpu(size_t idx = 0) const
{
// Cast is necessary to generically handle both const and non-const internal data
m_ptrToData = (data_t*)getDataRGPU<DataType>(*m_context, m_handle);
return m_ptrToData + m_offset + idx;
}
/**
* Set the context. This is done to allow the same wrapper class to be used for
* multiple evaluations in different contexts.
*
* @param[in] context The graph context to which the attribute belongs
*/
void setContext(const GraphContextObj& context)
{
m_context = &context;
if (m_ptrToData)
{
OptionalMethod::setContext<data_t>(*m_ptrToData, context);
}
}
/**
* Set the attribute handle. This is done to allow the same wrapper class to be used for
* multiple evaluations in different contexts.
*
* @param[in] handle Handle to the attribute to which the attribute belongs
*/
void setHandle(handle_t handle)
{
m_handle = handle;
}
/**
* @return Role of the managed attribute
*/
AttributeRole role() const
{
return m_role;
}
/**
* @return True if the underlying attribute data is valid for accessing
*/
template <eMemoryType Type = MemoryType>
bool isValid() const
{
return m_handle.isValid();
}
protected:
mutable data_t* m_ptrToData{ nullptr }; //!< Cached pointer to fabric data
AttributeRole m_role{ AttributeRole::eNone }; //!< Role interpretation for the attribute this struct manages
const GraphContextObj* m_context{ nullptr }; //!< ABI OmniGraph object, for JIT access to data
handle_t m_handle{ handle_t::invalidValue() }; //!< Handle to this attribute's data, for JIT access to data
mutable Type m_originalDataType{ BaseDataType::eUnknown }; //!< The actual type of the underlying data in fabric
//!< (used for auto conversion)
size_t const& m_offset; //!< An offset (in terms of object count) to apply to the pointer to access the object
};
// ======================================================================
/**
* Wrapper template that handles POD input attribute values.
*/
template <typename DataType, eMemoryType MemoryType = kCpu>
struct SimpleInput : public SimpleAttribute<std::add_const_t<DataType>, kOgnInput, MemoryType>
{
using parent_t = SimpleAttribute<DataType, kOgnInput, MemoryType>;
using data_t = typename parent_t::data_t;
using handle_t = typename parent_t::handle_t;
/**
* Set up the accessor for input attributes with simple data
*
* @param[in] offset: A reference to the instance offset currently pointed by owning database
* @param[in] role: Attribute's role
*/
SimpleInput(size_t const& offset, AttributeRole role = AttributeRole::eNone) : parent_t(offset, role)
{
}
/**
* @param[in] idx: For vectorized compute, the instance index/offset relative to the one currently pointed by the owning database
* @return Reference to the raw fabric data; only enabled when it lives on the CPU
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type == kCpu>::type>
const DataType& operator()(size_t idx = 0) const
{
auto& data = this->m_ptrToData == nullptr ? this->template cpu<Type>(idx) : this->m_ptrToData[idx+this->m_offset];
if (this->m_originalDataType.baseType == BaseDataType::eUnknown)
{
if (this->m_context)
this->m_originalDataType = this->m_context->iAttributeData->getType(*this->m_context, this->m_handle);
else
return data;
}
return *converter.convertValue(&data, this->m_originalDataType);
}
/**
* @param[in] idx: For vectorized compute, the instance index/offset relative to the one currently pointed by the owning database
* @return Pointer to the raw flatcache data (or the converted value); only enabled when it lives on the GPU
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type == kCuda>::type>
const DataType* operator()(size_t idx = 0) const
{
if (!this->m_context->iAttributeData->gpuValid(this->m_handle, *this->m_context))
this->m_ptrToData = nullptr;
return this->m_ptrToData == nullptr ? this->template gpu<Type>(idx) : (this->m_ptrToData + idx + this->m_offset);
}
/**
* @return True if the attribute can be accessed for vectorized compute
*/
bool const canVectorize() const
{
if (this->m_originalDataType.baseType == BaseDataType::eUnknown)
{
if (this->m_context)
this->m_originalDataType = this->m_context->iAttributeData->getType(*this->m_context, this->m_handle);
else
return false;
}
return converter.willConvert(this->m_originalDataType) == false;
}
/**
* @param[in] count: The number of instances available for vectorized access
* @return A span for the vectorized range if available. If not available, user must call operator() in a loop with incremented indices instead
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type == kCpu>::type>
gsl::span<DataType const> vectorized(size_t count) const
{
auto& data = this->m_ptrToData == nullptr ? this->template cpu<Type>() : this->m_ptrToData[this->m_offset];
if (this->m_originalDataType.baseType == BaseDataType::eUnknown)
{
if (this->m_context)
this->m_originalDataType = this->m_context->iAttributeData->getType(*this->m_context, this->m_handle);
else
return { &data, count };
}
if (converter.willConvert(this->m_originalDataType))
{
if (count != 1)
return {};
return { converter.convertValue(&data, this->m_originalDataType), count /*= 1*/ };
}
return { &data, count };
}
/**
* @param[in] index: For vectorized compute, the instance index/offset relative to the one currently pointed by the owning database
* @return A copy of the underlying ABI data handle for the attribute
*/
handle_t abi_handle(size_t index = 0) const
{
size_t const idx = this->m_offset + index;
return idx == 0 ? this->m_handle :
this->m_context->iAttributeData->moveToAnotherInstanceR(*this->m_context, this->m_handle, (int)idx);
}
private:
Converter<DataType> converter;
};
// ======================================================================
/**
* Wrapper template that handles POD output attribute values.
* It adds methods that provide write access to the underlying attribute data onto the functionality of SimpleInput.
*/
template <typename DataType, eAttributeType AttributeType, eMemoryType MemoryType = kCpu>
struct SimpleWritableAttribute : public SimpleAttribute<DataType, AttributeType, MemoryType>
{
using parent_t = SimpleAttribute<DataType, AttributeType, MemoryType>;
using data_t = typename parent_t::data_t;
using handle_t = typename parent_t::handle_t;
/**
* Set up the accessor for output attributes with simple data
*
* @param[in] offset: A reference to the instance offset currently pointed by owning database
* @param[in] Attribute's role
*/
SimpleWritableAttribute(size_t const& offset, AttributeRole role = AttributeRole::eNone) : parent_t(offset, role)
{
}
/**
* Query if the attribute can be accessed in a vectorized manner
* @return True: SimpleWritableAttribute can always vectorize
*/
bool const canVectorize() const
{
return true;
}
/**
* @return A span for the vectorized range
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type == kCpu>::type>
gsl::span<DataType> vectorized(size_t count)
{
if (this->m_ptrToData)
return { this->m_ptrToData + this->m_offset, count };
return { &cpu(), count };
}
/**
* @param[in] idx: For vectorized compute, the instance index/offset relative to the one currently pointed by the owning database
* @return Reference to the raw fabric data; only enabled when it lives on the CPU
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type == kCpu>::type>
DataType& operator()(size_t idx = 0) const
{
if (this->m_ptrToData)
return this->m_ptrToData[idx+this->m_offset];
return cpu(idx);
}
/**
* @param[in] idx: For vectorized compute, the instance index/offset relative to the one currently pointed by the owning database
* @return Pointer to the raw fabric data; only enabled when it lives on the GPU
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type == kCuda>::type>
DataType* operator()(size_t idx = 0) const
{
if (!this->m_context->iAttributeData->gpuValid(this->m_handle, *this->m_context))
this->m_ptrToData = nullptr;
if (this->m_ptrToData)
return this->m_ptrToData + idx + this->m_offset;
return gpu(idx);
}
/**
* @param[in] idx: For vectorized compute, the instance index/offset relative to the one currently pointed by the owning database
* @return Reference to the raw fabric data extracted for use on the CPU
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type != kCuda>::type>
DataType& cpu(size_t idx = 0) const
{
this->m_ptrToData = getDataW<DataType>(*this->m_context, this->m_handle);
return this->m_ptrToData[idx+this->m_offset];
}
/**
* @param[in] idx: For vectorized compute, the instance index/offset relative to the one currently pointed by the owning database
* @return Pointer to the raw fabric data extracted for use on the GPU
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type != kCpu>::type>
DataType* gpu(size_t idx = 0) const
{
this->m_ptrToData = getDataWGPU<DataType>(*this->m_context, this->m_handle);
return this->m_ptrToData + idx + this->m_offset;
}
/**
* @param[in] index: For vectorized compute, the instance index/offset relative to the one currently pointed by the owning database
* @return A copy of the underlying ABI data handle for the attribute
*/
handle_t abi_handle(size_t index = 0) const
{
size_t const idx = this->m_offset + index;
return idx == 0 ? this->m_handle :
this->m_context->iAttributeData->moveToAnotherInstanceW(*this->m_context, this->m_handle, (int)idx);
}
};
// Typedefs to differentiate state from output types
template <typename DataType, eMemoryType MemoryType = kCpu>
using SimpleOutput = SimpleWritableAttribute<DataType, kOgnOutput, MemoryType>;
template <typename DataType, eMemoryType MemoryType = kCpu>
using SimpleState = SimpleWritableAttribute<DataType, kOgnState, MemoryType>;
// Backward compatibility for previously existing data types
template <typename DataType>
using DualInput = SimpleInput<DataType, kAny>;
template <typename DataType>
using DualOutput = SimpleOutput<DataType, kAny>;
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 16,062 | C | 41.160105 | 147 | 0.651289 |
omniverse-code/kit/include/omni/graph/core/ogn/ArrayAttribute.h | // 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.
//
#pragma once
// =================================================================================================================
// This file contains simple interface classes which wrap data in the OGN database for easier use.
//
// ArrayInput Read-only wrapper for attributes that are arrays of values on CPU or GPU
// ArrayOutput Writable wrapper for attributes that are arrays of values on CPU or GPU
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/CppWrappers.h>
#include <omni/graph/core/ogn/Types.h>
#include <omni/graph/core/ogn/array.h>
#include <omni/graph/core/ogn/string.h>
#include <carb/InterfaceUtils.h>
#include <omni/fabric/Enums.h>
using omni::fabric::PtrToPtrKind;
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// ==============================================================================================================
/** House the shared data types that will be used by all array type accessors.
* Provides typedefs for data access with similar but subtly different types, e.g. const versus non-const
* Its unowned data points to the real data in the fabric. It provides a consistent interface to the data,
* with an isValid() method to use for compute validation and an appropriate operator() for data extraction.
*/
template <typename DataType, eAttributeType AttributeType, eMemoryType MemoryType = kCpu, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct ArrayAttribute
{
// Make const-ness aware at compile time so that this class be used in const and non-const contexts
static constexpr bool readOnly = (AttributeType == ogn::kOgnInput);
using this_t = ArrayAttribute<DataType, AttributeType, MemoryType, GpuPtrType>;
using data_t = DataType;
using array_t = std::conditional_t<
readOnly,
std::conditional_t<std::is_same<const char, DataType>::value, const_string, const_array<std::remove_const_t<DataType>>>,
std::conditional_t<std::is_same<char, DataType>::value, string, array<DataType>>
>;
using handle_t = std::conditional_t<readOnly, ConstAttributeDataHandle, AttributeDataHandle>;
/**
* Set up the accessor for attributes with array data
*
* @param[in] offset: A reference to the instance offset currently pointed by owning database
* @param[in] role Attribute's role
*/
ArrayAttribute(size_t const& offset, AttributeRole role = AttributeRole::eNone)
: m_role(role),
m_offset(offset),
m_currentOffset(offset)
{
static_assert(readOnly == std::is_const<DataType>::value, "Cannot construct input attributes from non-const types");
}
/**
* @return Role of the managed attribute
*/
AttributeRole role() const
{
return m_role;
}
/**
* Set the context. This is done to allow the same wrapper class to be used for
* multiple evaluations in different contexts.
*
* @param[in] context The graph context to which the array belongs
*/
void setContext(const GraphContextObj& context)
{
m_arrayData.setContext(context);
}
/**
* Set the attribute handle. This is done to allow the same wrapper class to be used for
* multiple evaluations in different contexts.
*
* @param[in] handle Handle to the attribute to which the array belongs
*/
void setHandle(handle_t handle)
{
m_arrayData.setHandle(handle);
}
/**
* Perform any action necessary before computation happens
*/
void preCompute()
{
//array data needs to be re-fetched every frame,
// as any external change of the value might have invalidated the pointers
m_arrayData.setDirty();
}
/**
* @param[in] index: For vectorized compute, the instance index relative to the one currently pointed by the owning database
* @return Reference to an array wrapper around the raw fabric CPU data
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type == kCpu>::type>
const array_t& operator()(size_t index = 0) const
{
return cpu(index);
}
/**
* @param[in] index: For vectorized compute, the instance index relative to the one currently pointed by the owning database
* @return Reference to an array wrapper around the raw fabric GPU data
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type == kCuda>::type>
const DataType** operator()(size_t index = 0) const
{
return gpu(index);
}
/**
* @param[in] index: For vectorized compute, the instance index relative to the one currently pointed by the owning database
* @return Reference to an array wrapper around the raw fabric CPU data
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type != kCuda>::type>
const array_t& cpu(size_t index = 0) const
{
adjustHandle(index);
return m_arrayData;
}
/**
* @param[in] index: For vectorized compute, the instance index relative to the one currently pointed by the owning database
* @return Reference to GPU data
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type != kCpu>::type>
auto gpu(size_t index = 0) const
{
return gpuGet(abi_handle(index), context());
}
/**
* Query the size of the underlying array
* @param[in] index: For vectorized compute, the instance index relative to the one currently pointed by the owning database
* @return the size of the underlying array
*/
const size_t size(size_t index = 0) const
{
size_t count = 0;
ConstAttributeDataHandle chdl = abi_handle(index);
context()->iAttributeData->getElementCount(&count, *context(), &chdl, 1);
return count;
}
/**
* @return True if the underlying attribute data is valid for accessing
*/
bool isValid() const
{
return m_arrayData.isValid();
}
/**
* @param[in] index: For vectorized compute, the instance index relative to the one currently pointed by the owning database
* @return A copy of the underlying ABI data handle for the attribute
*/
handle_t abi_handle(size_t index = 0) const
{
adjustHandle(index);
return m_arrayData.m_handle;
}
//@deprecated use abi_handle instead
[[deprecated("Calling handle() is deprecated. Use abi_handle() instead")]]
inline handle_t handle(size_t index = 0) const { return abi_handle(index);}
/**
* @return A copy of the underlying ABI data handle for the attribute
*/
GraphContextObj const* context() const
{
return m_arrayData.m_context;
}
/**
* @param[in] index: For vectorized compute, the instance index relative to the one currently pointed by the owning database
* @param[in] defValue: The default value to return if the array is empty
* @return the first item in the array, or the default value if the array is empty
*/
const DataType& firstOrDefault(size_t index = 0,
const DataType& defValue = DataType())
{
return size(index) ? (*this)(index)[0] : defValue;
}
protected:
/**
* Make the handle point to the proper instance, referred by its index, in a vectorized context
* @param[in] index: For vectorized compute, the instance index relative to the one currently pointed by the owning database
*/
void adjustHandle(size_t index) const
{
if (m_arrayData.isValid())
{
size_t wantedIndex = m_offset + index;
if (m_currentOffset != wantedIndex)
{
const_cast<array_t&>(m_arrayData).adjustHandle(wantedIndex - m_currentOffset);
m_currentOffset = wantedIndex;
}
}
}
protected:
//! Role interpretation for the attribute this struct manages
AttributeRole m_role{ AttributeRole::eNone };
//! Helper for accessing array data (last as it uses the others in initializing)
array_t m_arrayData;
//! Offset (in terms of objects) to apply to the fabric pointer to access the current object
size_t const& m_offset;
//! Offset at which the array data is currently configured
size_t mutable m_currentOffset{ 0 };
private:
//select appropriate ABI function based on handle type
static const DataType** gpuGet(ConstAttributeDataHandle const& hdl, GraphContextObj const* ctx)
{
const DataType** ptrToData{ nullptr };
ctx->iAttributeData->getDataRGpuAt((const void**)&ptrToData, *ctx, &hdl, 1, GpuPtrType);
return ptrToData;
}
static DataType** gpuGet(AttributeDataHandle const& hdl, GraphContextObj const* ctx)
{
DataType** ptrToData{ nullptr };
ctx->iAttributeData->getDataWGpuAt((void**)&ptrToData, *ctx, &hdl, 1, GpuPtrType);
return ptrToData;
}
};
// ======================================================================
/**
* Wrapper template that handles arrays of input attribute values.
*/
template <typename DataType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
using ArrayInput = ArrayAttribute<std::add_const_t<DataType>, kOgnInput, MemoryType, GpuPtrType>;
// ======================================================================
/**
* Handle arrays of output attribute values.
* It adds methods that provide write access to the underlying attribute data onto the functionality of ArrayInput.
*/
template <typename DataType, eAttributeType AttributeType, eMemoryType MemoryType = kCpu, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct ArrayWritableAttribute : public ArrayAttribute<DataType, AttributeType, MemoryType, GpuPtrType>
{
// Make const-ness aware at compile time so that this class be used in const and non-const contexts
static constexpr bool readOnly = (AttributeType == ogn::kOgnInput);
using parent_t = ArrayAttribute<DataType, AttributeType, MemoryType, GpuPtrType>;
using data_t = typename parent_t::data_t;
using handle_t = typename parent_t::handle_t;
using array_t = typename parent_t::array_t;
using this_t = ArrayWritableAttribute<DataType, AttributeType, MemoryType, GpuPtrType>;
/**
* Set up the accessor for output attributes with array data
*
* @param[in] offset: A reference to the instance offset currently pointed by owning database
* @param[in] role Attribute's role
*/
ArrayWritableAttribute(size_t const& offset, AttributeRole role = AttributeRole::eNone)
: parent_t(offset, role)
{
}
/**
* @param[in] offset: A reference to the instance offset currently pointed by owning database
* @return Reference to an array wrapper around the raw fabric CPU data
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type == kCpu>::type>
array_t& operator()(size_t index = 0)
{
//always go through fetch for array as it has special treatment in datamodel
return cpu(index);
}
/**
* @param[in] offset: A reference to the instance offset currently pointed by owning database
* @return Reference to an array wrapper around the raw fabric GPU data
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type == kCuda>::type>
data_t** operator()(size_t index = 0)
{
// always go through fetch for array as it has special treatment in datamodel
return gpu(index);
}
/**
* @param[in] offset: A reference to the instance offset currently pointed by owning database
* @return Reference to an array wrapper around the raw fabric CPU data
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type != kCuda>::type>
array_t& cpu(size_t index = 0)
{
auto const* const_this = this;
auto const& ret = const_this->parent_t::cpu(index);
return const_cast<array_t&>(ret);
}
/**
* @param[in] offset: A reference to the instance offset currently pointed by owning database
* @return Reference to an array wrapper around the raw fabric GPU data
*/
template <eMemoryType Type = MemoryType, typename = typename std::enable_if<Type != kCpu>::type>
data_t** gpu(size_t index = 0)
{
auto const* const_this = this;
auto ret = const_this->parent_t::gpu(index);
return const_cast<data_t**>(ret);
}
/**
* Resize of the underlying array
* @input newSize: the size to set for the underlying array
* @input index: the index of the instance to query in a vectorized context
*/
const void resize(size_t newSize, size_t index = 0)
{
auto& ctx = *this->context();
ctx.iAttributeData->setElementCount(ctx, this->abi_handle(index), newSize);
this->m_arrayData.setDirty();
}
/**
* Copy some array data to another through the ABI
* Will handle all the underlying optimizations (such as CoW or DataStealing)
*
* @return Reference to itself
*/
this_t& operator=(const ArrayInput<DataType, MemoryType, GpuPtrType>& toBeCopied) { return shallowCopy(toBeCopied);}
// @param[in] index: For vectorized compute, the instance index relative to the one currently pointed by the owning database
this_t& shallowCopy(const ArrayInput<DataType, MemoryType, GpuPtrType>& toBeCopied, size_t index = 0)
{
const IAttributeData& iData = *(this->context()->iAttributeData);
iData.copyData(this->abi_handle(index), *this->context(), toBeCopied.abi_handle(index));
this->m_arrayData.setDirty();
return *this;
}
};
// Convenience types for distinguishing output and state attributes
template <typename DataType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
using ArrayOutput = ArrayWritableAttribute<DataType, kOgnOutput, MemoryType, GpuPtrType>;
template <typename DataType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
using ArrayState = ArrayWritableAttribute<DataType, kOgnState, MemoryType, GpuPtrType>;
// Backward compatibility for previously existing data types
template <typename DataType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
using DualArrayInput = ArrayInput<DataType, kAny, GpuPtrType>;
template <typename DataType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
using DualArrayOutput = ArrayOutput<DataType, kAny, GpuPtrType>;
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 15,510 | C | 39.393229 | 145 | 0.663701 |
omniverse-code/kit/include/omni/graph/core/ogn/UsdTypes.h | // 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.
//
#pragma once
// This file contains helper utilities for managing casting and interpretation of the USD
// data types. Keeping this separate enables the ability for any other libraries to
// provide their own type casting, so that the OGN code can use native types only.
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/base/gf/half.h>
#include <pxr/base/gf/matrix2d.h>
#include <pxr/base/gf/matrix3d.h>
#include <pxr/base/gf/matrix4d.h>
#include <pxr/base/gf/vec2d.h>
#include <pxr/base/gf/vec2f.h>
#include <pxr/base/gf/vec2h.h>
#include <pxr/base/gf/vec2i.h>
#include <pxr/base/gf/vec3d.h>
#include <pxr/base/gf/vec3f.h>
#include <pxr/base/gf/vec3h.h>
#include <pxr/base/gf/vec3i.h>
#include <pxr/base/gf/vec4d.h>
#include <pxr/base/gf/vec4f.h>
#include <pxr/base/gf/vec4h.h>
#include <pxr/base/gf/vec4i.h>
#include <pxr/base/gf/quatd.h>
#include <pxr/base/gf/quatf.h>
#include <pxr/base/gf/quath.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/sdf/timeCode.h>
#include <pxr/base/tf/token.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/fabric/IPath.h>
#include <omni/fabric/IToken.h>
#include <omni/graph/core/Type.h>
#include <omni/graph/core/ogn/TypeTraits.h>
namespace omni
{
namespace graph
{
namespace core
{
namespace ogn
{
// GfHalf, TfToken, SdfPath, and SdfTimeCode are the base types that allow special casting
template <> struct attribute_base_t<pxr::GfHalf> { static constexpr BaseDataType value = BaseDataType::eHalf; };
template <> struct attribute_base_t<pxr::TfToken> { static constexpr BaseDataType value = BaseDataType::eToken; };
template <> struct attribute_base_t<pxr::SdfPath> { static constexpr BaseDataType value = BaseDataType::eRelationship; };
template <> struct attribute_base_t<pxr::SdfTimeCode> { static constexpr BaseDataType value = BaseDataType::eDouble; };
// All of the matrix and vector types have USD implementations
template <> struct attribute_base_t<pxr::GfMatrix2d> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<pxr::GfMatrix3d> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<pxr::GfMatrix4d> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<pxr::GfVec2d> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<pxr::GfVec2f> { static constexpr BaseDataType value = BaseDataType::eFloat; };
template <> struct attribute_base_t<pxr::GfVec2h> { static constexpr BaseDataType value = BaseDataType::eHalf; };
template <> struct attribute_base_t<pxr::GfVec2i> { static constexpr BaseDataType value = BaseDataType::eInt; };
template <> struct attribute_base_t<pxr::GfVec3d> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<pxr::GfVec3f> { static constexpr BaseDataType value = BaseDataType::eFloat; };
template <> struct attribute_base_t<pxr::GfVec3h> { static constexpr BaseDataType value = BaseDataType::eHalf; };
template <> struct attribute_base_t<pxr::GfVec3i> { static constexpr BaseDataType value = BaseDataType::eInt; };
template <> struct attribute_base_t<pxr::GfVec4d> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<pxr::GfVec4f> { static constexpr BaseDataType value = BaseDataType::eFloat; };
template <> struct attribute_base_t<pxr::GfVec4h> { static constexpr BaseDataType value = BaseDataType::eHalf; };
template <> struct attribute_base_t<pxr::GfVec4i> { static constexpr BaseDataType value = BaseDataType::eInt; };
template <> struct attribute_base_t<pxr::GfQuatd> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<pxr::GfQuatf> { static constexpr BaseDataType value = BaseDataType::eFloat; };
template <> struct attribute_base_t<pxr::GfQuath> { static constexpr BaseDataType value = BaseDataType::eHalf; };
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
// Simple type casting from the internal Fabric types to their equivalent USD types
inline const pxr::TfToken& asTfToken(const omni::fabric::TokenC& token)
{
return reinterpret_cast<const pxr::TfToken&>(token);
}
inline pxr::TfToken& asTfToken(omni::fabric::TokenC& token)
{
return reinterpret_cast<pxr::TfToken&>(token);
}
inline const pxr::SdfPath& asSdfPath(const omni::fabric::PathC& path)
{
return reinterpret_cast<const pxr::SdfPath&>(path);
}
inline pxr::SdfPath& asSdfPath(omni::fabric::PathC& path)
{
return reinterpret_cast<pxr::SdfPath&>(path);
}
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// ==============================================================================================================
// Specializing the attribute_type_traits gives more options for casting data extracted from RuntimeAttributes.
//
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfHalf>();
template <>
struct attribute_type_traits<pxr::GfHalf>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = true;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfHalf>::value;
using actual_t = pxr::GfHalf;
using element_t = pxr::GfHalf;
using data_t = pxr::GfHalf;
static constexpr int tupleCount = 1;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfHalf[]>();
template <>
struct attribute_type_traits<pxr::GfHalf[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = true;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfHalf>::value;
using actual_t = pxr::GfHalf[];
using element_t = pxr::GfHalf;
using data_t = pxr::GfHalf;
static constexpr int tupleCount = 1;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::TfToken>();
template <>
struct attribute_type_traits<pxr::TfToken>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = true;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::TfToken>::value;
using actual_t = pxr::TfToken;
using element_t = pxr::TfToken;
using data_t = pxr::TfToken;
static constexpr int tupleCount = 1;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::TfToken[]>();
template <>
struct attribute_type_traits<pxr::TfToken[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = true;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::TfToken>::value;
using actual_t = pxr::TfToken[];
using element_t = pxr::TfToken;
using data_t = pxr::TfToken;
static constexpr int tupleCount = 1;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::SdfPath>();
template <>
struct attribute_type_traits<pxr::SdfPath>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = true;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::SdfPath>::value;
using actual_t = pxr::SdfPath;
using element_t = pxr::SdfPath;
using data_t = pxr::SdfPath;
static constexpr int tupleCount = 1;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::SdfPath[]>();
template <>
struct attribute_type_traits<pxr::SdfPath[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = true;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::SdfPath>::value;
using actual_t = pxr::SdfPath[];
using element_t = pxr::SdfPath;
using data_t = pxr::SdfPath;
static constexpr int tupleCount = 1;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::SdfTimeCode>();
template <>
struct attribute_type_traits<pxr::SdfTimeCode>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = true;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::SdfTimeCode>::value;
using actual_t = pxr::SdfTimeCode;
using element_t = pxr::SdfTimeCode;
using data_t = pxr::SdfTimeCode;
static constexpr int tupleCount = 1;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::SdfTimeCode[]>();
template <>
struct attribute_type_traits<pxr::SdfTimeCode[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = true;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::SdfTimeCode>::value;
using actual_t = pxr::SdfTimeCode[];
using element_t = pxr::SdfTimeCode;
using data_t = pxr::SdfTimeCode;
static constexpr int tupleCount = 1;
};// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfMatrix2d>();
template <>
struct attribute_type_traits<pxr::GfMatrix2d>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfMatrix2d>::value;
using actual_t = pxr::GfMatrix2d;
using element_t = double;
using data_t = pxr::GfMatrix2d;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfMatrix2d[]>();
template <>
struct attribute_type_traits<pxr::GfMatrix2d[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfMatrix2d>::value;
using actual_t = pxr::GfMatrix2d[];
using element_t = double;
using data_t = pxr::GfMatrix2d;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfMatrix3d>();
template <>
struct attribute_type_traits<pxr::GfMatrix3d>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfMatrix3d>::value;
using actual_t = pxr::GfMatrix3d;
using element_t = double;
using data_t = pxr::GfMatrix3d;
static constexpr int tupleCount = 9;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfMatrix3d[]>();
template <>
struct attribute_type_traits<pxr::GfMatrix3d[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfMatrix3d>::value;
using actual_t = pxr::GfMatrix3d[];
using element_t = double;
using data_t = pxr::GfMatrix3d;
static constexpr int tupleCount = 9;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfMatrix4d>();
template <>
struct attribute_type_traits<pxr::GfMatrix4d>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfMatrix4d>::value;
using actual_t = pxr::GfMatrix4d;
using element_t = double;
using data_t = pxr::GfMatrix4d;
static constexpr int tupleCount = 16;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfMatrix4d[]>();
template <>
struct attribute_type_traits<pxr::GfMatrix4d[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfMatrix4d>::value;
using actual_t = pxr::GfMatrix4d[];
using element_t = double;
using data_t = pxr::GfMatrix4d;
static constexpr int tupleCount = 16;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec2d>();
template <>
struct attribute_type_traits<pxr::GfVec2d>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec2d>::value;
using actual_t = pxr::GfVec2d;
using element_t = double;
using data_t = pxr::GfVec2d;
static constexpr int tupleCount = 2;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec2d[]>();
template <>
struct attribute_type_traits<pxr::GfVec2d[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec2d>::value;
using actual_t = pxr::GfVec2d[];
using element_t = double;
using data_t = pxr::GfVec2d;
static constexpr int tupleCount = 2;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec2f>();
template <>
struct attribute_type_traits<pxr::GfVec2f>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec2f>::value;
using actual_t = pxr::GfVec2f;
using element_t = float;
using data_t = pxr::GfVec2f;
static constexpr int tupleCount = 2;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec2f[]>();
template <>
struct attribute_type_traits<pxr::GfVec2f[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec2f>::value;
using actual_t = pxr::GfVec2f[];
using element_t = float;
using data_t = pxr::GfVec2f;
static constexpr int tupleCount = 2;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec2h>();
template <>
struct attribute_type_traits<pxr::GfVec2h>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec2h>::value;
using actual_t = pxr::GfVec2h;
using element_t = pxr::GfHalf;
using data_t = pxr::GfVec2h;
static constexpr int tupleCount = 2;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec2h[]>();
template <>
struct attribute_type_traits<pxr::GfVec2h[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec2h>::value;
using actual_t = pxr::GfVec2h[];
using element_t = pxr::GfHalf;
using data_t = pxr::GfVec2h;
static constexpr int tupleCount = 2;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec2i>();
template <>
struct attribute_type_traits<pxr::GfVec2i>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec2i>::value;
using actual_t = pxr::GfVec2i;
using element_t = int;
using data_t = pxr::GfVec2i;
static constexpr int tupleCount = 2;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec2i[]>();
template <>
struct attribute_type_traits<pxr::GfVec2i[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec2i>::value;
using actual_t = pxr::GfVec2i[];
using element_t = int;
using data_t = pxr::GfVec2i;
static constexpr int tupleCount = 2;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec3d>();
template <>
struct attribute_type_traits<pxr::GfVec3d>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec3d>::value;
using actual_t = pxr::GfVec3d;
using element_t = double;
using data_t = pxr::GfVec3d;
static constexpr int tupleCount = 3;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec3d[]>();
template <>
struct attribute_type_traits<pxr::GfVec3d[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec3d>::value;
using actual_t = pxr::GfVec3d[];
using element_t = double;
using data_t = pxr::GfVec3d;
static constexpr int tupleCount = 3;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec3f>();
template <>
struct attribute_type_traits<pxr::GfVec3f>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec3f>::value;
using actual_t = pxr::GfVec3f;
using element_t = float;
using data_t = pxr::GfVec3f;
static constexpr int tupleCount = 3;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec3f[]>();
template <>
struct attribute_type_traits<pxr::GfVec3f[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec3f>::value;
using actual_t = pxr::GfVec3f[];
using element_t = float;
using data_t = pxr::GfVec3f;
static constexpr int tupleCount = 3;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec3h>();
template <>
struct attribute_type_traits<pxr::GfVec3h>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec3h>::value;
using actual_t = pxr::GfVec3h;
using element_t = pxr::GfHalf;
using data_t = pxr::GfVec3h;
static constexpr int tupleCount = 3;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec3h[]>();
template <>
struct attribute_type_traits<pxr::GfVec3h[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec3h>::value;
using actual_t = pxr::GfVec3h[];
using element_t = pxr::GfHalf;
using data_t = pxr::GfVec3h;
static constexpr int tupleCount = 3;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec3i>();
template <>
struct attribute_type_traits<pxr::GfVec3i>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec3i>::value;
using actual_t = pxr::GfVec3i;
using element_t = int;
using data_t = pxr::GfVec3i;
static constexpr int tupleCount = 3;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec3i[]>();
template <>
struct attribute_type_traits<pxr::GfVec3i[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec3i>::value;
using actual_t = pxr::GfVec3i[];
using element_t = int;
using data_t = pxr::GfVec3i;
static constexpr int tupleCount = 3;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec4d>();
template <>
struct attribute_type_traits<pxr::GfVec4d>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec4d>::value;
using actual_t = pxr::GfVec4d;
using element_t = double;
using data_t = pxr::GfVec4d;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec4d[]>();
template <>
struct attribute_type_traits<pxr::GfVec4d[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec4d>::value;
using actual_t = pxr::GfVec4d[];
using element_t = double;
using data_t = pxr::GfVec4d;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec4f>();
template <>
struct attribute_type_traits<pxr::GfVec4f>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec4f>::value;
using actual_t = pxr::GfVec4f;
using element_t = float;
using data_t = pxr::GfVec4f;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec4f[]>();
template <>
struct attribute_type_traits<pxr::GfVec4f[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec4f>::value;
using actual_t = pxr::GfVec4f[];
using element_t = float;
using data_t = pxr::GfVec4f;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec4h>();
template <>
struct attribute_type_traits<pxr::GfVec4h>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec4h>::value;
using actual_t = pxr::GfVec4h;
using element_t = pxr::GfHalf;
using data_t = pxr::GfVec4h;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec4h[]>();
template <>
struct attribute_type_traits<pxr::GfVec4h[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec4h>::value;
using actual_t = pxr::GfVec4h[];
using element_t = pxr::GfHalf;
using data_t = pxr::GfVec4h;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec4i>();
template <>
struct attribute_type_traits<pxr::GfVec4i>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec4i>::value;
using actual_t = pxr::GfVec4i;
using element_t = int;
using data_t = pxr::GfVec4i;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfVec4i[]>();
template <>
struct attribute_type_traits<pxr::GfVec4i[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfVec4i>::value;
using actual_t = pxr::GfVec4i[];
using element_t = int;
using data_t = pxr::GfVec4i;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfQuatd>();
template <>
struct attribute_type_traits<pxr::GfQuatd>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfQuatd>::value;
using actual_t = pxr::GfQuatd;
using element_t = double;
using data_t = pxr::GfQuatd;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfQuatd[]>();
template <>
struct attribute_type_traits<pxr::GfQuatd[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfQuatd>::value;
using actual_t = pxr::GfQuatd[];
using element_t = double;
using data_t = pxr::GfQuatd;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfQuatf>();
template <>
struct attribute_type_traits<pxr::GfQuatf>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfQuatf>::value;
using actual_t = pxr::GfQuatf;
using element_t = float;
using data_t = pxr::GfQuatf;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfQuatf[]>();
template <>
struct attribute_type_traits<pxr::GfQuatf[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfQuatf>::value;
using actual_t = pxr::GfQuatf[];
using element_t = float;
using data_t = pxr::GfQuatf;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfQuath>();
template <>
struct attribute_type_traits<pxr::GfQuath>
{
static constexpr bool isArray = false;
static constexpr int arrayDepth = 0;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = true;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = false;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfQuath>::value;
using actual_t = pxr::GfQuath;
using element_t = pxr::GfHalf;
using data_t = pxr::GfQuath;
static constexpr int tupleCount = 4;
};
// --------------------------------------------------------------------------------------------------------------
// auto value = runtimeAttribute.get<pxr::GfQuath[]>();
template <>
struct attribute_type_traits<pxr::GfQuath[]>
{
static constexpr bool isArray = true;
static constexpr int arrayDepth = 1;
static constexpr bool isSimpleType = false;
static constexpr bool isTupleType = false;
static constexpr bool isArrayType = false;
static constexpr bool isTupleArrayType = true;
static constexpr BaseDataType baseType = attribute_base_t<pxr::GfQuath>::value;
using actual_t = pxr::GfQuath[];
using element_t = pxr::GfHalf;
using data_t = pxr::GfQuath;
static constexpr int tupleCount = 4;
};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 37,767 | C | 42.712963 | 121 | 0.622792 |
omniverse-code/kit/include/omni/graph/core/ogn/OmniGraphNodeABI.h | // 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.
//
#pragma once
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/ComputeGraph.h>
#include <omni/graph/core/IGraphRegistry.h>
#include <omni/graph/core/TemplateUtils.h>
#include <omni/graph/core/ogn/Database.h>
#include <omni/graph/core/ogn/Types.h>
#include <omni/graph/core/unstable/INodeTypeForwarding.h>
#include <carb/profiler/Profile.h>
#include <carb/Framework.h>
#include <carb/logging/Log.h>
// =================================================================================================================
// This file contains simple interface classes which wrap data in the OGN database for easier use.
//
// OmniGraphNode_ABI Templated base class for generated OmniGraph node type definitions
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
// Uncomment the first line to see debug output, the second to see nothing
// #define OGN_DBG
#define OGN_DBG if (false)
#include <iostream>
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// ======================================================================
// Function declarations for registering and deregistering node types. Used so that a node type
// can either use the static functions available within the core or the ABI functions outside of it.
using OmniGraphNodeRegisterFn = void (*)(const omni::graph::core::INodeType&, int);
using OmniGraphNodeDeregisterFn = void (*)(const char*);
using OmniGraphNodeRegisterAliasFn = void (*)(const omni::graph::core::INodeType&, const char*);
// ======================================================================
// The has_XXX templated types are a set of metaprograms that use type dispatching in conjunction with the
// is_detected template to resolve to a std::true_type when a class contains a certain function and std::false_type
// when it does not. This allows compile time choice of two overloaded versions of each of the ABI functions from
// the call_XXX() version of them.
//
// See the description of is_detected in TemplateUtils.h for more details on how the template match occurs.
//
// The functions defined are the ones that are used as part of the interface to the OmniGraph Node C ABI.
// The formatting is consistent to make it easier to recognize and add new types:
// Line 1. The template declaration
// Line 2. The typename declaration, with the expected return type of the function
// Line 3. The function name declaration
// Lines 4+. Declarations for each of the function parameters
// clang-format off
// ----------------------------------------------------------------------------------------------------
// static void addInput(const NodeTypeObj&, const char*, const char*, bool, const void*, const size_t*)
template <class NodeTypeClass>
using has_addInput = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().addInput(
std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<const void*>(),
std::declval<const size_t*>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void addOutput(const NodeTypeObj&, const char*, const char*, bool, const void*, const size_t*)
template <class NodeTypeClass>
using has_addOutput = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().addOutput(
std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<const void*>(),
std::declval<const size_t*>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void addState(const NodeTypeObj&, const char*, const char*, bool, const void*, const size_t*)
template <class NodeTypeClass>
using has_addState = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().addState(
std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<const void*>(),
std::declval<const size_t*>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void addExtendedInput(const NodeTypeObj&, const char*, const char*, bool, ExtendedAttributeType)
template <class NodeTypeClass>
using has_addExtendedInput = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().addExtendedInput(
std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<ExtendedAttributeType>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void addExtendedOutput(const NodeTypeObj&, const char*, const char*, bool, ExtendedAttributeType)
template <class NodeTypeClass>
using has_addExtendedOutput = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().addExtendedOutput(
std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<ExtendedAttributeType>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void addExtendedState(const NodeTypeObj&, const char*, const char*, bool, ExtendedAttributeType)
template <class NodeTypeClass>
using has_addExtendedState = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().addExtendedState(
std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>(),
std::declval<bool>(),
std::declval<ExtendedAttributeType>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static bool hasState()
template <class NodeTypeClass>
using has_hasState = typename std::is_same<bool,
decltype(std::declval<const NodeTypeClass&>().hasState(
std::declval<const NodeTypeObj&>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void setHasState(bool)
template <class NodeTypeClass>
using has_setHasState = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().setHasState(
std::declval<const NodeTypeObj&>(),
std::declval<bool>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static bool compute(const GraphContextObj&, const NodeObj&)
template <class NodeTypeClass>
using has_computeABI = typename std::is_same<bool,
decltype(std::declval<const NodeTypeClass&>().compute(
std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static bool compute(NodeTypeDataClass&, size_t)
template <class NodeTypeClass, class NodeTypeDataClass>
using has_computeOGNT = typename std::is_same<bool,
decltype(std::declval<NodeTypeClass&>().compute(
std::declval<NodeTypeDataClass&>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static bool computeVectorized(const GraphContextObj&, const NodeObj&, size_t)
template <class NodeTypeClass>
using has_computeVectorizedABI = typename std::is_same<size_t,
decltype(std::declval<const NodeTypeClass&>().computeVectorized(
std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>(),
std::declval<size_t>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static bool computeVectorized(NodeTypeDataClass&, size_t)
template <class NodeTypeClass, class NodeTypeDataClass>
using has_computeVectorizedOGNT = typename std::is_same<size_t,
decltype(std::declval<NodeTypeClass&>().computeVectorized(
std::declval<NodeTypeDataClass&>(),
std::declval<size_t>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static const char* getNodeType()
template <class NodeTypeClass>
using has_getNodeType = typename std::is_same<const char*,
decltype(std::declval<const NodeTypeClass&>().getNodeType(
))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static const char* getTypeName(const NodeTypeObj&)
template <class NodeTypeClass>
using has_getTypeName = typename std::is_same<const char*,
decltype(std::declval<const NodeTypeClass&>().getTypeName(
std::declval<const NodeTypeObj&>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void getScheduleNodeCount()
template <class NodeTypeClass>
using has_getScheduleNodeCount = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().getScheduleNodeCount(
std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>(),
std::declval<const ScheduleNodeObj*>(),
std::declval<size_t>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void getScheduleNodes()
template <class NodeTypeClass>
using has_getScheduleNodes = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().getScheduleNodes(
std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>(),
std::declval<const ScheduleNodeObj*>(),
std::declval<size_t>(),
std::declval<ScheduleNodeObj*>(),
std::declval<size_t>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void initialize(const GraphContextObj&, const NodeObj&)
template <class NodeTypeClass>
using has_initialize = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().initialize(
std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void initializeType(const NodeTypeObj&)
template <class NodeTypeClass>
using has_initializeType = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().initializeType(
std::declval<const NodeTypeObj&>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void registerTasks()
template <class NodeTypeClass>
using has_registerTasks = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().registerTasks(
))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void release(const NodeObj&)
template <class NodeTypeClass>
using has_release = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().release(
std::declval<const NodeObj&>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static bool updateNodeVersion(const GraphContextObj&, const NodeObj&, int, int)
template <class NodeTypeClass>
using has_updateNodeVersion = typename std::is_same<bool,
decltype(std::declval<const NodeTypeClass&>().updateNodeVersion(
std::declval<const GraphContextObj&>(),
std::declval<const NodeObj&>(),
std::declval<int>(),
std::declval<int>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static size_t getAllMetadata(const NodeTypeObj&, const char**, const char**, size_t)
template <class NodeTypeClass>
using has_getAllMetadata = typename std::is_same<size_t,
decltype(std::declval<const NodeTypeClass&>().getAllMetadata(
std::declval<const NodeTypeObj&>(),
std::declval<const char**>(),
std::declval<const char**>(),
std::declval<size_t>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static const char* getMetadata(const NodeTypeObj&, const char*)
template <class NodeTypeClass>
using has_getMetadata = typename std::is_same<const char*,
decltype(std::declval<const NodeTypeClass&>().getMetadata(
std::declval<const NodeTypeObj&>(),
std::declval<const char*>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static size_t getMetadataCount(const NodeTypeObj&)
template <class NodeTypeClass>
using has_getMetadataCount = typename std::is_same<size_t,
decltype(std::declval<const NodeTypeClass&>().getMetadataCount(
std::declval<const NodeTypeObj&>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void setMetadata(const NodeTypeObj&, const char*, const char*)
template <class NodeTypeClass>
using has_setMetadata = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().setMetadata(
std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const char*>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
template <class NodeTypeClass>
using has_addSubNodeType = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().addSubNodeType(
std::declval<const NodeTypeObj&>(),
std::declval<const char*>(),
std::declval<const NodeTypeObj&>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
template <class NodeTypeClass>
using has_getSubNodeType = typename std::is_same<NodeTypeObj,
decltype(std::declval<const NodeTypeClass&>().getSubNodeType(
std::declval<const NodeTypeObj&>(),
std::declval<const char*>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
template <class NodeTypeClass>
using has_createNodeType = typename std::is_same<NodeTypeObj,
decltype(std::declval<const NodeTypeClass&>().createNodeType(
std::declval<const char*>(),
std::declval<int>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void onConnectionTypeResolve(const NodeTypeObj&)
template <class NodeTypeClass>
using has_onConnectionTypeResolve = typename std::is_same<void,
decltype(std::declval<const NodeTypeClass&>().onConnectionTypeResolve(
std::declval<const NodeObj&>()))>::value_type;
// ----------------------------------------------------------------------------------------------------
// static void inspect(const NodeTypeObj&, inspect::IInspector*)
template <class NodeTypeClass>
using has_inspect = typename std::is_same<bool,
decltype(std::declval<const NodeTypeClass&>().inspect(
std::declval<const NodeTypeObj&>(),
std::declval<inspect::IInspector*>()))>::value_type;
// clang-format on
// ==============================================================================================================
/**
* @brief Common base class for all node type implementation definitions, so that they can be in a common container
*/
class NodeTypeABI
{
protected:
// Remembering these values allow the node type to be registered and deregistered at will
const char* m_nodeTypeName{ nullptr }; //!< Unique name of the node type
int m_version{ 1 }; //!< Current version of the node type
const char* m_extensionName{ nullptr }; //!< Extension to which this node type belongs
/**
* @brief Construct a new NodeTypeABI object
*
* @param nodeTypeName Unique name of the node type
* @param version Version number of the node type
* @param extensionName Extension to which this node type belongs
*/
NodeTypeABI(const char* nodeTypeName, int version, const char* extensionName)
: m_nodeTypeName{nodeTypeName}
, m_version(version)
, m_extensionName(extensionName)
{}
public:
// --------------------------------------------------------------------------------------------------------------
/**
* @brief Populate an INodeType interface with the functions that implement this particular templated node type
*
* @param[out] nodeTypeInterface Interface to be populated
*/
virtual void populateNodeTypeInterface(INodeType& nodeTypeInterface) const = 0;
// --------------------------------------------------------------------------------------------------------------
/**
* @brief Register the node type encapsulated in this description.
*/
void registerNodeType(IGraphRegistry& iGraphRegistry)
{
INodeType iNodeType{};
populateNodeTypeInterface(iNodeType);
OGN_DBG std::cout << "DBG: ABI Registration of " << m_nodeTypeName << ", version " << m_version << " from " << m_extensionName << std::endl;
iGraphRegistry.registerNodeTypeInterface(iNodeType, m_version, sizeof(INodeType));
// One potential source of node type forwarding is if the node has overridden the getNodeType() method and
// supplied a different name than the one generated through the .ogn file. Add that one here.
if (iNodeType.getNodeType)
{
const char* overriddenTypeName = iNodeType.getNodeType();
if (strcmp(overriddenTypeName, m_nodeTypeName) != 0)
{
auto iNodeTypeForwarding = carb::getCachedInterface<ComputeGraph>()->getNodeTypeForwardingInterfacePtr();
if (iNodeTypeForwarding)
{
iNodeTypeForwarding->defineForward(m_nodeTypeName, m_version, overriddenTypeName, m_version, m_extensionName);
}
}
}
if (iNodeType.getScheduleNodeCount || iNodeType.getScheduleNodes)
{
CARB_LOG_WARN_ONCE(
"%s: getScheduleNodeCount() and getScheduleNodes() are deprecated, please remove", m_nodeTypeName);
}
}
// --------------------------------------------------------------------------------------------------------------
/**
* @brief Deregister the node type encapsulated in this description.
*/
void deregisterNodeType(IGraphRegistry& iGraphRegistry)
{
iGraphRegistry.unregisterNodeType(m_nodeTypeName);
}
};
// ======================================================================
/**
* @brief ABI proxy class for OGN generated nodes. It provides implementations for all of the
* INodeType ABI functions which will call the actual node's versions of those functions
* if the node defines them.
*
* This class uses a technique called "tag dispatching", which is a compile-time switch that decides
* which version of a method will be called. By defining overloaded methods taking either the
* `std::true_type` or `std::false_type` type as the first parameter, the version that is called can
* be decided at compile time by using a template that instantiates one of the two.
*
* In this template class the methods "X()" use tag dispatching to decide which two versions of the `call_X()`
* method to call. The version accepting `std::true_type` is called when an override of `X()` is detected and calls
* the override directly. The version accepting std::false_type performs the default version of `X()`.
*
* Each of the INode ABI functions is implemented with these three functions. Here is an annotated example
* of how this works for a fictional ABI method X that takes a single int argument:
*
* @code{.cpp}
* // By making this a template it can change types at compile-time
* template <class NodeTypeClass>
* // std::is_same will check to see if the named type matches the return type of the declared function
* using has_X = typename std::is_same<void,
* // decltype extracts the type of the declared entity
* // declval gives a compile-time stand-in for the declared entity
* // This statement says "get the type of the value returned by a NodeTypeClass function named X"
* decltype(std::declval<const NodeTypeClass&>().X(
* // This line adds the requirement that the function X takes an integer argument
* std::declval<int>())
* // The value_type trait gets the return type of the is_same template (std::true_type/std::false_type)
* )>::value_type;
* // These are two overloads of the same method
* // Since the last parameters are incompatible only one can be chosen
* void call_X(int value, std::true_type) {}
* void call_X(int value, std::false_type) {}
* // This is the public method called from outside the class
* void X(int value) {
* // If NodeTypeClass::X exists then is_detected<> selects the std::true_type variation
* // for the first argument. Subsequent arguments are passed through from this method's arguments.
* call_X(is_detected<has_X, NodeTypeClass>(), value);
* }
* @endcode
*
* For a full description of the SFINAE technique in general and the tag dispatching implementation see
* https://www.bfilipek.com/2016/02/notes-on-c-sfinae.html#tag-dispatching
*
* The net result of this metaprogramming is that OmniGraphNode_ABI<MyNode, MyNodeDatabase> instantiates
* an ABI-compatible class that calls overrides in MyNode where available and the default where not. This
* is functionally equivalent to acquiring and extracting the Node ABI interface and calling the methods
* on it. MyNodeDatabase is automatically generated by the .ogn processor and MyNode is the class the node
* writer provides, giving them full control over the ABI implementation if they wish, and use of the
* default implementation and generated helper classes if not.
*
* @tparam NodeTypeClass Class the user has defined for implementing the custom parts of the node type interface
* @tparam NodeTypeDataClass Generated database class for @p NodeTypeClass
*/
template <typename NodeTypeClass, typename NodeTypeDataClass>
class OmniGraphNode_ABI : public NodeTypeABI
{
static void call_addInput(std::true_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr) noexcept
{
OGN_DBG std::cout << "DBG: Override(addInput " << name << ", " << typeName << ")" << std::endl;
NodeTypeClass::addInput(nodeType, name, typeName, required, defaultValuePtr, defaultElemCountPtr);
}
static void call_addInput(std::false_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr) noexcept
{
OGN_DBG std::cout << "DBG: Default(addInput " << name << ", " << typeName << ")" << std::endl;
return;
}
// ----------------------------------------------------------------------
static void call_addOutput(std::true_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr) noexcept
{
OGN_DBG std::cout << "DBG: Override(addOutput " << name << ", " << typeName << ")" << std::endl;
NodeTypeClass::addOutput(nodeType, name, typeName, required, defaultValuePtr, defaultElemCountPtr);
}
static void call_addOutput(std::false_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr) noexcept
{
OGN_DBG std::cout << "DBG: Default(addOutput " << name << ", " << typeName << ")" << std::endl;
return;
}
// ----------------------------------------------------------------------
static void call_addState(std::true_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr) noexcept
{
OGN_DBG std::cout << "DBG: Override(addState " << name << ", " << typeName << ")" << std::endl;
NodeTypeClass::addState(nodeType, name, typeName, required, defaultValuePtr, defaultElemCountPtr);
}
static void call_addState(std::false_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr) noexcept
{
OGN_DBG std::cout << "DBG: Default(addState " << name << ", " << typeName << ")" << std::endl;
return;
}
// ----------------------------------------------------------------------
static void call_addExtendedInput(std::true_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
ExtendedAttributeType extendedType) noexcept
{
OGN_DBG std::cout << "DBG: Override(addExtendedInput " << name << ", " << typeName << ")" << std::endl;
NodeTypeClass::addExtendedInput(nodeType, name, typeName, required, extendedType);
}
static void call_addExtendedInput(std::false_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
ExtendedAttributeType extendedType) noexcept
{
OGN_DBG std::cout << "DBG: Default(addExtendedInput " << name << ", " << typeName << ")" << std::endl;
return;
}
// ----------------------------------------------------------------------
static void call_addExtendedOutput(std::true_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
ExtendedAttributeType extendedType) noexcept
{
OGN_DBG std::cout << "DBG: Override(addExtendedOutput " << name << ", " << typeName << ")" << std::endl;
NodeTypeClass::addExtendedOutput(nodeType, name, typeName, required, extendedType);
}
static void call_addExtendedOutput(std::false_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
ExtendedAttributeType) noexcept
{
OGN_DBG std::cout << "DBG: Default(addExtendedOutput " << name << ", " << typeName << ")" << std::endl;
return;
}
// ----------------------------------------------------------------------
static void call_addExtendedState(std::true_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
ExtendedAttributeType extendedType) noexcept
{
OGN_DBG std::cout << "DBG: Override(addExtendedState " << name << ", " << typeName << ")" << std::endl;
NodeTypeClass::addExtendedState(nodeType, name, typeName, required, extendedType);
}
static void call_addExtendedState(std::false_type,
const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
ExtendedAttributeType extendedType) noexcept
{
OGN_DBG std::cout << "DBG: Default(addExtendedState " << name << ", " << typeName << ")" << std::endl;
return;
}
// ----------------------------------------------------------------------
static bool call_hasState(std::true_type, const NodeTypeObj& nodeType) noexcept
{
OGN_DBG std::cout << "DBG: Override(hasState)" << std::endl;
return NodeTypeClass::hasState(nodeType);
}
static bool call_hasState(std::false_type, const NodeTypeObj&) noexcept
{
OGN_DBG std::cout << "DBG: Default(hasState)" << std::endl;
return false;
}
// ----------------------------------------------------------------------
static void call_setHasState(std::true_type, const NodeTypeObj& nodeType, bool hasState) noexcept
{
OGN_DBG std::cout << "DBG: Override(setHasState)" << std::endl;
NodeTypeClass::setHasState(nodeType, hasState);
}
static void call_setHasState(std::false_type, const NodeTypeObj&, bool) noexcept
{
OGN_DBG std::cout << "DBG: Default(setHasState)" << std::endl;
}
// ----------------------------------------------------------------------
template<typename FUNC>
static bool call_computeCommonOGN(const GraphContextObj& context, const NodeObj& node, FUNC const& compute, size_t batchCount)
{
auto create = [](GraphContextObj const* contexts, NodeObj const* nodes, size_t count) -> ogn::OmniGraphDatabase*
{
return new NodeTypeDataClass(contexts, nodes, count);
};
NodeTypeDataClass* nodeDataPtr = reinterpret_cast<NodeTypeDataClass*>(node.iNode->getOgnDatabase(node, create));
if (nodeDataPtr == nullptr || nodeDataPtr->validate() == false)
return false;
//warn the node we're about to compute
node.iNode->increaseComputeCount(node, batchCount);
// Call compute
nodeDataPtr->preCompute();
bool result = compute(*nodeDataPtr);
return result;
}
// ----------------------------------------------------------------------
template <typename T>
using has_computeOGN = has_computeOGNT<T, NodeTypeDataClass>;
template <typename T>
using has_computeVectorizedOGN = has_computeVectorizedOGNT<T, NodeTypeDataClass>;
using regOGN = is_detected<has_computeOGN, NodeTypeClass>;
using regABI = is_detected<has_computeABI, NodeTypeClass>;
using vecOGN = is_detected<has_computeVectorizedOGN, NodeTypeClass>;
using vecABI = is_detected<has_computeVectorizedABI, NodeTypeClass>;
static_assert((regOGN() || regABI()) ^ (vecOGN() || vecABI()), "Implements 'compute' xor 'computeVectorized' (ie. not both)");
//===============
template <typename UNSED1, typename UNSED2, typename UNSED3>
//regOGN, regABI, vecOGN, vecABI
static bool call_compute(std::true_type, UNSED1, UNSED2, UNSED3,
const GraphContextObj& context, const NodeObj& node) noexcept
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "[Compute][OGN] %s", node.iNode->getPrimPath(node));
return call_computeCommonOGN(context, node, NodeTypeClass::compute, 1);
}
//===============
template <typename UNSED1, typename UNSED2>
// regOGN, regABI, vecOGN, vecABI
static bool call_compute( std::false_type, std::true_type, UNSED1, UNSED2,
const GraphContextObj& context, const NodeObj& node) noexcept
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "[Compute][ABI] %s", node.iNode->getPrimPath(node));
node.iNode->increaseComputeCount(node, 1);
return NodeTypeClass::compute(context, node);
}
//===============
template <typename UNSED1>
// regOGN, regABI, vecOGN, vecABI
static bool call_compute(std::false_type,std::false_type, std::true_type, UNSED1,
const GraphContextObj& context, const NodeObj& node) noexcept
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "[ComputeVectorized][OGN][x1] %s", node.iNode->getPrimPath(node));
auto adapter = [](NodeTypeDataClass& db) { return NodeTypeClass::computeVectorized(db, 1) != 0; };
return call_computeCommonOGN(context, node, adapter, 1);
}
//===============
// regOGN, regABI, vecOGN, vecABI
static bool call_compute(std::false_type,std::false_type, std::false_type, std::true_type,
const GraphContextObj& context, const NodeObj& node) noexcept
{
CARB_PROFILE_ZONE(
carb::profiler::kCaptureMaskDefault, "[ComputeVectorized][ABI][x1] %s", node.iNode->getPrimPath(node));
node.iNode->increaseComputeCount(node, 1);
return NodeTypeClass::computeVectorized(context, node, 1) != 0;
}
// ----------------------------------------------------------------------
//===============
template <typename UNSED1, typename UNSED2, typename UNSED3>
//regOGN, regABI, vecOGN, vecABI
static size_t call_computeVectorized( UNSED1, UNSED2, std::true_type, UNSED3,
const GraphContextObj& context, const NodeObj& node, size_t count) noexcept
{
// user has implemented the OGN version
size_t ret = 0;
auto adapter = [count, &ret, &node](NodeTypeDataClass& db)
{
db.resetToFirstInstance();
if (db.canVectorize()) // auto conversion for instance might prevent vectorization
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "[ComputeVectorized][OGN][x%d] %s", (int)count,
node.iNode->getPrimPath(node));
ret = NodeTypeClass::computeVectorized(db, count);
return true;
}
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "[ComputeVectorized][OGN][1 by 1][x%d] %s",
(int)count, node.iNode->getPrimPath(node));
auto remaining = count;
db.resetToFirstInstance();
while (remaining--)
{
if (NodeTypeClass::computeVectorized(db, 1) != 0)
++ret;
db.moveToNextInstance();
}
db.resetToFirstInstance();
return true;
};
call_computeCommonOGN(context, node, adapter, count);
return ret;
}
//===============
template <typename UNSED1, typename UNSED2>
//regOGN, regABI, vecOGN, vecABI
static size_t call_computeVectorized( UNSED1, UNSED2, std::false_type, std::true_type,
const GraphContextObj& context, const NodeObj& node, size_t count) noexcept
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "[ComputeVectorized][ABI][x%d] %s", (int)count,
node.iNode->getPrimPath(node));
// user has implemented the ABI version
node.iNode->increaseComputeCount(node, count);
return NodeTypeClass::computeVectorized(context, node, count);
}
//===============
template <typename UNSED1>
//regOGN, regABI, vecOGN, vecABI
static size_t call_computeVectorized( std::true_type, UNSED1, std::false_type, std::false_type,
const GraphContextObj& context, const NodeObj& node, size_t count) noexcept
{
// user has implemented the OGN version
size_t ret = 0;
auto adapter = [count, &ret, &node](NodeTypeDataClass& db)
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "[Compute][OGN][1 by 1][x%d] %s", (int)count,
node.iNode->getPrimPath(node));
auto remaining = count;
db.resetToFirstInstance();
while (remaining--)
{
if (NodeTypeClass::compute(db))
ret++;
db.moveToNextInstance();
}
db.resetToFirstInstance();
return true;
};
call_computeCommonOGN(context, node, adapter, count);
return ret;
}
//===============
//regOGN, regABI, vecOGN, vecABI
static size_t call_computeVectorized(std::false_type, std::true_type, std::false_type, std::false_type,
const GraphContextObj& context, const NodeObj& node, size_t count) noexcept
{
//unreachable
CARB_LOG_FATAL("reaching abnormal code path in OmniGraphNodeABI");
return 0;
}
// ----------------------------------------------------------------------
static const char* call_getNodeType(std::true_type) noexcept
{
OGN_DBG std::cout << "DBG: Override(getNodeType)" << std::endl;
return NodeTypeClass::getNodeType();
}
static const char* call_getNodeType(std::false_type) noexcept
{
// The node type name must always be available, usually as the one the .ogn file specified
OGN_DBG std::cout << "DBG: Default(getNodeType)" << std::endl;
return sm_nodeTypeName;
}
// ----------------------------------------------------------------------
static const char* call_getTypeName(std::true_type, const NodeTypeObj& nodeType) noexcept
{
OGN_DBG std::cout << "DBG: Override(getTypeName)" << std::endl;
return NodeTypeClass::getTypeName(nodeType);
}
static const char* call_getTypeName(std::false_type, const NodeTypeObj& nodeType) noexcept
{
OGN_DBG std::cout << "DBG: Default(getTypeName)" << std::endl;
return sm_nodeTypeName;
}
// ----------------------------------------------------------------------
static size_t call_getScheduleNodeCount(std::true_type,
const GraphContextObj& context,
const NodeObj& node,
const ScheduleNodeObj* upstreamScheduleNodesBuf,
size_t upstreamBufferSize) noexcept
{
OGN_DBG std::cout << "DBG: Override(getScheduleNodeCount)" << std::endl;
return NodeTypeClass::getScheduleNodeCount(context, node, upstreamScheduleNodesBuf, upstreamBufferSize);
}
static size_t call_getScheduleNodeCount(std::false_type,
const GraphContextObj& context,
const NodeObj& node,
const ScheduleNodeObj* upstreamScheduleNodesBuf,
size_t upstreamBufferSize) noexcept
{
OGN_DBG std::cout << "DBG: Default(getScheduleNodeCount)" << std::endl;
return 0;
}
// ----------------------------------------------------------------------
static void call_getScheduleNodes(std::true_type,
const GraphContextObj& context,
const NodeObj& node,
const ScheduleNodeObj* upstreamScheduleNodesBuf,
size_t upstreamBufferSize,
ScheduleNodeObj* scheduleNodesBuf,
size_t bufferSize) noexcept
{
OGN_DBG std::cout << "DBG: Override(getScheduleNodes)" << std::endl;
NodeTypeClass::getScheduleNodes(
context, node, upstreamScheduleNodesBuf, upstreamBufferSize, scheduleNodesBuf, bufferSize);
}
static void call_getScheduleNodes(std::false_type,
const GraphContextObj& context,
const NodeObj& node,
const ScheduleNodeObj* upstreamScheduleNodesBuf,
size_t upstreamBufferSize,
ScheduleNodeObj* scheduleNodesBuf,
size_t bufferSize) noexcept
{
OGN_DBG std::cout << "DBG: Default(getScheduleNodes)" << std::endl;
return;
}
// ----------------------------------------------------------------------
// The generated database class may have overrides for the initialize() method if attribute metadata is present
// so this function has two layers of calls.
static void call_database_initialize(std::true_type, const GraphContextObj& context, const NodeObj& node) noexcept
{
OGN_DBG std::cout << "DBG: Database Override(initialize)" << std::endl;
NodeTypeDataClass::initialize(context, node);
}
static void call_database_initialize(std::false_type, const GraphContextObj& context, const NodeObj& node) noexcept
{
OGN_DBG std::cout << "DBG: Default(initialize)" << std::endl;
return;
}
static void call_initialize(std::true_type, const GraphContextObj& context, const NodeObj& node) noexcept
{
OGN_DBG std::cout << "DBG: Override(initialize)" << std::endl;
call_database_initialize(is_detected<has_initialize, NodeTypeDataClass>(), context, node);
NodeTypeClass::initialize(context, node);
}
static void call_initialize(std::false_type, const GraphContextObj& context, const NodeObj& node) noexcept
{
call_database_initialize(is_detected<has_initialize, NodeTypeDataClass>(), context, node);
return;
}
// ----------------------------------------------------------------------
static void call_initializeType(std::true_type, const NodeTypeObj& nodeType) noexcept
{
OGN_DBG std::cout << "DBG: Override(initializeType)" << std::endl;
// Rely on the database to handle the case of state attributes, this is just for internal state data
if (!std::is_empty<NodeTypeClass>::value)
{
nodeType.iNodeType->setHasState(nodeType, true);
}
NodeTypeDataClass::initializeType(nodeType);
NodeTypeClass::initializeType(nodeType);
}
static void call_initializeType(std::false_type, const NodeTypeObj& nodeType) noexcept
{
OGN_DBG std::cout << "DBG: Default(initializeType)" << std::endl;
// Rely on the database to handle the case of state attributes, this is just for internal state data
if (!std::is_empty<NodeTypeClass>::value)
{
nodeType.iNodeType->setHasState(nodeType, true);
}
NodeTypeDataClass::initializeType(nodeType);
}
// ----------------------------------------------------------------------
static void call_registerTasks(std::true_type) noexcept
{
OGN_DBG std::cout << "DBG: Override(registerTasks)" << std::endl;
NodeTypeClass::registerTasks();
}
static void call_registerTasks(std::false_type) noexcept
{
OGN_DBG std::cout << "DBG: Default(registerTasks)" << std::endl;
return;
}
// ----------------------------------------------------------------------
static void call_release(std::true_type, const NodeObj& node) noexcept
{
OGN_DBG std::cout << "DBG: Override(release)" << std::endl;
NodeTypeClass::release(node);
}
static void call_release(std::false_type, const NodeObj& node) noexcept
{
OGN_DBG std::cout << "DBG: Default(release)" << std::endl;
return;
}
// ----------------------------------------------------------------------
static bool call_updateNodeVersion(
std::true_type, const GraphContextObj& context, const NodeObj& node, int oldVersion, int newVersion) noexcept
{
OGN_DBG std::cout << "DBG: Override(updateNodeVersion)" << std::endl;
return NodeTypeClass::updateNodeVersion(context, node, oldVersion, newVersion);
}
static bool call_updateNodeVersion(
std::false_type, const GraphContextObj& context, const NodeObj& node, int oldVersion, int newVersion) noexcept
{
OGN_DBG std::cout << "DBG: Default(updateNodeVersion)" << std::endl;
return true;
}
// ----------------------------------------------------------------------
static size_t call_getAllMetadata(
std::true_type, const NodeTypeObj& nodeType, const char** keyBuf, const char** valueBuf, size_t bufSize) noexcept
{
OGN_DBG std::cout << "DBG: Override(getAllMetadata)" << std::endl;
return NodeTypeClass::getAllMetadata(nodeType, keyBuf, valueBuf, bufSize);
}
static size_t call_getAllMetadata(
std::false_type, const NodeTypeObj& nodeType, const char** keyBuf, const char** valueBuf, size_t bufSize) noexcept
{
OGN_DBG std::cout << "DBG: Default(getAllMetadata)" << std::endl;
return 0;
}
// ----------------------------------------------------------------------
static const char* call_getMetadata(std::true_type, const NodeTypeObj& nodeType, const char* key) noexcept
{
OGN_DBG std::cout << "DBG: Override(getMetadata)" << std::endl;
return NodeTypeClass::getMetadata(nodeType, key);
}
static const char* call_getMetadata(std::false_type, const NodeTypeObj& nodeType, const char* key) noexcept
{
OGN_DBG std::cout << "DBG: Default(getMetadata)" << std::endl;
return nullptr;
}
// ----------------------------------------------------------------------
static size_t call_getMetadataCount(std::true_type, const NodeTypeObj& nodeType) noexcept
{
OGN_DBG std::cout << "DBG: Override(getMetadataCount)" << std::endl;
return NodeTypeClass::getMetadataCount(nodeType);
}
static size_t call_getMetadataCount(std::false_type, const NodeTypeObj& nodeType) noexcept
{
OGN_DBG std::cout << "DBG: Default(getMetadataCount)" << std::endl;
return 0;
}
// ----------------------------------------------------------------------
static void call_setMetadata(std::true_type, const NodeTypeObj& nodeType, const char* key, const char* value) noexcept
{
OGN_DBG std::cout << "DBG: Override(setMetadata)" << std::endl;
NodeTypeClass::setMetadata(nodeType, key, value);
}
static void call_setMetadata(std::false_type, const NodeTypeObj& nodeType, const char* key, const char* value) noexcept
{
OGN_DBG std::cout << "DBG: Default(setMetadata)" << std::endl;
}
// ----------------------------------------------------------------------
static void call_addSubNodeType(std::true_type,
const NodeTypeObj& nodeType,
const char* subNodeTypeName,
const NodeTypeObj& subNodeType) noexcept
{
OGN_DBG std::cout << "DBG: Override(addSubNodeType)" << std::endl;
NodeTypeClass::addSubNodeType(nodeType, subNodeTypeName, subNodeType);
}
static void call_addSubNodeType(std::false_type,
const NodeTypeObj& nodeType,
const char* subNodeTypeName,
const NodeTypeObj& subNodeType) noexcept
{
OGN_DBG std::cout << "DBG: Default(addSubNodeType)" << std::endl;
}
// ----------------------------------------------------------------------
static NodeTypeObj call_getSubNodeType(std::true_type, const NodeTypeObj& nodeType, const char* subNodeTypeName) noexcept
{
OGN_DBG std::cout << "DBG: Override(getSubNodeType)" << std::endl;
return NodeTypeClass::getSubNodeType(nodeType, subNodeTypeName);
}
static NodeTypeObj call_getSubNodeType(std::false_type, const NodeTypeObj& nodeType, const char* subNodeTypeName) noexcept
{
OGN_DBG std::cout << "DBG: Default(getSubNodeType)" << std::endl;
return NodeTypeObj();
}
// ----------------------------------------------------------------------
static NodeTypeObj call_createNodeType(std::true_type, const char* nodeTypeName, int version) noexcept
{
OGN_DBG std::cout << "DBG: Override(createNodeType)" << std::endl;
return NodeTypeClass::createNodeType(nodeTypeName, version);
}
static NodeTypeObj call_createNodeType(std::false_type, const char* nodeTypeName, int version) noexcept
{
OGN_DBG std::cout << "DBG: Default(createNodeType)" << std::endl;
return NodeTypeObj();
}
// ----------------------------------------------------------------------
static void call_database_onConnectionTypeResolve(std::true_type, const NodeObj& node) noexcept
{
OGN_DBG std::cout << "DBG: Database Override(onConnectionTypeResolve)" << std::endl;
NodeTypeDataClass::onConnectionTypeResolve(node);
}
static void call_database_onConnectionTypeResolve(std::false_type, const NodeObj& node) noexcept
{
OGN_DBG std::cout << "DBG: Database Default(onConnectionTypeResolve)" << std::endl;
}
static void call_onConnectionTypeResolve(std::true_type, const NodeObj& node) noexcept
{
OGN_DBG std::cout << "DBG: Override(onConnectionTypeResolve)" << std::endl;
NodeTypeClass::onConnectionTypeResolve(node);
call_database_onConnectionTypeResolve(
is_detected<has_onConnectionTypeResolve, NodeTypeDataClass>(), node);
}
static void call_onConnectionTypeResolve(std::false_type, const NodeObj& node) noexcept
{
OGN_DBG std::cout << "DBG: Default(onConnectionTypeResolve)" << std::endl;
call_database_onConnectionTypeResolve(
is_detected<has_onConnectionTypeResolve, NodeTypeDataClass>(), node);
}
// ----------------------------------------------------------------------
static bool call_inspect(
std::true_type, const NodeTypeObj& nodeType, inspect::IInspector* inspector) noexcept
{
OGN_DBG std::cout << "DBG: Override(inspect)" << std::endl;
return NodeTypeClass::inspect(nodeType, inspector);
}
static bool call_inspect(
std::false_type, const NodeTypeObj& nodeType, inspect::IInspector* inspector) noexcept
{
OGN_DBG std::cout << "DBG: Default(inspect)" << std::endl;
return false;
}
public:
// ----------------------------------------------------------------------
// These are the ABI implementations, which call the right version of the above call_DBG: functions
// based on whether the node class has custom implementations of the ABI functions or not.
/**
* Implementation of omni::graph::core::INodeType::addInput to use as part of a node type definition
*/
static void addInput(const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr) noexcept
{
return call_addInput(is_detected<has_addInput, NodeTypeClass>(), nodeType, name, typeName, required,
defaultValuePtr, defaultElemCountPtr);
}
/**
* Implementation of omni::graph::core::INodeType::addOutput to use as part of a node type definition
*/
static void addOutput(const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr) noexcept
{
return call_addOutput(is_detected<has_addOutput, NodeTypeClass>(), nodeType, name, typeName, required,
defaultValuePtr, defaultElemCountPtr);
}
/**
* Implementation of omni::graph::core::INodeType::addState to use as part of a node type definition
*/
static void addState(const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
const void* defaultValuePtr,
const size_t* defaultElemCountPtr) noexcept
{
return call_addState(is_detected<has_addState, NodeTypeClass>(), nodeType, name, typeName, required,
defaultValuePtr, defaultElemCountPtr);
}
/**
* Implementation of omni::graph::core::INodeType::addExtendedInput to use as part of a node type definition
*/
static void addExtendedInput(const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
ExtendedAttributeType extendedType) noexcept
{
return call_addExtendedInput(is_detected<has_addExtendedInput, NodeTypeClass>(), nodeType, name, typeName,
required, extendedType);
}
/**
* Implementation of omni::graph::core::INodeType::addExtendedOutput to use as part of a node type definition
*/
static void addExtendedOutput(const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
ExtendedAttributeType extendedType) noexcept
{
return call_addExtendedOutput(is_detected<has_addExtendedOutput, NodeTypeClass>(), nodeType, name, typeName,
required, extendedType);
}
/**
* Implementation of omni::graph::core::INodeType::addExtendedState to use as part of a node type definition
*/
static void addExtendedState(const NodeTypeObj& nodeType,
const char* name,
const char* typeName,
bool required,
ExtendedAttributeType extendedType) noexcept
{
return call_addExtendedState(is_detected<has_addExtendedState, NodeTypeClass>(), nodeType, name, typeName,
required, extendedType);
}
/**
* Implementation of omni::graph::core::INodeType::hasState to use as part of a node type definition
*/
static bool hasState(const NodeTypeObj& nodeType) noexcept
{
return call_hasState(is_detected<has_hasState, NodeTypeClass>(), nodeType);
}
/**
* Implementation of omni::graph::core::INodeType::setHasState to use as part of a node type definition
*/
static void setHasState(const NodeTypeObj& nodeType, bool hasState) noexcept
{
call_setHasState(is_detected<has_setHasState, NodeTypeClass>(), nodeType, hasState);
}
// If the compute ABI function is overridden the user loses all of the nice setup
// we've done with the data class, however we won't disallow it as there may be reasons
// for doing it that aren't currently apparent.
/**
* Implementation of omni::graph::core::INodeType::compute to use as part of a node type definition
*/
static bool compute(const GraphContextObj& context, const NodeObj& node) noexcept
{
return call_compute(regOGN(), regABI(), vecOGN(), vecABI(), context, node);
}
/**
* Implementation of omni::graph::core::INodeType::computeVectorized to use as part of a node type definition
*/
static size_t computeVectorized(const GraphContextObj& context, const NodeObj& node, size_t count) noexcept
{
return call_computeVectorized(regOGN(), regABI(), vecOGN(), vecABI(), context, node, count);
}
/**
* Implementation of omni::graph::core::INodeType::getNodeType to use as part of a node type definition
*/
static const char* getNodeType()
{
return call_getNodeType(is_detected<has_getNodeType, NodeTypeClass>());
}
/**
* Implementation of omni::graph::core::INodeType::getTypeName to use as part of a node type definition
*/
static const char* getTypeName(const NodeTypeObj& nodeType)
{
return call_getTypeName(is_detected<has_getTypeName, NodeTypeClass>(), nodeType);
}
/**
* Implementation of omni::graph::core::INodeType::getScheduleNodeCount to use as part of a node type definition
*/
static size_t getScheduleNodeCount(const GraphContextObj& context,
const NodeObj& node,
const ScheduleNodeObj* upstreamScheduleNodesBuf,
size_t upstreamBufferSize) noexcept
{
return call_getScheduleNodeCount(is_detected<has_getScheduleNodeCount, NodeTypeClass>(), context, node,
upstreamScheduleNodesBuf, upstreamBufferSize);
}
/**
* Implementation of omni::graph::core::INodeType::getScheduleNodes to use as part of a node type definition
*/
static void getScheduleNodes(const GraphContextObj& context,
const NodeObj& node,
const ScheduleNodeObj* upstreamScheduleNodesBuf,
size_t upstreamBufferSize,
ScheduleNodeObj* scheduleNodesBuf,
size_t bufferSize) noexcept
{
call_getScheduleNodes(is_detected<has_getScheduleNodes, NodeTypeClass>(), context, node,
upstreamScheduleNodesBuf, upstreamBufferSize, scheduleNodesBuf, bufferSize);
}
/**
* Implementation of omni::graph::core::INodeType::initialize to use as part of a node type definition
*/
static void initialize(const GraphContextObj& context, const NodeObj& node) noexcept
{
call_initialize(is_detected<has_initialize, NodeTypeClass>(), context, node);
}
/**
* Implementation of omni::graph::core::INodeType::initializeType to use as part of a node type definition
*/
static void initializeType(const NodeTypeObj& nodeType) noexcept
{
call_initializeType(is_detected<has_initializeType, NodeTypeClass>(), nodeType);
}
/**
* Implementation of omni::graph::core::INodeType::registerTasks to use as part of a node type definition
*/
static void registerTasks() noexcept
{
call_registerTasks(is_detected<has_registerTasks, NodeTypeClass>());
}
/**
* Implementation of omni::graph::core::INodeType::release to use as part of a node type definition
*/
static void release(const NodeObj& node) noexcept
{
call_release(is_detected<has_release, NodeTypeClass>(), node);
}
/**
* Implementation of omni::graph::core::INodeType::releaseInstace to use as part of a node type definition
*/
static void releaseInstance(const NodeObj& node, NameToken instanceID) noexcept
{
NodeTypeDataClass::release(node, instanceID);
}
/**
* Implementation of omni::graph::core::INodeType::destroyDB to use as part of a node type definition
*/
static void destroyDB(const NodeObj& node, ogn::OmniGraphDatabase* db)
{
delete static_cast<NodeTypeDataClass*>(db);
}
/**
* Implementation of omni::graph::core::INodeType::notifyTypeResolution to use as part of a node type definition
*/
static void notifyTypeResolution(AttributeObj const& attrib, ogn::OmniGraphDatabase* db)
{
static_cast<NodeTypeDataClass*>(db)->onTypeResolutionChanged(attrib);
}
/**
* Implementation of omni::graph::core::INodeType::notifyDynamicAttributeChanged to use as part of a node type definition
*/
static void notifyDynamicAttributeChanged(ogn::OmniGraphDatabase* db, AttributeObj const& attr, bool isAttributeCreated)
{
static_cast<NodeTypeDataClass*>(db)->onDynamicAttributesChanged(attr, isAttributeCreated);
}
/**
* Implementation of omni::graph::core::INodeType::udpateNodeVersion to use as part of a node type definition
*/
static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& node, int oldVersion, int newVersion) noexcept
{
return call_updateNodeVersion(
is_detected<has_updateNodeVersion, NodeTypeClass>(), context, node, oldVersion, newVersion);
}
/**
* Implementation of omni::graph::core::INodeType::getAllMetadata to use as part of a node type definition
*/
static size_t getAllMetadata(const NodeTypeObj& nodeType, const char** keyBuf, const char** valueBuf, size_t bufSize) noexcept
{
return call_getAllMetadata(is_detected<has_getAllMetadata, NodeTypeClass>(), nodeType, keyBuf, valueBuf, bufSize);
}
/**
* Implementation of omni::graph::core::INodeType::getMetadata to use as part of a node type definition
*/
static const char* getMetadata(const NodeTypeObj& nodeType, const char* key) noexcept
{
return call_getMetadata(is_detected<has_getMetadata, NodeTypeClass>(), nodeType, key);
}
/**
* Implementation of omni::graph::core::INodeType::getMetadataCount to use as part of a node type definition
*/
static size_t getMetadataCount(const NodeTypeObj& nodeType) noexcept
{
return call_getMetadataCount(is_detected<has_getMetadataCount, NodeTypeClass>(), nodeType);
}
/**
* Implementation of omni::graph::core::INodeType::setMetadata to use as part of a node type definition
*/
static void setMetadata(const NodeTypeObj& nodeType, const char* key, const char* value) noexcept
{
call_setMetadata(is_detected<has_setMetadata, NodeTypeClass>(), nodeType, key, value);
}
/**
* Implementation of omni::graph::core::INodeType::addSubNodeType to use as part of a node type definition
*/
static void addSubNodeType(const NodeTypeObj& nodeType, const char* subNodeTypeName, const NodeTypeObj& subNodeType)
{
call_addSubNodeType(is_detected<has_addSubNodeType, NodeTypeClass>(), nodeType, subNodeTypeName, subNodeType);
}
/**
* Implementation of omni::graph::core::INodeType::getSubNodeType to use as part of a node type definition
*/
static NodeTypeObj getSubNodeType(const NodeTypeObj& nodeType, const char* subNodeTypeName)
{
return call_getSubNodeType(is_detected<has_getSubNodeType, NodeTypeClass>(), nodeType, subNodeTypeName);
}
/**
* Implementation of omni::graph::core::INodeType::createNodeType to use as part of a node type definition
*/
static NodeTypeObj createNodeType(const char* nodeTypeName, int version)
{
return call_createNodeType(is_detected<has_createNodeType, NodeTypeClass>(), nodeTypeName, version);
}
/**
* Implementation of omni::graph::core::INodeType::onConnectionTypeResolve to use as part of a node type definition
*/
static void onConnectionTypeResolve(const NodeObj& node)
{
call_onConnectionTypeResolve(is_detected<has_onConnectionTypeResolve, NodeTypeClass>(), node);
}
/**
* Implementation of omni::graph::core::INodeType::inspect to use as part of a node type definition
*/
static bool inspect(const NodeTypeObj& nodeType, inspect::IInspector* inspector)
{
return call_inspect(is_detected<has_inspect, NodeTypeClass>(), nodeType, inspector);
}
public:
/**
* @brief Constructor with the basic information that is needed to identify a node type
*
* @param nodeTypeName Unique name of the node type
* @param nodeTypeVersion Version of the node type being defined
* @param nodeTypeExtension Extension owning the node type
*/
OmniGraphNode_ABI(const char* nodeTypeName,
int nodeTypeVersion,
const char* nodeTypeExtension) : NodeTypeABI(nodeTypeName, nodeTypeVersion, nodeTypeExtension)
{
sm_nodeTypeName = nodeTypeName;
}
/**
* @brief Populate an INodeType interface with the functions that implement this particular templated node type
*
* @param[out] nodeTypeInterface Interface to be populated
*/
void populateNodeTypeInterface(INodeType& nodeTypeInterface) const override
{
// Any functions required in order for the interface to work are left as nullptr when
// there is no implementation of them overridden by the node so that the defaults can be used.
nodeTypeInterface.addInput = is_detected<has_addInput, NodeTypeClass>::value ? addInput : nullptr;
nodeTypeInterface.addOutput = is_detected<has_addOutput, NodeTypeClass>::value ? addOutput : nullptr;
nodeTypeInterface.addState = is_detected<has_addState, NodeTypeClass>::value ? addState : nullptr;
nodeTypeInterface.addExtendedInput = is_detected<has_addExtendedInput, NodeTypeClass>::value ? addExtendedInput : nullptr;
nodeTypeInterface.addExtendedOutput = is_detected<has_addExtendedOutput, NodeTypeClass>::value ? addExtendedOutput : nullptr;
nodeTypeInterface.addExtendedState = is_detected<has_addExtendedState, NodeTypeClass>::value ? addExtendedState : nullptr;
nodeTypeInterface.hasState = is_detected<has_hasState, NodeTypeClass>::value ? hasState : nullptr;
nodeTypeInterface.setHasState = is_detected<has_setHasState, NodeTypeClass>::value ? setHasState : nullptr;
nodeTypeInterface.getNodeType = getNodeType;
nodeTypeInterface.getTypeName = getTypeName;
nodeTypeInterface.initialize = initialize;
nodeTypeInterface.initializeType = initializeType;
nodeTypeInterface.registerTasks = registerTasks;
nodeTypeInterface.release = release;
nodeTypeInterface.updateNodeVersion = updateNodeVersion;
nodeTypeInterface.getAllMetadata =
is_detected<has_getAllMetadata, NodeTypeClass>::value ? getAllMetadata : nullptr;
nodeTypeInterface.getMetadata = is_detected<has_getMetadata, NodeTypeClass>::value ? getMetadata : nullptr;
nodeTypeInterface.getMetadataCount =
is_detected<has_getMetadataCount, NodeTypeClass>::value ? getMetadataCount : nullptr;
nodeTypeInterface.setMetadata = is_detected<has_setMetadata, NodeTypeClass>::value ? setMetadata : nullptr;
nodeTypeInterface.addSubNodeType =
is_detected<has_addSubNodeType, NodeTypeClass>::value ? addSubNodeType : nullptr;
nodeTypeInterface.getScheduleNodeCount =
is_detected<has_getScheduleNodeCount, NodeTypeClass>::value ? getScheduleNodeCount : nullptr;
nodeTypeInterface.getScheduleNodes =
is_detected<has_getScheduleNodes, NodeTypeClass>::value ? getScheduleNodes : nullptr;
nodeTypeInterface.getSubNodeType =
is_detected<has_getSubNodeType, NodeTypeClass>::value ? getSubNodeType : nullptr;
nodeTypeInterface.createNodeType =
is_detected<has_createNodeType, NodeTypeClass>::value ? createNodeType : nullptr;
nodeTypeInterface.onConnectionTypeResolve = onConnectionTypeResolve;
nodeTypeInterface.inspect = is_detected<has_inspect, NodeTypeClass>::value ? inspect : nullptr;
nodeTypeInterface.compute = regOGN() || regABI() || vecOGN() || vecABI() ? compute : nullptr;
nodeTypeInterface.computeVectorized = regOGN() || vecOGN() || vecABI() ? computeVectorized : nullptr;
nodeTypeInterface.releaseInstance = releaseInstance;
nodeTypeInterface.destroyDB = destroyDB;
nodeTypeInterface.notifyTypeResolution = notifyTypeResolution;
nodeTypeInterface.notifyDynamicAttributeChanged = notifyDynamicAttributeChanged;
nodeTypeInterface.getCarbABIVersion = []() { return INodeType::getInterfaceDesc().version; };
}
static const char* sm_nodeTypeName; //!< Name of node type, to allow passing a static function to ABI
};
template <typename NodeTypeClass, typename NodeTypeDataClass>
const char* OmniGraphNode_ABI<NodeTypeClass, NodeTypeDataClass>::sm_nodeTypeName{ nullptr };
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 70,145 | C | 48.294448 | 148 | 0.584774 |
omniverse-code/kit/include/omni/graph/core/ogn/ComputeHelpersDynamicInputsDetails.h |
namespace Private
{
template <size_t TUPLE_SIZE, typename ComputeType, typename InputType>
inline bool validateInputsAndOutput(gsl::span<InputType const> const inputs,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu> result)
{
if (TUPLE_SIZE == 1)
{
if (result.type().arrayDepth == 0)
{
// handle single values
auto resultValue = result.template get<ComputeType>();
if (!TryComputeHelper<decltype(resultValue)>::testValid(resultValue))
return false;
for (auto const& input : inputs)
{
auto const inputValue = input.template get<ComputeType>();
if (!TryComputeHelper<decltype(inputValue)>::testValid(inputValue))
return false;
}
}
else
{
// handle arrays
auto resultValue = result.template get<ComputeType[]>();
if (!TryComputeHelper<decltype(resultValue)>::testValid(resultValue))
return false;
for (auto const& input : inputs)
{
if (RuntimeAttribHelper<TUPLE_SIZE, typename remove_const_ref<decltype(input)>::type>::isArray(input))
{
auto const inputValue = input.template get<ComputeType[]>();
if (!TryComputeHelper<decltype(inputValue)>::testValid(inputValue))
return false;
}
else
{
auto const inputValue = input.template get<ComputeType>();
if (!TryComputeHelper<decltype(inputValue)>::testValid(inputValue))
return false;
}
}
}
}
else
{
using ComputeTypeTuple = ComputeType[TUPLE_SIZE];
if (result.type().componentCount != TUPLE_SIZE)
return false;
if (result.type().arrayDepth == 0)
{
// handle tuple values
auto resultValue = result.get<ComputeTypeTuple>();
if (!TryComputeHelper<decltype(resultValue)>::testValid(resultValue))
return false;
for (auto const& input : inputs)
{
if (RuntimeAttribHelper<TUPLE_SIZE, typename remove_const_ref<decltype(input)>::type>::isTuple(input))
{
auto const inputValue = input.template get<ComputeTypeTuple>();
if (!TryComputeHelper<decltype(inputValue)>::testValid(inputValue))
return false;
}
else
{
auto const inputValue = input.template get<ComputeType>();
if (!TryComputeHelper<decltype(inputValue)>::testValid(inputValue))
return false;
}
}
}
else
{
// handle arrays of tuples
auto resultValue = result.get<ComputeTypeTuple[]>();
if (!TryComputeHelper<decltype(resultValue)>::testValid(resultValue))
return false;
for (auto const& input : inputs)
{
if (RuntimeAttribHelper<TUPLE_SIZE, typename remove_const_ref<decltype(input)>::type>::isArray(input))
{
if (RuntimeAttribHelper<TUPLE_SIZE, typename remove_const_ref<decltype(input)>::type>::isTuple(input))
{
auto const inputValue = input.template get<ComputeTypeTuple[]>();
if (!TryComputeHelper<decltype(inputValue)>::testValid(inputValue))
return false;
}
else
{
auto const inputValue = input.template get<ComputeType[]>();
if (!TryComputeHelper<decltype(inputValue)>::testValid(inputValue))
return false;
}
}
else
{
if (RuntimeAttribHelper<TUPLE_SIZE, typename remove_const_ref<decltype(input)>::type>::isTuple(input))
{
auto const inputValue = input.template get<ComputeTypeTuple>();
if (!TryComputeHelper<decltype(inputValue)>::testValid(inputValue))
return false;
}
else
{
auto const inputValue = input.template get<ComputeType>();
if (!TryComputeHelper<decltype(inputValue)>::testValid(inputValue))
return false;
}
}
}
}
}
return true;
}
template <typename ComputeType, typename InputType, typename Functor>
inline bool tryComputeInputsWithArrayBroadcasting(gsl::span<InputType const> const inputs,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu> result,
Functor functor,
size_t count)
{
if (!validateInputsAndOutput<1, ComputeType, InputType>(inputs, result))
return false;
if (result.type().arrayDepth == 0)
{
// the output is not an array
auto resultValue = result.get<ComputeType>();
using TResultValue = typename remove_const_ref<decltype(*resultValue)>::type;
auto inputIt = inputs.begin();
// initialize the result
{
auto const inputValue = inputIt->template get<ComputeType>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t instance = 0; instance < count; ++instance)
{
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, 0, 0, instance);
auto& resultData = ArrayHelper<1, TResultValue>::accessArg(*resultValue, 0, 0, instance);
resultData = inputData;
}
}
// accumulate the result by iterating over the remaining inputs
++inputIt;
for (; inputIt != inputs.end(); ++inputIt)
{
auto const inputValue = inputIt->template get<ComputeType>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t instance = 0; instance < count; ++instance)
{
functor(ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, 0, 0, instance),
ArrayHelper<1, TResultValue>::accessArg(*resultValue, 0, 0, instance));
}
}
return true;
}
else
{
// cache for the array data, to avoid having to get it from fabric multiple times
// (once for getting the size, a second time for computing the result)
std::vector<ArrayDataReadOnly<ComputeType[], ogn::kCpu>> arrayDataCache;
arrayDataCache.reserve(inputs.size());
// the output is an array of single values
// result.get<ComputeType[]>() returns a temporary value, so it has to be cached.
auto arrayObj = result.template get<ComputeType[]>();
auto& resultArray = *arrayObj;
using TResultValue = typename remove_const_ref<decltype(resultArray)>::type;
for (size_t instance = 0; instance < count; ++instance)
{
// find the output length
size_t len = 1;
for (const auto& input : inputs)
{
using TInput = typename remove_const_ref<decltype(input)>::type;
if (RuntimeAttribHelper<1, TInput>::isArray(input))
{
arrayDataCache.emplace_back(input.template get<ComputeType[]>());
auto const& array = *arrayDataCache.back();
auto s = ArrayHelper<1, decltype(array)>::getArgsLengthAndAdjustHandle(array, instance);
len = std::max(len, s);
}
}
if (instance)
resultArray.adjustHandle(1);
resultArray.resize(len);
auto arrayDataCacheIt = arrayDataCache.cbegin();
auto inputIt = inputs.begin();
using TInput = typename remove_const_ref<decltype(*inputIt)>::type;
if (RuntimeAttribHelper<1, TInput>::isArray(*inputIt))
{
const auto& inputValue = *arrayDataCacheIt++;
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t idx = 0; idx < len; ++idx)
{
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, idx, 0, instance);
auto& resultData = ArrayHelper<1, TResultValue>::accessArg(resultArray, idx, 0, instance);
resultData = inputData;
}
}
else
{
auto const inputValue = inputIt->template get<ComputeType>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, 0, 0, instance);
for (size_t idx = 0; idx < len; ++idx)
{
auto& resultData = ArrayHelper<1, TResultValue>::accessArg(resultArray, idx, 0, instance);
resultData = inputData;
}
}
++inputIt;
for (; inputIt != inputs.end(); ++inputIt)
{
using TInput = typename remove_const_ref<decltype(*inputIt)>::type;
if (RuntimeAttribHelper<1, TInput>::isArray(*inputIt))
{
auto const& inputValue = *arrayDataCacheIt++;
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t idx = 0; idx < len; ++idx)
{
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, idx, 0, instance);
auto& resultData = ArrayHelper<1, TResultValue>::accessArg(resultArray, idx, 0, instance);
functor(inputData, resultData);
}
}
else
{
auto const inputValue = inputIt->template get<ComputeType>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, 0, 0, instance);
for (size_t idx = 0; idx < len; ++idx)
{
auto& resultData = ArrayHelper<1, TResultValue>::accessArg(resultArray, idx, 0, instance);
functor(inputData, resultData);
}
}
}
}
return true;
}
return false;
}
template<size_t N, typename InputIterator>
inline bool isTuple(InputIterator it)
{
return N != 1 && it->type().componentCount == N;
}
template<typename InputIterator>
inline bool isArray(InputIterator it)
{
return it->type().arrayDepth != 0;
}
template <size_t N, typename ComputeType, typename InputType, typename Functor>
inline bool tryComputeInputsWithTupleBroadcasting(gsl::span<InputType const> const inputs,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu> result,
Functor functor,
size_t count)
{
if (!validateInputsAndOutput<N, ComputeType, InputType>(inputs, result))
return false;
using ComputeTypeTuple = ComputeType[N];
if (result.type().arrayDepth == 0)
{
// the output is not an array
auto resultValue = result.get<ComputeTypeTuple>();
using TResultValue = typename remove_const_ref<decltype(*resultValue)>::type;
auto inputIt = inputs.begin();
// initialize the result
using TInput = typename remove_const_ref<decltype(*inputIt)>::type;
if (RuntimeAttribHelper<N, TInput>::isTuple(*inputIt))
{
auto const inputValue = inputIt->template get<ComputeTypeTuple>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t instance = 0; instance < count; ++instance)
{
for (uint8_t t = 0; t < N; ++t)
{
auto const& inputData = ArrayHelper<N, TInputValue>::accessArgConst(*inputValue, 0, t, instance);
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(*resultValue, 0, t, instance);
resultData = inputData;
}
}
}
else
{
auto const inputValue = inputIt->template get<ComputeType>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t instance = 0; instance < count; ++instance)
{
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, 0, 0, instance);
for (uint8_t t = 0; t < N; ++t)
{
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(*resultValue, 0, t, instance);
resultData = inputData;
}
}
}
++inputIt;
for (; inputIt != inputs.end(); ++inputIt)
{
using TInput = typename remove_const_ref<decltype(*inputIt)>::type;
if (RuntimeAttribHelper<N, TInput>::isTuple(*inputIt))
{
auto const inputValue = inputIt->template get<ComputeTypeTuple>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t instance = 0; instance < count; ++instance)
{
for (uint8_t t = 0; t < N; ++t)
{
auto const& inputData = ArrayHelper<N, TInputValue>::accessArgConst(*inputValue, 0, t, instance);
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(*resultValue, 0, t, instance);
functor(inputData, resultData);
}
}
}
else
{
auto const& inputValue = inputIt->template get<ComputeType>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t instance = 0; instance < count; ++instance)
{
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, 0, 0, instance);
for (uint8_t t = 0; t < N; ++t)
{
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(*resultValue, 0, t, instance);
functor(inputData, resultData);
}
}
}
}
return true;
}
else // result.type().arrayDepth > 0
{
// cache for the array data, to avoid having to get it from fabric multiple times
// (once for getting the size, a second time for computing the result)
// Note: we need different caches for tuple and non tuple arrays
std::vector<ArrayDataReadOnly<ComputeType[], ogn::kCpu>> arrayDataCache;
arrayDataCache.reserve(inputs.size());
std::vector<TupleArrayDataReadOnly<ComputeTypeTuple[], ogn::kCpu>> tupleArrayDataCache;
tupleArrayDataCache.reserve(inputs.size());
// result.get<ComputeTypeTuple[]>() returns a temporary value, so it has to be cached.
auto arrayObj = result.template get<ComputeTypeTuple[]>();
auto& resultArray = *arrayObj;
using TResultValue = typename remove_const_ref<decltype(resultArray)>::type;
for (size_t instance = 0; instance < count; ++instance)
{
size_t len = 1;
for (auto const& input : inputs)
{
using TInput = typename remove_const_ref<decltype(input)>::type;
if (RuntimeAttribHelper<N, TInput>::isArray(input))
{
tupleArrayDataCache.emplace_back(input.template get<ComputeTypeTuple[]>());
auto const& array = *tupleArrayDataCache.back();
auto s = ArrayHelper<N, decltype(array)>::getArgsLengthAndAdjustHandle(array, instance);
len = std::max(len, s);
}
else if (RuntimeAttribHelper<1, TInput>::isArray(input))
{
arrayDataCache.emplace_back(input.template get<ComputeType[]>());
auto const& array = *arrayDataCache.back();
auto s = ArrayHelper<1, decltype(array)>::getArgsLengthAndAdjustHandle(array, instance);
len = std::max(len, s);
}
}
if (instance)
resultArray.adjustHandle(1);
resultArray.resize(len);
auto arrayDataCacheIt = arrayDataCache.cbegin();
auto tupleArrayDataCacheIt = tupleArrayDataCache.cbegin();
auto inputIt = inputs.begin();
if (!isArray(inputIt))
{
if (isTuple<N>(inputIt))
{
auto const inputValue = inputIt->template get<ComputeTypeTuple>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t idx = 0; idx < len; ++idx)
{
for (uint8_t t = 0; t < N; ++t)
{
auto const& inputData = ArrayHelper<N, TInputValue>::accessArgConst(*inputValue, 0, t, instance);
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(resultArray, idx, t, instance);
resultData = inputData;
}
}
}
else
{
auto const inputValue = inputIt->template get<ComputeType>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, 0, 0, instance);
for (size_t idx = 0; idx < len; ++idx)
{
for (uint8_t t = 0; t < N; ++t)
{
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(resultArray, idx, t, instance);
resultData = inputData;
}
}
}
}
else
{
if (isTuple<N>(inputIt))
{
auto const& inputValue = *tupleArrayDataCacheIt++;
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t idx = 0; idx < len; ++idx)
{
for (uint8_t t = 0; t < N; ++t)
{
auto const& inputData = ArrayHelper<N, TInputValue>::accessArgConst(*inputValue, idx, t, instance);
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(resultArray, idx, t, instance);
resultData = inputData;
}
}
}
else
{
const auto& inputValue = *arrayDataCacheIt++;
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t idx = 0; idx < len; ++idx)
{
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, idx, 0, instance);
for (uint8_t t = 0; t < N; ++t)
{
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(resultArray, idx, t, instance);
resultData = inputData;
}
}
}
}
++inputIt;
for (; inputIt != inputs.end(); ++inputIt)
{
if (!isArray(inputIt))
{
if (isTuple<N>(inputIt))
{
auto const inputValue = inputIt->template get<ComputeTypeTuple>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
for (size_t idx = 0; idx < len; ++idx)
{
for (uint8_t t = 0; t < N; ++t)
{
auto const& inputData = ArrayHelper<N, TInputValue>::accessArgConst(*inputValue, 0, t, instance);
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(resultArray, idx, t, instance);
functor(inputData, resultData);
}
}
}
else
{
auto const inputValue = inputIt->template get<ComputeType>();
using TInputValue = typename remove_const_ref<decltype(*inputValue)>::type;
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValue, 0, 0, instance);
for (size_t idx = 0; idx < len; ++idx)
{
for (uint8_t t = 0; t < N; ++t)
{
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(resultArray, idx, t, instance);
functor(inputData, resultData);
}
}
}
}
else
{
if (isTuple<N>(inputIt))
{
auto const& inputValueArray = *tupleArrayDataCacheIt++;
using TInputValue = typename remove_const_ref<decltype(*inputValueArray)>::type;
for (size_t idx = 0; idx < len; ++idx)
{
for (uint8_t t = 0; t < N; ++t)
{
auto const& inputData = ArrayHelper<N, TInputValue>::accessArgConst(*inputValueArray, idx, t, instance);
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(resultArray, idx, t, instance);
functor(inputData, resultData);
}
}
}
else
{
auto const& inputValueArray = *arrayDataCacheIt++;
using TInputValue = typename remove_const_ref<decltype(*inputValueArray)>::type;
for (size_t idx = 0; idx < len; ++idx)
{
auto const& inputData = ArrayHelper<1, TInputValue>::accessArgConst(*inputValueArray, idx, 0, instance);
for (uint8_t t = 0; t < N; ++t)
{
auto& resultData = ArrayHelper<N, TResultValue>::accessArg(resultArray, idx, t, instance);
functor(inputData, resultData);
}
}
}
}
}
}
return true;
}
return false;
}
}//namespace private
| 24,309 | C | 43.119782 | 136 | 0.495454 |
omniverse-code/kit/include/omni/graph/core/ogn/Types.h | // 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.
//
#pragma once
#include <omni/graph/core/Handle.h>
#include <omni/graph/core/TemplateUtils.h>
#include <omni/fabric/IPath.h>
#include <omni/fabric/IToken.h>
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// ======================================================================
/**
* Enumeration of the memory locations an attribute's data might have. The data location will determine which of
* the data accessors will be used, and what type of data they will return. (GPU data will always be returned
* as raw pointers since the CPU cannot access that memory.)
*
* This type will be used as a template parameter to adjust the behaviour of OGN wrapper classes.
*/
enum eMemoryType
{
kCpu, //!< The attribute's data is always on the CPU
kCuda, //!< The attribute's data is always on the GPU
kAny //!< The attribute's data location can be either, decided at runtime
};
// ======================================================================
/**
* Enumeration of an attribute's access type. In order to provide information to the scheduler about how
* fabric data will be accessed, one of these access types is associated with all generated attributes.
*
* This type will be used as a template parameter to adjust the behaviour of OGN wrapper classes.
*/
enum eAttributeType
{
kOgnInput,
kOgnOutput,
kOgnState
};
// ======================================================================
/**
* Severity level for logging messages.
*/
enum class Severity : uint8_t
{
eInfo = 0,
eWarning,
eError,
eCount
};
// ======================================================================
/**
* When templating methods by data type the template types must be unique. The implementation of
* NameToken in iComputeGraph defines it as a simple uint64_t, which is also a raw data type used by OGN.
* To allow different templates to be instantiated for these two data types, identical in implementation but
* vastly different in semantics, this wrapper can be used instead as a drop-in replacement for NameToken.
*
* Thus these two template instantiations will be determined to be unique by the compiler, but the data
* passed in will be identical, to be interpreted in the correct way by the function:
*
* template <typename DataType> void myData(DataType& value);
* myData(OgnToken&); // Receives an OgnToken, which is directly convertible to NameToken
* myData(uint64_t&); // Receives a raw uint64_t
*
* This type will be used as a template parameter to adjust the behaviour of OGN wrapper classes.
*/
using Token = omni::fabric::Token;
static_assert(::std::is_convertible<Token, NameToken>::value, "ogn::Token must be equivalent to NameToken");
using Path = omni::fabric::Path;
static_assert(::std::is_convertible<Path, TargetPath>::value, "ogn::Path must be equivalent to TargetPath");
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
// Declare this outside of the namespaces, relying on the uniqueness of the name to provide easy access
using OgnToken = omni::graph::core::ogn::Token;
using OgnPath = omni::graph::core::ogn::Path;
// Generated code is kept smaller by assuming this namespace is active. The alternative would be to explicitly
// reference all types and values used by the generated code, which would end up amounting to the same thing.
// Core types can be accessed directly (e.g. getDataW()) and OGN types use the shortened "ogn::string"
using namespace omni::graph::core;
| 3,952 | C | 39.336734 | 112 | 0.690283 |
omniverse-code/kit/include/omni/graph/core/ogn/array.h | // 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.
//
#pragma once
// =================================================================================================================
// This file contains simple interface classes which wrap data in the OGN database for easier use.
//
// ogn::const_array Read-only array of fabric data
// ogn::array Array of fabric data, with writing and resizing capabilities
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
#include <gsl/span>
#include <cstring>
#include <stdexcept>
#include <type_traits>
#include <omni/graph/core/Handle.h>
#include <omni/graph/core/Type.h>
#include <omni/graph/core/CudaUtils.h>
#include <omni/graph/core/iAttributeData.h>
using omni::fabric::PtrToPtrKind;
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// =================================================================================================================
/**
* std::span-like wrapper class for array attribute data in the Ogn Database.
*
* In attribute terms an array is a variable sized collection of data of a single type, not to be confused with
* the C++ notion of an array, which is a fixed sized collection of data of a single type.
*
* This wrapper operates by using the Fabric interface to interact with array data it has stored.
* The base array class provides common operations common to both const and non-const data.
*
* @tparam BaseDataType Type of data contained within the array
* @tparam HandleType Attribute handle used to access the underlying Fabric copy of the data
*/
template <typename BaseDataType, typename HandleType>
class base_array
{
//from regular attributes
template <typename, eAttributeType, eMemoryType, PtrToPtrKind>
friend struct ArrayAttribute;
//from runtime attributes
template <typename, bool, eMemoryType, PtrToPtrKind >
friend struct ArrayData;
public:
/** const version of the BaseDataType */
using ConstBaseDataType = const typename std::remove_const<BaseDataType>::type;
/** Type definition of this class */
using this_t = base_array<BaseDataType, HandleType>;
// Pass through the span iterator so that this class can iterate over it transparently
/** Iterator over the array contents */
using iterator = typename gsl::span<BaseDataType>::iterator;
/** Reverse iterator over the array contents */
using reverse_iterator = typename gsl::span<BaseDataType>::reverse_iterator;
/**
* Constructor
*/
base_array() = default;
/**
* Confirm that the data values are safe for accessing
*
* @return true if the context and attribute handle values are both valid
*/
bool isValid() const
{
return context() && (AttrKey)handle() != handle().invalidValue();
}
/**
* @return The number of elements in the currently managed array
*/
size_t size() const { return span().size();}
/**
* @return Is the currently managed array empty?
*/
bool empty() const { return span().empty(); }
/**
* @return Pointer to the raw data in the array (first element)
*/
ConstBaseDataType* data() const { return span().data();}
/**
* @return Iterator pointing to the beginning of the array
*/
const iterator begin() const { return span().begin(); }
/**
* @return Iterator pointing past the end of the array
*/
const iterator end() const { return span().end(); }
/**
* @return Iterator pointing to the end of the array
*/
const reverse_iterator rbegin() const { return span().rbegin(); }
/**
* @return Iterator pointing before the beginning of the array
*/
const reverse_iterator rend() const { return span().rend(); }
/**
* Access a specific element of the array. No bounds checking is performed.
*
* @param[in] index Element index into the array
* @return Reference to the index'th element of the array
*/
ConstBaseDataType& operator[](size_t index) const { return span()[index]; }
/**
* Access a specific element of the array with bounds checking.
*
* @param[in] index Element index into the array
* @return Reference to the index'th element of the array
* @exception std::out_of_range if there is no data for the given index
*/
ConstBaseDataType& at(size_t index) const
{
auto const& spanObj = span();
if (!spanObj.data() || (spanObj.size() <= index))
{
std::string rangeMessage("Attempt to access out of range index ");
rangeMessage += std::to_string(index);
throw std::out_of_range(rangeMessage);
}
return spanObj[index];
}
/**
* Access the underlying span that allows to access the array data
*
* @return A reference to the underlying span
*/
gsl::span<BaseDataType> const& span() const
{
if (m_dirty)
const_cast<this_t*>(this)->reset();
m_dirty = false;
return m_span;
}
/**
* @brief Access the context to which this array belongs
*
* @returns Pointer to the context to which this array belongs
*/
GraphContextObj const* context() const { return m_context;}
/**
* @brief Access the attribute handle used to access the array data in Fabric
*
* @returns Pointer to the attribute handle used to access the array data in Fabric
*/
HandleType const& handle() const { return m_handle;}
/**
* Flag the span data as not being up2Date
*
*/
void setDirty() const { m_dirty = true; }
/**
* In a vectorized context, move forward the current handle
*
* @param[in] idx The amount of instance(s) to offset the current handle
*/
void adjustHandle(size_t idx)
{
const IAttributeData& iData = *(context()->iAttributeData);
moveHdl(iData, idx, m_handle);
setDirty();
}
protected:
/**
* Reset the internal span to point to new data.
*
*/
void reset()
{
if (isValid())
{
const IAttributeData& iData = *(m_context->iAttributeData);
size_t count = 0;
ConstAttributeDataHandle chdl = m_handle;
iData.getElementCount(&count, *m_context, &chdl, 1);
BaseDataType** ptrToData = getData(iData, m_handle);
this->m_span = gsl::span<BaseDataType>(*ptrToData, count);
}
else
{
this->m_span = gsl::span<BaseDataType>();
}
}
/**
* @brief Get a pointer to the array data from a specific const data handle
*
* @param iData Interface class containing the accessor functions
* @param hdl Handle to the attribute data whose value is being retrieved
* @return BaseDataType** Pointer to the array of retrieved data
*/
BaseDataType** getData(const IAttributeData& iData, ConstAttributeDataHandle const& hdl)
{
BaseDataType** ptrToData = nullptr;
iData.getDataR((const void**)&ptrToData, *m_context, &hdl, 1);
return ptrToData;
}
/**
* @brief Get a pointer to the array data from a specific mutable data handle
*
* @param iData Interface class containing the accessor functions
* @param hdl Handle to the attribute data whose value is being retrieved
* @return BaseDataType** Pointer to the array of retrieved data
*/
BaseDataType** getData(const IAttributeData& iData, AttributeDataHandle const& hdl)
{
BaseDataType** ptrToData = nullptr;
iData.getDataW((void**)&ptrToData, *m_context, &hdl, 1);
return ptrToData;
}
/**
* Set the context. This is done to allow the same wrapper class to be used for
* multiple evaluations in different contexts.
*
* @param[in] context The graph context to which the array belongs
*/
void setContext(const GraphContextObj& context)
{
m_context = &context;
setDirty();
}
/**
* Set the attribute handle. This is done to allow the same wrapper class to be used for
* multiple evaluations in different contexts.
*
* @param[in] handle Handle to the attribute to which the array belongs
*/
void setHandle(HandleType handle)
{
m_handle = handle;
setDirty();
}
private:
/**
* helper that allows to make the proper call depending on the type of the handle
*/
void moveHdl(const IAttributeData& iData, size_t index, ConstAttributeDataHandle& hdl) const
{
hdl = iData.moveToAnotherInstanceR(*m_context, hdl, (int)index);
}
void moveHdl(const IAttributeData& iData, size_t index, AttributeDataHandle& hdl) const
{
hdl = iData.moveToAnotherInstanceW(*m_context, hdl, (int)index);
}
const GraphContextObj* m_context{ nullptr }; //!< The graph context to which the array belongs
HandleType m_handle{ HandleType::invalidValue() }; //!< Handle to the attribute data
bool mutable m_dirty { true }; //!< whether the span is uptodate or not
gsl::span<BaseDataType> m_span; //!< Iterable managed array data
};
// =================================================================================================================
/**
* std::vector-like wrapper class for constant array attribute data in the Ogn Database.
* It operates by using the Fabric interface to interact with array data it has stored.
* This const version of the array wrapper should be used for input attributes, whose data cannot be changed.
* (The naming is "array" for consistency with how attribute types are named, even though it doesn't
* behave like a std::array, whose content size is determined at compile time.)
*
* @tparam BaseDataType Type of data contained within the array
*/
template <typename BaseDataType>
class const_array : public base_array<const BaseDataType, ConstAttributeDataHandle>
{
public:
/**
* Constructor
*/
const_array() = default;
};
// =================================================================================================================
/**
* std::vector-like wrapper class for array attribute data in the Ogn Database.
* It operates by using the Fabric interface to interact with array data it has stored.
* This non-const version of the array wrapper should be used for output attributes, whose data will be changed.
* (The naming is "array" for consistency with how attribute types are named, even though it doesn't
* behave like a std::array, whose content size is determined at compile time.)
*
* @tparam BaseDataType Type of data contained within the array
*/
template <typename BaseDataType>
class array : public base_array<BaseDataType, AttributeDataHandle>
{
public:
/** The type of the parent class */
using parent_t = base_array<BaseDataType, AttributeDataHandle>;
// Make non-templated functions available to pass 1 of template resolution
// http://www.gotw.ca/gotw/087.htm
using parent_t::data;
using parent_t::size;
// Pass through the span iterator so that this class can iterate over it transparently
/** Iterator over the array contents */
using iterator = typename gsl::span<BaseDataType>::iterator;
/** Reverse iterator over the array contents */
using reverse_iterator = typename gsl::span<BaseDataType>::reverse_iterator;
/**
* Constructor
*/
array() = default;
/**
* Assignment operator: performs a shallow copy
*
* @param[in] rhs The array being copied in
* @return Reference to this
*/
array& operator=(array<BaseDataType> const& rhs)
{
return shallowCopy(reinterpret_cast<const_array<BaseDataType> const&>(rhs));
}
/**
* Assignment operator: performs a shallow copy of a const array of const data
*
* @param[in] rhs The array being copied in
* @return Reference to this
*/
array& operator=(const_array<const BaseDataType> const& rhs)
{
return shallowCopy(reinterpret_cast<const_array<BaseDataType> const&>(rhs));
}
/**
* Assignment operator: performs a shallow copy of a const array of non-const data
*
* @param[in] rhs The array being copied in
* @return Reference to this
*/
array& operator=(const_array<BaseDataType> const& rhs)
{
return shallowCopy(rhs);
}
/**
* Performs a shallow copy the provided object over this object
*
* This will create a reference for this object that points to the provided object
*
* @param[in] from The array being copied in
* @return Reference to this
*/
array& shallowCopy(const_array<BaseDataType> const& from)
{
this->context()->iAttributeData->copyData(this->handle(), *this->context(), from.handle());
this->setDirty();
return *this;
}
/**
* Overwrite this object data with data from the provided object
*
* This will create a duplicate of all array members and reset the references
*
* @param[in] rhs The array being copied in
* @return Reference to this
*/
array& deepCopy(parent_t const& rhs)
{
// Resize this array first so that it has the proper space to receive the new data
resize(rhs.size());
if (rhs.size() == 0)
{
// No work to do when the new array is empty
return *this;
}
// Get the raw arrays and walk them directly for the copy to minimize friction.
rawCopyFrom(rhs.data(), std::conditional_t<std::is_assignable<BaseDataType, std::add_const_t<BaseDataType>>::value,
std::true_type, std::false_type>());
return *this;
}
/**
* Set the size of the array data to a new value.
*
* This may or may not relocate memory. If anything is holding a raw pointer from contents()
* that pointer should be refreshed by calling contents() again when this method returns.
*
* @param[in] newCount New element count of the array.
*/
void resize(size_t newCount)
{
CUDA_SAFE_ASSERT(this->isValid());
const IAttributeData& iData = *(this->context()->iAttributeData);
iData.setElementCount(*this->context(), this->handle(), newCount);
this->setDirty();
}
/**
* @return Non-const pointer to the raw data in the array (first element)
*/
BaseDataType* data()
{
return const_cast<BaseDataType*>(this->parent_t::data());
}
/**
* Access a specific element of the array. No bounds checking is performed.
*
* @param[in] index Element index into the array
* @return Reference to the index'th element of the array
*/
BaseDataType& operator[](size_t index)
{
return const_cast<BaseDataType&>(this->parent_t::operator[](index));
}
/**
* Access a specific element of the array with bounds checking.
*
* @param[in] index Element index into the array
* @return Reference to the index'th element of the array
* @exception std::out_of_range if there is no data for the given index
*/
BaseDataType& at(size_t index)
{
return const_cast<BaseDataType&>(this->parent_t::at(index));
}
private:
/**
* Safe copy; one version for when the array members are assignable, the other as a fallback to do raw memcpy
*
* @param[in] srcArray The location of the raw data to be copied in (already vetted for size compatibility)
* @param[in] assignable Overload selected when the base data type can or cannot be assigned
*/
void rawCopyFrom(const BaseDataType* srcArray, std::true_type assignable)
{
auto dstArray = data();
for (size_t i = 0; i < size(); ++i)
{
dstArray[i] = srcArray[i];
}
}
void rawCopyFrom(const BaseDataType* srcArray, std::false_type assignable)
{
memcpy(data(), srcArray, sizeof(BaseDataType) * size());
}
};
/** Default trait indicating if the class is one of our array types
* @tparam T Class type to check for being an array
*/
template<class T>
struct is_array : std::false_type {};
/** Trait indicating that specific templated types are array types
* @tparam T Class type to check for being an array
* @tparam HandleType Attribute data handle type for the array
*/
template<class T, typename HandleType>
struct is_array<base_array<T, HandleType>> : std::true_type {};
/** Trait indicating that mutable templated types are array types
* @tparam T Class type to check for being an array
*/
template<class T>
struct is_array<array<T>> : std::true_type {};
/** Trait indicating that constant templated types are array types
* @tparam T Class type to check for being an array
*/
template<class T>
struct is_array<const_array<T>> : std::true_type {};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 17,758 | C | 34.027613 | 123 | 0.631208 |
omniverse-code/kit/include/omni/graph/core/ogn/RuntimeAttribute.h | // 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.
//
#pragma once
// =================================================================================================================
// This file contains simple interface classes which wrap data in the OGN database for easier use.
//
// RuntimeAttribute Wrapper providing access to attributes whose type is only known at runtime
// This includes attributes inside bundles and attributes with extended types
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
#ifdef THIS_IS_INCLUDED_IN_THE_DOCUMENTATION
// The information bracketed here with begin/end describes the interface that is recommended for use with attributes
// whose data type is decided at runtime. The documentation uses these markers to perform a literal include of this
// code into the docs so that it can be the single source of truth.
// Note that the interface described here is not the complete set of C++ functions available, merely the ones that make
// sense for the user to access when dealing with runtime attributes.
//
//
// begin-extended-attribute-interface-description
// A runtime attribute can either be an attribute defined as one of the extended types ("union" or "any") or an
// attribute that is a member of a bundle. As you might guess, the defining feature of such attributes is the fact
// that the type of data they store is not known until runtime. And further, that type can change from one evaluation
// to the next. For that reason the runtime attribute accessors have different methods of acquiring their data than
// regular attributes.
//
// The two ways of acquiring the accessor for a runtime attribute are directly, for extended types
const auto& anyType = db.inputs.anyTypeAttribute();
// and as a member, for bundled attributes
const auto memberAttribute = db.inputs.myBundle().attributeByName(db.tokens.memberName);
// Runtime attributes can be copied, which copies both the type and the data of the attribute (unlike regular
// attributes, which would just copy the data)
auto newAttribute = anyType;
// There is also another method that will just copy the data, though it is up to you to ensure that the data
// types of the two attributes are the same.
newAttribute.copyData(anyType);
// As with regular attributes you can check if their data is valid...
const bool anyIsValid = anyType.isValid();
// ...get the number of elements in the array, if they are an array type...
const size_t howManyAnysDoIHave = anyType.size();
// ...and drop down to the ABI to get a handle for direct ABI calls (although for runtime attributes the handle
// is AttributeDataHandle/ConstAttributeDataHandle, not AttributeHandle as it is for regular attributes since
// the ABI has different capabilities for them)
const auto& abiHandle = anyType.abi_handle();
// They also have a method to determine if the actual type of the attribute has been resolved. Until the type is
// resolved the attribute's data cannot be accessed
const bool isTheTypeKnown = anyType.resolved();
// For bundled attributes the name is not known until runtime either so a method to access that is provided,
// returning the hardcoded name for extended attributes
const memberName& = memberAttribute.name();
// And the resolved type information is also available. Checking for an unknown type is another way to determine
// if the attribute type has not yet been resolved.
const auto& anyAttributesType = anyType.type();
// Finally there are the data access methods. The primary one is a templated function through which you can access
// the attribute's data in its raw form. The value returned isn't the data itself, it is a thin wrapper around the
// data that has a few functions of its own.
//
// This is the function to call for the majority of attributes, whose memory space is fixed either to CPU or GPU.
// It returns an object that can be used to access information about the attribute's value, including its memory location.
const auto dataAsFloatObj = anyType.get<float>();
// The types allowed in the template are the set of all allowed attribute types, expressed as regular C++ types
// without the attribute roles. For example float, float[], float[3], float[][3], etc. In most cases trying to access
// the data with an unsupported type will result in a compile error (the exceptions being types that are aliases for
// a supported type, e.g. "using float3 = float[3]"). In fact, since the "NameToken" supported type is an alias for
// another supported type it must be retrieved with a special type set up for that purpose
const auto dataAsToken = anyType.get<OgnToken>();
// The wrapper has a boolean cast operator, which checks to see if the requested type matches the actual resolved
// data type of the attribute. This allows you to make a cascading check for types of attributes you are supporting
if (const auto dataAsFloatObj = anyType.get<float>())
{
processAsFloat(*dataAsFloatObj);
}
else if (const auto dataAsDoubleObj = anyType.get<double>())
{
processAsDouble(*dataAsDoubleObj);
}
// In addition to the simple boolean validity test, the wrapper returned will have a few different methods,
// depending on the template data type.
// The dereference operators return references to the actual underlying attribute data (on the CPU - if your
// attribute lives on the GPU you'll get a reference to a pointer to the underlying attribute data, which lives in
// the GPU memory space and cannot be dereferenced on the CPU). Note that the default memory location of a bundled
// attribute is whatever was specified for the bundle itself.
const auto dataAsFloatObj = anyType.get<float>();
float const& floatValueDeref = *dataAsFloatObj;
float const& floatValueFn = dataAsFloatObj();
float const* floatValuePtr = dataAsFloatObj.operator->();
// The same dereference operators work for tuple types as well
const auto dataAsFloat3Obj = anyType.get<float[3]();
float const (&float3ValueDeref)[3] = *dataAsFloat3Obj;
// The tuple values also give you access to the tuple count and element-wise access
float x = dataAsFloat3Obj[0];
assert( dataAsFloat3Obj.tupleSize() == 3);
// Array data type wrappers dereference to the same array wrappers you get from regular attributes
const auto dataAsFloatArrayObj = anyType.get<float[]>();
for (const auto& floatValue : *dataAsFloatArrayObj)
{ /* ... */ }
size_t arrayElements = dataAsFloatArrayObj->size();
// For GPU attributes, which do not have the ability to dereference their array memory location, the wrapper instead
// returns a raw pointer to the underlying GPU memory location of the array.
const auto gpuFloatArrayObj = anyType.get<float[]>();
float const ***ptrToRawGpuData = *gpuFloatArrayObj;
// When the node is configured to extract CUDA pointers on the CPU there is one fewer level of indirection for
// arrays as the pointer returned is on the CPU.
const auto gpuFloatArrayObj = anyType.get<float[]>();
float const ***ptrToGpuDataOnCpu = *gpuFloatArrayObj;
float const **ptrToRawGpuData = *ptrToGpuDataOnCpu;
// As with regular array attributes, before writing to elements of an output array attribute you must first resize
// it to have the desired number of elements.
auto outputFloatArrayObj = data.outputs.results().get<float[]>();
outputFloatArrayObj.resize( howManyDoINeed );
// For attributes whose memory space is determined at runtime, or when you want to access attribute data in a different
// memory space than they were originally defined, you can force the retrieved data to be either on the CPU or GPU.
const auto gpuVersionObj = anyType.getGpu<float>();
const auto cpuVersionObj = anyType.getCpu<float>();
// On rare occasions you may need to resolve the attribute's type at runtime, inside a node's compute() function. In
// those cases the runtime attribute data can get out of sync so you need to notify it that a change has been made.
AttributeObj out = db.abi_node().iNode->getAttributeByToken(db.abi_node(), outputs::anyOutput.m_token);
out.iAttribute->setResolvedType(out, someNewType);
anyOutput.reset(db.abi_context(), out.iAttribute->getAttributeDataHandle(out, kAccordingToContextIndex));
// end-extended-attribute-interface-description
//
#endif
#include <omni/graph/core/ogn/TypeConversion.h>
#include <omni/graph/core/ogn/Types.h>
#include <omni/graph/core/ogn/array.h>
#include <omni/graph/core/ogn/string.h>
#include <omni/fabric/Enums.h>
using omni::fabric::PtrToPtrKind;
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// ==============================================================================================================
// House the shared data types that will be used by all data type accessors.
// Not all types are used by all classes, this just provides a single point of type definitions.
template <typename CppType, bool readOnly, eMemoryType MemoryType, PtrToPtrKind GpuPtrType>
struct data_type_traits : attribute_type_traits<CppType>
{
using parent_t = attribute_type_traits<CppType>;
// Type that allows switching on memory type
using isCpu_t = std::integral_constant<bool, MemoryType == kCpu>;
// Template inheritance isn't smart enough to forward the types and constexprs so manually forward them here
static constexpr bool isArray = parent_t::isArray;
static constexpr uint8_t tupleCount = parent_t::tupleCount;
static constexpr uint8_t arrayDepth = parent_t::arrayDepth;
static constexpr BaseDataType baseType = parent_t::baseType;
using data_t = typename parent_t::data_t;
// The type of attribute handle used to call the ABI functions
using handle_t = std::conditional_t<readOnly, const ConstAttributeDataHandle, AttributeDataHandle>;
// The type that will be returned from individual element access (simple or tuple data)
using element_t = typename std::conditional_t<
readOnly,
typename parent_t::element_t const,
typename parent_t::element_t>;
// The types used for storage where the constness is hardcoded into the attribute type
using data_access_t = std::conditional_t<readOnly, data_t const, data_t>;
using array_t = std::conditional_t<
readOnly,
std::conditional_t<std::is_same<const char, data_access_t>::value, const_string, const_array<data_access_t>>,
std::conditional_t<std::is_same<char, data_access_t>::value, string, array<data_access_t>>>;
// const, non-const, and appropriate const pointers to the Fabric data
using data_ptr_t = std::conditional_t<isArray, data_t**, data_t*>;
using data_ptr_const_t = std::conditional_t<isArray, data_t const**, data_t const*>;
using data_ptr_access_t = std::conditional_t<readOnly, data_ptr_const_t, data_ptr_t>;
// CPU array data lives in the wrappers, GPU data is raw since it cannot be dereferenced
using array_data_t = std::conditional_t<MemoryType == kCpu, array_t, data_ptr_access_t>;
// ==============================================================================================================
// Simple test to see if the type of data in the template parameter is compatible with a specific Type()
static bool matchesType(const Type& attributeType)
{
return attributeType.baseType == baseType
&& attributeType.componentCount == tupleCount
&& attributeType.arrayDepth == arrayDepth;
}
// ==============================================================================================================
// Templated access to getting read-only and writable values, calling the correct ABI functions based on memory location
static data_ptr_const_t readOnlyData(const GraphContextObj& contextObj, const ConstAttributeDataHandle& attrHandle)
{
return _readOnlyData(contextObj, attrHandle, std::conditional_t<MemoryType == kCpu, std::false_type, std::true_type>());
}
static data_ptr_t writableData(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle)
{
return _writableData(contextObj, attrHandle, std::conditional_t<MemoryType == kCpu, std::false_type, std::true_type>());
}
// Calling the right one depending on the handle type
static data_ptr_const_t data(const GraphContextObj& contextObj, const ConstAttributeDataHandle& attrHandle)
{
return _readOnlyData(contextObj, attrHandle, std::conditional_t<MemoryType == kCpu, std::false_type, std::true_type>());
}
static data_ptr_t data(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle)
{
return _writableData(contextObj, attrHandle, std::conditional_t<MemoryType == kCpu, std::false_type, std::true_type>());
}
// ==============================================================================================================
// Retrieving a reference on existing data.
// If data is not located at the right place (gpu/cpu), returns nullptr
static void dataReference(const GraphContextObj& contextObj,
ConstAttributeDataHandle const& attrHandle,
ConstRawPtr& ref,
size_t& size)
{
_dataReference(contextObj, attrHandle, ref, size,
std::conditional_t<MemoryType == kCpu, std::false_type, std::true_type>(),
std::conditional_t<readOnly, std::true_type, std::false_type>());
}
static void dataReference(const GraphContextObj& contextObj,
AttributeDataHandle const& attrHandle,
RawPtr& ref,
size_t& size)
{
_dataReference(contextObj, attrHandle, ref, size,
std::conditional_t<MemoryType == kCpu, std::false_type, std::true_type>(),
std::conditional_t<readOnly, std::true_type, std::false_type>());
}
private:
// These methods could not use the getDataX<> templates due to an oddity in how const is handled in composed typedefs.
// It's slightly more efficient to build anyway, and since it goes through the ABI it's just as safe
static data_ptr_const_t _readOnlyData(const GraphContextObj& contextObj, ConstAttributeDataHandle const& attrHandle, std::true_type)
{
data_ptr_const_t out{ nullptr };
const void** outPtr = (const void**)(&out);
contextObj.iAttributeData->getDataRGpuAt(outPtr, contextObj, &attrHandle, 1, GpuPtrType);
return out;
}
static data_ptr_const_t _readOnlyData(const GraphContextObj& contextObj, ConstAttributeDataHandle const& attrHandle, std::false_type)
{
data_ptr_const_t out{ nullptr };
const void** outPtr = (const void**)(&out);
contextObj.iAttributeData->getDataR(outPtr, contextObj, &attrHandle, 1);
return out;
}
static data_ptr_t _writableData(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle, std::true_type)
{
data_ptr_t out{ nullptr };
void** outPtr = (void**)(&out);
contextObj.iAttributeData->getDataWGpuAt(outPtr, contextObj, &attrHandle, 1, GpuPtrType);
return out;
}
static data_ptr_t _writableData(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle, std::false_type)
{
data_ptr_t out{ nullptr };
void** outPtr = (void**)(&out);
contextObj.iAttributeData->getDataW(outPtr, contextObj, &attrHandle, 1);
return out;
}
static void _dataReference(const GraphContextObj& contextObj, ConstAttributeDataHandle const& attrHandle,
ConstRawPtr& ref, size_t& size, std::true_type isGpu, std::true_type isRO)
{
contextObj.iAttributeData->getDataReferenceRGpuAt(attrHandle, contextObj, GpuPtrType, ref, size);
}
static void _dataReference(const GraphContextObj& contextObj, ConstAttributeDataHandle const& attrHandle,
ConstRawPtr& ref, size_t& size, std::false_type isGpu, std::true_type isRO)
{
contextObj.iAttributeData->getDataReferenceR(attrHandle, contextObj, ref, size);
}
static void _dataReference(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle,
RawPtr& ref, size_t& size, std::true_type isGpu, std::false_type isRO)
{
contextObj.iAttributeData->getDataReferenceWGpuAt(attrHandle, contextObj, GpuPtrType, ref, size);
}
static void _dataReference(const GraphContextObj& contextObj, AttributeDataHandle const& attrHandle,
RawPtr& ref, size_t& size, std::false_type isGpu, std::false_type isRO)
{
contextObj.iAttributeData->getDataReferenceW(attrHandle, contextObj, ref, size);
}
};
// ==============================================================================================================
// Simple wrapper to access the actual value with potential conversion on the read one
template <typename CppType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct SimpleDataReadOnly
{
using data_traits = data_type_traits<CppType, true, MemoryType, GpuPtrType>;
using return_type = const typename data_traits::data_t;
typename data_traits::data_ptr_access_t m_value{nullptr};
Converter<typename data_traits::data_t> m_converter;
Type const& m_type;
explicit SimpleDataReadOnly(typename data_traits::data_access_t* value, Type const& type) : m_value{ value }, m_type{ type } {}
return_type& operator*() const { return *m_converter.convertValue(m_value, m_type); }
return_type* operator->() const { return m_converter.convertValue(m_value, m_type); }
gsl::span<return_type> vectorized(size_t count) const
{
if (m_converter.willConvert(m_type))
{
if (count != 1)
return gsl::span<return_type>{};
return gsl::span<return_type>{ m_converter.convertValue(m_value, m_type), 1 };
}
return gsl::span<return_type>{ m_value, count };
}
operator bool() const { return m_value; }
};
template <typename CppType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct SimpleDataWritable
{
using data_traits = data_type_traits<CppType, false, MemoryType, GpuPtrType>;
using return_type = typename data_traits::data_t;
typename data_traits::data_ptr_access_t m_value{ nullptr };
SimpleDataWritable(typename data_traits::data_access_t* m_value, Type const&) : m_value{m_value} {}
return_type& operator*() { return *this->m_value; }
return_type* operator->() { return this->m_value; }
gsl::span<return_type> vectorized(size_t count) const { return { m_value, count }; }
operator bool() const { return m_value; }
};
// ==============================================================================================================
// Tuple data behaves the same as simple data, with the addition of element accessors and a size function.
template <typename CppType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct TupleDataReadOnly : SimpleDataReadOnly<CppType, MemoryType, GpuPtrType>
{
using data_traits = data_type_traits<CppType, true, MemoryType, GpuPtrType>;
TupleDataReadOnly(typename data_traits::data_access_t* value, Type const& type) : SimpleDataReadOnly<CppType, MemoryType, GpuPtrType>{value, type} {}
// GPU data is passed as a pointer to the tuple so for now there is no need for elementwise access here
const typename data_traits::element_t& operator[](uint8_t index) const
{
static_assert(MemoryType == kCpu, "Cannot access individual tuple elements on GPU data");
CARB_ASSERT(index < this->tupleSize());
return (**this)[index];
}
uint8_t tupleSize() const { return data_traits::tupleCount; }
};
template <typename CppType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct TupleDataWritable : SimpleDataWritable<CppType, MemoryType, GpuPtrType>
{
using data_traits = data_type_traits<CppType, false, MemoryType, GpuPtrType>;
TupleDataWritable(typename data_traits::data_access_t* value, Type const& type) : SimpleDataWritable<CppType, MemoryType, GpuPtrType>{value, type} {}
// GPU data is passed as a pointer to the tuple so for now there is no need for elementwise access here
typename data_traits::element_t& operator[](uint8_t index)
{
static_assert(MemoryType == kCpu, "Cannot access individual tuple elements on GPU data");
CARB_ASSERT(index < this->tupleSize());
return (**this)[index];
}
uint8_t tupleSize() const { return data_traits::tupleCount; }
};
// ==============================================================================================================
//Default version, for CPU
template <typename CppType, bool readOnly, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct ArrayData
{
using data_traits = data_type_traits<CppType, readOnly, MemoryType, GpuPtrType>;
using return_type = typename data_traits::array_data_t;
using handle_type = typename data_traits::handle_t;
explicit ArrayData(const GraphContextObj& context, handle_type const* handle, bool isValid)
{
if (isValid)
{
m_arrayData.setContext(context);
m_arrayData.setHandle(*handle);
}
}
size_t size() const { return m_arrayData.isValid() ? m_arrayData.size() : 0; }
return_type& operator*() { return m_arrayData; }
return_type& operator()() { return m_arrayData; }
return_type* operator->() { return &m_arrayData; }
//const accessors
return_type const& operator*() const { return m_arrayData; }
return_type const& operator()() const { return m_arrayData; }
return_type const* operator->() const { return &m_arrayData; }
//Bool operator
operator bool() const { return m_arrayData.isValid(); }
//Invalidate
void invalidate() { m_arrayData.setDirty();}
GraphContextObj const* context() const { return m_arrayData.context(); }
handle_type const& handle() const { return m_arrayData.handle(); }
protected:
return_type m_arrayData;
};
// ==============================================================================================================
// Special version, for GPU
template <typename CppType, bool readOnly, PtrToPtrKind GpuPtrType>
struct ArrayData<CppType, readOnly, kCuda, GpuPtrType>
{
using data_traits = data_type_traits<CppType, readOnly, kCuda, GpuPtrType>;
using return_type = typename data_traits::array_data_t;
using handle_type = typename data_traits::handle_t;
using this_t = ArrayData<CppType, readOnly, kCuda, GpuPtrType>;
explicit ArrayData(const GraphContextObj& context, handle_type const* handle, bool isValid)
{
if (isValid)
{
m_ctx = &context;
m_hdl = handle;
}
else
{
m_ctx = nullptr;
m_hdl = nullptr;
}
}
size_t size() const
{
size_t count = 0;
ConstAttributeDataHandle hdl = *m_hdl;
m_ctx->iAttributeData->getElementCount(&count, *m_ctx, &hdl, 1);
return count;
}
//accessors
return_type deref()
{
using PtrType = typename std::conditional<readOnly, ConstRawPtr, RawPtr>::type;
return_type dataPtr{ nullptr };
size_t size = 0;
data_traits::dataReference(*m_ctx, *m_hdl, (PtrType&) dataPtr, size);
return size ? dataPtr : 0;
}
return_type operator*() { return data_traits::data(*this->m_ctx, *this->m_hdl); }
return_type operator()() { return data_traits::data(*this->m_ctx, *this->m_hdl); }
//const accessors
return_type const operator*() const { return const_cast<this_t*>(this)->operator*(); }
return_type const operator()() const { return const_cast<this_t*>(this)->operator()(); }
operator bool() const { return m_ctx && m_hdl; }
void invalidate() {}
GraphContextObj const* context() const { return m_ctx; }
handle_type const& handle() const { return *m_hdl; }
protected:
GraphContextObj const* m_ctx;
handle_type const* m_hdl;
};
template <typename CppType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct ArrayDataReadOnly : ArrayData<CppType, true, MemoryType, GpuPtrType>
{
ArrayDataReadOnly(const GraphContextObj& context, ConstAttributeDataHandle const* handle, bool isValid)
: ArrayData<CppType, true, MemoryType, GpuPtrType>{ context, handle, isValid }
{}
};
template <typename CppType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct ArrayDataWritable : ArrayData<CppType, false, MemoryType, GpuPtrType>
{
ArrayDataWritable(const GraphContextObj& context, AttributeDataHandle const* handle, bool isValid)
: ArrayData<CppType, false, MemoryType, GpuPtrType>{context, handle, isValid}
{}
void resize(size_t newCount)
{
auto const& ctx = *this->context();
const IAttributeData& iData = *(ctx.iAttributeData);
iData.setElementCount(ctx, this->handle(), newCount);
this->invalidate();
}
};
// ==============================================================================================================
template <typename CppType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct TupleArrayDataReadOnly : ArrayDataReadOnly<CppType, MemoryType, GpuPtrType>
{
using data_traits = data_type_traits<CppType, true, MemoryType, GpuPtrType>;
TupleArrayDataReadOnly(const GraphContextObj& context, ConstAttributeDataHandle const* handle, bool isValid)
: ArrayDataReadOnly<CppType, MemoryType, GpuPtrType>{context, handle, isValid} {}
// GPU data is passed as a pointer to the tuple so for now there is no need for element wise access here
const typename data_traits::data_t& operator[] (uint8_t index) const
{
static_assert(MemoryType == kCpu, "Cannot access individual tuple elements on GPU data");
CARB_ASSERT(index < this->tupleSize());
return this->m_arrayData[index];
}
uint8_t tupleSize() const { return data_traits::tupleCount; }
};
template <typename CppType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct TupleArrayDataWritable : ArrayDataWritable<CppType, MemoryType, GpuPtrType>
{
using data_traits = data_type_traits<CppType, false, MemoryType, GpuPtrType>;
TupleArrayDataWritable(const GraphContextObj& context, AttributeDataHandle const* handle, bool isValid)
: ArrayDataWritable<CppType, MemoryType, GpuPtrType>{context, handle, isValid} {}
// GPU data is passed as a pointer to the tuple so for now there is no need for element wise access here
typename data_traits::data_t& operator[](uint8_t index)
{
static_assert(MemoryType == kCpu, "Cannot access individual tuple elements on GPU data");
CARB_ASSERT(index < this->tupleSize());
return this->m_arrayData[index];
}
uint8_t tupleSize() const { return data_traits::tupleCount; }
};
// ======================================================================
/**
* Class responsible for managing the interaction with an attribute whose data type is determined at runtime.
* These attributes may or may not not have a corresponding node attribute object. Those within bundles are virtual
* and do not have a concrete attribute. Those with extended types, do.
*
* It wraps the attribute information in an interface with a more natural interaction than the raw ABI calls.
*/
template <eAttributeType AttributeType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
class RuntimeAttribute
{
public :
// Make const-ness aware at compile time so that this class be used in const and non-const contexts
static constexpr bool readOnly = (AttributeType == ogn::kOgnInput);
//! The handle types are not simply "X" and "const X" variations so the type has to be explicitly defined
//! for writable (output/state) and non-writable (input) attribute types.
using dataHandle_t = typename std::conditional_t<readOnly, ConstAttributeDataHandle, AttributeDataHandle>;
private:
//! Traits for generic access to the raw memory.
template <eMemoryType MT>
using raw_data_traits_mt = data_type_traits<uint8_t, readOnly, MT, GpuPtrType>;
using raw_data_traits = raw_data_traits_mt<MemoryType>;
template <typename CppType, eMemoryType AccessorMemoryType, PtrToPtrKind AccessorGpuPtrType = PtrToPtrKind::eNotApplicable>
using simpleData_t = std::conditional_t<
readOnly,
ogn::SimpleDataReadOnly<CppType, AccessorMemoryType, AccessorGpuPtrType>,
ogn::SimpleDataWritable<CppType, AccessorMemoryType, AccessorGpuPtrType>
>;
template <typename CppType, eMemoryType AccessorMemoryType, PtrToPtrKind AccessorGpuPtrType = PtrToPtrKind::eNotApplicable>
using tupleData_t = typename std::conditional_t<
readOnly,
ogn::TupleDataReadOnly<CppType, AccessorMemoryType, AccessorGpuPtrType>,
ogn::TupleDataWritable<CppType, AccessorMemoryType, AccessorGpuPtrType>
>;
template <typename CppType, eMemoryType AccessorMemoryType, PtrToPtrKind AccessorGpuPtrType = PtrToPtrKind::eNotApplicable>
using arrayData_t = typename std::conditional_t<
readOnly,
ogn::ArrayDataReadOnly<CppType, AccessorMemoryType, AccessorGpuPtrType>,
ogn::ArrayDataWritable<CppType, AccessorMemoryType, AccessorGpuPtrType>
>;
template <typename CppType, eMemoryType AccessorMemoryType, PtrToPtrKind AccessorGpuPtrType = PtrToPtrKind::eNotApplicable>
using tupleArrayData_t = typename std::conditional_t<
readOnly,
ogn::TupleArrayDataReadOnly<CppType, AccessorMemoryType, AccessorGpuPtrType>,
ogn::TupleArrayDataWritable<CppType, AccessorMemoryType, AccessorGpuPtrType>
>;
/**
* helper that allows to make the proper call depending on the type of the handle
*/
inline void _moveHdl(const IAttributeData& iData, size_t index, ConstAttributeDataHandle& hdl) const
{
hdl = iData.moveToAnotherInstanceR(m_context, hdl, (int)index);
}
inline void _moveHdl(const IAttributeData& iData, size_t index, AttributeDataHandle& hdl) const
{
hdl = iData.moveToAnotherInstanceW(m_context, hdl, (int)index);
}
/**
* helper that prefetch the data pointer for the attribute
*/
template <eMemoryType MT = MemoryType>
inline void _prefetch() const
{
if (MT != kAny)
m_cachedData = raw_data_traits_mt<MT>::data(m_context, m_handle);
}
GraphContextObj m_context{ 0 }; //!< Evaluation context for which this attribute is valid
NameToken m_name; //!< Name by which this attribute is accessed
Type m_type; //!< Type information for the actual attribute data
Type m_resolvedType; //!< Type information for the attribute interface
dataHandle_t m_handle; //!< Handle of the attribute data
mutable typename raw_data_traits::data_access_t* m_cachedData{ nullptr };
public:
/**
* Default constructor will create an invalid attribute
*/
RuntimeAttribute()
: m_type(BaseDataType::eUnknown),
m_resolvedType(BaseDataType::eUnknown),
m_handle(dataHandle_t::invalidValue())
{
}
/**
* Although the destructor should always be implemented with copy constructors it has no resources to release
*/
~RuntimeAttribute() = default;
/**
* Copy constructor, to allow these objects to be easily passed around.
* Only attributes with the same accessibility and memory type should be copied.
*/
RuntimeAttribute(const RuntimeAttribute<AttributeType, MemoryType, GpuPtrType>& toCopy)
: m_context(toCopy.m_context),
m_name(toCopy.m_name),
m_type(toCopy.m_type),
m_resolvedType(toCopy.m_resolvedType),
m_handle(toCopy.m_handle)
{
if (m_handle != dataHandle_t::invalidHandle())
_prefetch<>();
else
m_cachedData = nullptr;
}
/**
* Move constructor, to allow these objects to be efficiently passed around
* Only attributes with the same accessibility and memory type should be copied.
*/
RuntimeAttribute(RuntimeAttribute<AttributeType, MemoryType, GpuPtrType>&& toCopy)
: m_context(toCopy.m_context),
m_name(toCopy.m_name),
m_type(toCopy.m_type),
m_resolvedType(toCopy.m_resolvedType),
m_handle(toCopy.m_handle)
{
if (m_handle != dataHandle_t::invalidHandle())
_prefetch();
else
m_cachedData = nullptr;
}
/**
* Copy assignment, to match the constructor
* Only attributes with the same accessibility and memory type should be copied.
*/
RuntimeAttribute<AttributeType, MemoryType, GpuPtrType>&
operator=(const RuntimeAttribute<AttributeType, MemoryType, GpuPtrType>& toCopy)
{
m_context = toCopy.m_context;
m_name = toCopy.m_name;
m_type = toCopy.m_type;
m_resolvedType = toCopy.m_resolvedType;
m_handle = toCopy.m_handle;
m_cachedData = toCopy.m_cachedData;
return *this;
}
/**
* Move assignment, to match the constructor
* Only attributes with the same accessibility and memory type should be copied.
*/
RuntimeAttribute<AttributeType, MemoryType, GpuPtrType>&
operator=(RuntimeAttribute<AttributeType, MemoryType, GpuPtrType>&& toCopy)
{
m_context = toCopy.m_context;
m_name = toCopy.m_name;
m_type = toCopy.m_type;
m_resolvedType = toCopy.m_resolvedType;
m_handle = toCopy.m_handle;
m_cachedData = toCopy.m_cachedData;
return *this;
}
/**
* Standard constructor, extracts the attribute information if it is valid.
*
* @param[in] context Evaluaton context of this attribute
* @param[in] handle Handle to the attribute
* @param[in] resolvedType The type exposed to end user (conversion will happen if different from the actual real type)
*/
RuntimeAttribute(const GraphContextObj& context, dataHandle_t& handle, Type const& resolvedType = { BaseDataType::eUnknown })
: m_context(context), m_type(BaseDataType::eUnknown), m_resolvedType(resolvedType), m_handle(handle)
{
if (m_handle.isValid())
{
m_name = context.iAttributeData->getName(context, handle);
m_type = context.iAttributeData->getType(context, handle);
if (m_resolvedType.baseType == BaseDataType::eUnknown)
m_resolvedType = m_type;
_prefetch();
}
else
{
m_cachedData = nullptr;
}
}
/**
* Standard constructor, extracts the attribute information if it is valid.
*
* @param[in] context Evaluaton context of this attribute
* @param[in] handle Handle to the attribute
* @param[in] @param[in] resolvedType The type exposed to end user (conversion will happen if different from the actual real type)
*/
RuntimeAttribute(GraphContextObj&& context, dataHandle_t&& handle, Type const& resolvedType = { BaseDataType::eUnknown })
: m_context(context), m_type(BaseDataType::eUnknown), m_resolvedType(resolvedType), m_handle(handle)
{
if (m_handle.isValid())
{
m_name = context.iAttributeData->getName(context, handle);
m_type = context.iAttributeData->getType(context, handle);
if (m_resolvedType.baseType == BaseDataType::eUnknown)
m_resolvedType = m_type;
_prefetch();
}
else
{
m_cachedData = nullptr;
}
}
/**
* Copy the data from another runtime attribute into this one (only valid for non-const objects)
*
* @param[in] rhs Runtime attribute being copied
*/
template <typename SourceAttribute>
void copyData(const SourceAttribute& rhs)
{
static_assert(! readOnly, "Attribute data can only be copied to writable attributes");
ConstAttributeDataHandle constSrcHandle(rhs.abi_handle());
m_context.iAttributeData->copyData(m_handle, m_context, constSrcHandle);
}
/**
* Set the context and attribute handle for evaluation. Delayed so that the contents can be created
* early with just-in-time initialization.
*
* @param[in] context Evaluation context to use when extracting information
* @param[in] handle Handle to the attribute being wrapped
* @param[in] attr The attribute object represented by this wrapper
*/
void reset(const GraphContextObj& context, const dataHandle_t& handle, const AttributeObj& attr)
{
m_handle = handle;
m_context = context;
if (m_handle.isValid())
{
m_name = context.iAttributeData->getName(context, handle);
m_type = context.iAttributeData->getType(context, handle);
m_resolvedType = attr.iAttribute->getResolvedType(attr);
_prefetch();
}
else
{
m_type = Type{BaseDataType::eUnknown};
m_resolvedType = Type{ BaseDataType::eUnknown };
m_name = fabric::kUninitializedToken;
m_cachedData = nullptr;
}
}
/**
* @return true if the handle and context point to valid data within the fabric
*/
bool isValid() const
{
return m_handle.isValid();
}
/**
* @return Name by which this attribute's data is referenced
*/
const NameToken& name() const
{
return m_name;
}
/**
* @return Type information for this attribute's data
*/
const Type& type() const
{
return m_resolvedType.baseType != BaseDataType ::eUnknown ? m_resolvedType : m_type;
}
/**
* @return True if the data can be accessed in a vectorized manner for this attribute
*/
const bool canVectorize() const
{
//attrib needs to exists, and to be resolved as the the same type (ie. no auto conversion)
//we don't care about role
return m_type.baseType != BaseDataType::eUnknown &&
m_type.baseType == m_resolvedType.baseType &&
m_type.componentCount == m_resolvedType.componentCount &&
m_type.arrayDepth == m_resolvedType.arrayDepth;
}
/**
* @return The standardized type name for this attribute's data
*/
std::string typeName() const
{
return getOgnTypeName(type());
}
/**
* @return True if the attribute has a fully resolved type
*/
bool resolved() const
{
return m_type.baseType != BaseDataType::eUnknown;
}
/**
* @return Raw attribute data handle to use for direct ABI manipulation
*/
dataHandle_t abi_handle() const
{
return m_handle;
}
/**
* In vectorized context, make this attribute point to another instance
* @param[in] offset The distance at which the target instance is located relative to the currently pointed one
*/
void adjustHandle(size_t offset)
{
const IAttributeData& iData = *m_context.iAttributeData;
_moveHdl(iData, offset, m_handle);
_prefetch();
}
/**
* @return Raw graph context assotiated to the handle to use for direct ABI manipulation
*/
GraphContextObj const& abi_context() const
{
return m_context;
}
/**
* @return the number of elements in the array, or 1 if it is not an array type
*/
size_t size() const
{
size_t count{ 1 };
if (m_type.arrayDepth > 0)
{
ConstAttributeDataHandle constHandle{ m_handle }; // getElementCount requires the Const version
m_context.iAttributeData->getElementCount(&count, m_context, &constHandle, 1);
}
return count;
}
// ------------------------------------------------------------------------------------------------------------
// Support for the various methods to retrieve a generic value type as get<TYPE>().
//
// The details in the template and traits information is intended to make access to the data is generic as possible
// given the information provided by the data types and this attribute's class members.
//
// Almost all of the time you will access what appears to be a single templated method as this:
//
// auto dataAccessor = thisAttribute.get<DATA_TYPE>();
// if (dataAccessor.isValid()) ... // The data is the right type, and is valid
// // e.g. auto intData = intAttribute.get<int>();
//
// This hardcodes the compile time information about whether the attribute was read-only, what type of data it
// accepts, and the memory location, into what appears to be a single accessor (though behind the scenes it is
// actually a small set of them that provide appropriate access points for the type of data).
//
// For special attributes who have their memory location designated as "any", the decision of memory location is
// made at access time so two variations of the above method are available which explicitly get accessors on either
// the CPU or GPU memory locations:
//
// auto dataAccessorCpu = thisAttribute.getCpu<DATA_TYPE>();
// auto dataAccessorGpu = thisAttribute.getGpu<DATA_TYPE>();
//
// Note: Use only one of the two memory location accessors as accessing one type will often invalidate the other
// type, potentially causing excessive slow copying of data.
//
template <typename POD, eMemoryType GetAtMemoryType, PtrToPtrKind GetAtGpuPtrType = PtrToPtrKind::eNotApplicable, typename std::enable_if_t<attribute_type_traits<POD>::isSimpleType, int> = 0>
const simpleData_t<POD, GetAtMemoryType, GetAtGpuPtrType> getAt() const
{
using data_traits = data_type_traits<POD, readOnly, GetAtMemoryType, GetAtGpuPtrType>;
using data_ptr_access_t = typename data_traits::data_ptr_access_t;
return simpleData_t<POD, GetAtMemoryType, GetAtGpuPtrType>(
data_traits::matchesType(m_resolvedType) ? data_ptr_access_t(m_cachedData) : nullptr,
m_type);
}
template <typename POD, eMemoryType GetAtMemoryType, PtrToPtrKind GetAtGpuPtrType = PtrToPtrKind::eNotApplicable, typename std::enable_if_t<attribute_type_traits<POD>::isSimpleType, int> = 0>
simpleData_t<POD, GetAtMemoryType, GetAtGpuPtrType> getAt()
{
static_assert(! readOnly, "non-const get() can only be called on output attributes");
using data_traits = data_type_traits<POD, readOnly, GetAtMemoryType, GetAtGpuPtrType>;
using data_ptr_access_t = typename data_traits::data_ptr_access_t;
return simpleData_t<POD, GetAtMemoryType, GetAtGpuPtrType>(
data_traits::matchesType(m_type) ? data_ptr_access_t(m_cachedData) : nullptr,
m_type);
}
template <typename POD, eMemoryType GetAtMemoryType, PtrToPtrKind GetAtGpuPtrType = PtrToPtrKind::eNotApplicable, typename std::enable_if_t<attribute_type_traits<POD>::isTupleType, int> = 0>
const tupleData_t<POD, GetAtMemoryType, GetAtGpuPtrType> getAt() const
{
using data_traits = data_type_traits<POD, readOnly, GetAtMemoryType, GetAtGpuPtrType>;
using data_ptr_access_t = typename data_traits::data_ptr_access_t;
return tupleData_t<POD, GetAtMemoryType, GetAtGpuPtrType>(
data_traits::matchesType(m_resolvedType) ? data_ptr_access_t(m_cachedData) : nullptr,
m_type);
}
template <typename POD, eMemoryType GetAtMemoryType, PtrToPtrKind GetAtGpuPtrType = PtrToPtrKind::eNotApplicable, typename std::enable_if_t<attribute_type_traits<POD>::isTupleType, int> = 0>
tupleData_t<POD, GetAtMemoryType, GetAtGpuPtrType> getAt()
{
static_assert(! readOnly, "non-const get() can only be called on output attributes");
using data_traits = data_type_traits<POD, readOnly, GetAtMemoryType, GetAtGpuPtrType>;
using data_ptr_access_t = typename data_traits::data_ptr_access_t;
return tupleData_t<POD, GetAtMemoryType, GetAtGpuPtrType>(
data_traits::matchesType(m_type) ? data_ptr_access_t(m_cachedData) : nullptr,
m_type);
}
template <typename POD, eMemoryType GetAtMemoryType, PtrToPtrKind GetAtGpuPtrType = PtrToPtrKind::eNotApplicable, typename std::enable_if_t<attribute_type_traits<POD>::isArrayType, int> = 0>
const arrayData_t<POD, GetAtMemoryType, GetAtGpuPtrType> getAt() const
{
using data_traits = data_type_traits<POD, readOnly, GetAtMemoryType, GetAtGpuPtrType>;
return arrayData_t<POD, GetAtMemoryType, GetAtGpuPtrType>(m_context, &m_handle, data_traits::matchesType(m_type));
}
template <typename POD, eMemoryType GetAtMemoryType, PtrToPtrKind GetAtGpuPtrType = PtrToPtrKind::eNotApplicable, typename std::enable_if_t<attribute_type_traits<POD>::isArrayType, int> = 0>
arrayData_t<POD, GetAtMemoryType, GetAtGpuPtrType> getAt()
{
static_assert(! readOnly, "non-const get() can only be called on output attributes");
using data_traits = data_type_traits<POD, readOnly, GetAtMemoryType, GetAtGpuPtrType>;
return arrayData_t<POD, GetAtMemoryType, GetAtGpuPtrType>(m_context, &m_handle, data_traits::matchesType(m_type));
}
template <typename POD, eMemoryType GetAtMemoryType, PtrToPtrKind GetAtGpuPtrType = PtrToPtrKind::eNotApplicable, typename std::enable_if_t<attribute_type_traits<POD>::isTupleArrayType, int> = 0>
const tupleArrayData_t<POD, GetAtMemoryType, GetAtGpuPtrType> getAt() const
{
using data_traits = data_type_traits<POD, readOnly, GetAtMemoryType, GetAtGpuPtrType>;
return tupleArrayData_t<POD, GetAtMemoryType, GetAtGpuPtrType>(m_context, &m_handle, data_traits::matchesType(m_type));
}
template <typename POD, eMemoryType GetAtMemoryType, PtrToPtrKind GetAtGpuPtrType = PtrToPtrKind::eNotApplicable, typename std::enable_if_t<attribute_type_traits<POD>::isTupleArrayType, int> = 0>
tupleArrayData_t<POD, GetAtMemoryType, GetAtGpuPtrType> getAt()
{
static_assert(! readOnly, "non-const get() can only be called on output attributes");
using data_traits = data_type_traits<POD, readOnly, GetAtMemoryType, GetAtGpuPtrType>;
return tupleArrayData_t<POD, GetAtMemoryType, GetAtGpuPtrType>(m_context, &m_handle, data_traits::matchesType(m_type));
}
// ------------------------------------------------------------------------------------------------------------
// Variations of the get<>() functions that force either CPU or GPU memory location. These are used when the
// memory location of the attributes was set to "any", meaning they decide CPU or GPU at runtime, though there's
// no reason they can't be used for explicit memory locations either.
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isSimpleType, int> = 0>
const simpleData_t<POD, MemoryType, GpuPtrType> get() const
{
static_assert(MemoryType != kAny, "Use getCpu() or getGpu() to specify where the attribute's memory lives");
return getAt<POD, MemoryType, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isSimpleType, int> = 0>
simpleData_t<POD, MemoryType, GpuPtrType> get()
{
static_assert(MemoryType != kAny, "Use getCpu() or getGpu() to specify where the attribute's memory lives");
return getAt<POD, MemoryType, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleType, int> = 0>
const tupleData_t<POD, MemoryType, GpuPtrType> get() const
{
static_assert(MemoryType != kAny, "Use getCpu() or getGpu() to specify where the attribute's memory lives");
return getAt<POD, MemoryType, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleType, int> = 0>
tupleData_t<POD, MemoryType, GpuPtrType> get()
{
static_assert(MemoryType != kAny, "Use getCpu() or getGpu() to specify where the attribute's memory lives");
return getAt<POD, MemoryType, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isArrayType, int> = 0>
const arrayData_t<POD, MemoryType, GpuPtrType> get() const
{
static_assert(MemoryType != kAny, "Use getCpu() or getGpu() to specify where the attribute's memory lives");
return getAt<POD, MemoryType, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isArrayType, int> = 0>
arrayData_t<POD, MemoryType, GpuPtrType> get()
{
static_assert(MemoryType != kAny, "Use getCpu() or getGpu() to specify where the attribute's memory lives");
return getAt<POD, MemoryType, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleArrayType, int> = 0>
const tupleArrayData_t<POD, MemoryType, GpuPtrType> get() const
{
static_assert(MemoryType != kAny, "Use getCpu() or getGpu() to specify where the attribute's memory lives");
return getAt<POD, MemoryType, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleArrayType, int> = 0>
tupleArrayData_t<POD, MemoryType, GpuPtrType> get()
{
static_assert(MemoryType != kAny, "Use getCpu() or getGpu() to specify where the attribute's memory lives");
return getAt<POD, MemoryType, GpuPtrType>();
}
// --------------------------------------------------------------------------------------------------------------
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isSimpleType, int> = 0>
const simpleData_t<POD, kCpu> getCpu() const
{
_prefetch<kCpu>();
return getAt<POD, kCpu>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isSimpleType, int> = 0>
simpleData_t<POD, kCpu> getCpu()
{
_prefetch<kCpu>();
return getAt<POD, kCpu>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleType, int> = 0>
const tupleData_t<POD, kCpu> getCpu() const
{
_prefetch<kCpu>();
return getAt<POD, kCpu>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleType, int> = 0>
tupleData_t<POD, kCpu> getCpu()
{
_prefetch<kCpu>();
return getAt<POD, kCpu>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isArrayType, int> = 0>
const arrayData_t<POD, kCpu> getCpu() const
{
return getAt<POD, kCpu>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isArrayType, int> = 0>
arrayData_t<POD, kCpu> getCpu()
{
return getAt<POD, kCpu>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleArrayType, int> = 0>
const tupleArrayData_t<POD, kCpu> getCpu() const
{
return getAt<POD, kCpu>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleArrayType, int> = 0>
tupleArrayData_t<POD, kCpu> getCpu()
{
return getAt<POD, kCpu>();
}
// --------------------------------------------------------------------------------------------------------------
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isSimpleType, int> = 0>
const simpleData_t<POD, kCuda, GpuPtrType> getGpu() const
{
_prefetch<kCuda>();
return getAt<POD, kCuda, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isSimpleType, int> = 0>
simpleData_t<POD, kCuda, GpuPtrType> getGpu()
{
_prefetch<kCuda>();
return getAt<POD, kCuda, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleType, int> = 0>
const tupleData_t<POD, kCuda, GpuPtrType> getGpu() const
{
_prefetch<kCuda>();
return getAt<POD, kCuda, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleType, int> = 0>
tupleData_t<POD, kCuda, GpuPtrType> getGpu()
{
_prefetch<kCuda>();
return getAt<POD, kCuda, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isArrayType, int> = 0>
const arrayData_t<POD, kCuda, GpuPtrType> getGpu() const
{
return getAt<POD, kCuda, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isArrayType, int> = 0>
arrayData_t<POD, kCuda, GpuPtrType> getGpu()
{
return getAt<POD, kCuda, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleArrayType, int> = 0>
const tupleArrayData_t<POD, kCuda, GpuPtrType> getGpu() const
{
return getAt<POD, kCuda, GpuPtrType>();
}
template <typename POD, typename std::enable_if_t<attribute_type_traits<POD>::isTupleArrayType, int> = 0>
tupleArrayData_t<POD, kCuda, GpuPtrType> getGpu()
{
return getAt<POD, kCuda, GpuPtrType>();
}
// --------------------------------------------------------------------------------------------------------------
// Raw data access method, which returns size and pointer but ignores type information. Its usage should be rare,
// but it is useful to have it available for those times.
template <eMemoryType RawMemoryType = MemoryType, PtrToPtrKind RawGpuPtrType = PtrToPtrKind::eNotApplicable>
void rawData(ConstRawPtr& ptr, size_t& size) const
{
static_assert(RawMemoryType != kAny, "Cannot access raw data on an attribute with runtime memory location");
using data_traits = data_type_traits<uint8_t, readOnly, RawMemoryType, RawGpuPtrType>;
data_traits::dataReference(m_context, m_handle, ptr, size);
}
template <eMemoryType RawMemoryType = MemoryType, PtrToPtrKind RawGpuPtrType = PtrToPtrKind::eNotApplicable>
void rawData(RawPtr& ptr, size_t& size)
{
static_assert(RawMemoryType != kAny, "Cannot access raw data on an attribute with runtime memory location");
static_assert(! readOnly, "Cannot access writable raw data on a read-only attribute");
using data_traits = data_type_traits<uint8_t, readOnly, RawMemoryType, RawGpuPtrType>;
data_traits::dataReference(m_context, m_handle, ptr, size);
}
};
/* Runtime Attribute type traits */
template<class T>
struct is_runtime_data : std::false_type {};
template<class T, bool ReadOnly, eMemoryType MemoryType>
struct is_runtime_data<ArrayData<T, ReadOnly, MemoryType, PtrToPtrKind::eNotApplicable>> : std::true_type {};
template<class T, eMemoryType MemoryType>
struct is_runtime_data<SimpleDataReadOnly<T, MemoryType, PtrToPtrKind::eNotApplicable>> : std::true_type {};
template<class T, eMemoryType MemoryType>
struct is_runtime_data<SimpleDataWritable<T, MemoryType, PtrToPtrKind::eNotApplicable>> : std::true_type {};
template<class T, eMemoryType MemoryType>
struct is_runtime_data<TupleDataReadOnly<T, MemoryType, PtrToPtrKind::eNotApplicable>> : std::true_type {};
template<class T, eMemoryType MemoryType>
struct is_runtime_data<TupleDataWritable<T, MemoryType, PtrToPtrKind::eNotApplicable>> : std::true_type {};
template<class T, eMemoryType MemoryType>
struct is_runtime_data<ArrayDataReadOnly<T, MemoryType, PtrToPtrKind::eNotApplicable>> : std::true_type {};
template<class T, eMemoryType MemoryType>
struct is_runtime_data<ArrayDataWritable<T, MemoryType, PtrToPtrKind::eNotApplicable>> : std::true_type {};
template<class T, eMemoryType MemoryType>
struct is_runtime_data<TupleArrayDataReadOnly<T, MemoryType, PtrToPtrKind::eNotApplicable>> : std::true_type {};
template<class T, eMemoryType MemoryType>
struct is_runtime_data<TupleArrayDataWritable<T, MemoryType, PtrToPtrKind::eNotApplicable>> : std::true_type {};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 57,389 | C | 48.219554 | 199 | 0.672063 |
omniverse-code/kit/include/omni/graph/core/ogn/TypeTraits.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <omni/graph/core/Type.h>
#include <omni/graph/core/ogn/Types.h>
#include <omni/graph/core/TemplateUtils.h>
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// Helper that provides a templated conversion from C++ simple data type to the base data type enum in core::Type
template <typename CppType>
struct attribute_base_t { static constexpr BaseDataType value = BaseDataType::eUnknown; };
template <> struct attribute_base_t<bool> { static constexpr BaseDataType value = BaseDataType::eBool; };
template <> struct attribute_base_t<double> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<float> { static constexpr BaseDataType value = BaseDataType::eFloat; };
template <> struct attribute_base_t<int> { static constexpr BaseDataType value = BaseDataType::eInt; };
template <> struct attribute_base_t<int64_t> { static constexpr BaseDataType value = BaseDataType::eInt64; };
template <> struct attribute_base_t<Token> { static constexpr BaseDataType value = BaseDataType::eToken; };
template <> struct attribute_base_t<NameToken> { static constexpr BaseDataType value = BaseDataType::eToken; };
template <> struct attribute_base_t<Path> { static constexpr BaseDataType value = BaseDataType::eRelationship; };
template <> struct attribute_base_t<TargetPath> { static constexpr BaseDataType value = BaseDataType::eRelationship; };
template <> struct attribute_base_t<uint32_t> { static constexpr BaseDataType value = BaseDataType::eUInt; };
template <> struct attribute_base_t<uint64_t> { static constexpr BaseDataType value = BaseDataType::eUInt64; };
template <> struct attribute_base_t<uint8_t> { static constexpr BaseDataType value = BaseDataType::eUChar; };
template <> struct attribute_base_t<char> { static constexpr BaseDataType value = BaseDataType::eUChar; };//char is used for string, but implemented as uchar
//carb base types
template <> struct attribute_base_t<carb::Float2> { static constexpr BaseDataType value = BaseDataType::eFloat; };
template <> struct attribute_base_t<carb::Float3> { static constexpr BaseDataType value = BaseDataType::eFloat; };
template <> struct attribute_base_t<carb::Float4> { static constexpr BaseDataType value = BaseDataType::eFloat; };
template <> struct attribute_base_t<carb::Double2> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<carb::Double3> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<carb::Double4> { static constexpr BaseDataType value = BaseDataType::eDouble; };
template <> struct attribute_base_t<carb::Int2> { static constexpr BaseDataType value = BaseDataType::eInt; };
template <> struct attribute_base_t<carb::Int3> { static constexpr BaseDataType value = BaseDataType::eInt; };
template <> struct attribute_base_t<carb::Int4> { static constexpr BaseDataType value = BaseDataType::eInt; };
template <> struct attribute_base_t<carb::Uint2> { static constexpr BaseDataType value = BaseDataType::eUInt; };
template <> struct attribute_base_t<carb::Uint3> { static constexpr BaseDataType value = BaseDataType::eUInt; };
template <> struct attribute_base_t<carb::Uint4> { static constexpr BaseDataType value = BaseDataType::eUInt; };
// Helper struct to convert at compile time from BaseDataType to corresponding cpp type
template <BaseDataType eBaseType>
struct attribute_t { using type = void; };
template <> struct attribute_t<BaseDataType::eBool> { using type = bool; };
template <> struct attribute_t<BaseDataType::eDouble> { using type = double; };
template <> struct attribute_t<BaseDataType::eFloat> { using type = float; };
template <> struct attribute_t<BaseDataType::eInt> { using type = int; };
template <> struct attribute_t<BaseDataType::eInt64> { using type = int64_t; };
template <> struct attribute_t<BaseDataType::eToken> { using type = Token; };
template <> struct attribute_t<BaseDataType::eUInt> { using type = uint32_t; };
template <> struct attribute_t<BaseDataType::eUInt64> { using type = uint64_t; };
template <> struct attribute_t<BaseDataType::eUChar> { using type = uint8_t; };
// Templated conversions defining attribute traits given the actual C++ data types they implement.
// The role does not enter in to this conversion as it is an interpretation of a data type, not a separate data type.
//
// Constants:
// isArray Boolean indicating if the data type includes an array of variable length
// tupleCount Number of tuple values in the data type (1 for a simple value)
// baseType BaseDataType enum matching the data's unencumbered type
// Types:
// actual_t Actual data type to be handled (managing types that resolve to the same POD)
// element_t Data type for the unencumbered value (e.g float for a float[][3])
// data_t Data type for a single value (e.g. float for float/float[] but float[3] for float[3]/float[][3])
//
// The comments above the definitions give examples of how the values are set for representative template types
//
// Note: The pxr GfVec/GfMatrix types are not included here for simplicity, though they can be defined in a separate
// file for those that wish to use them by specializing the attribute_type_traits struct.
template <typename CppType>
struct attribute_type_traits
{
// float/float[3] -> false, float[]/float[][3] -> true
static constexpr bool isArray = !is_bounded_array<CppType>::value && std::is_array<CppType>::value;
static constexpr uint8_t arrayDepth = isArray ? 1 : 0;
// Flags that break apart the data type into the four main mutually-exclusive categories used as accessors
static constexpr bool isSimpleType = !is_bounded_array<CppType>::value && !std::is_array<CppType>::value;
static constexpr bool isTupleType = is_bounded_array<CppType>::value;
static constexpr bool isArrayType = std::is_array<CppType>::value && !is_bounded_array<CppType>::value && !is_bounded_array<std::remove_extent_t<CppType>>::value;
static constexpr bool isTupleArrayType = std::is_array<CppType>::value && !is_bounded_array<CppType>::value && is_bounded_array<std::remove_extent_t<CppType>>::value;
// Get the actual data type this class references. This is needed due to the fact that our token implementation,
// NameToken, is typedefed to uint64_t, making it indistinguishable from a regular uint64_t to the compiler. By
// passing ogn::Token/ogn::Token[] instead, the ambiguity can be resolved and the actual type deduced. (This
// wouldn't quite work as-is if it supported tuples, but as it doesn't the extra complexity can be omitted.)
using actual_t = std::conditional_t<std::is_same<std::remove_all_extents_t<CppType>, ogn::Token>::value,
std::conditional_t<isArray, NameToken[], NameToken>,
CppType
>;
// float/float[3]/float[]/float[][3] -> float
using element_t = std::remove_const_t<std::remove_all_extents_t<actual_t>>;
// float/float[]/float[3]/float[][3] -> BaseDataType::eFloat
static constexpr BaseDataType baseType = attribute_base_t<element_t>::value;
// float/float[] -> float, float[3]/float[][3] -> float[3]
using data_t = std::conditional_t<isArray, std::remove_extent_t<actual_t>, actual_t>;
// float/float[] -> 1, float[3]/float[][3] -> 3
static constexpr int tupleCount = std::is_array<data_t>::value ? std::extent<data_t, 0>::value : 1;
};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 7,978 | C | 62.831999 | 170 | 0.736901 |
omniverse-code/kit/include/omni/graph/core/ogn/TypeConversion.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <omni/graph/core/ogn/TypeTraits.h>
namespace omni
{
namespace graph
{
namespace core
{
namespace ogn
{
// Utility struct to implement conversion between 2 BaseDataType
// Note: simple runtime dispatch on the source type (dst type must be known at compile time)
static constexpr BaseDataType kLastBaseType = BaseDataType::eToken;
template <typename DST_TYPE, BaseDataType BASE_SRC_TYPE = kLastBaseType>
struct BaseTypeConversion
{
using next = BaseTypeConversion<DST_TYPE, (BaseDataType)((uint8_t)BASE_SRC_TYPE - 1)>;
static int canConvertFrom(BaseDataType srcType)
{
if (srcType == BASE_SRC_TYPE)
return false;
return next::canConvertFrom(srcType);
}
static bool convert(DST_TYPE* dst, void const* src, BaseDataType srcType, size_t count)
{
if (srcType == BASE_SRC_TYPE)
return false;
return next::convert(dst, src, srcType, count);
}
};
template <typename T>
struct BaseTypeConversion<T, BaseDataType::eUnknown>
{
static constexpr int canConvertFrom(BaseDataType) { return 0; }
static bool convert(T*, void const*, BaseDataType, size_t) { return false; }
};
template<typename T, BaseDataType eDataType>
struct BaseTypeConversionBase
{
using next = BaseTypeConversion<T, (BaseDataType)((uint8_t)eDataType - 1)>;
static bool canConvertFromBase(BaseDataType srcType)
{
if (eDataType == srcType)
return true;
return false;
}
template<typename FUNC>
static bool convertBase(T* dst, void const* srcBuffer, BaseDataType srcType, size_t count, FUNC const& func)
{
if (eDataType == srcType)
{
using srcType = typename attribute_t<eDataType>::type;
srcType const* srcPtr = (srcType const*)srcBuffer;
while (count--)
func(*dst++, *srcPtr++);
return true;
}
return next::convert(dst, srcBuffer, srcType, count);
}
};
#define IMPLEMENT_BASE_TYPE_CONVERSION(dstType, srcBaseType, func)\
template <> struct BaseTypeConversion<dstType, srcBaseType> : public BaseTypeConversionBase<dstType, srcBaseType> {\
static int canConvertFrom(BaseDataType srcType) {if(canConvertFromBase(srcType)) return __LINE__; return next::canConvertFrom(srcType);}\
static bool convert(dstType* dst, void const* srcBuffer, BaseDataType srcType, size_t count) {return convertBase(dst, srcBuffer, srcType, count, func);}}
#define IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(SRC, DST) \
IMPLEMENT_BASE_TYPE_CONVERSION(DST, attribute_base_t<SRC>::value, [](DST& dst, SRC const& src) { dst = (DST)src; })
//! <summary>
//! Implements all conversions
//! Note: order is important for BOTH source type and destination type
//! source type oder : template instantiation needs to happen in order of the enum since higher type ID template
//! will call lower ones (so they need to be already defined)
//! => ORDER IN THE BASE TYPE ENUM ORDER
//! dst type order : conversion precedence will follow order of declaration
//! ie. : when several conversions are possible, the one declared before the others will be used
//! => ORDER BY "QUALITY" OF THE CONVERSION
//! </summary>
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(int, unsigned int); // signed -> unsigned is allowed by fabric
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(int, int64_t);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(int, float);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(int, double);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(int, bool);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(unsigned int, uint64_t);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(unsigned int, int);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(unsigned int, int64_t);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(unsigned int, float);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(unsigned int, double);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(unsigned int, bool);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(int64_t, uint64_t); // signed -> unsigned is allowed by fabric
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(int64_t, int);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(int64_t, double);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(int64_t, float);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(int64_t, bool);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(uint64_t, int64_t);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(uint64_t, unsigned int);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(uint64_t, int);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(uint64_t, double);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(uint64_t, float);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(uint64_t, bool);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(float, double);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(float, int);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(float, int64_t);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(double, float);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(double, int64_t);
IMPLEMENT_BASE_TYPE_CONVERSION_AS_CAST(double, int);
//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//
//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//
// This implements the Double dispatch solve, when none of the type are known at compile time
template <BaseDataType BASE_DST_TYPE = kLastBaseType>
struct BaseDoubleDispatchTypeConversionTest
{
using TYPE = typename attribute_t<BASE_DST_TYPE>::type;
static int canConvert(BaseDataType from, BaseDataType to)
{
if (BASE_DST_TYPE == to)
return BaseTypeConversion<TYPE>::canConvertFrom(from);
return BaseDoubleDispatchTypeConversionTest<(BaseDataType)((uint8_t)BASE_DST_TYPE - 1)>::canConvert(from, to);
}
static bool convert(void* dstBuffer, BaseDataType dstType, void const* srcBuffer, BaseDataType srcType, size_t count)
{
if (BASE_DST_TYPE == dstType)
return BaseTypeConversion<TYPE>::convert((TYPE*) dstBuffer, srcBuffer, srcType, count);
return BaseDoubleDispatchTypeConversionTest<(BaseDataType)((uint8_t)BASE_DST_TYPE - 1)>::convert(dstBuffer, dstType, srcBuffer, srcType, count);
}
};
template <>
struct BaseDoubleDispatchTypeConversionTest<BaseDataType::eUnknown>
{
static int canConvert(BaseDataType from, BaseDataType to)
{
return 0;
}
static bool convert(void* dst, BaseDataType dstType, void const* srcBuffer, BaseDataType srcType, size_t count)
{
return false;
}
};
//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//
//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//
//Convert at compile time a type to its corresponding BaseDataType
template<typename T>
constexpr BaseDataType getDataType()
{
using U = std::decay_t<T>;
using V = std::remove_pointer_t<U>;
return attribute_base_t<V>::value;
}
//Returns a positive value if a conversion exists between the 2 provided types, 0 else
// The lower the returned value is, the prefered is the conversion
static inline int isRawDataConvertible(BaseDataType from, BaseDataType to)
{
return BaseDoubleDispatchTypeConversionTest<>::canConvert(from, to);
}
// Indicate whether, for a given type pair reputed to be convertible, the actual conversion can be bypassed
static inline bool isRawBinaryDataCompatible(BaseDataType t0, BaseDataType t1)
{
if (t0 == t1)
return true;
if (t0 > t1)
std::swap(t0, t1);
switch (t0)//always smaller
{
case omni::graph::core::BaseDataType::eUnknown:
break;
case omni::graph::core::BaseDataType::eBool:
break;
case omni::graph::core::BaseDataType::eUChar:
break;
case omni::graph::core::BaseDataType::eInt:
break;
case omni::graph::core::BaseDataType::eUInt:
break;
case omni::graph::core::BaseDataType::eInt64:
break;
case omni::graph::core::BaseDataType::eUInt64:
return t1 == omni::graph::core::BaseDataType::eToken;
break;
case omni::graph::core::BaseDataType::eHalf:
break;
case omni::graph::core::BaseDataType::eFloat:
break;
case omni::graph::core::BaseDataType::eDouble:
break;
case omni::graph::core::BaseDataType::eToken:
break;
case omni::graph::core::BaseDataType::eRelationship:
break;
case omni::graph::core::BaseDataType::eAsset:
break;
case omni::graph::core::BaseDataType::ePrim:
break;
case omni::graph::core::BaseDataType::eConnection:
break;
case omni::graph::core::BaseDataType::eTag:
break;
default:
break;
}
return false;
}
//Perform the actual conversion between 2 instantiated values
template <typename Dst>
static inline bool doConversion(Dst* dst, void const* src, BaseDataType srcType, size_t count)
{
static_assert(getDataType<Dst>() != BaseDataType::eUnknown, "");
CARB_ASSERT(srcType != BaseDataType::eUnknown);
using UnderlyingType = typename attribute_t<getDataType<Dst>()>::type;//ex: Vec3 -> float
return BaseTypeConversion<UnderlyingType>::convert((UnderlyingType*)dst, src, srcType, count);
}
static inline bool doConversion(void* dst, BaseDataType dstType, void const* src, BaseDataType srcType, size_t count)
{
CARB_ASSERT(dstType != BaseDataType::eUnknown);
CARB_ASSERT(srcType != BaseDataType::eUnknown);
return BaseDoubleDispatchTypeConversionTest<>::convert(dst, dstType, src, srcType, count);
}
// Helper to determine if the given roles are compatible for matching base type
static inline bool areMatchedBaseTypesRoleCompatible(BaseDataType baseType, AttributeRole srcRole, AttributeRole destRole)
{
// Execution (which has base type uint) can only be connected to another Execution attribute
if ((baseType == BaseDataType::eUInt) &&
((destRole == AttributeRole::eExecution) != (srcRole == AttributeRole::eExecution)))
{
return false;
}
else if (baseType == omni::fabric::BaseDataType::eUChar)
{
// Path and strings are compatible
bool isSrcString = (srcRole == AttributeRole::ePath || srcRole == AttributeRole::eText);
bool isDstString = (destRole == AttributeRole::ePath || destRole == AttributeRole::eText);
return isSrcString == isDstString;
}
return true;
};
// Helper to return true if the given types are compatible
static inline int areTypesCompatible(const Type& srcType, const Type& destType)
{
if (srcType == destType)
return 1;
// They aren't exactly the same, but check for signed/unsigned compatibility, which FC can support
if (srcType.arrayDepth != destType.arrayDepth)
return 0;
if (srcType.componentCount != destType.componentCount)
return 0;
// If base types match, we are compatible with a possible exception for the role
if (srcType.baseType == destType.baseType)
return areMatchedBaseTypesRoleCompatible(srcType.baseType, srcType.role, destType.role) ? 1 : 0;
// Arrays are not convertible
// but arrays of int(64) signed <-> unsigned are through fabric
if (srcType.arrayDepth)
{
return ((srcType.baseType == BaseDataType::eInt || srcType.baseType == BaseDataType::eUInt) &&
(destType.baseType == BaseDataType::eInt || destType.baseType == BaseDataType::eUInt)) ||
((srcType.baseType == BaseDataType::eInt64 || srcType.baseType == BaseDataType::eUInt64) &&
(destType.baseType == BaseDataType::eInt64 || destType.baseType == BaseDataType::eUInt64)) ? 1 : 0;
}
return isRawDataConvertible(srcType.baseType, destType.baseType);
};
// Helper to return if there is any compatibility between two type groups
static inline int areAnyTypesCompatible(const std::vector<Type>& srcTypes, const std::vector<Type>& destTypes)
{
for (const auto& src: srcTypes)
{
for (const auto& dst: destTypes)
{
if (areTypesCompatible(src, dst))
return true;
}
}
return false;
}
//Small struct helper that:
// - hold the converted value so a reference can be returned
// - specialize to an empty pass-through if no conversion exists
template <typename DataType, BaseDataType eType = getDataType<DataType>()>
struct Converter
{
private:
using Data = typename std::decay<DataType>::type;
Data convertedValue{};
public:
Converter(){}
DataType const* convertValue(DataType const* originalData, Type const& originalDataType) const
{
if (willConvert(originalDataType))
{
doConversion(
&convertedValue, (void*)originalData, originalDataType.baseType, originalDataType.componentCount);
return (DataType const*)&convertedValue;
}
return originalData;
}
bool willConvert(Type const& originalDataType) const
{
BaseDataType constexpr bdt = getDataType<DataType>();
return !isRawBinaryDataCompatible(originalDataType.baseType, bdt);
}
};
template <typename DataType>
struct Converter<DataType, BaseDataType::eUnknown>
{
inline DataType const* convertValue(DataType const* originalData, Type const&) const
{
return originalData;
}
bool willConvert(Type const& originalDataType) const
{
return false;
}
};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 13,832 | C | 37.002747 | 157 | 0.683126 |
omniverse-code/kit/include/omni/graph/core/ogn/Bundle.h | // 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.
//
#pragma once
// =================================================================================================================
// This file contains interface classes which wrap attribute bundles in the OGN database for ease of use
//
// BundleContents Accessor to get at the attributes inside the bundle
// BundleAttribute Access to the bundle attribute, with appropriate read/write abilities depending on port type
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
#ifdef THIS_IS_INCLUDED_IN_THE_DOCUMENTATION
// The information bracketed here with begin/end describes the interface that is recommended for use with bundled
// attributes. The documentation uses these markers to perform a literal include of this code into the docs so that
// it can be the single source of truth. Note that the interface described here is not the complete set of C++
// functions available, merely the ones that make sense for the user to access when dealing with bundles.
// begin-bundle-interface-description
// A bundle can be described as an opaque collection of attributes that travel together through the graph, whose
// contents and types can be introspected in order to determine how to deal with them. This section describes how
// the typical node will interface with the bundle content access. Use of the attributes within the bundles is the
// same as for the extended type attributes, described with their access methods.
//
// An important note regarding GPU bundles is that the bundle itself always lives on the CPU, specifying a memory
// space of "GPU/CUDA" for the bundle actually means that the default location of the attributes it contains will
// be on the GPU.
//
// The main bundle is extracted the same as any other attribute, by referencing its generated database location.
// For this example the bundle will be called "color" and it will have members that could either be the set
// ("r", "g", "b", "a") or the set ("c", "m", "y", "k") with the obvious implications of implied color space.
//
// The bundle itself has a path to which it refers; normally unnecessary to use but helpful for debugging
std::cout << "The color bundle came from " << db.inputs.color.path() << std::endl;
// As with other attribute types you can get an accessor to the bundle:
const auto& colorBundle = db.inputs.color();
// The accessor can determine if it points to valid data
const bool validColor = colorBundle.isValid();
// It can be queried for the number of attributes it holds
auto bundleAttributeCount = colorBundle.size();
// It can have its contents iterated over
for (const auto& bundledAttribute : colorBundle)
{ /* ... */ }
// It can be queried for an attribute in it with a specific name
auto bundledAttribute = colorBundle.attributeByName(db.tokens.red);
// And on the rare occasion when it is necessary, it can access the low level IBundle interface or ABI handle of the bundle's data
// to make direct ABI calls on it. (This is discouraged as it may bypass some important state updates.)
const auto& bundleHandle = colorBundle.abi_bundleHandle();
// *** The rest of these methods are for output bundles only, as they change the makeup of the bundle
// It can be assigned to an output bundle, which merely transfers ownership of the bundle.
// As in all C++ it's important to make the distinction between assignment and merely obtaining a reference
auto& computedColorBundle = db.outputs.computedColorBundle(); // No copy, just assignment of a reference object
computedColorBundle = colorBundle; // Copy the input bundle to the output bundle
// It can have its contents (i.e. attribute membership) cleared
computedColorBundle.clear();
// It can insert a new bundle, without replacing its current contents (with the caveat that all attribute names
// in the current and inserted bundle must be unique)
computedColorBundle.insertBundle(colorBundle);
// It can have a single attribute from another bundle inserted into its current list, like if you don't want
// the transparency value in your output color
computedColorBundle.clear();
computedColorBundle.insertAttribute(colorBundle.attributeByName(db.tokens.red));
computedColorBundle.insertAttribute(colorBundle.attributeByName(db.tokens.green));
computedColorBundle.insertAttribute(colorBundle.attributeByName(db.tokens.blue));
// It can add a brand new attribute with a specific type and name
namespace og = omni::graph::core;
og::Type floatType(og::BaseDataType::eFLOAT);
computedColorBundle.addAttribute(db.tokens.opacity, floatType);
// If you are adding an array attribute you can set its initial element count with the same call
og::Type boolArrayType(og::BaseDataType::eBOOLEAN, 1, 1);
computedColorBundle.addAttribute(db.tokens.bits, boolArrayType, 32);
// If you want to remove an attribute from a bundle you only need its name
computedColorBundle.removeAttribute(db.tokens.bits);
// end-bundle-interface-description
#endif
#include <omni/graph/core/ogn/RuntimeAttribute.h>
#include <omni/graph/core/Type.h>
#include <omni/graph/core/ogn/Types.h>
#include <omni/graph/core/IBundle.h>
#include <omni/graph/core/ComputeGraph.h>
#include <omni/graph/core/IBundleChanges.h>
#include <carb/InterfaceUtils.h>
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// ======================================================================
/**
* Class responsible for managing the interaction with bundles of attributes.
* It wraps the bundle in an interface with a more natural interaction than the raw ABI calls.
*
* <AttributeType> How the attribute is interpreted - input, output, or state value
* <MemoryType> where the memory for the attributes in this bundle will live (CPU, GPU, or decided at runtime)
* <GpuPtrType> where the pointer to array attributes in this bundle will live (CPU or GPU, for GPU data only)
*/
template <eAttributeType AttributeType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
class BundleContents
{
//! Aliases used during overload resolution to differentiate between read-only and read-write.
using roTag_t = std::true_type;
using rwTag_t = std::false_type;
//! The writability of a bundle will determine what kinds of operations can be performed on it
static constexpr bool readOnly = (AttributeType == kOgnInput);
using readOnly_t = std::conditional_t<AttributeType == kOgnInput, roTag_t, rwTag_t>;
//! By defining the bundle type based on attribute type duplication of code in this class can be avoided
using bundleHandle_t = std::conditional_t<readOnly, ConstBundleHandle, BundleHandle>;
//! By defining the interface type based on attribute type duplication of code in this class can be avoided
using bundleInterface_t = std::conditional_t<readOnly, IConstBundle2, IBundle2>;
//! The handle types are not simply "X" and "const X" variations so the type has to be explicitly defined
//! for writable (output/state) and non-writable (input) attribute types.
using dataHandle_t = std::conditional_t<readOnly, ConstAttributeDataHandle, AttributeDataHandle>;
//! Short form to reduce line length
using runtime_t = RuntimeAttribute<AttributeType, MemoryType, GpuPtrType>;
using bundleInterfacePtr = omni::core::ObjectPtr<bundleInterface_t>;
bundleInterfacePtr m_bundlePtr;
runtime_t m_invalid; //!< Special object representing invalid data
mutable gsl::span<runtime_t> m_iterableArray; //!< Iterator wrapper
// ================================================================================
// Functions supporting both read-only and writable versions, necessitated by the different function calls
// and argument types used for both (i.e. you can't just do a const_cast for these). Ideally they would be
// broken out into utility functions and shared everywhere.
//
// They are selected by calling them using a first argument of "readOnly_t()", which will use overloading to
// select the proper version. (roTag_t for read-only versions, rwTag_t for writable versions)
/**
* Extract the interface for an attribute in the bundle with the given name.
*
* @param name Token representing the name of the attribute in the bundle
* @return Bundle member from which attribute information can be extracted (invalid if name was not found)
*/
dataHandle_t extractNamedAttribute(rwTag_t, NameToken const& name) const
{
return m_bundlePtr->getAttributeByName(name);
}
dataHandle_t extractNamedAttribute(roTag_t, NameToken const& name) const
{
return m_bundlePtr->getConstAttributeByName(name);
}
/**
* Get the list of attribute handles present on the bundle.
*
* @param Type representing writable (rwTag_t) or read-only (roTag_t) data
* @param allHandles Pointer to array of handles that were extracted
* @param count The size of the provided pointer array (in pointer count)
*/
void extractHandles(rwTag_t, dataHandle_t* allHandles, size_t count) const
{
m_bundlePtr->getAttributes(allHandles, count);
}
void extractHandles(roTag_t, dataHandle_t* allHandles, size_t count) const
{
m_bundlePtr->getConstAttributes(allHandles, count);
}
/**
* Construct bundle interface based on provided context and bundle handle.
*
* @param context Evaluation context.
* @param handle Bundle handle.
*/
bundleInterfacePtr getInterface(rwTag_t, GraphContextObj const& context, bundleHandle_t handle) const
{
return getBundleFactoryInterface()->getBundle(context, handle);
}
bundleInterfacePtr getInterface(roTag_t, GraphContextObj const& context, bundleHandle_t handle) const
{
return getBundleFactoryInterface()->getConstBundle(context, handle);
}
/**
* Construct bundle interface based on provided context and bundle path.
*
* @param context Evaluation context.
* @param path Bundle path.
*/
bundleInterfacePtr getInterface(rwTag_t, GraphContextObj const& context, omni::fabric::PathC path) const
{
auto factory = omni::core::cast<IBundleFactory2>(getBundleFactoryInterface());
return factory ? factory->getBundleFromPath(context, path) : bundleInterfacePtr{};
}
bundleInterfacePtr getInterface(roTag_t, GraphContextObj const& context, omni::fabric::PathC path) const
{
auto factory = omni::core::cast<IBundleFactory2>(getBundleFactoryInterface());
return factory ? factory->getConstBundleFromPath(context, path) : bundleInterfacePtr{};
}
/**
* Get read-only or read-write handle depending on writability permissions of this interface.
*/
bundleHandle_t getBundleHandle(rwTag_t) const
{
return m_bundlePtr->getHandle();
}
bundleHandle_t getBundleHandle(roTag_t) const
{
return m_bundlePtr->getConstHandle();
}
void clearAttributeCache() const
{
delete[] m_iterableArray.data();
m_iterableArray = gsl::span<runtime_t>{};
}
void updateAttributeCache() const
{
// Only reallocate the bundle members if the size changed. If it didn't then the
// in-place constructor will put the correct data in place.
size_t newSize = attributeCount();
if (!m_iterableArray.empty() && (newSize != m_iterableArray.size()))
{
clearAttributeCache();
}
if (m_iterableArray.empty() && (newSize > 0))
{
m_iterableArray = gsl::span<runtime_t>{ new runtime_t[newSize], newSize };
}
if (!m_iterableArray.empty())
{
auto context = m_bundlePtr->getContext();
dataHandle_t* allHandles = reinterpret_cast<dataHandle_t*>(alloca(newSize * sizeof(dataHandle_t)));
extractHandles(readOnly_t(), allHandles, newSize);
for (size_t i = 0; i < newSize; ++i)
{
new (&m_iterableArray[i]) runtime_t(context, allHandles[i]);
}
}
}
public:
// Pass through the span iterator so that this class can iterate over it transparently
using iterator = typename gsl::span<runtime_t>::iterator;
using reverse_iterator = typename gsl::span<runtime_t>::reverse_iterator;
/**
* Default constructor
*/
BundleContents() = default;
/**
* Constructor with direct initialization from context and bundle handle.
*/
BundleContents(GraphContextObj const& context, bundleHandle_t handle) : BundleContents()
{
reset(context, handle);
}
/**
* Constructor with direct initialization from context and bundle path.
*/
BundleContents(GraphContextObj const& context, omni::fabric::Path path)
: BundleContents()
{
reset(getInterface(readOnly_t{}, context, path));
}
/**
* Data managed by the bundle cannot be duplicated
*/
BundleContents(const BundleContents&) = delete;
BundleContents& operator=(const BundleContents&) = delete;
/**
* Clean up any cached data
*/
~BundleContents()
{
clearAttributeCache();
}
/**
* @deprecated Calling abi_primHandle() is deprecated. Use abi_bundleHandle() instead!
*/
[[deprecated("Calling abi_primHandle() is deprecated. Use abi_bundleHandle() instead!")]]
bundleHandle_t const abi_primHandle() const
{
return abi_bundleHandle();
}
/**
* @deprecated Calling abi_primHandle() is deprecated. Use abi_bundleHandle() instead!
*/
[[deprecated("Calling abi_primHandle() is deprecated. Use abi_bundleHandle() instead!")]]
bundleHandle_t abi_primHandle()
{
return abi_bundleHandle();
}
/**
* Return bundle factory interface.
*/
static IBundleFactory* getBundleFactoryInterface()
{
static omni::core::ObjectPtr<IBundleFactory> factory =
carb::getCachedInterface<ComputeGraph>()->getBundleFactoryInterfacePtr();
return factory.get();
}
/**
* @return the raw bundle handle for use via the ABI directly
*/
bundleHandle_t const abi_bundleHandle() const
{
if (isValid())
return getBundleHandle(readOnly_t{});
return {};
}
/**
* @return the raw bundle handle for use via the ABI directly
*/
bundleHandle_t abi_bundleHandle()
{
if (isValid())
return getBundleHandle(readOnly_t{});
return {};
}
/**
* @return the raw bundle interface for use via the ABI directly
*/
bundleInterface_t* abi_bundleInterface() const
{
return m_bundlePtr.get();
}
/**
* @return true if the handle points to valid data within the fabric
*/
bool isValid() const
{
return m_bundlePtr && m_bundlePtr->isValid();
}
/**
* Set the bundle for evaluation. Delayed so that the contents can be created
* early with just-in-time initialization.
*
* @param bundle Evaluation context to use when extracting information
*/
void reset(omni::core::ObjectParam<bundleInterface_t> bundle)
{
m_bundlePtr = omni::core::borrow(bundle.get());
clearAttributeCache();
}
/**
* Set the context and prim handle for evaluation. Delayed so that the contents can be created
* early with just-in-time initialization.
*
* @param context Evaluation context to use when extracting information
* @param handle Virtual prim implementing the bundle interface
*/
void reset(GraphContextObj const& context, bundleHandle_t handle)
{
reset(getInterface(readOnly_t{}, context, handle));
}
/**
* @deprecated Calling size() is deprecated. Use attributeCount instead!
*/
[[deprecated("Calling size() is deprecated. Use attributeCount instead!")]]
size_t size() const
{
return attributeCount();
}
/**
* @return The number of attributes contained within the bundle if valid, 0 otherwise
*/
size_t attributeCount() const
{
return isValid() ? m_bundlePtr->getAttributeCount() : 0;
}
/**
* @return The number of child bundles contained within the bundle if valid, 0 otherwise
*/
size_t childCount() const
{
return isValid() ? m_bundlePtr->getChildBundleCount() : 0;
}
/**
* Extract the interface for an attribute in the bundle with the given name.
*
* @param[in] name Token representing the name of the attribute in the bundle
* @return Bundle member from which attribute information can be extracted (invalid if name was not found)
*/
runtime_t const attributeByName(NameToken const& name) const
{
if ((name == omni::fabric::kUninitializedToken) or ! isValid())
{
return runtime_t();
}
updateAttributeCache();
auto namedAttribute = extractNamedAttribute(readOnly_t(), name);
return runtime_t(m_bundlePtr->getContext(), namedAttribute);
}
/**
* Iteration interfaces that just pass through responsibility to the underlying span data.
* Inputs call with const objects, hence the two variations of the functions.
*/
iterator begin() const
{
updateAttributeCache();
return m_iterableArray.begin();
}
iterator end() const
{
updateAttributeCache();
return m_iterableArray.end();
}
reverse_iterator rbegin() const
{
updateAttributeCache();
return m_iterableArray.rbegin();
}
reverse_iterator rend() const
{
updateAttributeCache();
return m_iterableArray.rend();
}
iterator begin()
{
updateAttributeCache();
return m_iterableArray.begin();
}
iterator end()
{
updateAttributeCache();
return m_iterableArray.end();
}
reverse_iterator rbegin()
{
updateAttributeCache();
return m_iterableArray.rbegin();
}
reverse_iterator rend()
{
updateAttributeCache();
return m_iterableArray.rend();
}
/**
* Assignment operator is only active for writable bundle contents (i.e. outputs)
* Copies the entire input bundle onto the output.
*
* @param[in] toBeCopied Bundle attribute to be copied
* @returns Reference to this bundle
*/
template <eAttributeType AttributeTypeToCopy, eMemoryType MemoryTypeToCopy, PtrToPtrKind GpuPtrTypeToCopy = PtrToPtrKind::eNotApplicable>
BundleContents<AttributeType, MemoryType, GpuPtrType>& operator=(const BundleContents<AttributeTypeToCopy, MemoryTypeToCopy, GpuPtrTypeToCopy>& toBeCopied)
{
static_assert(!readOnly, "Assignment is not allowed on input bundles");
m_bundlePtr->clearContents();
m_bundlePtr->copyBundle(toBeCopied.abi_bundleHandle());
reset(m_bundlePtr);
return *this;
}
/**
* Bundle insertion is only active for writable bundle contents (i.e. outputs)
* Adds the entire input bundle onto the output.
*
* @param[in] toBeInserted Bundle attribute to be inserted
* @returns Reference to this bundle
*/
template <eAttributeType AttributeTypeToInsert, eMemoryType MemoryTypeToInsert, PtrToPtrKind GpuPtrTypeToInsert = PtrToPtrKind::eNotApplicable>
void insertBundle(const BundleContents<AttributeTypeToInsert, MemoryTypeToInsert, GpuPtrTypeToInsert>& toBeInserted)
{
static_assert(!readOnly, "Bundle insertion is not allowed on input bundles");
if (! toBeInserted.isValid())
{
CARB_LOG_ERROR("Cannot insert an invalid bundle");
return;
}
if (! isValid())
{
CARB_LOG_ERROR("Cannot insert into an invalid bundle");
return;
}
m_bundlePtr->copyBundle(toBeInserted.abi_bundleHandle());
reset(m_bundlePtr);
}
/**
* Clear the entire bundle contents (outputs only).
*/
bool clear()
{
static_assert(!readOnly, "Clearing of input bundles is not allowed");
if (!isValid())
{
CARB_LOG_ERROR("Cannot clear an invalid bundle");
return false;
}
clearAttributeCache();
return OMNI_SUCCEEDED(m_bundlePtr->clearContents(true));
}
/**
* Copy an attribute into the bundle. If no name is passed in then use the attribute's current name.
*/
template <typename RuntimeAttributeType>
bool insertAttribute(RuntimeAttributeType const& attributeToCopy,
NameToken newName = omni::fabric::kUninitializedToken)
{
static_assert(!readOnly, "Attribute insertion is not allowed on input bundles");
if (!isValid())
{
CARB_LOG_ERROR("Cannot insert into an invalid bundle");
return false;
}
clearAttributeCache();
AttributeDataHandle attrib = m_bundlePtr->copyAttribute(attributeToCopy.abi_handle(), true, newName);
return attrib.isValid();
}
/**
* Create a new attribute in the bundle.
*
* @param[in] attributeName Name for the new attribute
* @param[in] attributeType Base type for the attribute
* @param[in] elementCount If an array type then this is the initial element count
* @return Runtime attribute wrapper for the newly created attribute
*/
runtime_t addAttribute(NameToken const& attributeName, Type const& attributeType, size_t elementCount = 0)
{
static_assert(!readOnly, "Attribute addition is not allowed on input bundles");
if (! isValid())
{
CARB_LOG_ERROR("Cannot add to an invalid bundle");
return runtime_t();
}
clearAttributeCache();
auto attribHandle = m_bundlePtr->createAttribute(attributeName, attributeType, elementCount);
return runtime_t(m_bundlePtr->getContext(), attribHandle);
}
/**
* Add a batch of attributes to a bundle prim.
*
* @param[in] attributeCount Number of attributes to be added
* @param[in] attrNames Array of names for the new attributes
* @param[in] attrTypes Array of types for the new attributes
* @return Whether addition was successful
*/
bool addAttributes(size_t attributeCount, NameToken const* attributeNames, Type const* attributeTypes)
{
static_assert(!readOnly, "Attribute addition is not allowed on input bundles");
if (! isValid())
{
CARB_LOG_ERROR("Cannot add attributes to an invalid bundle");
return false;
}
clearAttributeCache();
size_t createdCount = 0;
auto result =
m_bundlePtr->createAttributes(attributeNames, attributeTypes, attributeCount, nullptr /*elementCount*/,
nullptr /*createdAttributes*/, &createdCount);
if (OMNI_FAILED(result))
return false;
return attributeCount == createdCount;
}
/**
* Add a batch of child bundles to this bundle.
*
* @param childCount Number of children to be added
* @param childNames Array of names for the new children
* @param childHandles Output handles of child bundles, 'nullptr' can be passed if no output is required
* @return Whether addition was successful
*/
bool addChildBundles(size_t childCount, NameToken const* childNames, BundleHandle* childHandles = nullptr)
{
static_assert(!readOnly, "Attribute addition is not allowed on input bundles");
if (!isValid())
{
CARB_LOG_ERROR("Cannot add children to an invalid bundle");
return false;
}
size_t createdCount = 0;
auto result = m_bundlePtr->createChildBundles(childNames, childCount, childHandles, &createdCount);
if (OMNI_FAILED(result))
return false;
return childCount == createdCount;
}
/**
* Remove an existing attribute from the bundle.
* Silently succeeds if an attribute with the given name did not exist on the bundle
*
* @param[in] attributeName Name of the attribute to remove
*/
bool removeAttribute(NameToken const& attributeName)
{
return removeAttributes(1, &attributeName);
}
/**
* Remove a batch of attributes from a bundle prim.
*
* @param[in] attributeCount Number of attributes to be removed
* @param[in] attrNames Array of names to be removed
* @return Whether removal was successful
*/
bool removeAttributes(size_t attributeCount, NameToken const* attributeNames)
{
static_assert(!readOnly, "Attribute removal is not allowed on input bundles");
if (!isValid())
{
CARB_LOG_ERROR("Cannot remove attributes to an invalid bundle");
return false;
}
clearAttributeCache();
size_t removedCount = 0;
auto result = m_bundlePtr->removeAttributesByName(attributeNames, attributeCount, &removedCount);
if (OMNI_FAILED(result))
return false;
return removedCount == attributeCount;
}
};
//! ======================================================================
//! @class BundleChanges
//! @brief This class is designed for inspecting modifications within a bundle during its lifetime.
//!
//! The BundleChanges class enables the inspection of changes in a bundle's attributes and child bundles
//! during the lifetime of the BundleChanges instance. It keeps a record of modifications that have occurred,
//! providing a suite of functionalities to inspect these changes.
//!
//! An integral feature of BundleChanges is its automatic clearing of changes upon destruction,
//! i.e., when the instance goes out of scope. This ties the lifetime of the recorded changes tightly
//! with the BundleChanges instance, ensuring the changes do not persist beyond the intended scope.
template <bool readOnly>
class BundleChanges
{
using BundleHandle_t = std::conditional_t<readOnly, ConstBundleHandle, BundleHandle>;
public:
BundleChanges(omni::core::ObjectPtr<IBundleChanges> const& changes, BundleHandle_t handle, bool clearAtExit = true)
: m_bundleChanges(changes),
m_bundleHandle(handle),
m_clearAtExit(clearAtExit)
{
CARB_ASSERT(m_bundleChanges);
}
BundleChanges(BundleChanges const&) = delete;
BundleChanges(BundleChanges&&) = default;
BundleChanges& operator=(BundleChanges const&) = delete;
BundleChanges& operator=(BundleChanges&&) = default;
~BundleChanges()
{
if (m_clearAtExit)
{
clearChanges();
}
}
//! @brief Activates the change tracking system for a bundle.
//!
//! This method controls the change tracking system of a bundle. It's only applicable
//! for read-write bundles (when readOnly template parameter is false). For read-only
//! bundles, this method will cause a compilation error if called.
//!
//! @throws A static_assert error at compile-time if the method is called on a
//! read-only bundle.
void activate() noexcept
{
static_assert(!readOnly, "Can't activate change tracking for read-only bundle.");
CARB_ASSERT(m_bundleChanges);
m_bundleChanges->activateChangeTracking(m_bundleHandle);
}
//! @brief Deactivates the change tracking system for a bundle.
//!
//! This method controls the change tracking system of a bundle. It's only applicable
//! for read-write bundles (when readOnly template parameter is false). For read-only
//! bundles, this method will cause a compilation error if called.
//!
//! @throws A static_assert error at compile-time if the method is called on a
//! read-only bundle.
void deactivate() noexcept
{
static_assert(!readOnly, "Can't activate change tracking for read-only bundle.");
CARB_ASSERT(m_bundleChanges);
m_bundleChanges->deactivateChangeTracking(m_bundleHandle);
}
//! @brief Implicit conversion to bool.
//!
//! This operator allows an instance of BundleChanges to be automatically converted to a bool.
//! The boolean value indicates whether the bundle has undergone any changes within its lifetime.
//! It leverages the hasChanged() method to provide this information.
//!
//! @returns True if the bundle has changed; false otherwise.
operator bool() noexcept
{
return hasChanged();
}
//! @brief Clears the recorded changes.
//!
//! This method is used to manually clear the recorded changes of the bundle.
omni::core::Result clearChanges() noexcept
{
CARB_ASSERT(m_bundleChanges);
return m_bundleChanges->clearChanges();
}
//! @brief Checks if the bundle has changed.
//!
//! This method is used to check if any changes have been made to the bundle's attributes or child bundles
//! within the lifetime of the BundleChanges instance.
//!
//! @returns True if the bundle has changed; false otherwise.
bool hasChanged() noexcept
{
CARB_ASSERT(m_bundleChanges);
return m_bundleChanges->getChange(m_bundleHandle) != BundleChangeType::None;
}
//! @brief Retrieves the change status of a specific attribute.
//!
//! This method is used to check if a specific attribute of the bundle has been modified
//! within the lifetime of the BundleChanges instance.
//!
//! @param attribute The specific attribute of the bundle to check for modifications.
//!
//! @returns True if the specified attribute has changed; false otherwise.
template <eAttributeType AttributeType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType>
BundleChangeType getChange(RuntimeAttribute<AttributeType, MemoryType, GpuPtrType> const& attribute) noexcept
{
CARB_ASSERT(m_bundleChanges);
auto const handle = attribute.abi_handle();
return m_bundleChanges->getChange(handle);
}
//! @brief Retrieves the change status of a specific bundle.
//!
//! This method is used to check if a specific bundle or its contents have been modified
//! within the lifetime of the BundleChanges instance.
//!
//! @param bundle The specific bundle to check for modifications.
//!
//! @returns A BundleChangeType value indicating the type of change (if any) that has occurred to the specified
//! bundle.
template <eAttributeType AttributeType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType>
BundleChangeType getChange(BundleContents<AttributeType, MemoryType, GpuPtrType> const& bundle) noexcept
{
CARB_ASSERT(m_bundleChanges);
auto const handle = bundle.abi_bundleHandle();
return m_bundleChanges->getChange(handle);
}
//! @brief Retrieves the change status of a specific bundle or attribute using its handle.
//!
//! This function is used to check if a specific bundle or attribute, identified by its handle, has been modified
//! within the lifetime of the BundleChanges instance.
//!
//! @tparam HANDLE_TYPE The type of the handle (ConstBundleHandle or ConstAttributeDataHandle).
//! @param handle The handle to the specific bundle or attribute to check for modifications.
//!
//! @returns A BundleChangeType value indicating the type of change (if any) that has occurred to the bundle or
//! attribute associated with the specified handle.
template <typename HANDLE_TYPE>
BundleChangeType abi_getChange(HANDLE_TYPE const& handle) noexcept
{
constexpr auto isBundle =
std::is_same<HANDLE_TYPE, ConstBundleHandle>::value || std::is_same<HANDLE_TYPE, BundleHandle>::value;
constexpr auto isAttrib =
std::is_same<HANDLE_TYPE, ConstAttributeDataHandle>::value || std::is_same<HANDLE_TYPE, AttributeDataHandle>::value;
static_assert(isBundle || isAttrib, "Unsupported handle type for abi_getChange!");
CARB_ASSERT(m_bundleChanges);
return m_bundleChanges->getChange(handle);
}
private:
omni::core::ObjectPtr<IBundleChanges> m_bundleChanges;
BundleHandle_t m_bundleHandle;
bool m_clearAtExit;
};
// ======================================================================
/**
* Template class responsible for managing the interaction with bundle type input attributes.
* It wraps the bundle in an interface with a more natural interaction than the raw ABI calls.
*
* <AttributeType> How the attribute is interpreted - input, output, or state value
* <MemoryType> where the memory for the attributes in this bundle will live (CPU, GPU, or decided at runtime)
*/
template <eAttributeType AttributeType, eMemoryType MemoryType, PtrToPtrKind GpuPtrType = PtrToPtrKind::eNotApplicable>
struct BundleAttribute
{
//friend with other templates
template <eAttributeType, eMemoryType, PtrToPtrKind>
friend struct BundleAttribute;
private :
//! Aliases used during overload resolution to differentiate between read-only and read-write.
using roTag_t = std::true_type;
using rwTag_t = std::false_type;
// The writability of a bundle will determine what kinds of operations can be performed on it
static constexpr bool readOnly = (AttributeType == kOgnInput);
using readOnly_t = std::conditional_t<AttributeType == kOgnInput, roTag_t, rwTag_t>;
using bundleHandle_t = std::conditional_t<readOnly, ConstBundleHandle, BundleHandle>;
/**
* Construct bundle interface based on provided context and bundle handle.
*
* @param context Evaluation context.
* @param handle Bundle handle.
*/
auto getInterface(rwTag_t, GraphContextObj const& context, bundleHandle_t handle) const
{
auto iComputeGraph = carb::getCachedInterface<ComputeGraph>();
auto factory = iComputeGraph->getBundleFactoryInterfacePtr();
return factory->getBundle(context, handle);
}
auto getInterface(roTag_t, GraphContextObj const& context, bundleHandle_t handle) const
{
auto iComputeGraph = carb::getCachedInterface<ComputeGraph>();
auto factory = iComputeGraph->getBundleFactoryInterfacePtr();
return factory->getConstBundle(context, handle);
}
/**
* Bundle attributes always live on the CPU since they are always small, containing only a single value through
* which their contents can be referenced. The memory type is passed down though, to provide the appropriate
* interfaces to the attributes within the bundle.
*
* @param[in] index In vectorized context, the instance index to access
* @return The corresponding bundle handle
*/
bundleHandle_t bundleHandle(size_t index = 0) const
{
bundleHandle_t* rel = m_bundleHandleArrayPtr ? m_bundleHandleArrayPtr[m_offset + index] : nullptr;
//TODO: multiple input rel
return rel ? rel[0] : bundleHandle_t{ bundleHandle_t::invalidValue() };
}
// --------------------------------------------------------------------------------------------------------------
//! Data members
//! Pointer to the vectorized set of data
bundleHandle_t** m_bundleHandleArrayPtr{ nullptr };
//! ABI OmniGraph context object
const GraphContextObj* m_context{ nullptr };
//! Interface to the bundle data, constructed on demand
BundleContents<AttributeType, MemoryType, GpuPtrType> m_bundle;
//! In vectorized context, offset at which we should read our handle
size_t const& m_offset;
//! Top level bundle change tracking
omni::core::ObjectPtr<IBundleChanges> m_bundleChanges;
public:
// --------------------------------------------------------------------------------------------------------------
/**
* Set up the accessor for output attributes with Bundle data
*/
BundleAttribute(size_t const& offset)
: m_offset(offset)
{
}
/**
* Bundle attributes always live on the CPU since they are always small, containing only a single value through
* which their contents can be referenced. The memory type is passed down though, to provide the appropriate
* interfaces to the attributes within the bundle.
*
* @param[in] index In vectorized context, the instance index to access
* @return Reference to the raw fabric data.
*/
BundleContents<AttributeType, MemoryType, GpuPtrType>& operator()(size_t index = 0)
{
CARB_ASSERT(context());
m_bundle.reset(*context(), bundleHandle(index));
return m_bundle;
}
/**
* Set the evaluation context for the attribute to allow later access. The data isn't available at construction
* time so this method is provided to add it in when it becomes available.
*
* @param[in] contextObj OmniGraph context object to which this attribute belongs
*/
void setContext(const GraphContextObj& contextObj)
{
m_context = &contextObj;
m_bundleChanges.release();
}
/**
* Set the attribute handle for input bundles
*
* @param[in] handle Handle to the attribute to which the bundle belongs
*/
void setHandle(ConstAttributeDataHandle handle)
{
m_context->iAttributeData->getDataR((const void**)&m_bundleHandleArrayPtr, *m_context, &handle, 1);
m_bundleChanges.release();
}
/**
* Retrieve the context object
*
*/
GraphContextObj const* context() const
{
return m_context;
}
/**
* @param[in] index In vectorized context, the instance index to access
* @return The path to the bundle data
*/
char const* path(size_t index = 0) const
{
auto bundlePtr = getInterface(readOnly_t{}, *context(), bundleHandle(index));
if (!bundlePtr)
{
return nullptr;
}
omni::fabric::PathC path = bundlePtr->getPath();
return carb::getCachedInterface<omni::fabric::IPath>()->getText(path);
}
/**
* @param[in] index In vectorized context, the instance index to access
* @return True if the underlying attribute data is valid for accessing
*/
bool isValid(size_t index = 0) const
{
return bundleHandle(index).isValid();
}
/**
* Assignment operator is only active for writable bundle contents (i.e. outputs).
* At this level if the data is being stolen it redirects the output to point to the input, otherwise it
* copies the entire bundle.
*
* @note Any accessors to this bundle (operator()) must be called after the assignment or they will be invalid
*
* @param[in] toBeCopied Bundle attribute from which this one will be redirected or copied
* @returns Reference to this bundle
*/
template <eAttributeType AttributeTypeToCopy, eMemoryType MemoryTypeToCopy, PtrToPtrKind GpuPtrTypeToCopy = PtrToPtrKind::eNotApplicable>
BundleAttribute<AttributeType, MemoryType, GpuPtrType>& operator=(const BundleAttribute<AttributeTypeToCopy, MemoryTypeToCopy, GpuPtrTypeToCopy>& toBeCopied)
{
static_assert(!readOnly, "Assignment is not allowed on input bundles");
if (!context() || !toBeCopied.isValid())
{
CARB_LOG_ERROR_ONCE("Could not assign to or from invalid bundle attribute");
return *this;
}
auto bundlePtr = getInterface(readOnly_t{}, *context(), bundleHandle());
if (bundlePtr)
{
bundlePtr->clearContents(true);
bundlePtr->copyBundle(toBeCopied.bundleHandle());
}
return *this;
}
//! @brief Retrieves the `BundleChanges` object.
//!
//! The `changes` function returns the `BundleChanges` object associated with requested instance.
//! It allows access to the bundle change tracking.
//!
//! @return Returns the `BundleChanges` object associated with requested instance.
BundleChanges<readOnly> changes(size_t instanceIndex = 0, bool clearAtExit = true) noexcept
{
CARB_ASSERT(context());
if (!m_bundleChanges)
{
m_bundleChanges = carb::getCachedInterface<ComputeGraph>()->getBundleChangesInterfacePtr(*context());
}
return { m_bundleChanges, bundleHandle(instanceIndex), clearAtExit };
}
};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 41,258 | C | 38.182336 | 161 | 0.669228 |
omniverse-code/kit/include/omni/graph/core/ogn/SimpleRuntimeAttribute.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <omni/graph/core/ogn/RuntimeAttribute.h>
#include <omni/graph/core/ogn/SimpleAttribute.h>
namespace omni
{
namespace graph
{
namespace core
{
namespace ogn
{
template <typename RTAttrib>
struct SimpleRTAttrib
{
using dataHandle_t = typename RTAttrib::dataHandle_t;
using attrib_t = typename std::remove_const<RTAttrib>::type;
using this_t = SimpleRTAttrib<RTAttrib>;
private:
size_t const& m_offset;
attrib_t m_attrib;
size_t m_rootHandleOffset{0};
bool m_dirty{ false };
AttributeObj m_dirtyPendingObj;
public:
SimpleRTAttrib(size_t const& offset)
: m_offset(offset)
{}
SimpleRTAttrib(SimpleRTAttrib const& other) = default;
SimpleRTAttrib(SimpleRTAttrib&&) = default;
SimpleRTAttrib& operator=(SimpleRTAttrib const& other)
{
const_cast<size_t&>(m_offset) = other.m_offset;
m_attrib = other.m_attrib;
m_rootHandleOffset = other.m_rootHandleOffset;
m_dirty = other.m_dirty;
m_dirtyPendingObj = other.m_dirtyPendingObj;
return *this;
}
SimpleRTAttrib& operator=(SimpleRTAttrib&&) = default;
/**
* @return Reference to the inner runtime attribute
*/
RTAttrib& operator()(size_t index = 0)
{
static const dataHandle_t kInvalidHandle = dataHandle_t{ dataHandle_t::invalidValue() };
if (m_dirty)
{
auto hdl = m_dirtyPendingObj.iAttribute->getAttributeDataHandle(m_dirtyPendingObj, { m_rootHandleOffset });
m_attrib.reset(m_attrib.abi_context(), hdl, m_dirtyPendingObj);
m_dirtyPendingObj = { nullptr, kInvalidAttributeHandle };
m_dirty = false;
}
//if our attrib already points to something...
if (m_attrib.abi_handle() != kInvalidHandle)
{
//check that this something is actually the asked instance
auto offset = index + m_offset;
if (offset != m_rootHandleOffset)
{
//if not, make it point to the proper instance
m_attrib.adjustHandle(offset - m_rootHandleOffset);
//... and keep trace of which instance is currently pointed
m_rootHandleOffset = offset;
}
}
return m_attrib;
}
RTAttrib const& operator()(size_t index = 0) const
{
return const_cast<this_t*>(this)->operator()(index);
}
/**
* @return True if the attribute can be accessed for vectorized compute
*/
bool const canVectorize() const
{
return m_attrib.canVectorize();
}
void const fetchDetails(const AttributeObj& attr)
{
//This is called on type resolution changes, lots of other changes are probably going to happen on the graph
// So do not fetch anything right away at this would force a useless graph bucket creation,
// and just defer the fetch on first access
m_dirty = true;
m_dirtyPendingObj = attr;
}
};
template <eAttributeType AttributeType, eMemoryType MemoryType, eMemoryType DUMMY, PtrToPtrKind GpuPtrType>
struct SimpleInput<const RuntimeAttribute<AttributeType, MemoryType, GpuPtrType>, DUMMY>
: public SimpleRTAttrib< const RuntimeAttribute<AttributeType, MemoryType, GpuPtrType> >
{
using super = SimpleRTAttrib< const RuntimeAttribute<AttributeType, MemoryType, GpuPtrType> >;
SimpleInput(size_t const& offset) : super(offset) {}
};
template <eAttributeType AttributeType, eMemoryType MemoryType, eMemoryType DUMMY, PtrToPtrKind GpuPtrType>
struct SimpleWritableAttribute<RuntimeAttribute<AttributeType, MemoryType, GpuPtrType>, AttributeType, DUMMY>
: public SimpleRTAttrib< RuntimeAttribute<AttributeType, MemoryType, GpuPtrType> >
{
using super = SimpleRTAttrib< RuntimeAttribute<AttributeType, MemoryType, GpuPtrType> >;
SimpleWritableAttribute(size_t const& offset) : super(offset) {}
};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 4,453 | C | 33 | 119 | 0.679991 |
omniverse-code/kit/include/omni/graph/core/ogn/State.h | // 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.
//
#pragma once
#include <omni/graph/core/iComputeGraph.h>
#include <tbb/concurrent_hash_map.h>
#include <memory>
// =================================================================================================================
// This file contains simple interface classes which wrap data in the OGN database for easier use.
//
// StateManager Class that automatically manages per-node state data
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// ======================================================================
/**
* This class structure provides support for internal state data. The reason for such a tricky implementation is to
* make it easier to access from the node implementation code. At compute time only the database is accessible, so
* the state information is best retrieved from there. At the same time the minimal amount of effort required to set
* up state information is to put it in the node implementation class, so the database needs to know how the class is
* structured and the class needs to know how the database is structured, leading to a recursive inclusion, not handled
* well by C++.
*
* Instead of this a templated state manager is instantiated by the .ogn generation code that lives as a static member
* of the generated database class. The template parameters hide the fact that the state exists in the not-yet-defined
* node implementation class, at the cost of requiring the class be mentioned when retrieving the state information.
*
* Inside the node's compute method the state information is retrieved as:
* auto& state = db.internalState<OgnMyNode>();
*/
struct StateManager
{
// As the map from NodeHandle to the state information cannot know the template type (not yet defined as per the
// above explanation) this base class is set up as a basic form of type hiding. This way the map can hold
// references to the heterogeneous set of templated state information. This is safe because every NodeHandle will
// uniquely reference a different type of state class, and the virtual base class hides that fact from the
// non-templated part of this manager.
struct StateHolderBase
{
virtual ~StateHolderBase() {}
};
// The templated holder class provides access to the underlying state information.
template <typename StateInformationClass>
struct StateHolder : StateHolderBase
{
std::unique_ptr<StateInformationClass> m_stateObject;
StateHolder() : m_stateObject{ std::make_unique<StateInformationClass>() } {}
StateInformationClass& value() { return *m_stateObject; }
};
using Key = std::pair<NodeHandle, size_t>;//pair of the node and the graph instance ID (ie. represent a unique node in a unique graph instance)
using ConcurrentHashMap = tbb::concurrent_hash_map<Key, std::unique_ptr<StateHolderBase>>;
using WriteAccessor = typename ConcurrentHashMap::accessor;
// This method provides access to the
template <typename StateInformationClass>
StateInformationClass& getState(NodeHandle value, InstanceIndex idx = kAccordingToContextIndex)
{
// It would have been better to avoid having a state manager at all when no state exists but a simple method
// of doing so was not found. This approach looked promising but suffered from the same circular dependency
// that mandated the current approach: https://stackoverflow.com/questions/25492589/
// Here we at least let the node writer know that they need to add state for this call to make sense.
static_assert(!std::is_empty<StateInformationClass>::value, "State class is empty");
Key k{ value, carb::getCachedInterface<INode>()->getGraphInstanceID(value, idx).token};
WriteAccessor writeIt;
if(!m_managedState.find(writeIt, k))
{
m_managedState.emplace(writeIt, k, std::make_unique<StateHolder<StateInformationClass>>());
}
// This is the magic that lets a generic map correctly handle members of templated types. We've
// constructed the class to guarantee that a reinterpret_cast will work, avoiding the more expensive
// dynamic_cast, and since this method is templated the exact type for casting is known.
return (reinterpret_cast<StateHolder<StateInformationClass>*>(writeIt->second.get()))->value();
}
// As the lifespan of node handles is limited they must remove themselves from the state map when they are
// released. Note that this is required due to the fact that the node implementation classes are not
// themselves instantiated, except for this state management. The NodeHandle refers to a unique instantiation
// of a node of a particular type in a unique OmniGraph evaluation context.
//
// This method does not need to be templated because the underlying StateHolder knows how to destroy its type.
void removeState(NodeHandle value, NameToken instanceID)
{
Key k{ value, instanceID.token };
m_managedState.erase(k);
}
// Quick lookup of state information associated with a node, using the base class type to mask the templated
// type that lies beneath. Using a unique_ptr ensures it is properly destroyed when the node is released.
ConcurrentHashMap m_managedState;
};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 6,196 | C | 52.422413 | 147 | 0.701259 |
omniverse-code/kit/include/omni/graph/core/ogn/string.h | // 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.
//
#pragma once
// =================================================================================================================
// This file contains simple interface classes which wrap data in the OGN database for easier use.
//
// ogn::const_string Read-only access to a string in fabric
// ogn::string Writable access to a string in fabric, with resizing and reallocation wrapped in
// string-like functions
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
#include <gsl/string_span>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/ogn/Types.h>
#include <algorithm>
#include <string>
#include <stdexcept>
namespace omni {
namespace graph {
namespace core {
namespace ogn {
/**
* std::string_view-like wrapper class for string attribute data in the Ogn Database.
* As of this writing OGN is built on C++14 and std::string_view requires C++17 so the Microsoft forward
* compatible implementaton of gsl::string_span<> is used.
* *
* This wrapper operates by using the Fabric interface to interact with string data it has stored.
* The base string class provides common operations common to both const and non-const data.
*/
template <typename CharType, typename HandleType>
class base_string : public base_array<CharType, HandleType>
{
public:
/**
* @return The number of elements in the currently managed array
*/
size_t length() const
{
return this->size();
}
/**
* Cast the string data to a std::string.
*
* After you do this the string data is now a copy of the original so you can manipulate it without
* affecting the original, however it means you must reassign it back to a writable ogn::string if you
* do want to change the string.
*
* @return String containing a copy of the internal raw string data
*/
operator std::string() const
{
auto const& spanObj = this->span();
if (spanObj.data())
{
return std::string{ spanObj.data(), spanObj.size() };
}
return std::string{};
}
/**
* See if two strings are equal.
*
* These simple comparison operators avoid extra conversions to std::string, to help minimize allocations
*
* @tparam IterableStringType String variant that supports iteration for comparison
* @param[in] rhs String to compare against - just requires iterability
* @return True if the strings have the same contents
*/
template <typename IterableStringType>
bool operator==(const IterableStringType& rhs) const
{
return this->data() ? std::equal(this->begin(), this->end(), rhs.begin(), rhs.end()) : (rhs.begin() == rhs.end());
}
/**
* See if two strings are not equal.
*
* These simple comparison operators avoid extra conversions to std::string, to help minimize allocations
*
* @tparam IterableStringType String variant that supports iteration for comparison
* @param[in] rhs String to compare against - just requires iterability
* @return True if the strings do not have the same contents
*/
template <typename IterableStringType>
bool operator!=(const IterableStringType& rhs) const
{
return this->data() ? !std::equal(this->begin(), this->end(), rhs.begin(), rhs.end()) :
(rhs.begin() != rhs.end());
}
/**
* See if this string is lexicographically less than the provided one.
*
* These simple comparison operators avoid extra conversions to std::string, to help minimize allocations
*
* @tparam IterableStringType String variant that supports iteration for comparison
* @param[in] rhs String to compare against - just requires iterability
* @return True if this string is lexicographically less than the provided one
*/
template <typename IterableStringType>
bool operator<(const IterableStringType& rhs) const
{
return std::lexicographical_compare(this->begin(), this->end(), rhs.begin(), rhs.end());
}
/**
* See if this string is lexicographically greater than the provided one.
*
* These simple comparison operators avoid extra conversions to std::string, to help minimize allocations
*
* @tparam IterableStringType String variant that supports iteration for comparison
* @param[in] rhs String to compare against - just requires iterability
* @return True if this string is lexicographically greater than the provided one
*/
template <typename IterableStringType>
bool operator>(const IterableStringType& rhs) const
{
return std::lexicographical_compare(rhs.begin(), rhs.end(), this->begin(), this->end());
}
/**
* See if this string is lexicographically less than or equal to the provided one.
*
* These simple comparison operators avoid extra conversions to std::string, to help minimize allocations
*
* @tparam IterableStringType String variant that supports iteration for comparison
* @param[in] rhs String to compare against - just requires iterability
* @return True if this string is lexicographically less than or equal to the provided one
*/
template <typename IterableStringType>
bool operator<=(const IterableStringType& rhs) const
{
return operator<(rhs) || operator==(rhs);
}
/**
* See if this string is lexicographically greater than or equal to the provided one.
*
* These simple comparison operators avoid extra conversions to std::string, to help minimize allocations
*
* @tparam IterableStringType String variant that supports iteration for comparison
* @param[in] rhs String to compare against - just requires iterability
* @return True if this string is lexicographically greater than or equal to the provided one
*/
template <typename IterableStringType>
bool operator>=(const IterableStringType& rhs) const
{
return operator>(rhs) || operator==(rhs);
}
};
/**
* std::string_view-like wrapper class for constant string attribute data in the Ogn Database.
* It operates by using the Fabric interface to interact with string data it has stored.
* This const version of the string wrapper should be used for input attributes, whose data cannot be changed.
*
*/
class const_string : public base_string<const char, ConstAttributeDataHandle>
{
// from regular attributes
template <typename, eAttributeType, eMemoryType, PtrToPtrKind>
friend struct ArrayAttribute;
// from runtime attributes
template <typename, bool, eMemoryType, PtrToPtrKind>
friend struct ArrayData;
public:
/**
* Default constructor to start pointing to nothing.
*/
const_string() = default;
};
/**
* std::string_view-like class for string output attribute data in the Ogn Database.
* It operates by using the Fabric interface to interact with string data it has stored.
* This non-const version of the string wrapper should be used for output attributes, whose data will be changed.
*
*/
class string : public base_string<char, AttributeDataHandle>
{
public:
/** Type of the parent class */
using parent_t = base_string<char, AttributeDataHandle>;
// Make non-templated functions available to pass 1 of template resolution
// http://www.gotw.ca/gotw/087.htm
using base_string::data;
using base_string::size;
using base_string::reset;
/**
* Default constructor to start pointing to nothing.
*/
string() = default;
/**
* Set the size of the array data to a new value.
*
* This may or may not relocate memory. If anything is holding a raw pointer from contents()
* that pointer should be refreshed by calling contents() again when this method returns.
*
* @param[in] newCount New element count of the array.
*/
void resize(size_t newCount)
{
CUDA_SAFE_ASSERT(isValid());
const IAttributeData& iData = *(this->context()->iAttributeData);
iData.setElementCount(*this->context(), this->handle(), newCount);
this->setDirty();
}
/**
* @return Non-const pointer to the raw string data
*/
char* data()
{
return const_cast<char*>(this->span().data());
}
/**
* Access a specific character in the string. No bounds checking is performed.
*
* @param[in] index Element index into the string
* @return Reference to the index'th character of the string
*/
char& operator[](size_t index)
{
return const_cast<char&>(this->operator[](index));
}
/**
* Access a specific character in the string. Bounds checking is performed.
*
* @param[in] index Element index into the string
* @return Reference to the index'th character of the string
*/
char& at(size_t index)
{
return const_cast<char&>(this->at(index));
}
/**
* Assignment of a raw sized string to this object, used by all variations.
*
* This will create a duplicate of all string members and reset the references into the Fabric, leaving the
* context and the handle unchanged.
*
* @param[in] dataToCopy The string being copied in
* @param[in] charCount The number of characters in the string being copied
* @return Pointer to this
*/
string& assign(char const* dataToCopy, size_t charCount)
{
CUDA_SAFE_ASSERT(isValid());
// Resize this string first so that it has the proper space to receive the new data
resize(charCount);
if (charCount == 0)
{
// No work to do when the new string is empty
return *this;
}
std::memcpy(data(), dataToCopy, charCount);
return *this;
}
/**
* Generic string assignment operator
*
* This template handles all compatible string types with a data() and size() method. At minimum
* ogn::string, ogn::const_string, std::string, const std::string
*
* @param[in] rhs The string being copied in
* @return Pointer to this
*/
template <typename StringType>
string& operator=(StringType& rhs)
{
return assign(rhs.data(), rhs.size());
}
/**
* const char* assignment operator (avoids alloc, and disambiguates between std::string and ogn::const_string)
*
* This will create a duplicate of all string members and reset the references into the Fabric, leaving the
* context and the handle unchanged.
*
* @param[in] rhs The string being copied in
* @return Pointer to this
*/
string& operator=(const char* rhs)
{
return assign(rhs, rhs ? std::strlen(rhs) : 0);
}
/**
* Standard method to clear a string, i.e. assign the empty string to it.
* Since the null terminator is not needed in fabric the string truly is empty
*/
void clear()
{
resize(0);
}
};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 11,815 | C | 35.134556 | 122 | 0.656115 |
omniverse-code/kit/include/omni/graph/core/ogn/AttributeInitializer.h | // 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.
//
#pragma once
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/ogn/Types.h>
// =================================================================================================================
// This file contains simple interface classes which wrap data in the OGN database for easier use.
//
// AttributeInitializer Generated code uses this to store unchanging attribute information
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// Determine if the underlying data type can be copy-constructed or if it has to use a raw memcpy
template<class DataType>
constexpr bool needs_memcpy_v = ! std::is_copy_constructible<DataType>::value;
// Copy an array into the default value, where the array elements are copy-constructible
template <typename FromDataType, typename ToDataType, std::enable_if_t<! needs_memcpy_v<std::remove_pointer_t<ToDataType>>, int> = 0>
void copyArrayValue(FromDataType from, ToDataType& to, size_t elementCount)
{
if (elementCount == 0)
{
to = nullptr;
return;
}
to = new std::remove_pointer_t<ToDataType>[elementCount];
for (size_t i=0; i<elementCount; ++i)
{
to[i] = from[i];
}
}
// Copy an array into the default value, where the array elements are not copy-constructible and have to be memcpy'd
template <typename FromDataType, typename ToDataType, std::enable_if_t<needs_memcpy_v<std::remove_pointer_t<ToDataType>>, int> = 0>
void copyArrayValue(FromDataType from, ToDataType& to, size_t elementCount)
{
if (elementCount == 0)
{
to = nullptr;
return;
}
to = new std::remove_pointer_t<ToDataType>[elementCount];
memcpy(to, from, elementCount * sizeof(std::remove_pointer_t<ToDataType>));
}
template <typename DataType, std::enable_if_t<std::is_pointer<DataType>::value, int> = 0>
void destroyArrayValue(DataType& defaultValuePointer)
{
delete [] defaultValuePointer;
}
template <typename DataType, std::enable_if_t<! std::is_pointer<DataType>::value, int> = 0>
void destroyArrayValue(DataType&)
{
}
// ======================================================================
/**
* Templated class containing the minimal amount of information required to
* manage the information on attributes that is independent of evaluation context.
* Some of the structures are a little non-standard, intentionally so to make
* access to the attribute and node type ABI easier.
*
* The DataType of the attribute is solely used for storing its default value. For single values the default member is
* an instance of the attribute data type. For arrays it is a pointer to the type, used in conjunction with an element
* count to determine the size of the array.
*
* None of this interface should be called directly; only from generated code.
* The "attributeType" template parameter is used to selectively enable or disable features
* that are specific to input, output, or state types (e.g. the INodeType method addInput/addOuput/addState)
*/
template <typename DataType, ogn::eAttributeType attributeType = ogn::kOgnInput>
struct AttributeInitializer
{
// This is needed due to the way const types are specified. add_const(int*) -> "int* const", not "int const*"
using DefaultParameterType = std::conditional_t<
std::is_pointer<DataType>::value,
std::add_pointer_t<std::add_const_t<std::remove_pointer_t<DataType>>>,
std::add_const_t<DataType>&
>;
using DefaultMemberType = std::conditional_t<
std::is_pointer<DataType>::value,
std::add_pointer_t<std::remove_const_t<std::remove_pointer_t<DataType>>>,
std::remove_const_t<DataType>
>;
// TODO: Much of this information is already stored internally; there should be a way to avoid this duplication
const char* m_name{ nullptr }; //!< Unique name of this attribute
const char* m_dataType{ nullptr }; //!< Identifying name for the data type of the attribute
NameToken m_token; //!< Unique token for this attribute's name
DefaultMemberType m_defaultValue; //!< Default value for this attribute
size_t m_elementCount{ 0 }; //!< Element count for the attribute values type
ExtendedAttributeType m_extendedType{kExtendedAttributeType_Regular}; //!< Extended type of this attribute
bool m_isRequired{ true }; //!< Is the attribute required?
bool m_hasDefaultValue{ false }; //!< Was a default value explicitly set?
bool m_hasElementCount{ false }; //!< Was an element count value explicitly set?
/**
* This interface is helpful in nodes, to make it easier to find attributes by name.
* Internal storage may change but this method will continue to exist.
* @return Pointer to raw string with attribute name in it
*/
const char* name() const { return m_name; }
/**
* This interface is helpful in nodes, to make it easier to find attributes by name
* Internal storage may change but this method will continue to exist.
* @return Token with the attribute name in it
*/
NameToken const& token() const { return m_token; }
/**
* Destroy the allocated default value
*/
~AttributeInitializer()
{
if (m_hasElementCount)
{
destroyArrayValue<DefaultMemberType>(m_defaultValue);
}
}
/**
* Minimal constructor for attributes with no defaults
*
* @param[in] attributeName Name of the attribute to be accessed
* @param[in] dataTypeName Name of the attribute's data type
* @param[in] extendedType Extended type of the attribute
*/
AttributeInitializer(const char* attributeName, const char* dataTypeName, ExtendedAttributeType extendedType)
: m_name(attributeName)
, m_dataType(dataTypeName)
, m_extendedType(extendedType)
{
}
/**
* Constructor for attributes with a default value but no element counts (i.e. not arrays) where the type supports
* a copy constructor. There is a specialization of types for strings as "const char*" is not equivalent to
* "char const*", which is required to initialize strings from a raw string.
*
* @param[in] Name of the attribute to be accessed
* @param[in] Name of the attribute's data type
* @param[in] Reference to the default value of the attribute's data type
*/
template <typename ConstructedDataType = DataType, typename std::enable_if_t<! needs_memcpy_v<ConstructedDataType>, int> = 0>
AttributeInitializer(const char* attributeName,
const char* dataTypeName,
ExtendedAttributeType extendedType,
DefaultParameterType newDefault)
: m_name(attributeName)
, m_dataType(dataTypeName)
, m_defaultValue(newDefault)
, m_extendedType(extendedType)
, m_hasDefaultValue(true)
{
}
/**
* Constructor for attributes with a default value but no element counts (i.e. not arrays) where the type does not
* support a copy constructor. There is a specialization of types for strings as "const char*" is not equivalent to
* "char const*", which is required to initialize strings from a raw string.
*
* @param[in] Name of the attribute to be accessed
* @param[in] Name of the attribute's data type
* @param[in] Reference to the default value of the attribute's data type
*/
template <typename ConstructedDataType = DataType, typename std::enable_if_t<needs_memcpy_v<ConstructedDataType>, int> = 0>
AttributeInitializer(const char* attributeName,
const char* dataTypeName,
ExtendedAttributeType extendedType,
DefaultParameterType newDefault)
: m_name(attributeName)
, m_dataType(dataTypeName)
, m_extendedType(extendedType)
, m_hasDefaultValue(true)
{
// As this constructor is only called when there is no copy constructor it's reasonable to use a plain
// memcpy to get the bytes from one object to another. They are required to be bytewise compatible.
memcpy(&m_defaultValue, &newDefault, sizeof(ConstructedDataType));
}
/**
* Constructor for array attributes with a default value where the type supports a copy constructor
*
* @param[in] Name of the attribute to be accessed
* @param[in] Name of the attribute's data type
* @param[in] Reference to the default value of the attribute's data type
* @param[in] Number of elements in the default value
*/
AttributeInitializer(const char* attributeName,
const char* dataTypeName,
ExtendedAttributeType extendedType,
DefaultParameterType newDefault,
size_t newElementCount)
: m_name(attributeName)
, m_dataType(dataTypeName)
, m_defaultValue(nullptr)
, m_elementCount(newElementCount)
, m_extendedType(extendedType)
, m_hasDefaultValue(true)
, m_hasElementCount(true)
{
copyArrayValue<DefaultParameterType, DefaultMemberType>(newDefault, m_defaultValue, newElementCount);
}
/**
* Set a default value after the fact; for types that could have problems with static initialization order
* if they tried to do this in the constructor (e.g. NameToken)
*
* @param[in] newDefault Reference to the default value of the attribute's data type
*/
void setDefault(DefaultParameterType newDefault)
{
CARB_ASSERT(m_extendedType == kExtendedAttributeType_Regular, "Extended attribute types cannot set defaults");
m_hasDefaultValue = true;
m_defaultValue = newDefault;
}
/**
* Set a default array value after the fact; for types that could have problems with static initialization order
* if they tried to do this in the constructor (e.g. NameToken[])
*
* @param[in] newDefault Reference to the default value of the attribute's data type
*/
void setDefault(DefaultParameterType newDefault, size_t elementCount)
{
CARB_ASSERT(m_extendedType == kExtendedAttributeType_Regular, "Extended attribute types cannot set defaults");
if (m_hasDefaultValue && m_elementCount > 0 && m_defaultValue)
{
delete [] m_defaultValue;
}
m_hasDefaultValue = true;
copyArrayValue<DefaultParameterType, DefaultMemberType>(newDefault, m_defaultValue, elementCount);
m_elementCount = elementCount;
}
/**
* Initializer that looks up the attribute name's token; must be done before using it.
* This variation is for input attributes.
*
* @param[in] iNodeType Node type interface to which the attribute will be added as an input
* @param[in] nodeTypeObj Node to which the attribute will be added as an input
* @param[in] enable Template metaprogrammed value that enables this version of the method when the attribute is an input
*/
template <ogn::eAttributeType enabled = attributeType>
void addToNodeType(const INodeType& iNodeType,
const NodeTypeObj& nodeTypeObj,
typename std::enable_if<enabled == ogn::kOgnInput>::type* = 0)
{
if (m_extendedType == kExtendedAttributeType_Regular)
{
iNodeType.addInput(nodeTypeObj, m_name, m_dataType, m_isRequired,
m_hasDefaultValue ? &m_defaultValue : nullptr,
m_hasElementCount ? &m_elementCount : nullptr);
}
else
{
iNodeType.addExtendedInput(nodeTypeObj, m_name, m_dataType, m_isRequired, m_extendedType);
}
}
/**
* Initializer that looks up the attribute name's token; must be done before using it.
* This variation is for output attributes.
*
* @param[in] iNodeType Node type interface to which the attribute will be added as an output
* @param[in] nodeTypeObj Node to which the attribute will be added as an output
* @param[in] enable Template metaprogrammed value that enables this version of the method when the attribute is an output
*/
template <ogn::eAttributeType enabled = attributeType>
void addToNodeType(const INodeType& iNodeType,
const NodeTypeObj& nodeTypeObj,
typename std::enable_if<enabled == ogn::kOgnOutput>::type* = 0)
{
if (m_extendedType == kExtendedAttributeType_Regular)
{
iNodeType.addOutput(nodeTypeObj, m_name, m_dataType, m_isRequired,
m_hasDefaultValue ? &m_defaultValue : nullptr,
m_hasElementCount ? &m_elementCount : nullptr);
}
else
{
iNodeType.addExtendedOutput(nodeTypeObj, m_name, m_dataType, m_isRequired, m_extendedType);
}
}
/**
* Initializer that looks up the attribute name's token; must be done before using it.
* This variation is for state attributes.
*
* @param[in] iNodeType Node type interface to which the attribute will be added as a state
* @param[in] nodeTypeObj Node to which the attribute will be added as a state
* @param[in] enable Template metaprogrammed value that enables this version of the method when the attribute is a state
*/
template <ogn::eAttributeType enabled = attributeType>
void addToNodeType(const INodeType& iNodeType,
const NodeTypeObj& nodeTypeObj,
typename std::enable_if<enabled == ogn::kOgnState>::type* = 0)
{
if (m_extendedType == kExtendedAttributeType_Regular)
{
iNodeType.addState(nodeTypeObj, m_name, m_dataType, m_isRequired,
m_hasDefaultValue ? &m_defaultValue : nullptr,
m_hasElementCount ? &m_elementCount : nullptr);
}
else
{
iNodeType.addExtendedState(nodeTypeObj, m_name, m_dataType, m_isRequired, m_extendedType);
}
}
/**
* Initialization for the attribute on the node type, happens once for any given attribute.
*
* @param[in] iToken Attribute's token, for lookup
* @param[in] iNodeType Node type interface to which the attribute will be added
* @param[in] nodeTypeObj Node to which the attribute will be added
*/
void initialize(fabric::IToken& iToken, const INodeType& iNodeType, const NodeTypeObj& nodeTypeObj)
{
m_token = iToken.getHandle(m_name);
addToNodeType(iNodeType, nodeTypeObj);
}
};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 15,531 | C | 44.282799 | 133 | 0.658683 |
omniverse-code/kit/include/omni/graph/core/ogn/Registration.h | // 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.
//
#pragma once
#include <carb/Framework.h>
#include <carb/logging/Log.h>
#include <omni/graph/core/ogn/OmniGraphNodeABI.h>
#include <functional>
// =================================================================================================================
// This file contains helpers for facilitating automatic OGN node registration/deregistration.
//
// DECLARE_OGN_NODES() Added to your PluginInterface.cpp declarations where a static initializer would go
// INITIALIZE_OGN_NODES() Added to your carbOnPluginStartup() or IExtensionHooks::onStartup_abi function
// RELEASE_OGN_NODES() Added to your carbOnPluginShutdown() or IExtensionHooks::onShutdown_abi function
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// ==============================================================================================================
// This class has to be inlined or it would break ABI requirements. It is restricted to being instantiated and used
// within a single extension to enforce that.
class NodeTypeBootstrap
{
const char* m_nodeTypeName{ nullptr };
int m_version{ 1 };
const char* m_extensionName{ nullptr };
public:
NodeTypeBootstrap(const char* nodeTypeName, int version, const char* extensionName);
virtual NodeTypeABI& getABI() = 0;
void registerNodeType(IGraphRegistry& iGraphRegistry)
{
getABI().registerNodeType(iGraphRegistry);
}
void deregisterNodeType(IGraphRegistry& iGraphRegistry)
{
getABI().deregisterNodeType(iGraphRegistry);
}
};
// ==============================================================================================================
//
// The registration/dregistration process code flow:
//
// DECLARE_OGN_NODES() establishes a per-plugin manifest of registration records for its extension
// REGISTER_OGN_NODE(), added for each node type implementation, adds that node type's information to the manifest
// INITIALIZE_OGN_NODES() walks every node type in the manifest and registers it with OmniGraph
// RELEASE_OGN_NODES() walks every node type in the manifest and deregisters it with OmniGraph
//
// The code is set up to allow multiple calls to INITIALIZE_OGN_NODES()/RELEASE_OGN_NODES() within a plugin, however
// the typical case will only do those on startup and shutdown.
//
// ==============================================================================================================
// ==============================================================================================================
// This class has to be inlined or it would break ABI requirements. It is restricted to being instantiated and used
// within a single extension to enforce that.
template <typename NodeTypeClass, typename NodeTypeDataClass>
class NodeTypeBootstrapImpl : public NodeTypeBootstrap
{
OmniGraphNode_ABI<NodeTypeClass, NodeTypeDataClass> m_nodeTypeABI;
public:
NodeTypeBootstrapImpl(const char* nodeTypeName, int version, const char* extensionName)
: NodeTypeBootstrap(nodeTypeName, version, extensionName)
, m_nodeTypeABI(nodeTypeName, version, extensionName)
{}
NodeTypeABI& getABI()
{
return m_nodeTypeABI;
}
};
// ==============================================================================================================
class NodeTypeManifest
{
std::vector<NodeTypeBootstrap*> m_registrationList; //< List of node type information used for (de)registration
// Returns the interface to the registry, potentially using a supplied one (usually from omni.graph.core where
// the usual method of getting a cached interface is not available)
IGraphRegistry* getRegistryInterface(IGraphRegistry* potentialInterface, char const* processUsingIt) const
{
if (potentialInterface)
{
return potentialInterface;
}
auto iGraphRegistry = carb::getCachedInterface<omni::graph::core::IGraphRegistry>();
if (iGraphRegistry)
{
return iGraphRegistry;
}
// No interface is okay when there is no registration list
if (m_registrationList.empty())
{
return iGraphRegistry;
}
// This used to be an error, but it seems to get called on shutdown for some reason, where acquisition of
// the registry interface is not possible, so log a message for history but do not fail, relying on the
// caller to check for a nullptr return.
CARB_LOG_INFO_ONCE("Failed to %s - could not acquire omni::graph::core::IGraphRegistry", processUsingIt);
return nullptr;
}
public:
// Add a new node type record to the manifest. Should happen as a result of the REGISTER_OGN_NODE() macro
void add(NodeTypeBootstrap* newRecord)
{
m_registrationList.push_back(newRecord);
}
// Register
void registerAll(IGraphRegistry* iGraphRegistry = nullptr)
{
iGraphRegistry = getRegistryInterface(iGraphRegistry, "register node types");
if (iGraphRegistry)
{
for (const auto& registration : m_registrationList)
{
if (registration)
{
registration->registerNodeType(*iGraphRegistry);
}
else
{
CARB_LOG_ERROR_ONCE("Empty registration entry found when registering all node types");
}
}
}
}
void deregisterAll(IGraphRegistry* iGraphRegistry = nullptr)
{
iGraphRegistry = getRegistryInterface(iGraphRegistry, "register node types");
if (iGraphRegistry)
{
for (const auto& registration : m_registrationList)
{
if (registration)
{
registration->deregisterNodeType(*iGraphRegistry);
}
else
{
CARB_LOG_ERROR_ONCE("Empty registration entry found when deregistering all node types");
}
}
}
}
};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
// ======================================================================
/**
* In order to support delayed registration per-plugin each plugin must contain a list of
* registration functions to be called on startup. To that end the first macro is instantiated
* in the plugin interface file at the file-static level and the second is instantiated
* inside the carbOnPluginStartup function. No instantiation is needed in the carbOnPluginShutdown
* function as the registration object will take care of cleanup. The access is made through
* a function call with a static member to prevent static initialization ordering problems.
*/
extern omni::graph::core::ogn::NodeTypeManifest& __nodeTypeManifest();
// This has to be separate from the class declaration since it would otherwise create a circular dependency between
// NodeTypeManifest and NodeTypeBootstrap
inline omni::graph::core::ogn::NodeTypeBootstrap::NodeTypeBootstrap(const char* nodeTypeName, int version, const char* extensionName)
: m_nodeTypeName{nodeTypeName}
, m_version(version)
, m_extensionName(extensionName)
{
__nodeTypeManifest().add(this);
}
// This is included in the plugin definition file in the file-static declaration code block
#define DECLARE_OGN_NODES() \
omni::graph::core::ogn::NodeTypeManifest& __nodeTypeManifest() \
{ \
static omni::graph::core::ogn::NodeTypeManifest _nodeTypeManifest; \
return _nodeTypeManifest; \
}
// This is added to the plugin startup to register all (C++) node types owned by the plugin
#define INITIALIZE_OGN_NODES() __nodeTypeManifest().registerAll();
// This should be added to the plugin shutdown to ensure that all node types owned by the plugin are cleanly shut down
#define RELEASE_OGN_NODES() __nodeTypeManifest().deregisterAll();
// ==============================================================================================================
/* Everything below here was used on previous versions of generated code and should no longer be accessed. They only
continue to exist here on the off chance that somebody was using them directly.
_____ ______ _____ _____ ______ _____ _______ ______ _____
| __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \
| | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | |
| | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | |
| |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| |
|_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/
*/
namespace omni {
namespace graph {
namespace core {
namespace ogn {
// ======================================================================
// Define the type used for remembering the function to call for a delayed registration of a node type
using DelayedRegistrationFn = std::function<const char*(OmniGraphNodeRegisterFn&, OmniGraphNodeDeregisterFn&, OmniGraphNodeRegisterAliasFn&)>;
using DelayRegistrationFn = std::function<void(DelayedRegistrationFn)>;
// ======================================================================
/**
* Template for a class that manages registration of a node defined outside the omni.graph.core extension
* The OmniGraph interface is assumed to be available as any extension registering nodes must have a dependency on it.
* One of these objects must be statically instantiated for the node type registration to be properly managed.
*/
template <typename NodeTypeClass, typename NodeTypeDataClass>
class RegisterNode : OmniGraphNode_ABI<NodeTypeClass, NodeTypeDataClass>
{
public:
/**
* Construct a registration object and register it for delayed registration when the plugin starts up
*
* @param[in] nodeTypeName Name of the node type being registered
* @param[in] nodeTypeVersion Version of the node type being registered
* @param[in] extensionName Name of the extension owning this node type
* @param[in] delayRegistration Function to call to queue up a delayed registration in the plugin start-up code
*/
RegisterNode<NodeTypeClass, NodeTypeDataClass>(const char* nodeTypeName,
int nodeTypeVersion,
const char* extensionName,
DelayRegistrationFn delayRegistration)
: OmniGraphNode_ABI<NodeTypeClass, NodeTypeDataClass>()
{
// std::cout << "DBG: Delayed registration of " << nodeTypeName << " from " << extensionName << std::endl;
using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;
delayRegistration(std::bind(&RegisterNode<NodeTypeClass, NodeTypeDataClass>::performRegistration, this,
nodeTypeName, nodeTypeVersion, extensionName, _1, _2, _3));
}
/**
* A binding of this function for every node type is added to a delayed registration list, which will be processed
* when the plugin starts up.
*
* @param[in] nodeTypeName Name of the node type being registered
* @param[in] nodeTypeVersion Version of the node type being registered
* @param[in] extensionName Name of the extension owning this node type
* @param[in] registerFn Function to call to register the node type with the OmniGraph
* @param[in] deregisterFn Function to call to deregister the node type with the OmniGraph
* @param[in] registerAliasFn Function to call to register an alternate name for the node type
* @return The name of the node type as registered
*/
const char* performRegistration(const char* nodeTypeName,
int nodeTypeVersion,
const char* extensionName,
OmniGraphNodeRegisterFn& registerFn,
OmniGraphNodeDeregisterFn& deregisterFn,
OmniGraphNodeRegisterAliasFn& registerAliasFn)
{
// std::cout << "--- Registered " << nodeTypeName << " from " << extensionName << std::endl;
OmniGraphNode_ABI<NodeTypeClass, NodeTypeDataClass>::doRegister(
nodeTypeName, nodeTypeVersion, extensionName, registerFn, deregisterFn, registerAliasFn);
return nodeTypeName;
}
};
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 13,758 | C | 46.119863 | 142 | 0.591292 |
omniverse-code/kit/include/omni/graph/core/ogn/ComputeHelpers.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.
//
// =================================================================================================================
// This file contains helper functions for building c++ nodes that perform the operations on union runtime attributes
// with lots of different types. These helpers also support array broadcasting. This is especially useful
// for generic utility nodes such as Add, Multiply, etc.
// =================================================================================================================
#ifdef THIS_IS_INCLUDED_IN_THE_DOCUMENTATION
// The folllowing block describes the ogn::compute API and how it is intended to be used.
//
// begin-compute-helpers-interface-description
/*
* In python, working with extended unions types is easy - dynamic type resolution is incredibly simple, and NumPy
* handles array broadcasting, where a vector with smaller dimensions will be "repeated" so the inputs are compatible
* the compute helpers API hopes to provide utilities that make working with C++ union types significantly easier
*/
// The compute helpers API primarily relies on using generic lambdas for operations.
// The compiler will resolve the input types, allowing us to use the add function for a variety
// of different types (eg: double, float, int)
auto add = [](auto const& a, auto const& b, auto& result) { result = a + b; };
// We can use the ogn::compute::tryCompute function to attempt to apply add() to a variety of different types
// tryCompute will return true if the types are resolved properly, and false if they aren't. an ogn::compute::InputError
// will be thrown if the types are resolved but the computation is impossible (due to different array sizes, for example)
if (ogn::compute::tryCompute(db.inputs.a().get<int>(), db.inputs.b().get<int>(), db.inputs.result().get<int>(), add))
return true;
else if (ogn::compute::tryCompute(db.inputs.a().get<float>(), db.inputs.b().get<float>(), db.inputs.result().get<float>(), add))
return true;
// For arrays, add() will be called with each input in parallel, ie: add(a[i], b[i], result[i]).
else if (ogn::compute::tryCompute(db.inputs.a().get<double[]>(), db.inputs.b().get<double[]>(), db.inputs.result().get<double[]>(), add))
return true;
// For a mixture of arrays and singulars, the singular will be broadcast: add(a[i], b, result[i])
else if (ogn::compute::tryCompute(db.inputs.a().get<double[]>(), db.inputs.b().get<double>(), db.inputs.result().get<double[]>(), add))
return true;
else
{
db.logWarning("Failed to resolve input types");
return false;
}
/*
* Sometimes we want to support a mix of arrays and singular values, using broadcasting to match the singular values
* to the dimensions of the array. For this, we can use ogn::compute::tryComputeWithArrayBroadcasting().
*/
// Assuming a, b, and result all have base type int, tryComputeUsingArrrayBroadcasting will attempt to resolve each
// input to int or int[]. Then, perform broadcasting as necessary.
if (ogn::compute::tryComputeUsingArrrayBroadcasting<int>(db.inputs.a(), db.inputs.b(), db.inputs.sum(), add))
return true;
// Assumes a has base type int, b has base type float, and result has base type float
else if (ogn::compute::tryComputeUsingArrrayBroadcasting<int, float, float>(db.inputs.a(), db.inputs.b(), db.inputs.sum(), add))
return true;
// Also supports a random number of arguments, and a result. Here is an example with 3 arguments:
else if (ogn::compute::tryComputeUsingArrrayBroadcasting<int>(db.inputs.a(), db.inputs.b(), db.inputs.c(), db.inputs.sum(), add3))
return true;
else if (ogn::compute::tryComputeUsingArrrayBroadcasting<float, int, int, float>(db.inputs.a(), db.inputs.b(), db.inputs.c(), db.inputs.sum(), add3))
return true;
/*
* For tuple types, you'll have to change your lambda function to work with c++ fixed size arrays T[N]
* Your lambda function will need to be specialized for each different N.
* For this, I recommend using a helper function in your node implementation
*/
// Empty namespace to avoid multiple declarations at linking
namespace {
// compute helper assuming a scalar base type
template<typename T>
bool tryComputeAssumingType(db_type& db)
{
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);
}
// compute helper assuming a tuple base type
template<typename T, size_t N>
bool tryComputeAssumingType(db_type& db)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
for(size_t i = 0; i < N; i++)
{
result[i] = a[i] + b[i];
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N]>(db.inputs.a(), db.inputs.b(), db.outputs.sum(), functor);
}
} // namespace
// ...
if (tryComputeAssumingType<int>(db)) return true; // Calls the scalar helper
else if (tryComputeAssumingType<float>(db)) return true;
else if (tryComputeAssumingType<int, 3>(db)) return true; // Calls the tuple helper
else if (tryComputeAssumingType<float, 3>(db)) return true;
/*
* You may also want to support adding scalars to tuples. The above code unfortunately won't support that.
* For Tuple broadcasting, you can use ogn::compute::tryComputeWithTupleBroadcasting. This function will
* resolve each input to type T, T[], T[N] or T[N][], performing broadcasting as necessary.
*/
template<typename T, size_t N>
bool tryComputeAssumingType(db_type& db)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + b;
};
// Perform computation with tuple AND array broadcasting
return ogn::compute::tryComputeWithTupleBroadcasting<T, N>(db.inputs.a(), db.inputs.b(), db.outputs.sum(), functor);
}
// end-compute-helpers-interface-description
//
#endif
#pragma once
#include <algorithm>
#include <utility>
#include <type_traits>
#include <string>
#include <exception>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/base/gf/traits.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/graph/core/ogn/RuntimeAttribute.h>
#include <omni/graph/core/ogn/SimpleAttribute.h>
#include <omni/graph/core/ogn/ArrayAttribute.h>
#include <omni/graph/core/ogn/array.h>
namespace omni {
namespace graph {
namespace core {
namespace ogn {
namespace compute {
/* Tuple Attribute type traits */
template<class T>
using is_tuple_data = PXR_NS::GfIsGfVec<T>;
// Error thrown when inputs are not valid
struct InputError : public std::exception
{
std::string s;
InputError(std::string ss) : s(ss) {}
~InputError() throw () {}
const char* what() const throw() { return s.c_str(); }
};
#include <omni/graph/core/ogn/ComputeHelpersDetails.h>
#include <omni/graph/core/ogn/ComputeHelpersDynamicInputsDetails.h>
/** ========================= TryCompute utility =========================== */
/**
* Syntax:
* tryCompute(inputs..., result, functor [, count])
*
* Tries to apply the provided functor to the provided
* arguments.
* The number of inputs is random, and determined by the provided functor.
* It is assumed that the "result" argument is a RuntimeAttribute
* while inputs can be either RuntimeAttribute or direct POD/const_array<>.
*
* @param inputs: Random number of inputs
* @param result: the last argument for the functor and the destination for the computation
* @param functor: The computation to perform. Should have signature: (inputs const&..., result&) -> void
* @param [Optional] count: Activates vectorized compute of 'count' elements
* @return True if the inputs were resolved properly, false if not
*/
template <typename... Arguments>
inline bool tryCompute(Arguments&&... args)
{
using VH = Private::VectorizationHelper<Arguments...>;
return Private::tryCompute_ReverseHelper(
std::forward_as_tuple(args...),
std::make_index_sequence<sizeof...(Arguments) - 2 - VH::Offset>(),
VH::count(std::forward_as_tuple(args...)));
}
/** ========================= TryComputeArray utility =========================== */
/**
* Syntax:
* tryComputeWithArrayBroadcasting<T>(inputs..., result, functor [, count])
* OR
* tryComputeWithArrayBroadcasting<TypeIn0, TypeIn1,..., TypeResult>(inputs..., result, functor [, count])
*
* Apply the functor to runtime/regular set of attributes, assuming they all have base types T (syntax #1),
* or the provided set of types (syntax #2).
* The result is assumed to be a runtime attribute. If if it a singular value, inputs must be as well.
* If it is an array, each input is either an array or a singular value.
* IE, this function will attempt to resolve each input to T or T[] etc.
* Singular values will be broadcast to the length of the largest array in the input.
* All input arrays must be of the same length, or an ogn::compute::InputError will be thrown
*
* @param inputs: Random number of inputs passed to the functor
* @param result: the last argument for the functor and the destination for the computation
* @param functor: The computation to perform. Should have signature: (inputs const&..., result&) -> void
* @param [Optional] count: Activates vectorized compute of 'count' elements
* @return True if the inputs were resolved properly, false if not
*/
template <typename... ComputeTypes, typename... Arguments>
inline bool tryComputeWithArrayBroadcasting(Arguments&&... args)
{
using VH = Private::VectorizationHelper<Arguments...>;
//Validation of template arguments number
static_assert(
sizeof...(ComputeTypes) == 1 /*single type*/ || sizeof...(ComputeTypes) == sizeof...(Arguments) - 1 /*functor*/ - VH::Offset,
"Wrong number of template arguments provided to tryComputeWithArrayBroadcasting");
//Make the call
return Private::tryComputeWithArrayBroadcasting_ReverseHelper<1, ComputeTypes...>(
std::forward_as_tuple(args...), std::make_index_sequence<sizeof...(Arguments) - 2 /*functor and output*/ - VH::Offset>(),
VH::count(std::forward_as_tuple(args...)));
}
/** ========================= TryComputeTuple utility =========================== */
// Public interface
// Template argument(s): Single type + tuple components count,
// or Type pack to apply to input/output + tuple components count
// Arguments: input, input, input, ..., output, functor
/**
* Syntax:
* #1: tryComputeWithTupleBroadcasting<SIZE, T>(inputs..., result, functor [, count])
* OR
* #2: tryComputeWithTupleBroadcasting<SIZE, TypeIn0, TypeIn1,..., TypeResult>(inputs..., result, functor [, count])
*
* Apply the functor to runtime/regular set of attributes, assuming they all have base types T (syntax #1),
* or the provided set of types (syntax #2).
* The result is assumed to be a runtime attribute.
* If it is a singular value, inputs must be as well.
* If it is a tuple[SIZE] value, inputs can be either a singular value or a tuple[SIZE].
* If it is an array of (tuple) values, each input is either an array of (tuple) value or a singular (tuple) value.
* IE, function will attempt to resolve each input to T, T[SIZE], T[] or T[SIZE][]
* Singular values will be broadcast to the length of the largest array in the input.
* All input arrays must be of the same length, or an ogn::compute::InputError will be thrown
*
* @param inputs: Random number of inputs passed to the functor
* @param result: the last argument for the functor and the destination for the computation
* @param functor: The computation to perform. Should have signature: (inputs const&..., result&) -> void
* @param [Optional] count: Activates vectorized compute of 'count' elements
* @return True if the inputs were resolved properly, false if not
*/
/** ========================= UPGRADE NOTE / COMPILE ERROR ON EXISTING USAGE =========================== */
// Order of the template arguments has changed, starting in kit 105.
// The tuple count is now the first argument instead of the last one.
//
// If you get there with a compile error, modify your code as follow:
//
// [OLD] tryComputeWithTupleBroadcasting<T0, T1, ..., N>(...)
// [NEW] tryComputeWithTupleBroadcasting<N, T0, T1, ...>(...)
/** ==================================================================================================== */
template <size_t N, typename... ComputeTypes, typename... Arguments>
inline bool tryComputeWithTupleBroadcasting(Arguments&&... args)
{
using VH = Private::VectorizationHelper<Arguments...>;
static_assert(sizeof...(ComputeTypes) == 1 /*single type*/ ||
sizeof...(ComputeTypes) == sizeof...(Arguments) - 1 /*functor*/ - VH::Offset,
"Wrong number of template arguments provided to tryComputeWithTupleBroadcasting");
return Private::tryComputeWithArrayBroadcasting_ReverseHelper<N, ComputeTypes...>(
std::forward_as_tuple(args...),
std::make_index_sequence<sizeof...(Arguments) - 2 - VH::Offset>(),
VH::count(std::forward_as_tuple(args...)));
}
/** ========================= TryComputeArrayWithMultipleInputs utility =========================== */
/**
* Syntax:
* tryComputeInputsWithArrayBroadcasting<T>(inputArray, result, functor [, count])
*
* Apply the functor to an array of runtime attributes, assuming they all have base types T.
* The result is assumed to be a runtime attribute. If if it a singular value, inputs must be as well.
* If it is an array, each input is either an array or a singular value.
* IE, this function will attempt to resolve each input to T or T[] etc.
* Singular values will be broadcast to the length of the largest array in the input.
* All input arrays must be of the same length, or an ogn::compute::InputError will be thrown.
*
* Note: The functor is an accumulator. It always receives one input and the result value
* and expects the input to be iteratively added to the result.
* The result is initialized with the first input before the functor is invoked.
*
* For example, to subtract all inputs from the first input the functor can be implemented as follows:
* auto functor = [](const auto& input, auto& result)
* {
* result = result - input;
* };
*
* @param inputs: An array of runtime input attributes
* @param result: The last argument for the functor and the destination for the computation
* @param functor: The computation to perform. Should have signature: (input const&..., result&) -> void
* @param [Optional] count: Activates vectorized compute of 'count' elements
* @return True if the inputs were resolved properly, false if not
*/
template <typename ComputeType, typename Functor>
inline bool tryComputeInputsWithArrayBroadcasting(gsl::span<ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const> const inputs,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu> result,
Functor functor,
size_t count = 1)
{
using InputType = typename ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu>;
return Private::tryComputeInputsWithArrayBroadcasting<ComputeType, InputType, Functor>(inputs, result, functor, count);
}
/** ========================= TryComputeTupleWithMultipleInputs utility =========================== */
/**
* Syntax:
* tryComputeInputsWithTupleBroadcasting<T>(inputArray, result, functor [, count])
*
* Apply the functor to an array of runtime attributes, assuming they all have base types T.
* The result is assumed to be a runtime attribute.
* If it is a singular value, inputs must be as well.
* If it is a tuple[SIZE] value, inputs can be either a singular value or a tuple[SIZE].
* If it is an array of (tuple) values, each input is either an array of (tuple) value or a singular (tuple) value.
* IE, function will attempt to resolve each input to T, T[SIZE], T[] or T[SIZE][]
* Singular values will be broadcast to the length of the largest array in the input.
* All input arrays must be of the same length, or an ogn::compute::InputError will be thrown.
*
* Note: The functor is an accumulator. It always receives one input and the result value
* and expects the input to be iteratively added to the result.
* The result is initialized with the first input before the functor is invoked.
*
* For example, to subtract all inputs from the first input the functor can be implemented as follows:
* auto functor = [](const auto& input, auto& result)
* {
* result = result - input;
* };
*
* @param inputs: An array of runtime input attributes
* @param result: the last argument for the functor and the destination for the computation
* @param functor: The computation to perform. Should have signature: (input const&..., result&) -> void
* @param [Optional] count: Activates vectorized compute of 'count' elements
* @return True if the inputs were resolved properly, false if not
*/
template <size_t TUPLE_SIZE, typename ComputeType, typename Functor>
inline bool tryComputeInputsWithTupleBroadcasting(gsl::span<ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu> const> const inputs,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu> result,
Functor functor,
size_t count = 1)
{
using InputType = typename ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu>;
return Private::tryComputeInputsWithTupleBroadcasting<TUPLE_SIZE, ComputeType, InputType, Functor>(inputs, result, functor, count);
}
} // namespace compute
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 18,353 | C | 46.672727 | 149 | 0.67602 |
omniverse-code/kit/include/omni/graph/core/ogn/Database.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/InterfaceUtils.h>
#include <omni/fabric/IToken.h>
#include <carb/logging/Log.h>
#include <omni/graph/core/IAttributeType.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/IVariable2.h>
#include <omni/graph/core/StringUtils.h>
#include <omni/graph/core/ogn/RuntimeAttribute.h>
#include <omni/graph/core/ogn/SimpleRuntimeAttribute.h>
using omni::fabric::IToken;
// =================================================================================================================
// This file contains simple interface classes which wrap data in the OGN database for easier use.
//
// OmniGraphDatabase Base class for generated node database classes. Provides common functionality.
//
// WARNING: These interfaces are subject to change without warning and are only meant to be used by generated code.
// If you call them directly you may have to modify your code when they change.
// =================================================================================================================
// Helper definitions for hardcoded metadata names.
// These should match the Python constants in the MetadataKey object found in the file
// source/extensions/omni.graph.tools/python/node_generator/keys.py
#define kOgnMetadataAllowMultiInputs "allowMultiInputs"
#define kOgnMetadataAllowedTokens "allowedTokens"
#define kOgnMetadataAllowedTokensRaw "__allowedTokens"
#define kOgnMetadataCategories "__categories"
#define kOgnMetadataCategoryDescriptions "__categoryDescriptions"
#define kOgnMetadataCudaPointers "__cudaPointers"
#define kOgnMetadataDefault "__default"
#define kOgnMetadataDescription "__description"
#define kOgnMetadataExclusions "__exclusions"
#define kOgnMetadataExtension "__extension"
#define kOgnMetadataHidden "hidden"
#define kOgnMetadataIconBackgroundColor "__iconBackgroundColor"
#define kOgnMetadataIconBorderColor "__iconBorderColor"
#define kOgnMetadataIconColor "__iconColor"
#define kOgnMetadataIconPath "__icon"
#define kOgnMetadataInternal "internal"
#define kOgnMetadataLanguage "__language"
#define kOgnMetadataMemoryType "__memoryType"
#define kOgnMetadataObjectId "__objectId"
#define kOgnMetadataOptional "__optional"
#define kOgnMetadataOutputOnly "outputOnly"
#define kOgnMetadataLiteralOnly "literalOnly"
#define kOgnMetadataTags "tags"
#define kOgnMetadataTokens "__tokens"
#define kOgnMetadataUiName "uiName"
#define kOgnMetadataUiType "uiType"
#define kOgnSingletonName "singleton"
namespace omni {
namespace graph {
namespace core {
class Node;
namespace ogn {
// The following type aliases are internal and are meant to be used as opaque types.
// The underlying type definition can change in future releases.
/** Type of accessor returned for simple input attributes */
using InputAttribute = ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu>;
/** Type of accessor returned for simple output attributes */
using OutputAttribute = ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>;
/** Type of accessor returned for simple state attributes */
using VariableAttribute = RuntimeAttribute<ogn::kOgnState, ogn::kCpu>;
/** Type of accessor returned for simple dynamic input attributes */
using DynamicInput = ogn::SimpleInput<const InputAttribute, ogn::kCpu>;
/** Type of accessor returned for simple dynamic output attributes */
using DynamicOutput = ogn::SimpleOutput<OutputAttribute, ogn::kCpu>;
/** Type of accessor returned for simple dynamic state attributes */
using DynamicState = ogn::SimpleState<VariableAttribute, ogn::kCpu>;
// ======================================================================
/**
* Class defining the minimal amount of shared interface for the generated database interface classes.
* This class should never be instatiated directly as it is not safe across ABI boundaries. Instead,
* templated classes will derive from it to create new classes that live entirely on the plugin's side.
* The template parameter NodeClassType is the node implementation class that makes use of the database.
* This was necessary to avoid circular dependencies.
*/
class OmniGraphDatabase
{
protected:
GraphContextObj const* m_graphContextHandles{ nullptr }; //!< ABI object referencing the OmniGraph
NodeObj const* m_nodeHandles{ nullptr }; //!< List of node handles per-instance
InstanceIndex m_offset{ 0 };//!< Instance offset in vectorized context
size_t m_handleCounts{ 0 }; //!< Number of handles in m_nodeHandles
public:
/**
* @brief Common constructor for a node's database
*
* @param[in] graphContexts List of ABI objects referencing the graphs in which the node lives
* @param[in] nodeObjects List of ABI objects referencing the instanced nodes to which this database belongs
* @param[in] handleCount Number of node instances in @p nodeObjects
*/
OmniGraphDatabase(GraphContextObj const* graphContexts, NodeObj const* nodeObjects, size_t handleCount)
: m_graphContextHandles(graphContexts),
m_nodeHandles(nodeObjects),
m_handleCounts(handleCount)
{
}
/**
* @brief Get the attribute Type from the OGN type name
*
* @param[in] typeNameToken Token with the string representation of the attribute type used by OGN
* @returns Attribute type corresponding to the type name, invalid if the type name could not be parsed
*/
Type typeFromName(NameToken typeNameToken) const
{
auto typeInterface = carb::getCachedInterface<omni::graph::core::IAttributeType>();
if (!typeInterface)
{
CARB_LOG_ERROR_ONCE("Could not acquire the IAttributeType interface");
return {};
}
auto typeName = tokenToString(typeNameToken);
return typeInterface->typeFromOgnTypeName(typeName);
}
/**
* @brief Access the token interface to convert a string to a token, for dealing with unique managed strings
*
* @param[in] tokenName Name of the string representing a token
* @return Token corresponding to the unique string (for fast comparison)
*/
NameToken stringToToken(const char* tokenName) const
{
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!tokenInterface)
{
CARB_LOG_ERROR_ONCE("Failed to initialize node type - no token interface");
return omni::fabric::kUninitializedToken;
}
return tokenInterface->getHandle(tokenName);
}
/**
* @brief Access the token interface to convert a token to a string, for dealing with unique managed strings
*
* @param[in] token Name of the token representing a unique string
* @return String corresponding to the token
*/
const char* tokenToString(NameToken token) const
{
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!tokenInterface)
{
CARB_LOG_ERROR_ONCE("Failed to initialize node type - no token interface");
return nullptr;
}
return tokenInterface->getText(token);
}
/**
* @brief Access the path interface to convert a string to a path
*
* @param[in] pathString Name of the string representing a token
* @return Path corresponding to the string
*/
TargetPath stringToPath(const char* pathString) const
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
if (!pathInterface)
{
CARB_LOG_ERROR_ONCE("Failed to initialize node type - no path interface");
return omni::fabric::kUninitializedPath;
}
return pathInterface->getHandle(pathString);
}
/**
* @brief Access the path interface to convert a path to a string
*
* @param[in] path Input path
* @return String corresponding to the path
*/
const char* pathToString(const TargetPath path) const
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
if (!pathInterface)
{
CARB_LOG_ERROR_ONCE("Failed to initialize node type - no path interface");
return nullptr;
}
return pathInterface->getText(path);
}
/**
* @brief Access the path interface to convert a path to a token
*
* @param[in] path Input path
* @return Token corresponding to the path
*/
NameToken pathToToken(const TargetPath path) const
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!pathInterface || !tokenInterface)
{
CARB_LOG_ERROR_ONCE("Failed to initialize node type - no path or token interface");
return omni::fabric::kUninitializedToken;
}
return tokenInterface->getHandle(pathInterface->getText(path));
}
/**
* @brief Access the path interface to convert a token to a path
*
* @param[in] pathString Token of the path
* @return Path corresponding to the token
*/
TargetPath tokenToPath(const NameToken pathString) const
{
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!pathInterface || !tokenInterface)
{
CARB_LOG_ERROR_ONCE("Failed to initialize node type - no path or token interface");
return omni::fabric::kUninitializedPath;
}
return pathInterface->getHandle(tokenInterface->getText(pathString));
}
/**
* @brief Access the raw graph ABI object, for when you have to do something really unusual
*
* @return ABI object referencing the graph in which the node lives
*/
const GraphContextObj& abi_context(InstanceIndex relativeIdx = { 0 }) const
{
InstanceIndex idx = m_offset + relativeIdx;
if (idx.index < m_handleCounts)
return m_graphContextHandles[idx.index];
return m_graphContextHandles[0];
}
/**
* @brief Access the raw node ABI object, for when you have to do something really unusual
*
* @return ABI object referencing the node to which this database belongs
*/
const NodeObj& abi_node(InstanceIndex relativeIdx = { 0 }) const
{
InstanceIndex idx = m_offset + relativeIdx;
if (idx.index < m_handleCounts)
return m_nodeHandles[idx.index];
return m_nodeHandles[0];
}
/**
* @brief Access the user data, cast to the templated type.
*
* There is no guarantee that the existing user data is of the requested type - that is up to the
* caller to ensure.
*
* @tparam UserDataType Type of the user data
* @param[in] relativeIdx Instance index of the node to which the user data applies
* @return Internal user data that was set elsewhere, cast to the templated type
*/
template <typename UserDataType>
UserDataType* userData(InstanceIndex relativeIdx = { 0 }) const
{
NodeObj const& obj = abi_node(relativeIdx);
return reinterpret_cast<UserDataType*>(obj.iNode->getUserData(obj));
}
/**
* @brief Log an evaluation error, warning, or message.
* Takes a printf-style list of arguments indicating what happened during evaluation and logs the message.
*
* @tparam Args... Variable list of printf-like arguments to be formatted
* @param[in] nodeObj Node reporting the error
* @param[in] inst The graph instance for which this message should be logged
* @param[in] sev Severity of the message to report
* @param[in] fmt Formatting string
* @param[in] args Variadic template arguments in the same form as printf arguments.
*/
template <typename... Args>
static void logMessage(NodeObj const& nodeObj, InstanceIndex inst, Severity sev, const char* fmt, Args&&... args)
{
if (sizeof...(args) == 0)
{
nodeObj.iNode->logComputeMessageOnInstance(nodeObj, inst, sev, fmt);
}
else
{
std::string msg = formatString(fmt, args...);
nodeObj.iNode->logComputeMessageOnInstance(nodeObj, inst, sev, msg.c_str());
}
}
/**
* @brief Log an evaluation error.
* Takes a printf-style list of arguments indicating what error during evaluation and logs the message.
*
* @tparam Args... Variable list of printf-like arguments to be formatted
* @param[in] nodeObj Node reporting the error
* @param[in] fmt Formatting string
* @param[in] args Variadic template arguments in the same form as printf arguments.
*/
template <typename... Args>
static void logError(NodeObj const& nodeObj, const char* fmt, Args&&... args)
{ logMessage(nodeObj, kAccordingToContextIndex, Severity::eError, fmt, args...); }
/**
* @brief Log an evaluation error for a specific node instance.
* Takes a printf-style list of arguments indicating what error during evaluation and logs the message.
*
* @tparam Args... Variable list of printf-like arguments to be formatted
* @param[in] nodeObj Node reporting the error
* @param[in] inst The graph instance for which this message should be logged
* @param[in] fmt Formatting string
* @param[in] args Variadic template arguments in the same form as printf arguments.
*/
template <typename... Args>
static void logError(NodeObj const& nodeObj, InstanceIndex inst, const char* fmt, Args&&... args)
{ logMessage(nodeObj, inst, Severity::eError, fmt, args...); }
/**
* @brief Log an evaluation warning.
* Takes a printf-style list of arguments indicating what warning during evaluation and logs the message.
*
* @tparam Args... Variable list of printf-like arguments to be formatted
* @param[in] nodeObj Node reporting the warning
* @param[in] fmt Formatting string
* @param[in] args Variadic template arguments in the same form as printf arguments.
*/
template <typename... Args>
static void logWarning(NodeObj const& nodeObj, const char* fmt, Args&&... args)
{ logMessage(nodeObj, kAccordingToContextIndex, Severity::eWarning, fmt, args...); }
/**
* @brief Log an evaluation warning for a specific node instance.
* Takes a printf-style list of arguments indicating what warning during evaluation and logs the message.
*
* @tparam Args... Variable list of printf-like arguments to be formatted
* @param[in] nodeObj Node reporting the warning
* @param[in] inst The graph instance for which this message should be logged
* @param[in] fmt Formatting string
* @param[in] args Variadic template arguments in the same form as printf arguments.
*/
template <typename... Args>
static void logWarning(NodeObj const& nodeObj, InstanceIndex inst, const char* fmt, Args&&... args)
{ logMessage(nodeObj, inst, Severity::eWarning, fmt, args...); }
/**
* @brief Log an error using print-like formatting
*
* @tparam Args... Variable list of printf-like arguments to be formatted
* @param[in] fmt Printf-like formatting string
* @param[in] args Variable list of printf-like arguments to be formatted
*/
template <typename... Args>
void logError(const char* fmt, Args&&... args) { logError(abi_node(), m_offset, fmt, args...); }
/**
* @brief Log an error for a specific node instance using print-like formatting
*
* @tparam Args... Variable list of printf-like arguments to be formatted
* @param[in] relativeIdx The graph instance for which this message should be logged
* @param[in] fmt Printf-like formatting string
* @param[in] args Variable list of printf-like arguments to be formatted
*/
template <typename... Args>
void logError(InstanceIndex relativeIdx, const char* fmt, Args&&... args) { logError(abi_node(relativeIdx), m_offset + relativeIdx, fmt, args...); }
/**
* @brief Log a warning using print-like formatting
*
* @tparam Args... Variable list of printf-like arguments to be formatted
* @param[in] fmt Printf-like formatting string
* @param[in] args Variable list of printf-like arguments to be formatted
*/
template <typename... Args>
void logWarning(const char* fmt, Args&&... args) { logWarning(abi_node(), m_offset, fmt, args...); }
/**
* @brief Log a warning for a specific node instance using print-like formatting
*
* @tparam Args... Variable list of printf-like arguments to be formatted
* @param[in] relativeIdx The graph instance for which this message should be logged
* @param[in] fmt Printf-like formatting string
* @param[in] args Variable list of printf-like arguments to be formatted
*/
template <typename... Args>
void logWarning(InstanceIndex relativeIdx, const char* fmt, Args&&... args) { logWarning(abi_node(relativeIdx), m_offset + relativeIdx, fmt, args...); }
/**
* Retrieves an attribute representing the value of a variable. If the variable
* with the given name does not exist in the graph, an invalid attribute is returned.
*
* @param[in] token: A token representing the variable name
* @param[in] relativeIdx: The instance index/offset relative to the one currently pointed by the database
* @return An attribute that allows access to the variable data.
*/
VariableAttribute getVariable(NameToken token, InstanceIndex relativeIdx = { 0 })
{
return getVariable(tokenToString(token), relativeIdx);
}
/**
* Retrieves an attribute representing the value of a variable. If the variable
* with the given name does not exist in the graph, an invalid attribute is returned.
*
* @param[in] variableName: A string indicating the variable name
* @param[in] relativeIdx: The instance index/offset relative to the one currently pointed by the database
* @return An attribute that allows access to the variable data.
*/
VariableAttribute getVariable(const char* variableName, InstanceIndex relativeIdx = { 0 })
{
NodeObj const& obj = abi_node(relativeIdx);
GraphContextObj const& ctx = abi_context(relativeIdx);
auto graphObj = obj.iNode->getGraph(obj);
auto variable = graphObj.iGraph->findVariable(graphObj, variableName);
if (!variable)
return VariableAttribute();
auto handle = ctx.iContext->getVariableDataHandle(ctx, variable, m_offset + relativeIdx);
return VariableAttribute(ctx, handle);
}
/**
* Retrieves the target of the executing graph.
*
* @param[in] relativeIdx: The instance index/offset relative to the one currently pointed by the database
* @return A token representing the prim path of the graph target
*/
NameToken getGraphTarget(InstanceIndex relativeIdx = { 0 }) const
{
GraphContextObj const& ctx = abi_context(relativeIdx);
return ctx.iContext->getGraphTarget(ctx, relativeIdx+m_offset);
}
/**
* Retrieves the targets of the executing graph.
*
* @param[in] count: The number of instances available for vectorized access
* @return A span of token representing the prims path of the graph targets
*/
gsl::span<NameToken const> getGraphTargets(size_t count) const
{
GraphContextObj const& ctx = abi_context();
return { &ctx.iContext->getGraphTarget(ctx, m_offset), count };
}
/**
* Move to next instance in a vectorized context.
*
*/
inline void moveToNextInstance()
{
++m_offset.index;
}
/**
* Move to next instance in a vectorized context.
*
*/
inline void resetToFirstInstance()
{
m_offset = { 0 };
}
/**
* Get the current instance index, relative to the the one pointed by the context
*
*/
inline const InstanceIndex& getInstanceIndex() const
{
return m_offset;
}
protected:
/**
* Gets the dynamic attributes of the specified type, if any are registered with the node.
*
* @param[in] staticAttributeCount: The number of attributes that are statically defined in the ogn node definition.
* @param[out] dynamicAttributes: The buffer for the collected dynamic attributes.
* @return Returns true if any dynamic attributes of the requested type are found, otherwise returns false.
*/
template <AttributePortType portType, typename TAttribute>
bool tryGetDynamicAttributes(size_t staticAttributeCount, std::vector<TAttribute>& dynamicAttributes)
{
NodeObj const& obj = abi_node();
GraphContextObj const& ctx = abi_context();
auto totalAttributeCount = obj.iNode->getAttributeCount(obj);
if (totalAttributeCount > staticAttributeCount)
{
dynamicAttributes.reserve(totalAttributeCount - staticAttributeCount);
std::vector<AttributeObj> allAttributes(totalAttributeCount);
obj.iNode->getAttributes(obj, allAttributes.data(), totalAttributeCount);
bool foundAny = false;
for (auto const& __a : allAttributes)
{
if (__a.iAttribute->isDynamic(__a) && __a.iAttribute->getPortType(__a) == portType)
{
foundAny = true;
auto __h = __a.iAttribute->getAttributeDataHandle(__a, kAccordingToContextIndex);
dynamicAttributes.emplace_back(m_offset.index);
dynamicAttributes.back()().reset(ctx, __h, __a);
}
}
return foundAny;
}
return false;
}
/**
* @brief Populate an array of dynamic attributes from the node
*
* @tparam portType Port type from which the dynamic attributes will be pulled
* @param staticAttributeCount Number of static attributes on the node
* @param dynamicAttributes Array of dynamic attributes, to be populated on return
* @return true Dynamic attributes were found and populated
* @return false No dynamic attributes were found
*/
template <AttributePortType portType>
bool tryGetDynamicAttributes(size_t staticAttributeCount, std::vector<DynamicInput>& dynamicAttributes)
{
NodeObj const& obj = abi_node();
GraphContextObj const& ctx = abi_context();
auto totalAttributeCount = obj.iNode->getAttributeCount(obj);
if (totalAttributeCount > staticAttributeCount)
{
dynamicAttributes.reserve(totalAttributeCount - staticAttributeCount);
std::vector<AttributeObj> allAttributes(totalAttributeCount);
obj.iNode->getAttributes(obj, allAttributes.data(), totalAttributeCount);
bool foundAny = false;
for (auto const& __a : allAttributes)
{
if (__a.iAttribute->isDynamic(__a) &&
__a.iAttribute->getPortType(__a) == portType)
{
foundAny = true;
auto __h = __a.iAttribute->getAttributeDataHandle(__a, kAccordingToContextIndex);
dynamicAttributes.emplace_back(m_offset.index);
const_cast<typename std::remove_const_t<ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu>&>>(dynamicAttributes.back()())
.reset(ctx, __h, __a);
}
}
return foundAny;
}
return false;
}
/**
* Updates the node database when a dynamic attribute is created.
*
* @tparam TAttribute The type of the dynamic attribute that was created (DynamicInput/DynamicOutput/DynamicState)
* @param[out] dynamicAttributes: The dynamic attributes buffer.
* @param[in] attribute: The newly created attribute.
*/
template<typename TAttribute>
void onDynamicAttributeCreated(std::vector<TAttribute>& dynamicAttributes, AttributeObj const& attribute)
{
auto handle = attribute.iAttribute->getAttributeDataHandle(attribute, kAccordingToContextIndex);
dynamicAttributes.emplace_back(m_offset.index);
dynamicAttributes.back()().reset(abi_context(), handle, attribute);
}
/**
* Updates the node database when a dynamic input is created.
*
* @param[out] dynamicInputs: The dynamic attributes buffer.
* @param[in] attribute: The newly created attribute.
*/
void onDynamicInputsCreated(std::vector<DynamicInput>& dynamicInputs, AttributeObj const& attribute)
{
auto handle = attribute.iAttribute->getAttributeDataHandle(attribute, kAccordingToContextIndex);
dynamicInputs.emplace_back(m_offset.index);
const_cast<typename std::remove_const_t<ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu>&>>(
dynamicInputs.back()())
.reset(abi_context(), handle, attribute);
}
/**
* Updates the node database when a dynamic attribute is removed.
*
* @tparam TAttribute The type of the dynamic attribute that was created (DynamicInput/DynamicOutput/DynamicState)
* @param[out] dynamicAttributes: The dynamic attributes buffer.
* @param[in] attribute: The dynamic attribute about to be removed.
*/
template<typename TAttribute>
void onDynamicAttributeRemoved(std::vector<TAttribute>& dynamicAttributes, AttributeObj const& attribute)
{
auto handle = attribute.iAttribute->getAttributeDataHandle(attribute, kAccordingToContextIndex);
for (auto it = dynamicAttributes.begin(); it != dynamicAttributes.end(); ++it)
{
if ((*it)().abi_handle() == handle)
{
dynamicAttributes.erase(it);
return;
}
}
}
/**
* Updates the node database when a dynamic attribute is created or removed.
*
* @param[out] inputs: The buffer of input dynamic attributes.
* @param[out] outputs: The buffer of output dynamic attributes.
* @param[out] states: The buffer of state dynamic attributes.
* @param[in] attribute: The attribute added or removed.
* @param[in] isAttributeCreated: If true, the input attribute is newly created, otherwise it will be removed.
*/
void onDynamicAttributeCreatedOrRemoved(std::vector<DynamicInput>& inputs,
std::vector<DynamicOutput>& outputs,
std::vector<DynamicState>& states,
AttributeObj const& attribute,
bool isAttributeCreated)
{
switch (attribute.iAttribute->getPortType(attribute))
{
case AttributePortType::kAttributePortType_Input:
{
if (isAttributeCreated)
{
onDynamicInputsCreated(inputs, attribute);
}
else
{
onDynamicAttributeRemoved(inputs, attribute);
}
break;
}
case AttributePortType::kAttributePortType_Output:
{
if (isAttributeCreated)
{
onDynamicAttributeCreated(outputs, attribute);
}
else
{
onDynamicAttributeRemoved(outputs, attribute);
}
break;
}
case AttributePortType::kAttributePortType_State:
{
if (isAttributeCreated)
{
onDynamicAttributeCreated(states, attribute);
}
else
{
onDynamicAttributeRemoved(states, attribute);
}
break;
}
default:
break;
}
}
};
/**
* Creates an input RuntimeAttribute from an output RuntimeAttribute.
*
* When nodes have to chain the result of multiple computations, for example when
* accumulating a value in a loop, it is often necessary to treat the output attribute
* as an input in the next iteration of the loop. Because the runtime attributes are strongly typed
* and different depending if they are inputs or outputs, they cannot be used interchangeably as arguments
* to functions which compute one iteration of a computation.
*
* This helper function creates an input RuntimeAttribute from the same handle as the original output attribute.
* The raw data pointer of the original attribute and the newly constructed input attribute are the same.
*
* @tparam MemoryType The location of the memory expected for the attribute
* @param[in] db: The node database.
* @param[in] output: The original output RuntimeAttribute.
* @param[in] outputToken: The original output RuntimeAttribute name token.
*
* @return Returns a RuntimeAttribute with the template type ogn::kOgnInput and the same handle as the original output attribute.
*/
template <eMemoryType MemoryType>
static inline ogn::RuntimeAttribute<ogn::kOgnInput, MemoryType> constructInputFromOutput(
OmniGraphDatabase const& db,
ogn::RuntimeAttribute<ogn::kOgnOutput, MemoryType> const& output,
NameToken outputToken)
{
auto const& nodeObj = db.abi_node();
auto const& context = db.abi_context();
auto const& resultAttribute = nodeObj.iNode->getAttributeByToken(nodeObj, outputToken);
auto handle = resultAttribute.iAttribute->getConstAttributeDataHandle(resultAttribute, db.getInstanceIndex());
return ogn::RuntimeAttribute<ogn::kOgnInput, MemoryType>(context, handle, output.type());
}
} // namespace ogn
} // namespace core
} // namespace graph
} // namespace omni
| 30,198 | C | 41.354839 | 156 | 0.665872 |
omniverse-code/kit/include/omni/graph/core/ogn/ComputeHelpersDetails.h |
namespace Private
{
/** ========================= Compute utils=========================== */
// Solves array VS single value args/result
// Small helper structure to broacast operation on tuple component when asked for (TUPLE_SIZE != 1)
// In that case, computation will be broadcasted to actual tuple elements
template <size_t TUPLE_SIZE, typename T>
struct TupleHelper
{
static inline auto& get(T& val, size_t /*tupleIdx*/, size_t idx) { return (&val)[idx]; }
static inline auto& getConst(T const& val, size_t /*tupleIdx*/, size_t idx) { return (&val)[idx]; }
};
template <size_t TUPLE_SIZE, typename T>
struct TupleHelper <TUPLE_SIZE, T[TUPLE_SIZE]>
{
static inline auto& get(T* val, size_t tupleIdx, size_t idx) { return val[idx * TUPLE_SIZE + tupleIdx]; }
static inline auto& getConst(T const* val, size_t tupleIdx, size_t idx) { return val[idx * TUPLE_SIZE + tupleIdx]; }
};
template <typename T>
struct TupleHelper<1, T>
{
static inline auto& get(T& val, size_t /*tupleIdx*/, size_t idx) { return (&val)[idx]; }
static inline auto& getConst(T const& val, size_t /*tupleIdx*/, size_t idx) { return (&val)[idx]; }
};
template <typename T>
struct TupleHelper<1, T[1]>
{
template<typename U>
static inline auto& get(U& val, size_t tupleIdx, size_t idx) { return (&val[tupleIdx])[idx]; }
template <typename U>
static inline auto& getConst(U const& val, size_t tupleIdx, size_t idx) { return (&val[tupleIdx])[idx]; }
};
constexpr size_t kNotAnArray{ size_t(-1) };
//Small helper structure to differentiate array attributes from regular attribute,
// and allows to make the proper operation depending of it
template <size_t TUPLE_SIZE, typename T, bool IsArray = is_array<typename remove_const_ref<T>::type>::value>
struct ArrayHelper
{
static inline auto& accessArg(T& val, size_t /*index*/, size_t tupleIdx, size_t idx){
return TupleHelper<TUPLE_SIZE, T>::get(val, tupleIdx, idx);
}
static inline auto const& accessArgConst(T const& val, size_t /*index*/, size_t tupleIdx, size_t idx){
return TupleHelper<TUPLE_SIZE, T>::getConst(val, tupleIdx, idx);
}
template<typename... ARGS>
static constexpr size_t setResultLen(size_t, T&, const ARGS&...) { return 1; }
static constexpr size_t getArgsLengthAndAdjustHandle(T const&, size_t) { return kNotAnArray; }
};
template <size_t TUPLE_SIZE, typename T_>
struct ArrayHelper<TUPLE_SIZE, T_, true>
{
using T = typename remove_const_ref<T_>::type;
using InnerType = typename T::iterator::value_type;
static inline auto& accessArg(T& val, size_t index, size_t tupleIdx, size_t /*instance*/) {
return TupleHelper<TUPLE_SIZE, InnerType>::get(val[index], tupleIdx, 0);
}
static inline auto const& accessArgConst(T const& val, size_t index, size_t tupleIdx, size_t /*instance*/){
return TupleHelper<TUPLE_SIZE, InnerType>::getConst(val[index], tupleIdx, 0);
}
template <typename... ARGS>
static size_t const setResultLen(size_t instance, T& res, const ARGS&... args)
{
auto comp = [](size_t ret, size_t others)
{
if (ret != kNotAnArray)
{
if (others != kNotAnArray)
{
if (ret != others)
{
throw InputError("Unable to broadcast arrays of differing lengths: " + std::to_string(ret) +
"!= " + std::to_string(others));
}
return std::max(ret, others);
}
return ret;
}
return others;
};
size_t size = fold(comp, ArrayHelper<1, decltype(args)>::getArgsLengthAndAdjustHandle(args, instance)...);
if (size == kNotAnArray)
size = 1;
//The array is already pointing to the first instance
// offset it by 1 instance on every other calls
if (instance)
res.adjustHandle(1);
res.resize(size);
return size;
}
static size_t const getArgsLengthAndAdjustHandle(T const& arg, size_t instance)
{
// The array is already pointing to the first instance
// offset it by 1 instance on every other calls
if (instance)
const_cast<T&>(arg).adjustHandle(1);
return arg.size();
}
};
//Perform a broadcasted computation, expanding any provided scalar for each array entry
// All provided arrays must have the same length
template <size_t TUPLE_SIZE, typename Result, typename Functor, typename... Args>
void compute(size_t const count, Result& result, Functor const& functor, const Args&... args)
{
for (size_t idx = 0; idx < count; ++idx)
{
size_t const len = ArrayHelper<TUPLE_SIZE, Result>::setResultLen(idx, result, args...);
for (size_t i = 0; i < len; ++i)
for (size_t j = 0; j < TUPLE_SIZE; ++j)
functor(ArrayHelper<TUPLE_SIZE, Args>::accessArgConst(args, i, j, idx)...,
ArrayHelper<TUPLE_SIZE, Result>::accessArg(result, i, j, idx));
}
}
/** ========================= TryCompute utilities =========================== */
// Solves RuntimeAttribute compatibility VS Regular attribute
//Helper class to test the validity and access the data of RuntimeAttribute,
// or just return the data for regular attribute
template <typename T, bool RTData = is_runtime_data<typename remove_const_ref<T>::type>::value>
struct TryComputeHelper
{
static bool testValid(T const& val) { return (bool)val;}
static auto& accessData(T&& val) { return *val;}
};
template <typename T>
struct TryComputeHelper<T, false>
{
static bool testValid(T const& val) { return true; }
static T& accessData(T&& val) { return val; }
};
// This functions test validity of its runtime attributes, and if all valid,
// forward the call to do the broadcasted computation
template <size_t TUPLE_SIZE, typename Result, typename Functor, typename... Args>
bool tryCompute(size_t count, Result&& result, Functor const& functor, Args&&... args)
{
if (!TryComputeHelper<Result>::testValid(result) ||
!(fold(std::logical_and<>(), TryComputeHelper<decltype(args)>::testValid(args)...)))
return false;
compute<TUPLE_SIZE>(count, TryComputeHelper<Result>::accessData(std::forward<Result&&>(result)), functor,
TryComputeHelper<Args>::accessData(std::forward<Args&&>(args))...);
return true;
}
/** ========================= TryComputeArray utilities =========================== */
// Some/All args are Runtime, and might be array or simple value: this block of functionalities select the proper combination
// of array/not array for runtime attribs
//Small helper struct that separates RuntimeAttribute from regular attribute,
// and allows to retrieve the asked accessors for those Runtime attributes
template <size_t TUPLE_SIZE, typename T>
struct RuntimeAttribHelper
{
using T_ = typename remove_const_ref<T>::type;
// the templated type is only use with RT attribute to retrieve the value
template <typename Useless> static T_& accessData(T_& val) { return val; }
template <typename Useless> static T_ const& accessData(T_ const& val) { return val; }
static bool isArray(T const&) { return false; }
static bool isTuple(T const& val) { return false; }
};
template <size_t TUPLE_SIZE, eAttributeType AttributeType, eMemoryType MemoryType>
struct RuntimeAttribHelper<TUPLE_SIZE, ogn::RuntimeAttribute<AttributeType, MemoryType>>
{
using RTAttr = ogn::RuntimeAttribute<AttributeType, MemoryType>;
template <typename T>
static auto accessData(RTAttr const& val) { return val.template get<T>(); }
static bool isArray(RTAttr const& val) { return val.type().arrayDepth != 0; }
static bool isTuple(RTAttr const& val) { return TUPLE_SIZE != 1 && val.type().componentCount == TUPLE_SIZE; }
};
// This struct is a helper that will scan a list of input arguments to determine whether or not each of them is an array.
// This information is collected by recursively calling "callCorrectCompute", and acumulating the resolved types in the class
// template arguments "ResolvedTypes".
// Once the recursive call ends (when all the inputs have been scanned), a specialized version of "callCorrectCompute"
// unpack the tuple to forward the call to tryCompute (through "makeCall"), with all the appropriate accessors for runtime attribute resolved
template <typename... ResolvedTypes>
struct ArgumentTypeSelector
{
template <size_t TUPLE_SIZE, typename... ComputeTypes, typename Ret, typename Functor, typename Args>
static bool callCorrectCompute( bool const allowArrays,
size_t count,
Ret&& ret,
Functor const& f,
Args&& args,
typename std::enable_if<sizeof...(ResolvedTypes) != sizeof...(ComputeTypes)>::type* _cond = 0)
{
using ComputeType = typename std::tuple_element<sizeof...(ResolvedTypes), std::tuple<ComputeTypes...>>::type;
using ComputeTypeTuple = ComputeType[TUPLE_SIZE];
auto const& arg = std::get<sizeof...(ResolvedTypes)>(args);
using RTAH = RuntimeAttribHelper<TUPLE_SIZE, typename remove_const_ref<decltype(arg)>::type>;
if (RTAH::isArray(arg))
{
if (allowArrays == false)
return false;
if (RTAH::isTuple(arg))
return ArgumentTypeSelector<ResolvedTypes..., ComputeTypeTuple[]>::template callCorrectCompute<TUPLE_SIZE, ComputeTypes...>(allowArrays, count, ret, f, args);
return ArgumentTypeSelector<ResolvedTypes..., ComputeType[]>::template callCorrectCompute<TUPLE_SIZE, ComputeTypes...>(allowArrays, count, ret, f, args);
}
if (RTAH::isTuple(arg))
return ArgumentTypeSelector<ResolvedTypes..., ComputeTypeTuple>::template callCorrectCompute<TUPLE_SIZE, ComputeTypes...>(allowArrays, count, ret, f, args);
return ArgumentTypeSelector<ResolvedTypes..., ComputeType>::template callCorrectCompute<TUPLE_SIZE, ComputeTypes...>(allowArrays, count, ret, f, args);
}
template <size_t TUPLE_SIZE, typename... ComputeTypes, typename Ret, typename Functor, typename Args>
static bool callCorrectCompute( bool const /*allowArrays*/,
size_t count,
Ret&& ret,
Functor const& f,
Args&& args,
typename std::enable_if<sizeof...(ResolvedTypes) == sizeof...(ComputeTypes)>::type* _cond = 0)
{
return makeCall<TUPLE_SIZE>(count, ret, f, args, std::make_index_sequence<sizeof...(ComputeTypes)>());
}
template <size_t TUPLE_SIZE, size_t... Indices, typename Ret, typename Functor, typename Args>
static bool makeCall(size_t count, Ret&& ret, Functor const& f, Args&& args, std::index_sequence<Indices...>)
{
using Args_ = typename remove_const_ref<Args>::type;
return tryCompute<TUPLE_SIZE>( count, ret, f,
RuntimeAttribHelper<TUPLE_SIZE, typename remove_const_ref<typename std::tuple_element<Indices, Args_>::type>::type>
::template accessData<ResolvedTypes>(std::get<Indices>(args))...);
}
};
// Main entry point for broadcasting the provided functor to each element of arrays (if arrays are provided)
// In the case of the output not being an array, it is assumed that inputs are not either,
// and this call is just forwarded to the compute function which will check that that inputs have compatible types
// If the output is an array, the call is forwarded to the "ArgumentTypeSelector" helper class, that will scan each input argument
// to determine whether or not is an array, and perform the final broadcasting call.
// The parameter pack is passed as a std::tuple so it is workable
template <size_t TUPLE_SIZE, typename RetType, typename... ComputeTypes, typename Functor, typename... Args>
bool tryComputeWithArrayBroadcasting(size_t count,
ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& result,
Functor const& functor,
const Args&... args)
{
using RetTypeTuple = RetType[TUPLE_SIZE];
if (result.type().arrayDepth == 0)
{
if (TUPLE_SIZE != 1)
{
if (result.type().componentCount != TUPLE_SIZE)
return false;
return ArgumentTypeSelector<>::callCorrectCompute<TUPLE_SIZE, ComputeTypes...>(
false, count, result.get<RetTypeTuple>(), functor, std::forward_as_tuple(args...));
}
return ArgumentTypeSelector<>::callCorrectCompute<TUPLE_SIZE, ComputeTypes...>(
false, count, result.get<RetType>(), functor, std::forward_as_tuple(args...));
}
if (TUPLE_SIZE != 1)
{
if (result.type().componentCount != TUPLE_SIZE)
return false;
return ArgumentTypeSelector<>::callCorrectCompute<TUPLE_SIZE, ComputeTypes...>(
true, count, result.get<RetTypeTuple[]>(), functor, std::forward_as_tuple(args...));
}
return ArgumentTypeSelector<>::callCorrectCompute<TUPLE_SIZE, ComputeTypes...>(
true, count, result.get<RetType[]>(), functor, std::forward_as_tuple(args...));
}
// Meta function that selects a given element in a tuple, or, in the case of a single-element tuple
// returns this unique element regardless of the index
// @input TUPLE: the tuple on which to operate
// @input IDX: the index at which the element must be extracted
// @private COUNT: private argument that allows to specialize for single-element TUPLE input
template <typename TUPLE, size_t IDX, size_t COUNT = std::tuple_size<TUPLE>::value>
struct AccessComputeTypes
{
using type = typename std::tuple_element<IDX, TUPLE>::type;
};
template <typename TUPLE, size_t IDX>
struct AccessComputeTypes<TUPLE, IDX, 1>
{
using type = typename std::tuple_element<0, TUPLE>::type;
};
//This functions is a pass-through adapter that has 2 purposes:
//#1/ We allow to provide all the compute types that will be used to access the inputs/output data,
// but also a unique one, that will be applied to each input/output. This is the purpose of AccessComputeTypes:
// Selectively expand a unique type to a parameter pack duplicating this type the right amount of time,
// or use the parameter pack as provided. The pack provided (containing 1 or n elements) is converted to std::tuple
// in order to be workable.
//#2/ Changes the order of arguments, moving the output and the functor as first arguments,
// allowing to move a random number of inputs as a parameter pack at the end of the function
template <size_t TUPLE_SIZE, typename... ComputeTypes, typename TUPLE, size_t... Inputs>
inline bool tryComputeWithArrayBroadcasting_ReverseHelper(TUPLE&& tuple,
std::index_sequence<Inputs...>,
size_t count)
{
using CTTuple = std::tuple<ComputeTypes...>;
return tryComputeWithArrayBroadcasting< TUPLE_SIZE,
typename AccessComputeTypes<CTTuple, sizeof...(Inputs)>::type,
typename AccessComputeTypes<CTTuple, Inputs>::type...>(
count,
std::get<sizeof...(Inputs)>(tuple),
std::get<sizeof...(Inputs) + 1>(tuple),
std::get<Inputs>(tuple)...);
}
// This functions is a pass-through adapter that forward the arguments as a tuple, and creates a corresponding index_sequence
// This will allow the ReverseHelper to do its job of modifying the parameter order (see purpose #2 above)
template <typename TUPLE, size_t... Inputs>
inline bool tryCompute_ReverseHelper(TUPLE&& tuple, std::index_sequence<Inputs...>, size_t count)
{
using RetType = typename std::tuple_element<sizeof...(Inputs), TUPLE>::type;
return tryCompute<1>(
count,
std::forward<RetType&&>(std::get<sizeof...(Inputs)>(tuple)),
std::get<sizeof...(Inputs) + 1>(tuple),
std::get<Inputs>(tuple)...);
}
// Small helper to detect whether a vectorized compute has been asked or not
template <typename... Arguments>
struct VectorizationHelper
{
using Tuple = std::tuple<Arguments...>;
using LastType = typename std::tuple_element<sizeof...(Arguments) - 1, Tuple>::type;
static constexpr bool isVectorized = std::is_integral<typename remove_const_ref<LastType>::type>::value;
static constexpr int Offset = isVectorized ? 1 : 0;
static size_t count(Tuple&& args)
{
return count_helper(std::forward<Tuple>(args), std::integral_constant<bool,isVectorized>());
}
private:
static size_t count_helper(Tuple&& args, std::false_type /*isVectorized*/) { return 1; }
static size_t count_helper(Tuple&& args, std::true_type /*isVectorized*/) { return std::get<sizeof...(Arguments) - 1>(args);}
};
}//namespace private
| 17,419 | C | 47.121547 | 174 | 0.638383 |
omniverse-code/kit/include/omni/graph/core/dirtyid/IDirtyID2.h | // 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.
//
#pragma once
#include "IDirtyID1.h"
#include <omni/core/IObject.h>
#include <omni/graph/core/Handle.h>
#include <type_traits>
namespace omni
{
namespace graph
{
namespace core
{
namespace unstable
{
OMNI_DECLARE_INTERFACE(IDirtyID2);
// ====================================================================================================
/*
_____ _ _ _ _ _
| __ \ | \ | | | | | | | |
| | | | ___ | \| | ___ | |_ | | | |___ ___
| | | |/ _ \ | . ` |/ _ \| __| | | | / __|/ _ \
| |__| | (_) | | |\ | (_) | |_ | |__| \__ \ __/
|_____/ \___/ |_| \_|\___/ \__| \____/|___/\___|
*/
// The DirtyId interface exposes the implementation details of change tracking system for bundles.
// This functionality is exposed to allow old interfaces such as BundlePrims to function.
// Eventually this interface is going to be removed, once BundlePrims is fully deprecated.
// ====================================================================================================
class IDirtyID2_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.IDirtyID2")>
{
protected:
//! @brief Activate or deactivate dirty id tracking for specific bundle on its attributes and children.
//! @param handle to dirty id track.
//! @param isActive Bool flag indicating if tracking is on or off.
//! @return An omni::core::Result indicating the success of the operation.
OMNI_ATTR("no_py")
virtual omni::core::Result setup_abi(BundleHandle handle, bool isActive) noexcept = 0;
//! @brief Get dirty id values for bundles.
//!
//! The output array for dirty id values needs to be at least size of input
//! array of bundle handles.
//!
//! @param bundles Input bundles to get dirty ids for.
//! @param bundleCount Size of input bundles.
//! @param ids Output dirty id values for requested bundles.
//!
//! @returns Success if operation was successful.
OMNI_ATTR("no_py")
virtual omni::core::Result getForBundles_abi(
ConstBundleHandle const* const bundles OMNI_ATTR("in, throw_if_null, count=bundleCount"),
size_t bundleCount OMNI_ATTR("in"),
DirtyIDType* const ids OMNI_ATTR("out, throw_if_null, count=bundleCount")) noexcept = 0;
//! @brief Get dirty id values for attributes.
//!
//! The output array for dirty id values needs to be at least size of input
//! array of attribute handles.
//!
//! @param attributes Input attributes to get dirty ids for.
//! @param attributeCount Size of input attributes.
//! @param ids Output dirty id values for requested attributes.
//!
//! @returns Success if operation was successful.
OMNI_ATTR("no_py")
virtual omni::core::Result getForAttributes_abi(
ConstAttributeDataHandle const* const attributes OMNI_ATTR("in, throw_if_null, count=attributeCount"),
size_t attributeCount OMNI_ATTR("in"),
DirtyIDType* const ids OMNI_ATTR("out, throw_if_null, count=attributeCount")) noexcept = 0;
};
}
}
}
}
#include "IDirtyID2.gen.h"
OMNI_DEFINE_INTERFACE_API(omni::graph::core::unstable::IDirtyID2)
{
public:
using DirtyIDType = omni::graph::core::DirtyIDType;
using BundleHandle = omni::graph::core::BundleHandle;
using ConstBundleHandle = omni::graph::core::ConstBundleHandle;
using AttributeDataHandle = omni::graph::core::AttributeDataHandle;
using ConstAttributeDataHandle = omni::graph::core::ConstAttributeDataHandle;
//! @return Get invalid dirty id value.
static DirtyIDType getInvalid() noexcept
{
return omni::graph::core::kInvalidDirtyID;
}
//! @brief Checks if given dirty id is valid dirty id.
static bool isValid(DirtyIDType value) noexcept
{
return value != getInvalid();
}
//! @brief Get array of dirty id values for array of bundles.
//!
//! The output array for dirty id values needs to be at least size of input
//! array of bundle handles.
//!
//! @param bundles Input array bundle handles to get dirty ids for.
//! @param bundleCount Size of input array of bundle handles.
//! @param ids Output array of dirty id values for requested bundles.
//!
//! @returns Success if operation was successful.
template <typename BUNDLE_HANDLE>
omni::core::Result getForBundles(BUNDLE_HANDLE* const bundles,
size_t bundleCount,
DirtyIDType* const ids)
{
using BundleHandle_t = typename std::remove_cv<BUNDLE_HANDLE>::type;
static_assert(std::is_same<BundleHandle_t, BundleHandle>::value ||
std::is_same<BundleHandle_t, ConstBundleHandle>::value);
return getForBundles_abi(reinterpret_cast<ConstBundleHandle const* const>(bundles), bundleCount, ids);
}
//! @brief Get dirty id value for a bundle.
//!
//! @param handle Input bundle handle to get dirty id for.
//!
//! @returns A valid dirty id if success, invalid dirty id if failure.
DirtyIDType getForBundle(ConstBundleHandle handle)
{
DirtyIDType value = getInvalid();
auto const result = getForBundles_abi(&handle, 1, &value);
return result == kResultSuccess ? value : getInvalid();
}
//! @brief Get array of dirty id values for array of attributes.
//!
//! The output array for dirty id values needs to be at least size of input
//! array of attribute handles.
//!
//! @param attributes Input array attribute handles to get dirty ids for.
//! @param attributeCount Size of input array of attribute handles.
//! @param ids Output array of dirty id values for requested attributes.
//!
//! @returns Success if operation was successful.
template <typename ATTRIBUTE_HANDLE>
omni::core::Result getForAttributes(ATTRIBUTE_HANDLE* const attributes,
size_t attributeCount,
DirtyIDType* const ids)
{
using AttributeDataHandle_t = typename std::remove_cv<ATTRIBUTE_HANDLE>::type;
static_assert(std::is_same<AttributeDataHandle_t, AttributeDataHandle>::value ||
std::is_same<AttributeDataHandle_t, ConstAttributeDataHandle>::value);
return getForAttributes_abi(
reinterpret_cast<ConstAttributeDataHandle const* const>(attributes), attributeCount, ids);
}
//! @brief Get dirty id value for an attribute.
//!
//! @param handle Input attribute handle to get dirty id for.
//!
//! @returns A valid dirty id if success, invalid dirty id if failure.
DirtyIDType getForAttribute(ConstAttributeDataHandle handle)
{
DirtyIDType value = getInvalid();
auto const result = getForAttributes_abi(&handle, 1, &value);
return result == kResultSuccess ? value : getInvalid();
}
};
| 7,467 | C | 40.032967 | 113 | 0.624347 |
omniverse-code/kit/include/omni/graph/core/dirtyid/IDirtyID1.h | // 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.
//
#pragma once
// ====================================================================================================
/* _____ _ _ _ _ _
| __ \ | \ | | | | | | | |
| | | | ___ | \| | ___ | |_ | | | |___ ___
| | | |/ _ \ | . ` |/ _ \| __| | | | / __|/ _ \
| |__| | (_) | | |\ | (_) | |_ | |__| \__ \ __/
|_____/ \___/ |_| \_|\___/ \__| \____/|___/\___|
This is a temporary interface that can change at any time.
*/
// ====================================================================================================
#include <carb/Interface.h>
#include <cstdint>
namespace omni
{
namespace graph
{
namespace core
{
using DirtyIDType = uint64_t;
constexpr DirtyIDType kInvalidDirtyID = ~static_cast<DirtyIDType>(0);
struct IDirtyID
{
CARB_PLUGIN_INTERFACE("omni::graph::core::IDirtyID", 1, 0)
/**
* @return The next dirty ID, atomically incrementing the counter inside.
*/
DirtyIDType(CARB_ABI* getNextDirtyID)() = nullptr;
};
template <typename PREVIOUS_T>
bool checkDirtyIDChanged(PREVIOUS_T& previousID, DirtyIDType newID)
{
if (newID != previousID)
{
previousID = newID;
return true;
}
// Equal, but if they're invalid, still treat them as changed
return (newID == kInvalidDirtyID);
}
}
}
}
| 1,779 | C | 27.709677 | 103 | 0.512648 |
omniverse-code/kit/include/omni/graph/core/dirtyid/IDirtyID2.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
template <>
class omni::core::Generated<omni::graph::core::unstable::IDirtyID2_abi> : public omni::graph::core::unstable::IDirtyID2_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::unstable::IDirtyID2")
//! @brief Activate or deactivate dirty id tracking for specific bundle on its attributes and children.
//! @param handle to dirty id track.
//! @param isActive Bool flag indicating if tracking is on or off.
//! @return An omni::core::Result indicating the success of the operation.
omni::core::Result setup(const omni::graph::core::BundleHandle& handle, bool isActive) noexcept;
//! @brief Get dirty id values for bundles.
//!
//! The output array for dirty id values needs to be at least size of input
//! array of bundle handles.
//!
//! @param bundles Input bundles to get dirty ids for.
//! @param bundleCount Size of input bundles.
//! @param ids Output dirty id values for requested bundles.
//!
//! @returns Success if operation was successful.
omni::core::Result getForBundles(const omni::graph::core::ConstBundleHandle* const bundles,
size_t bundleCount,
omni::graph::core::DirtyIDType* const ids);
//! @brief Get dirty id values for attributes.
//!
//! The output array for dirty id values needs to be at least size of input
//! array of attribute handles.
//!
//! @param attributes Input attributes to get dirty ids for.
//! @param attributeCount Size of input attributes.
//! @param ids Output dirty id values for requested attributes.
//!
//! @returns Success if operation was successful.
omni::core::Result getForAttributes(const omni::graph::core::ConstAttributeDataHandle* const attributes,
size_t attributeCount,
omni::graph::core::DirtyIDType* const ids);
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::core::Result omni::core::Generated<omni::graph::core::unstable::IDirtyID2_abi>::setup(
const omni::graph::core::BundleHandle& handle, bool isActive) noexcept
{
return setup_abi(handle, isActive);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::unstable::IDirtyID2_abi>::getForBundles(
const omni::graph::core::ConstBundleHandle* const bundles, size_t bundleCount, omni::graph::core::DirtyIDType* const ids)
{
OMNI_THROW_IF_ARG_NULL(bundles);
OMNI_THROW_IF_ARG_NULL(ids);
auto return_ = getForBundles_abi(bundles, bundleCount, ids);
return return_;
}
inline omni::core::Result omni::core::Generated<omni::graph::core::unstable::IDirtyID2_abi>::getForAttributes(
const omni::graph::core::ConstAttributeDataHandle* const attributes,
size_t attributeCount,
omni::graph::core::DirtyIDType* const ids)
{
OMNI_THROW_IF_ARG_NULL(attributes);
OMNI_THROW_IF_ARG_NULL(ids);
auto return_ = getForAttributes_abi(attributes, attributeCount, ids);
return return_;
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 3,966 | C | 37.892156 | 125 | 0.682047 |
omniverse-code/kit/include/omni/graph/core/unstable/GenericNodeDef.h | // 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.
//
//! @file NodeDef.h
//!
//! @brief Declares @ref omni::graph::core::unstable::IGenericNodeDef.
#pragma once
#include <carb/profiler/Profile.h>
#include <omni/graph/core/IInternal.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/unstable/IGenericNodeDef.h>
#include <omni/graph/exec/unstable/NodeDef.h>
#include <omni/graph/exec/unstable/ExecutionTask.h>
namespace omni
{
namespace graph
{
namespace core
{
namespace unstable
{
//! @copydoc omni::graph::core::unstable::IGenericNodeDef
class GenericNodeDef : public exec::unstable::NodeDefT<IGenericNodeDef>
{
public:
//! Construct OmniGraph node definition which will use call ogn compute method to execute the node
//!
//! @param definitionName Definition name is considered as a token that transformation passes can register against
//! @param nodeObj Authoring node associated with this definition instance
//!
//! May throw.
static omni::core::ObjectPtr<GenericNodeDef> create(const char* definitionName, const NodeObj& nodeObj)
{
OMNI_THROW_IF_ARG_NULL(definitionName);
return omni::core::steal(new GenericNodeDef(definitionName, nodeObj));
}
//! Determine scheduling constraint based on the OmniGraph node object
static exec::unstable::SchedulingInfo getSchedulingInfo(const NodeObj& nodeObj)
{
auto schedulingInfo = exec::unstable::SchedulingInfo::eSerial;
NodeTypeObj nodeTypeObj = nodeObj.iNode->getNodeTypeObj(nodeObj);
ISchedulingHints* const schedulingHints = nodeTypeObj.iNodeType->getSchedulingHints(nodeTypeObj);
ISchedulingHints2* const schedulingHints2 = omni::core::cast<ISchedulingHints2>(schedulingHints).get();
if (schedulingHints)
{
if (schedulingHints->getThreadSafety() == eThreadSafety::eSafe ||
(schedulingHints2 && schedulingHints2->getPurityStatus() == ePurityStatus::ePure))
{
// schedulingHints()->getDataAccess(eAccessLocation::eUsd) == eAccessType::eRead
// depending on situation, above can be scheduled in parallel. In general it is safer
// to assume serial, since USD composition engine is not thread safe...but once the stage
// is composed, pulling out individual attribute values is safe.
// Currently we will hurt performance for nodes like OgnReadPrimAttribute and make
// our mainline branch be slower than prototype. We will explore runtime override
// to scheduling hints that would allow changing the dispatch based on runtime information.
// Also note that with the current ordering of the if-else statements, a node
// can technically be both threadsafe AND write to usd, if the node's compute
// implementation allows for it (e.g. with a delay write to USD that leverages
// the OG "registerForUSDWriteBack").
schedulingInfo = exec::unstable::SchedulingInfo::eParallel;
}
else if (schedulingHints->getDataAccess(eAccessLocation::eUsd) == eAccessType::eWrite)
{
schedulingInfo = exec::unstable::SchedulingInfo::eIsolate;
}
}
return schedulingInfo;
}
protected:
using BaseType = exec::unstable::NodeDefT<IGenericNodeDef>;
exec::unstable::Status execute_abi(exec::unstable::ExecutionTask* info) noexcept override
{
exec::unstable::ExecutionTask* currentTask = exec::unstable::getCurrentTask();
if (!m_nodeObj.iNode->isDisabled(m_nodeObj) && currentTask)
{
InstanceIndex baseInstanceIndex{ 0 };
size_t numberOfInstances{ 1 };
m_privateDef->getInstanceInfo(*info, baseInstanceIndex, numberOfInstances);
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "NodeCompute");
if (m_nodeTypeObj.iNodeType->computeVectorized)
{
currentTask->setUserIndex(baseInstanceIndex.index);
m_nodeTypeObj.iNodeType->computeVectorized(m_contextObj, m_nodeObj, numberOfInstances);
}
else
{
if (m_nodeTypeObj.iNodeType->compute == nullptr)
{
// this can happen if a node is provided by an extension and the user unloads the extension
CARB_LOG_ERROR_ONCE("Node implementation lost, aborting graph execution");
}
else
{
InstanceIndex currentInstance = baseInstanceIndex;
for (size_t i = 0; i < numberOfInstances; ++i)
{
currentTask->setUserIndex(currentInstance.index);
m_nodeTypeObj.iNodeType->compute(m_contextObj, m_nodeObj);
++currentInstance;
}
}
}
}
return exec::unstable::Status::eSuccess;
}
exec::unstable::SchedulingInfo getSchedulingInfo_abi(const exec::unstable::ExecutionTask* info) noexcept override
{
return m_schedulingInfo;
}
NodeObj getAuthoringNode_abi() noexcept override
{
return m_nodeObj;
}
GenericNodeDef(const char* definitionName, const NodeObj& nodeObj)
: BaseType(definitionName),
m_nodeObj{ nodeObj },
m_schedulingInfo(getSchedulingInfo(nodeObj)),
m_privateDef(carb::getCachedInterface<omni::graph::core::IInternal>()->createPrivateNodeDef(nodeObj),
omni::core::kSteal)
{
GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj);
m_contextObj = graphObj.iGraph->getDefaultGraphContext(graphObj);
m_nodeTypeObj = nodeObj.iNode->getNodeTypeObj(nodeObj);
}
private:
NodeObj m_nodeObj; //!< Authoring node this instance is defining for execution
GraphContextObj m_contextObj; //!< Authoring graph context stored for speed of execution
NodeTypeObj m_nodeTypeObj; //!< Authoring node type information stored for speed of execution
exec::unstable::SchedulingInfo m_schedulingInfo; //!< Scheduling constraint
omni::core::ObjectPtr<IPrivateNodeDef> m_privateDef; //!< Internal object, hiding implementation details
//!< relying on OG internals
};
} // namespace unstable
} // namespace core
} // namespace graph
} // namespace omni
| 6,945 | C | 41.613497 | 120 | 0.655292 |
omniverse-code/kit/include/omni/graph/core/unstable/IGenericNodeGraphDef.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Node graph definition interface for OmniGraph graph.
//!
//! This interface allows us to reason about OmniGraph graphs during graph transformation phase and access authoring
//! graph associated with this definition.
template <>
class omni::core::Generated<omni::graph::core::unstable::IGenericNodeGraphDef_abi>
: public omni::graph::core::unstable::IGenericNodeGraphDef_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::unstable::IGenericNodeGraphDef")
//! Returns a handle to authoring graph associated with this definition.
omni::graph::core::GraphObj getAuthoringGraph() noexcept;
//! Returns True if this graph is used as part of instancing pipeline, false otherwise.
//!
//! @note We will most likely remove this before making this interface stable
bool isInstanced() noexcept;
//! Returns execution node associated with a given authoring node, or nullptr
//! if no association was discovered in this definition.
//!
//! The returned @ref INode will *not* have @ref omni::core::IObject::acquire() called before being
//! returned.
omni::graph::exec::unstable::INode* getExecutionNode(const omni::graph::core::NodeObj& nodeObj) noexcept;
//! Construct the graph.
//!
//! Construction can happen for entire execution graph or only affected by a topological change definitions.
void build(omni::core::ObjectParam<omni::graph::exec::unstable::IGraphBuilder> builder) noexcept;
//! Inspect the state of the graph
bool inspect(omni::core::ObjectParam<inspect::IInspector> inspector) noexcept;
//! Acquire internal information about bucketing of instances for vectorized execution
//!
//! Arguments must not be @c nullptr.
void getInstanceInfo(const omni::graph::exec::unstable::ExecutionTask& info,
omni::graph::core::InstanceIndex& retBaseInstanceIndex,
size_t& retNumberOfInstances) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::graph::core::GraphObj omni::core::Generated<
omni::graph::core::unstable::IGenericNodeGraphDef_abi>::getAuthoringGraph() noexcept
{
return getAuthoringGraph_abi();
}
inline bool omni::core::Generated<omni::graph::core::unstable::IGenericNodeGraphDef_abi>::isInstanced() noexcept
{
return isInstanced_abi();
}
inline omni::graph::exec::unstable::INode* omni::core::Generated<
omni::graph::core::unstable::IGenericNodeGraphDef_abi>::getExecutionNode(const omni::graph::core::NodeObj& nodeObj) noexcept
{
return getExecutionNode_abi(&nodeObj);
}
inline void omni::core::Generated<omni::graph::core::unstable::IGenericNodeGraphDef_abi>::build(
omni::core::ObjectParam<omni::graph::exec::unstable::IGraphBuilder> builder) noexcept
{
build_abi(builder.get());
}
inline bool omni::core::Generated<omni::graph::core::unstable::IGenericNodeGraphDef_abi>::inspect(
omni::core::ObjectParam<inspect::IInspector> inspector) noexcept
{
return inspect_abi(inspector.get());
}
inline void omni::core::Generated<omni::graph::core::unstable::IGenericNodeGraphDef_abi>::getInstanceInfo(
const omni::graph::exec::unstable::ExecutionTask& info,
omni::graph::core::InstanceIndex& retBaseInstanceIndex,
size_t& retNumberOfInstances) noexcept
{
getInstanceInfo_abi(&info, &retBaseInstanceIndex, &retNumberOfInstances);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 4,264 | C | 36.41228 | 128 | 0.731473 |
omniverse-code/kit/include/omni/graph/core/unstable/INodeTypeForwarding.h | // 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.
//
#pragma once
// This file contains the definition of the INodeTypeForwarding ONI class
// This ABI is unstable and subject to change
/* _ _ _____ ______ _______ __ ______ _ _ _____ ______ ___ _ _____ _____ _____ _ __ */
/* | | | |/ ____| ____| /\|__ __| \ \ / / __ \| | | | __ \ / __ \ \ / / \ | | | __ \|_ _|/ ____| |/ / */
/* | | | | (___ | |__ / \ | | \ \_/ / | | | | | | |__) | | | | \ \ /\ / /| \| | | |__) | | | | (___ | ' / */
/* | | | |\___ \| __| / /\ \ | | \ /| | | | | | | _ / | | | |\ \/ \/ / | . ` | | _ / | | \___ \| < */
/* | |__| |____) | |____ / ____ \| | | | | |__| | |__| | | \ \ | |__| | \ /\ / | |\ | | | \ \ _| |_ ____) | . \ */
/* \____/|_____/|______| /_/ \_\_| |_| \____/ \____/|_| \_\ \____/ \/ \/ |_| \_| |_| \_\_____|_____/|_|\_| */
#include <omni/core/Omni.h>
#include <omni/core/IObject.h>
namespace omni {
namespace graph {
namespace core {
namespace unstable {
OMNI_DECLARE_INTERFACE(INodeTypeForwarding);
/**
* @brief Interface that creates a forward on a request for a node type to a different node type
*
* There are a couple of different common use cases for needing a forward:
* - Node type gets renamed
* - Node type moves from one extension to another
*
* The node type forward specifies the unique node type name so if extension omni.my.extension has a node whose type
* is specified as "MyNode" then the forward must be from "omni.my.extension.MyNode".
*
* The forwarding is version-based as well, where the version is a minimum number required for forwarding, the usual
* node version update mechanism not withstanding. For example, if you set up a forward from "omni.nodes.MyNode" version
* 2 to "omni.my_nodes.MyNode" version 3 then any larger version number is forwarded to the same location:
* - omni.nodes.MyNode(2) -> omni.my_nodes.MyNode(3)
* - omni.nodes.MyNode(3) -> omni.my_nodes.MyNode(3)
* - omni.nodes.MyNode(4) -> omni.my_nodes.MyNode(3)
*
* The forwards can also have multiple versions forwarding to different locations, so if on top of the above forward
* you also add a forward from "omni.nodes.MyNode" version 3 to "omni.new_nodes.MyNode" version 4 then these become
* the example forward locations:
* - omni.nodes.MyNode(2) -> omni.my_nodes.MyNode(3)
* - omni.nodes.MyNode(3) -> omni.new_nodes.MyNode(4)
* - omni.nodes.MyNode(4) -> omni.new_nodes.MyNode(4)
*
* Version numbers lower than the first forward are left as-is
* - omni.nodes.MyNode(1) -> omni.nodes.MyNode(1)
*
* @note The usual mechanism of calling updateVersionNumber on a node is only applied after a forward so in the above
* cases requesting omni.nodes.MyNode(2) does not call updateVersionNumber(1,2) on your omni.nodes.MyNode
* implementation.
*
* Node type forwards are associative, so if A forwards to B and B forwards to C then when you request A you get C.
* Adding a new forward from omni.my_nodes.MyNode(3) to omni.new_nodes.MyNode(2) above yields this forwarding:
* - omni.nodes.MyNode(2) -> omni.my_nodes.MyNode(3) -> omni.new_nodes.MyNode(2)
* - omni.nodes.MyNode(3) -> omni.new_nodes.MyNode(4)
* - omni.nodes.MyNode(4) -> omni.new_nodes.MyNode(4)
*/
class INodeTypeForwarding_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.INodeTypeForwarding")>
{
protected:
/**
* @returns Number of currently defined forwards
*/
virtual size_t getForwardCount_abi() noexcept = 0;
/**
* @brief Get the list of available forwards and their redirections.
* Note that there is no guarantee that the replacement names are legitimate node type names, only that they
* have been registered as replacements.
*
* The caller is responsible for allocating and destroying buffers large enough to hold "bufferSize" results.
* If bufferSize > getForwardCount() then the entries at the ends of the buffers will be filled with nullptr.
*
* @param[out] forwardNameBuffer List of forward names to be replaced
* @param[out] forwardVersionBuffer List of the first version of each forward name to be replaced
* @param[out] replacementNameBuffer List of node type names that replace the forwarded names
* @param[out] replacementVersionBuffer List of node type versions that replace the forwarded names
* @param[out] extensionIdBuffer List of extension IDs corresponding to the replacement node type names.
* @param[in] bufferSize Number of entries to fill in the buffers
* @return true if the buffers were successfully filled and the bufferSize matched the forward count
*/
OMNI_ATTR("no_py")
virtual bool getForwards_abi(
OMNI_ATTR("*c_str, out, not_null, count=bufferSize") char const** forwardNameBuffer,
OMNI_ATTR("out, not_null, count=bufferSize") int* forwardVersionBuffer,
OMNI_ATTR("*c_str, out, not_null, count=bufferSize") char const** replacementNameBuffer,
OMNI_ATTR("out, not_null, count=bufferSize") int* replacementVersionBuffer,
OMNI_ATTR("*c_str, out, not_null, count=bufferSize") char const** extensionIdBuffer,
size_t bufferSize
) noexcept = 0;
/**
* @brief Define a new node type forward.
* It is allowed to have the same forwardName to be defined more than once, however the "forwardVersion" must be
* different from any existing ones. Later "forwardVersion" numbers will supersede earlier ones in this case.
* For example if you have these two forwards set up:
* OldNode,1 -> BetterNode,1,omni.better.extension
* OldNode,2 -> MuchBetterNode,1,omni.much_better.extension
* then when version 1 of "OldNode" is requested it will treat it as if you requested "BetterNode", but when
* versions 2 or later are requested it will instead treat it as if you requested "MuchBetterNode". These can be
* chained together:
* OldNode,1 -> BetterNode,1,omni.better.extension
* BetterNode,1 -> MuchBetterNode,1,omni.much_better.extension
*
* @param[in] forwardName Name to be replaced
* @param[in] forwardVersion The first version of the forward name to be replaced
* @param[in] replacementName Node type name that replaces the forwarded name
* @param[in] replacementVersion Version of the node type that replaces the forwarded name
* @param[in] extensionId Extension ID in which the replacement node type can be found
* @return false if there was already an forward with the given name and initial version number
*/
virtual bool defineForward_abi(
OMNI_ATTR("c_str, in, not_null") char const* forwardName,
int forwardVersion,
OMNI_ATTR("c_str, in, not_null") char const* replacementName,
int replacementVersion,
OMNI_ATTR("c_str, in, not_null") char const* replacementExtensionId
) noexcept = 0;
/**
* @brief Remove an existing node type forward.
* Since an forwardName + forwardVersion combination is unique there is no need to pass in the replacement information.
* Only the forward with the matching version is removed. Any others with the same name remain untouched.
*
* @param[in] forwardName Forward to be removed
* @param[in] forwardVersion The version at which the forward is to be removed
* @return false if there was already an forward with the given name and initial version number
*/
virtual bool removeForward_abi(
OMNI_ATTR("c_str, in, not_null") char const* forwardName,
int forwardVersion
) noexcept = 0;
/**
* @brief Remove forwards referencing a given node type name.
*
* @param[in] referencedName Forward to be removed
* @param[in] referencedVersion The version at which the forward is to be removed
* @return number of forwards to the given type that were removed
*/
virtual size_t removeForwardedType_abi(
OMNI_ATTR("c_str, in, not_null") char const* referencedName,
int referencedVersion
) noexcept = 0;
/**
* @brief Find a node type name replacement corresponding to the given node type forward name and version
*
* @param[in] forwardName Name of the node type forward to look up
* @param[in] forwardVersion Version number of the node type forward being looked up
* @param[out] nodeTypeName Pointer to the name of the actual node type name corresponding to the forward,
* or nullptr if there is no equivalent. This string is a constant and managed
* by the node type forward system so it should not be stored on a long-term basis.
* @param[out] nodeTypeVersion Pointer to the version of the actual node type name corresponding to the forward
* @param[out] nodeTypeExtension Pointer to the name of the extension owning nodeTypeName
* @return true if the forwardName/forwardVersion found a valid mapping, with the result placed in the return parameters
*/
OMNI_ATTR("no_py")
virtual bool findForward_abi(
OMNI_ATTR("c_str, in, not_null") char const* forwardName,
int forwardVersion,
OMNI_ATTR("*c_str, out, not_null, count=1") char const** nodeTypeName,
OMNI_ATTR("out, count=1") int* nodeTypeVersion,
OMNI_ATTR("*c_str, out, not_null, count=1") char const** nodeTypeExtension
) noexcept = 0;
};
} // namespace unstable
} // namespace core
} // namespace graph
} // namespace omni
#include "INodeTypeForwarding.gen.h"
| 10,038 | C | 53.559782 | 128 | 0.656705 |
omniverse-code/kit/include/omni/graph/core/unstable/IGenericNodeGraphDef.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.
//
//! @file IGenericNodeGraphDef.h
//!
//! @brief Defines @ref omni::graph::core::unstable::IGenericNodeGraphDef.
#pragma once
#include <omni/graph/exec/unstable/INodeGraphDef.h>
#include <omni/graph/core/Handle.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/inspect/IInspector.h>
namespace omni
{
namespace graph
{
namespace exec
{
namespace unstable
{
// forward declarations needed by interface declaration
class INode;
class IGraphBuilder;
}
}
namespace core
{
namespace unstable
{
// forward declarations needed by interface declaration
class IGenericNodeGraphDef;
class IGenericNodeGraphDef_abi;
//! Node graph definition interface for OmniGraph graph.
//!
//! This interface allows us to reason about OmniGraph graphs during graph transformation phase and access authoring
//! graph associated with this definition.
class IGenericNodeGraphDef_abi : public omni::core::Inherits<exec::unstable::INodeGraphDef, OMNI_TYPE_ID("omni.graph.core.unstable.IGenericNodeGraphDef")>
{
protected:
//! Returns a handle to authoring graph associated with this definition.
virtual GraphObj getAuthoringGraph_abi() noexcept = 0;
//! Returns True if this graph is used as part of instancing pipeline, false otherwise.
//!
//! @note We will most likely remove this before making this interface stable
virtual bool isInstanced_abi() noexcept = 0;
//! Returns execution node associated with a given authoring node, or nullptr
//! if no association was discovered in this definition.
//!
//! The returned @ref INode will *not* have @ref omni::core::IObject::acquire() called before being
//! returned.
virtual OMNI_ATTR("no_acquire") omni::graph::exec::unstable::INode* getExecutionNode_abi(
OMNI_ATTR("in, not_null, throw_if_null, ref") const NodeObj* nodeObj) noexcept = 0;
//! Construct the graph.
//!
//! Construction can happen for entire execution graph or only affected by a topological change definitions.
virtual void build_abi(omni::graph::exec::unstable::IGraphBuilder* builder) noexcept = 0;
//! Inspect the state of the graph
virtual bool inspect_abi(
OMNI_ATTR("not_null") inspect::IInspector* inspector) noexcept = 0;
//! Acquire internal information about bucketing of instances for vectorized execution
//!
//! Arguments must not be @c nullptr.
virtual void getInstanceInfo_abi(OMNI_ATTR("in, not_null, throw_if_null, ref")
omni::graph::exec::unstable::ExecutionTask const* info,
OMNI_ATTR("out, not_null, ref") omni::graph::core::InstanceIndex* retBaseInstanceIndex,
OMNI_ATTR("out, not_null, ref") size_t* retNumberOfInstances) noexcept = 0;
};
} // namespace unstable
} // namespace core
} // namespace graph
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/graph/core/unstable/IGenericNodeGraphDef.gen.h>
// custom API declaration
//! @copydoc omni::graph::core::IGenericNodeGraphDef_abi
class omni::graph::core::unstable::IGenericNodeGraphDef : public omni::core::Generated<omni::graph::core::unstable::IGenericNodeGraphDef_abi>
{ };
// additional headers needed for API implementation
#include <omni/graph/exec/unstable/INode.h>
#include <omni/graph/exec/unstable/IGraphBuilder.h>
#include <omni/graph/exec/unstable/ExecutorFactory.h>
// custom API implementation
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/graph/core/unstable/IGenericNodeGraphDef.gen.h>
| 4,053 | C | 35.196428 | 154 | 0.72909 |
omniverse-code/kit/include/omni/graph/core/unstable/PyINodeTypeForwarding.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
#pragma once
#include <omni/core/ITypeFactory.h>
#include <omni/python/PyBind.h>
#include <omni/python/PyString.h>
#include <omni/python/PyVec.h>
#include <sstream>
auto bindINodeTypeForwarding(py::module& m)
{
// hack around pybind11 issues with C++17
// - https://github.com/pybind/pybind11/issues/2234
// - https://github.com/pybind/pybind11/issues/2666
// - https://github.com/pybind/pybind11/issues/2856
py::class_<omni::core::Generated<omni::graph::core::unstable::INodeTypeForwarding_abi>,
omni::python::detail::PyObjectPtr<omni::core::Generated<omni::graph::core::unstable::INodeTypeForwarding_abi>>,
omni::core::IObject>
clsParent(m, "_INodeTypeForwarding");
py::class_<omni::graph::core::unstable::INodeTypeForwarding,
omni::core::Generated<omni::graph::core::unstable::INodeTypeForwarding_abi>,
omni::python::detail::PyObjectPtr<omni::graph::core::unstable::INodeTypeForwarding>, omni::core::IObject>
cls(m, "INodeTypeForwarding",
R"OMNI_BIND_RAW_(@brief Interface that creates a forward on a request for a node type to a different node type
There are a couple of different common use cases for needing a forward:
- Node type gets renamed
- Node type moves from one extension to another
The node type forward specifies the unique node type name so if extension omni.my.extension has a node whose type
is specified as "MyNode" then the forward must be from "omni.my.extension.MyNode".
The forwarding is version-based as well, where the version is a minimum number required for forwarding, the usual
node version update mechanism not withstanding. For example, if you set up a forward from "omni.nodes.MyNode" version
2 to "omni.my_nodes.MyNode" version 3 then any larger version number is forwarded to the same location:
- omni.nodes.MyNode(2) -> omni.my_nodes.MyNode(3)
- omni.nodes.MyNode(3) -> omni.my_nodes.MyNode(3)
- omni.nodes.MyNode(4) -> omni.my_nodes.MyNode(3)
The forwards can also have multiple versions forwarding to different locations, so if on top of the above forward
you also add a forward from "omni.nodes.MyNode" version 3 to "omni.new_nodes.MyNode" version 4 then these become
the example forward locations:
- omni.nodes.MyNode(2) -> omni.my_nodes.MyNode(3)
- omni.nodes.MyNode(3) -> omni.new_nodes.MyNode(4)
- omni.nodes.MyNode(4) -> omni.new_nodes.MyNode(4)
Version numbers lower than the first forward are left as-is
- omni.nodes.MyNode(1) -> omni.nodes.MyNode(1)
@note The usual mechanism of calling updateVersionNumber on a node is only applied after a forward so in the above
cases requesting omni.nodes.MyNode(2) does not call updateVersionNumber(1,2) on your omni.nodes.MyNode
implementation.
Node type forwards are associative, so if A forwards to B and B forwards to C then when you request A you get C.
Adding a new forward from omni.my_nodes.MyNode(3) to omni.new_nodes.MyNode(2) above yields this forwarding:
- omni.nodes.MyNode(2) -> omni.my_nodes.MyNode(3) -> omni.new_nodes.MyNode(2)
- omni.nodes.MyNode(3) -> omni.new_nodes.MyNode(4)
- omni.nodes.MyNode(4) -> omni.new_nodes.MyNode(4))OMNI_BIND_RAW_");
cls.def(py::init(
[](const omni::core::ObjectPtr<omni::core::IObject>& obj)
{
auto tmp = omni::core::cast<omni::graph::core::unstable::INodeTypeForwarding>(obj.get());
if (!tmp)
{
throw std::runtime_error("invalid type conversion");
}
return tmp;
}));
cls.def(py::init(
[]()
{
auto tmp = omni::core::createType<omni::graph::core::unstable::INodeTypeForwarding>();
if (!tmp)
{
throw std::runtime_error(
"unable to create omni::graph::core::unstable::INodeTypeForwarding instantiation");
}
return tmp;
}));
cls.def_property_readonly("forward_count", &omni::graph::core::unstable::INodeTypeForwarding::getForwardCount);
cls.def("define_forward",
[](omni::graph::core::unstable::INodeTypeForwarding* self, const char* forwardName, int forwardVersion,
const char* replacementName, int replacementVersion, const char* replacementExtensionId)
{
auto return_value = self->defineForward(
forwardName, forwardVersion, replacementName, replacementVersion, replacementExtensionId);
return return_value;
},
R"OMNI_BIND_RAW_(@brief Define a new node type forward.
It is allowed to have the same forwardName to be defined more than once, however the "forwardVersion" must be
different from any existing ones. Later "forwardVersion" numbers will supersede earlier ones in this case.
For example if you have these two forwards set up:
OldNode,1 -> BetterNode,1,omni.better.extension
OldNode,2 -> MuchBetterNode,1,omni.much_better.extension
then when version 1 of "OldNode" is requested it will treat it as if you requested "BetterNode", but when
versions 2 or later are requested it will instead treat it as if you requested "MuchBetterNode". These can be
chained together:
OldNode,1 -> BetterNode,1,omni.better.extension
BetterNode,1 -> MuchBetterNode,1,omni.much_better.extension
@param[in] forwardName Name to be replaced
@param[in] forwardVersion The first version of the forward name to be replaced
@param[in] replacementName Node type name that replaces the forwarded name
@param[in] replacementVersion Version of the node type that replaces the forwarded name
@param[in] extensionId Extension ID in which the replacement node type can be found
@return false if there was already an forward with the given name and initial version number)OMNI_BIND_RAW_",
py::arg("forward_name"), py::arg("forward_version"), py::arg("replacement_name"),
py::arg("replacement_version"), py::arg("replacement_extension_id"));
cls.def("remove_forward",
[](omni::graph::core::unstable::INodeTypeForwarding* self, const char* forwardName, int forwardVersion)
{
auto return_value = self->removeForward(forwardName, forwardVersion);
return return_value;
},
R"OMNI_BIND_RAW_(@brief Remove an existing node type forward.
Since an forwardName + forwardVersion combination is unique there is no need to pass in the replacement information.
Only the forward with the matching version is removed. Any others with the same name remain untouched.
@param[in] forwardName Forward to be removed
@param[in] forwardVersion The version at which the forward is to be removed
@return false if there was already an forward with the given name and initial version number)OMNI_BIND_RAW_",
py::arg("forward_name"), py::arg("forward_version"));
cls.def("remove_forwarded_type",
[](omni::graph::core::unstable::INodeTypeForwarding* self, const char* referencedName, int referencedVersion)
{
auto return_value = self->removeForwardedType(referencedName, referencedVersion);
return return_value;
},
R"OMNI_BIND_RAW_(@brief Remove forwards referencing a given node type name.
@param[in] referencedName Forward to be removed
@param[in] referencedVersion The version at which the forward is to be removed
@return number of forwards to the given type that were removed)OMNI_BIND_RAW_",
py::arg("referenced_name"), py::arg("referenced_version"));
return omni::python::PyBind<omni::graph::core::unstable::INodeTypeForwarding>::bind(cls);
}
| 8,168 | C | 53.46 | 126 | 0.701273 |
omniverse-code/kit/include/omni/graph/core/unstable/IPrivateNodeGraphDef.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! This is a private interface. Rather than directly using this private interface,
//! access the functionality this interface provides by subclassing GenericGraphDef
template <>
class omni::core::Generated<omni::graph::core::unstable::IPrivateNodeGraphDef_abi>
: public omni::graph::core::unstable::IPrivateNodeGraphDef_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::unstable::IPrivateNodeGraphDef")
//! Returns a handle to authoring graph associated with this definition.
omni::graph::core::GraphObj getAuthoringGraph() noexcept;
//! Returns True if this graph is used as part of instancing pipeline, false otherwise.
//!
//! @note We will most likely remove this before making this interface stable
bool isInstanced() noexcept;
//! Internal binding to receive invalidation messages.
//!
//! @note Once OG will provide topology changed notifications we can register to, this should go away.
void attachToAuthoring(omni::core::ObjectParam<omni::graph::exec::unstable::IDef> definition) noexcept;
//! Pre-execution call can be used to setup the graph state prior to execution or skip entirely the execution.
//!
//! The given task must not be @c nullptr.
omni::graph::exec::unstable::Status preExecute(omni::graph::exec::unstable::ExecutionTask& info) noexcept;
//! Post-execution call can be used to finalize the execution, e.g. transfer computation results to consumers.
//!
//! The given task must not be @c nullptr.
omni::graph::exec::unstable::Status postExecute(omni::graph::exec::unstable::ExecutionTask& info) noexcept;
//! Acquire internal information about bucketing of instances for vectorized execution
//!
//! Arguments must not be @c nullptr.
void getInstanceInfo(const omni::graph::exec::unstable::ExecutionTask& info,
omni::graph::core::InstanceIndex& retBaseInstanceIndex,
size_t& retNumberOfInstances) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::graph::core::GraphObj omni::core::Generated<
omni::graph::core::unstable::IPrivateNodeGraphDef_abi>::getAuthoringGraph() noexcept
{
return getAuthoringGraph_abi();
}
inline bool omni::core::Generated<omni::graph::core::unstable::IPrivateNodeGraphDef_abi>::isInstanced() noexcept
{
return isInstanced_abi();
}
inline void omni::core::Generated<omni::graph::core::unstable::IPrivateNodeGraphDef_abi>::attachToAuthoring(
omni::core::ObjectParam<omni::graph::exec::unstable::IDef> definition) noexcept
{
attachToAuthoring_abi(definition.get());
}
inline omni::graph::exec::unstable::Status omni::core::Generated<omni::graph::core::unstable::IPrivateNodeGraphDef_abi>::preExecute(
omni::graph::exec::unstable::ExecutionTask& info) noexcept
{
return preExecute_abi(&info);
}
inline omni::graph::exec::unstable::Status omni::core::Generated<omni::graph::core::unstable::IPrivateNodeGraphDef_abi>::postExecute(
omni::graph::exec::unstable::ExecutionTask& info) noexcept
{
return postExecute_abi(&info);
}
inline void omni::core::Generated<omni::graph::core::unstable::IPrivateNodeGraphDef_abi>::getInstanceInfo(
const omni::graph::exec::unstable::ExecutionTask& info,
omni::graph::core::InstanceIndex& retBaseInstanceIndex,
size_t& retNumberOfInstances) noexcept
{
getInstanceInfo_abi(&info, &retBaseInstanceIndex, &retNumberOfInstances);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 4,338 | C | 37.741071 | 133 | 0.732135 |
omniverse-code/kit/include/omni/graph/core/unstable/GenericNodeGraphDef.h | // 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.
//
//! @file NodeDef.h
//!
//! @brief Declares @ref omni::graph::core::unstable::IGenericNodeGraphDef.
#pragma once
#include <carb/profiler/Profile.h>
#include <omni/String.h>
#include <omni/graph/core/IInternal.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/unstable/IGenericNodeGraphDef.h>
#include <omni/graph/exec/unstable/NodeGraphDef.h>
#include <omni/inspect/IInspectJsonSerializer.h>
namespace omni
{
namespace graph
{
namespace core
{
namespace unstable
{
//! @copydoc omni::graph::exec::unstable::IGenericNodeGraphDef
class GenericNodeGraphDef : public exec::unstable::NodeGraphDefT<IGenericNodeGraphDef, exec::unstable::INodeGraphDefDebug>
{
public:
//! Construct generic OmniGraph definition.
//!
//! This class is a base class for all OmniGraph node graph definitions and will use provided executor.
//!
//! @param builder Builder constructing the graph
//! @param executorFactory Executor factory to use for this instance of the graph
//! @param definitionName Definition name is considered as a token that transformation passes can register against
//! @param graphObj Authoring graph associated with this definition
//! @param isInstanced Is this an instanced OmniGraph
//!
//! May throw.
static omni::core::ObjectPtr<GenericNodeGraphDef> create(exec::unstable::IGraphBuilder* builder,
exec::unstable::ExecutorFactory executorFactory,
const char* definitionName,
const GraphObj& graphObj,
bool isInstanced)
{
OMNI_THROW_IF_ARG_NULL(builder);
OMNI_THROW_IF_ARG_NULL(definitionName);
return omni::core::steal(new GenericNodeGraphDef(builder, executorFactory, definitionName, graphObj, isInstanced));
}
void build_abi(exec::unstable::IGraphBuilder* builder) noexcept override
{
// make sure the topology of the graph is valid...this may not be the case if graph is empty
// because if happens lazily when requesting root node
getRoot()->validateOrResetTopology();
// attach to authoring graph
m_privateDef->attachToAuthoring(this);
}
bool inspect_abi(inspect::IInspector* inspector) noexcept override
{
return true;
}
static omni::string getDefinitionName(const GraphObj& graphObj)
{
static const omni::string sDefNamePrefix = "og.def.graph_";
return sDefNamePrefix + graphObj.iGraph->getEvaluatorName(graphObj);
}
protected:
using BaseType = exec::unstable::NodeGraphDefT<IGenericNodeGraphDef, exec::unstable::INodeGraphDefDebug>;
GraphObj getAuthoringGraph_abi() noexcept override
{
return m_privateDef->getAuthoringGraph();
}
bool isInstanced_abi() noexcept override
{
return m_privateDef->isInstanced();
}
exec::unstable::INode* getExecutionNode_abi(const NodeObj* nodeObj) noexcept override
{
return nullptr;
}
exec::unstable::Status preExecute_abi(exec::unstable::ExecutionTask* info) noexcept override
{
return m_privateDef->preExecute(*info);
}
exec::unstable::Status postExecute_abi(exec::unstable::ExecutionTask* info) noexcept override
{
return m_privateDef->postExecute(*info);
}
void getInstanceInfo_abi(omni::graph::exec::unstable::ExecutionTask const* info, InstanceIndex* retBaseInstanceIndex, size_t* retNumberOfInstances) noexcept override
{
m_privateDef->getInstanceInfo(*info, *retBaseInstanceIndex, *retNumberOfInstances);
}
GenericNodeGraphDef(exec::unstable::IGraphBuilder* builder,
exec::unstable::ExecutorFactory executorFactory,
const char* definitionName,
const GraphObj& graphObj,
bool isInstanced)
: BaseType(builder->getGraph(), executorFactory, definitionName) // may throw
,
m_privateDef(
carb::getCachedInterface<omni::graph::core::IInternal>()->createPrivateGraphDef(graphObj, isInstanced),
omni::core::kSteal)
{
}
private:
omni::core::ObjectPtr<IPrivateNodeGraphDef> m_privateDef; //!< Internal object, hiding implementation details
//!< relying on OG internals
};
} // namespace unstable
} // namespace core
} // namespace graph
} // namespace omni
| 5,067 | C | 36.264706 | 169 | 0.663114 |
omniverse-code/kit/include/omni/graph/core/unstable/IGenericNodeDef.gen.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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Node definition interface for OmniGraph nodes.
//!
//! This interface allows us to reason about OmniGraph nodes during graph transformation phase and access authoring
//! node associated with this definition.
//!
//! Execution of this definition will callback to OmniGraph node compute method.
template <>
class omni::core::Generated<omni::graph::core::unstable::IGenericNodeDef_abi>
: public omni::graph::core::unstable::IGenericNodeDef_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::unstable::IGenericNodeDef")
//! Returns a handle to authoring node associated with this definition.
omni::graph::core::NodeObj getAuthoringNode() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::graph::core::NodeObj omni::core::Generated<omni::graph::core::unstable::IGenericNodeDef_abi>::getAuthoringNode() noexcept
{
return getAuthoringNode_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 1,778 | C | 30.210526 | 134 | 0.749719 |
omniverse-code/kit/include/omni/graph/core/unstable/IPrivateNodeDef.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! This is a private interface. Rather than directly using this private interface,
//! access the functionality this interface provides by subclassing GenericNodeDef
template <>
class omni::core::Generated<omni::graph::core::unstable::IPrivateNodeDef_abi>
: public omni::graph::core::unstable::IPrivateNodeDef_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::unstable::IPrivateNodeDef")
//! Acquire internal information about bucketing of instances for vectorized execution
//!
//! Arguments must not be @c nullptr.
void getInstanceInfo(omni::graph::exec::unstable::ExecutionTask& info,
omni::graph::core::InstanceIndex& retBaseInstanceIndex,
size_t& retNumberOfInstances) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline void omni::core::Generated<omni::graph::core::unstable::IPrivateNodeDef_abi>::getInstanceInfo(
omni::graph::exec::unstable::ExecutionTask& info,
omni::graph::core::InstanceIndex& retBaseInstanceIndex,
size_t& retNumberOfInstances) noexcept
{
getInstanceInfo_abi(&info, &retBaseInstanceIndex, &retNumberOfInstances);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 2,041 | C | 33.033333 | 101 | 0.734444 |
omniverse-code/kit/include/omni/graph/core/unstable/IAttributeTemplate.h | // 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.
//
//
// This ABI is unstable and subject to change
/* _ _ _____ ______ _______ __ ______ _ _ _____ ______ ___ _ _____ _____ _____ _ __
| | | |/ ____| ____| /\|__ __| \ \ / / __ \| | | | __ \ / __ \ \ / / \ | | | __ \|_ _|/ ____| |/ /
| | | | (___ | |__ / \ | | \ \_/ / | | | | | | |__) | | | | \ \ /\ / /| \| | | |__) | | | | (___ | ' /
| | | |\___ \| __| / /\ \ | | \ /| | | | | | | _ / | | | |\ \/ \/ / | . ` | | _ / | | \___ \| <
| |__| |____) | |____ / ____ \| | | | | |__| | |__| | | \ \ | |__| | \ /\ / | |\ | | | \ \ _| |_ ____) | . \
\____/|_____/|______| /_/ \_\_| |_| \____/ \____/|_| \_\ \____/ \/ \/ |_| \_| |_| \_\_____|_____/|_|\_|
*/
#pragma once
#include <omni/graph/core/iComputeGraph.h>
namespace omni
{
namespace graph
{
namespace core
{
namespace unstable
{
// ======================================================================
// Support for attribute templates types
class AttributeTemplateHandle : public HandleBase<HandleInt, AttributeTemplateHandle>
{
public:
using BaseHandleType = HandleInt;
using HandleBase<HandleInt, AttributeTemplateHandle>::HandleBase;
static constexpr HandleInt invalidValue()
{
return 0;
}
};
struct IAttributeTemplate;
struct AttributeTemplateObj
{
const IAttributeTemplate* iAttributeTemplate;
AttributeTemplateHandle attributeTemplateHandle;
bool isValid() const
{
return attributeTemplateHandle.isValid();
}
};
/**
* Structure with information about the default data stored
* in an attribute template
*/
struct AttributeTemplateDefaultData
{
// Pointer to the data.
const uint8_t* dataPtr;
// The size of a single item in the array. For tuples, this represents the size of the tuple.
size_t itemSizeInBytes;
// The number of items stored. For scalars and tuples this is always 1, otherwise it is the number of elements
// in the array.
size_t elementCount;
};
/**
* Carb interface representing an attribute template. An AttributeTemplate is the definition used
* to create an attribute on a Node when created from a NodeType.
*
*/
struct IAttributeTemplate
{
CARB_PLUGIN_INTERFACE("omni::graph::core::unstable::IAttributeTemplate", 0, 2);
/**
* Returns the name of the attribute template, which includes any namespace prefixes prepended
* by the NodeType.
*
* @param[in] attributeObj. The attribute template to inspect
* @returns Retreives the name of the attribute template wit
*/
const char*(CARB_ABI* getName)(const AttributeTemplateObj& attributeObj);
/**
* Returns a string of the typename that will be used when creating the attribute.
*
* For extended attribute types, this will return "token".
* @see IAttribute::getTypeName
* @param[in] attributeObj. The attribute template to inspect
* @return The type name of the attribute template.
*/
const char*(CARB_ABI* getTypeName)(const AttributeTemplateObj& attributeObj);
/**
* Gets the AttributePortType of the attribute template. Use this to check whether
* an attribute template is an input, output, or state.
*
* @param[in] attributeObj. The attribute template to inspect
* @return The AttributePortType of the attribute template.
*/
AttributePortType(CARB_ABI* getPortType)(const AttributeTemplateObj& attributeObj);
/**
* Returns the extended type, if any, of the attribute template. Extended types are values such as "union"
* and "any" that indicate an attribute template can hold a set of different type.
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @return The extended type of the attribute template.
*/
ExtendedAttributeType(CARB_ABI* getExtendedAttributeType)(const AttributeTemplateObj& attributeObj);
/**
* Returns the type of the attribute template object. If the extended type is
* kExtendedAttributeType_Regular, this will return the assigned type to the port,
* otherwise it will return type representing an unknown type to indicate multiple values exist.
*
* To fetch all support types, use getExtendedAttributeTypes.
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @return The type of the attribute template.
*/
omni::graph::core::Type(CARB_ABI* getAttributeType)(const AttributeTemplateObj& attributeObj);
/**
* Returns the number of compatible types with an attribute template. If the extended type is a union type,
* returns the number of concrete types available.If the extended type is a regular type, this always
* returns 1. If is an "any", this will always return 0.
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @return The number of compatible types
*/
size_t(CARB_ABI* getExtendedAttributeTypeCount)(const AttributeTemplateObj& attributeObj);
/**
* Returns the list of compatible types. Note that 0 types are returned if the attribute template
* extended type is "any".
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @param[out] typeBuffer A buffer to store the compatible types.
* @param[in] typeBufferCount The number of types that can be stored in typeBuffer.
* @return The number of compatible types copied to typeBuffer.
*/
size_t(CARB_ABI* getExtendedAttributeTypes)(const AttributeTemplateObj& attributeObj,
omni::graph::core::Type* typeBuffer,
size_t typeBufferCount);
/**
* Sets the extended type of the attribute. Note that this may clear any default data for the type,
* as default data is only valid Regular typed attribute templates.
*
* When setting the extended type to be a regular type, use the setType function instead.
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @param[in] attributeType The ExtendedAttributeType to change the template to.
* @param[in] typeList For union types, a comma separated list of union names or types to support.
*/
void(CARB_ABI* setExtendedType)(const AttributeTemplateObj& attributeObj,
ExtendedAttributeType attributeType,
const char* typeList);
/**
* Sets the attribute template to use a regular (non-extended) type.
*
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @param[in] attributeType The type to set.
* @param[in] defaultValuePtr Pointer to default data to set on this type. Can be null to indicate
* no default data.
* @param[in] defaultElemCount If the type is an array type, this is the number of items. It is ignored for
* scalar types.
*/
void(CARB_ABI* setType)(const AttributeTemplateObj& attributeObj,
omni::graph::core::Type attributeType,
const void* defaultValuePtr,
size_t defaultElemCount);
/**
* If an attribute template is a compound node type, make the template expose an attribute on the associated compound graph.
* If the attribute template is an output, only one connection is supported, and this will overwrite the connection.
* If the attribute template is an input, this will append to the current list of connections.
*
* The connection must be on a child node of the graph template of the compound node type.
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @param[in] path. The path to attribute to connect to.
* @returns True if the connection was successfully set, false otherwise.
*/
bool(CARB_ABI* connectByPath)(const AttributeTemplateObj& attributeObj, const omni::fabric::PathC& path);
/**
* Disconnect all connections from the attribute template. Only works if the attribute template is
* part of a compound node type
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
*/
void(CARB_ABI* disconnectAll)(const AttributeTemplateObj& attributeObj);
/**
* Disconnect an attribute from the attribute template. Only applies if the attribute template is
* part of a compound node type.
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @param[path] path The path to disconnect.
* @returns True if the path was found and disconnected, false otherwise.
*/
bool(CARB_ABI* disconnectByPath)(const AttributeTemplateObj& attributeObj, const omni::fabric::PathC& path);
/**
* Retrieves the number of connections for an attribute template. Only applies if the attribute template is
* part of a compound node type.
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
*/
size_t(CARB_ABI* getConnectionCount)(const AttributeTemplateObj& attributeObj);
/**
* Retrieves the connections for an attribute template. Only applies if the attribute template is part of a
* compound node type.
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @param[out] pathsBuffer Pointer a buffer to store the paths
* @param[in] pathBufferCount The number of paths that can be stored in pathsBuffer.
*/
size_t(CARB_ABI* getConnections)(const AttributeTemplateObj& attributeObj,
omni::fabric::PathC* pathsBuffer,
size_t pathBufferCount);
/**
* Returns the number of metadata entries on this attribute template.
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @return the number of metadata key/value pairs on this attribute
*/
size_t(CARB_ABI* getMetadataCount)(const AttributeTemplateObj& attributeObj);
/**
* Returns the set of all metadata on this attribute template.
*
* The keyBuf and valueBuf arrays preallocated by the caller, and contain at least "getMetadataCount()"
* entries in them.
* All returned strings are owned by the node type and not to be destroyed.
* The returned keyBuf and valueBuf must have exactly the same size with corresponding index values; that is
* keyBuf[i] is the metadata name for the string in valueBuf[i].
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @param[out] keyBuf Buffer in which to put the list of metadata keys
* @param[out] valueBuf Buffer in which to put the list of metadata values
* @param[in] bufferSize the number of strings each of the two buffers is able to hold
* @return Number of metadata items successfully populated
*/
size_t(CARB_ABI* getAllMetadata)(const AttributeTemplateObj& attributeObj,
const char** keyBuf,
const char** valueBuf,
size_t bufferSize);
/**
* Retrieves a metadata value from this attribute
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @param[in] key The name of the metadata to be retrieved
* @return The value of the metadata, or nullptr if the named metadata was not set on this attribute
*/
const char*(CARB_ABI* getMetadata)(const AttributeTemplateObj& attributeObj, const char* key);
/**
* Sets a metadata value on this attribute template. Metadata applied to an AttributeTemplate does
* not apply to the underlying USD attribute itself, but will be applied to any corresponding
* attributes that are created from it.
*
* @param[in] attrObj Reference to the attribute template..
* @param[in] key The keyword, used as the name of the metadata. Cannot be null.
* @param[in] value The value of the metadata. Only string values are supported. if null, clears the existing
* metadata with the given key
* @return true if the keyword was successfully set
*/
bool(CARB_ABI* setMetadata)(const AttributeTemplateObj& attrObj, const char* key, const char* value);
/** Retrieves a readonly memory buffer containing the default data set on this attribute templates.
* If there is no default data set then nullptr will be returned.
*
* @param[in] attributeObj Reference to the AttributeTemplateObj representing the attribute template.
* @return Structure containing the raw data storing the default value and information about the memory stored.
* The data format will change depending on the value returned by getAttributeType().
*/
AttributeTemplateDefaultData(CARB_ABI* getDefaultData)(const AttributeTemplateObj& attributeObj);
};
STRUCT_INTEGRITY_CHECK(IAttributeTemplate, getDefaultData, 18);
}
}
}
}
| 14,102 | C | 44.493548 | 129 | 0.655297 |
omniverse-code/kit/include/omni/graph/core/unstable/SafeDispatch.h | // 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.
//
//! @file SafeDispatch.h
//!
//! @brief Declares a helper for OmniGraph types to run with serial initial frame. Also adds support for debugging
//! options.
#pragma once
#include <omni/graph/exec/unstable/Executor.h>
#include <omni/kit/exec/core/unstable/IExecutionContext.h>
#include <omni/kit/exec/core/unstable/IExecutionGraphSettings.h>
namespace omni
{
namespace graph
{
namespace core
{
namespace unstable
{
//! Class used to control globally how things should dispatch within OmniGraph
struct SafeDispatch
{
//! Method called by executor to determine scheduling info
static exec::unstable::SchedulingInfo getSchedulingInfo(const omni::graph::exec::unstable::ExecutionTask& task)
{
if (kit::exec::core::unstable::getExecutionGraphSettings()->shouldForceSerial())
return exec::unstable::SchedulingInfo::eSchedulerBypass;
else if (getNeedsIsolation(task))
return exec::unstable::SchedulingInfo::eIsolate;
else if (kit::exec::core::unstable::getExecutionGraphSettings()->shouldForceParallel())
return graph::exec::unstable::SchedulingInfo::eParallel;
else
return graph::exec::unstable::DefaultSchedulingStrategy::getSchedulingInfo(task);
}
//! Is task forced to execute in isolation. Currently used to stabilize the graph before parallel execution.
static bool getNeedsIsolation(const omni::graph::exec::unstable::ExecutionTask& task)
{
auto* context = exec::unstable::cast<kit::exec::core::unstable::IExecutionContext>(task.getContext());
auto* nodeState = context->getStateInfo(task);
const bool alreadyComputed = nodeState->getExecutionStamp().isValid();
nodeState->setExecutionStamp(context->getExecutionStamp());
return !alreadyComputed;
}
};
} // namespace unstable
} // namespace core
} // namespace graph
} // namespace omni
| 2,337 | C | 36.709677 | 115 | 0.731279 |
omniverse-code/kit/include/omni/graph/core/unstable/IPrivateNodeDef.h | // 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.
//
//! @file IPrivateNodeDef.h
//!
//! @brief Defines @ref omni::graph::core::unstable::IPrivateNodeDef.
#pragma once
#include <omni/graph/core/Handle.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/exec/unstable/ConstName.h>
#include <omni/graph/exec/unstable/IBase.h>
#include <omni/graph/exec/unstable/SchedulingInfo.h>
#include <omni/graph/exec/unstable/Status.h>
namespace omni
{
namespace graph
{
namespace exec
{
namespace unstable
{
// forward declarations needed by interface declaration
class ExecutionTask;
}
}
namespace core
{
namespace unstable
{
// forward declarations needed by interface declaration
class IPrivateNodeDef;
class IPrivateNodeDef_abi;
//! This is a private interface. Rather than directly using this private interface,
//! access the functionality this interface provides by subclassing GenericNodeDef
class IPrivateNodeDef_abi
: public omni::core::Inherits<exec::unstable::IBase, OMNI_TYPE_ID("omni.graph.core.unstable.IPrivateNodeDef")>
{
protected:
//! Acquire internal information about bucketing of instances for vectorized execution
//!
//! Arguments must not be @c nullptr.
virtual void getInstanceInfo_abi(OMNI_ATTR("in, out, not_null, throw_if_null, ref")
omni::graph::exec::unstable::ExecutionTask* info,
OMNI_ATTR("out, not_null, ref") InstanceIndex* retBaseInstanceIndex,
OMNI_ATTR("out, not_null, ref") size_t* retNumberOfInstances) noexcept = 0;
};
} // namespace unstable
} // namespace core
} // namespace graph
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/graph/core/unstable/IPrivateNodeDef.gen.h>
// custom API declaration
//! @copydoc omni::graph::core::IPrivateNodeDef_abi
class omni::graph::core::unstable::IPrivateNodeDef
: public omni::core::Generated<omni::graph::core::unstable::IPrivateNodeDef_abi>
{
};
// custom API implementation
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/graph/core/unstable/IPrivateNodeDef.gen.h>
| 2,586 | C | 30.168674 | 114 | 0.732405 |
omniverse-code/kit/include/omni/graph/core/unstable/IGenericNodeDef.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.
//
//! @file IGenericNodeDef.h
//!
//! @brief Defines @ref omni::graph::core::unstable::IGenericNodeDef.
#pragma once
#include <omni/graph/exec/unstable/INodeDef.h>
#include <omni/core/IObject.h>
#include <omni/graph/core/Handle.h>
namespace omni
{
namespace graph
{
namespace core
{
namespace unstable
{
// forward declarations needed by interface declaration
class IGenericNodeDef;
class IGenericNodeDef_abi;
//! Node definition interface for OmniGraph nodes.
//!
//! This interface allows us to reason about OmniGraph nodes during graph transformation phase and access authoring
//! node associated with this definition.
//!
//! Execution of this definition will callback to OmniGraph node compute method.
class IGenericNodeDef_abi : public omni::core::Inherits<exec::unstable::INodeDef, OMNI_TYPE_ID("omni.graph.core.unstable.IGenericNodeDef")>
{
protected:
//! Returns a handle to authoring node associated with this definition.
virtual NodeObj getAuthoringNode_abi() noexcept = 0;
};
//! Smart pointer managing an instance of @ref IGenericNodeDef.
using GenericNodeDefPtr = omni::core::ObjectPtr<IGenericNodeDef>;
} // namespace unstable
} // namespace core
} // namespace graph
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/graph/core/unstable/IGenericNodeDef.gen.h>
// custom API declaration
//! @copydoc omni::graph::core::IGenericNodeDef_abi
class omni::graph::core::unstable::IGenericNodeDef : public omni::core::Generated<omni::graph::core::unstable::IGenericNodeDef_abi>
{ };
// additional headers needed for API implementation
// ...
// custom API implementation
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/graph/core/unstable/IGenericNodeDef.gen.h>
| 2,222 | C | 29.452054 | 139 | 0.770477 |
omniverse-code/kit/include/omni/graph/core/unstable/ICompoundNodeType.h | // 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.
//
//
// This ABI is unstable and subject to change
/* _ _ _____ ______ _______ __ ______ _ _ _____ ______ ___ _ _____ _____ _____ _ __
| | | |/ ____| ____| /\|__ __| \ \ / / __ \| | | | __ \ / __ \ \ / / \ | | | __ \|_ _|/ ____| |/ /
| | | | (___ | |__ / \ | | \ \_/ / | | | | | | |__) | | | | \ \ /\ / /| \| | | |__) | | | | (___ | ' /
| | | |\___ \| __| / /\ \ | | \ /| | | | | | | _ / | | | |\ \/ \/ / | . ` | | _ / | | \___ \| <
| |__| |____) | |____ / ____ \| | | | | |__| | |__| | | \ \ | |__| | \ /\ / | |\ | | | \ \ _| |_ ____) | . \
\____/|_____/|______| /_/ \_\_| |_| \____/ \____/|_| \_\ \____/ \/ \/ |_| \_| |_| \_\_____|_____/|_|\_|
*/
#pragma once
#include <omni/graph/core/unstable/IAttributeTemplate.h>
namespace omni
{
namespace graph
{
namespace core
{
namespace unstable
{
struct ICompoundNodeType;
class CompoundNodeTypeHandle : public HandleBase<NodeTypeHandle, CompoundNodeTypeHandle>
{
public:
using HandleBase<NodeTypeHandle, CompoundNodeTypeHandle>::HandleBase;
static constexpr NodeTypeHandle invalidValue()
{
return kInvalidNodeTypeHandle;
}
};
struct CompoundNodeTypeObj
{
const ICompoundNodeType* iNodeType; //!< interface to functionality on the compound node type
CompoundNodeTypeHandle nodeTypeHandle; //!< opaque handle to actual underlying node type - managed by OmniGraph
bool isValid() const
{
return nodeTypeHandle.isValid();
}
};
/**
* Carb interface for manipulating compound node type objects
*
*/
struct ICompoundNodeType
{
CARB_PLUGIN_INTERFACE("omni::graph::core::unstable::ICompoundNodeType", 0, 1);
/**
* Given an existing node type object, casts it to a compound node type object
*
* @param[in] Node Type object to convert
* @returns A CompoundNodeTypeObj representing the same Node Type. If the Node Type
* is not a Compound Node Type, the returned object will not be valid.
*/
CompoundNodeTypeObj(CARB_ABI* getCompoundNodeType)(const NodeTypeObj& nodeType);
/**
* Finds a compound node type by its USD SdfPath
*
* @param[in] An SdfPath to the location of the correspond UsdPrim representing the Compound Node Type
* @returns An object representing the compound node type, or an invalid object
* if no compound node type exists at the given path
*/
CompoundNodeTypeObj(CARB_ABI* findCompoundNodeTypeByPath)(const char* path);
/**
* Create a Compound Node Type object at the given path.
*
* @param[in] compoundName The name of the compound to be created. This will be the name of the
* compound USD object, and the default name in registration. Cannot be null
* and must comform to USD naming standards.
* @param[in] graphDefinitionName The name of Omnigraph definition created defining the function of the
* compound. Cannot be null and must conform to USD naming standards.
* @param[in] nameSpace The namespace of the compound when registered in the node library. Can be
* null, which indicates a default of "local.nodes".
* @param[in] compoundFolder Sdf style Path the compound folder to store the compound in. Can be null,
* which indicates to use the default folder, which is a scope named "Compounds"
* parented to the default prim of the stage. If the folder does not exist,
* it will be created.
* @param[in] evaluatorType The type of the evaluator to associate with the graph
* @returns A CompoundNodeType object.
*/
CompoundNodeTypeObj(CARB_ABI* createCompoundNodeType)(const char* compoundName,
const char* graphDefinitionName,
const char* nameSpace,
const char* compoundFolder,
const char* evaluatorType);
/**
* Retrieves the default folder path where compound node types are placed on the stage.
* This is typically a Usd::Scope under the default prim. e.g. "/World/Compounds".
*
* @returns The path to the folder.
*/
omni::fabric::PathC(CARB_ABI* getDefaultFolder)();
/**
* Finds the input with the given name. The 'inputs:' prefix is optional.
*
* @param nodeType. The compound node type to search
* @param inputName. The name to search for.
*
* @returns An AttributeTemplateObj representing the input. If the input is not found, the
* returned objects isValid() method will return false.
*/
AttributeTemplateObj(CARB_ABI* findInput)(const CompoundNodeTypeObj& nodeType, const char* inputName);
/**
* Finds the output with the given name. The 'outputs:' prefix is optional.
*
* @param nodeType. The compound node type to search
* @param outputName. The name to search for.
*
* @returns An AttributeTemplateObj representing the output. If the output is not found, the
* returned objects isValid() method will return false.
*/
AttributeTemplateObj(CARB_ABI* findOutput)(const CompoundNodeTypeObj& nodeType, const char* outputName);
/**
* Removes an input with the given name. The 'inputs:' prefix is optional.
*
* @param nodeType. The compound node type to remove an input from.
* @param inputName. The name of the input to remove.
*
* @returns True if the input was removed, false otherwise.
*/
bool(CARB_ABI* removeInputByName)(const CompoundNodeTypeObj& nodeType, const char* inputName);
/**
* Removes an output with the given name. The 'outputs:' prefix is optional.
*
* @param nodeType. The compound node type to remove an output from.
* @param outputName. The name of the output to remove.
*
* @returns True if the output was removed, false otherwise.
*/
bool(CARB_ABI* removeOutputByName)(const CompoundNodeTypeObj& nodeType, const char* outputName);
/**
* Downcasts a CompoundNodeTypeObj to a regular NodeTypeObj.
*
* @param nodeType. The compound node type to downcast.
* @returns NodeType object also representing the compound node. If the ComoundNodeType object is not
* valid, an invalid NodeType object will be returned.
*/
NodeTypeObj(CARB_ABI* asNodeType)(const CompoundNodeTypeObj& nodeType);
/**
* Get the number of input attribute templates on this node type
*
* @param nodeType. The compound node type to fetch inputs from.
* @returns The number of input attributes on the compound node type.
*/
size_t(CARB_ABI* getInputCount)(const CompoundNodeTypeObj& nodeType);
/**
* Retrieves the input attributes from a compound node type.
*
* @param nodeType. The compound node type to retreive inputs from.
* @param templateBuffer. Buffer to hold the returned objects
* @param bufferElementCount. The number of objects the buffer can hold.
*
* @returns The number of items copied to bufferElementCount.
*/
size_t(CARB_ABI* getInputs)(const CompoundNodeTypeObj& nodeType, AttributeTemplateObj* templateBuffer, size_t bufferElementCount);
/**
* Get the number of output attribute templates on this node type.
*
* @param nodeType. The compound node type to fetch outputs from.
* @returns The number of output attributes on the compound node type.
*/
size_t(CARB_ABI* getOutputCount)(const CompoundNodeTypeObj& nodeType);
/**
* Retrieves the output attributes from a compound node type.
*
* @param nodeType. The compound node type to retreive outputs from.
* @param templateBuffer. Buffer to hold the returned objects
* @param bufferElementCount. The number of objects the buffer can hold.
*
* @returns The number of items copied to bufferElementCount.
*/
size_t(CARB_ABI* getOutputs)(const CompoundNodeTypeObj& nodeType, AttributeTemplateObj* templateBuffer, size_t bufferElementCount);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(ICompoundNodeType, getOutputs, 12);
}
}
}
}
| 9,026 | C | 40.986046 | 136 | 0.616441 |
omniverse-code/kit/include/omni/graph/core/unstable/IPrivateNodeGraphDef.h | // 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.
//
//! @file IPrivateNodeGraphDef.h
//!
//! @brief Defines @ref omni::graph::core::unstable::IPrivateNodeGraphDef.
#pragma once
#include <omni/graph/core/Handle.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/exec/unstable/ConstName.h>
#include <omni/graph/exec/unstable/IBase.h>
#include <omni/graph/exec/unstable/SchedulingInfo.h>
#include <omni/graph/exec/unstable/Status.h>
namespace omni
{
namespace graph
{
namespace exec
{
namespace unstable
{
// forward declarations needed by interface declaration
class IDef;
class INode;
class ExecutionTask;
}
}
namespace core
{
namespace unstable
{
// forward declarations needed by interface declaration
class IPrivateNodeGraphDef;
class IPrivateNodeGraphDef_abi;
//! This is a private interface. Rather than directly using this private interface,
//! access the functionality this interface provides by subclassing GenericGraphDef
class IPrivateNodeGraphDef_abi
: public omni::core::Inherits<exec::unstable::IBase, OMNI_TYPE_ID("omni.graph.core.unstable.IPrivateNodeGraphDef")>
{
protected:
//! Returns a handle to authoring graph associated with this definition.
virtual GraphObj getAuthoringGraph_abi() noexcept = 0;
//! Returns True if this graph is used as part of instancing pipeline, false otherwise.
//!
//! @note We will most likely remove this before making this interface stable
virtual bool isInstanced_abi() noexcept = 0;
//! Internal binding to receive invalidation messages.
//!
//! @note Once OG will provide topology changed notifications we can register to, this should go away.
virtual void attachToAuthoring_abi(OMNI_ATTR("not_null") omni::graph::exec::unstable::IDef* definition) noexcept = 0;
//! Pre-execution call can be used to setup the graph state prior to execution or skip entirely the execution.
//!
//! The given task must not be @c nullptr.
virtual omni::graph::exec::unstable::Status preExecute_abi(OMNI_ATTR(
"in, out, not_null, throw_if_null, ref") omni::graph::exec::unstable::ExecutionTask* info) noexcept = 0;
//! Post-execution call can be used to finalize the execution, e.g. transfer computation results to consumers.
//!
//! The given task must not be @c nullptr.
virtual omni::graph::exec::unstable::Status postExecute_abi(OMNI_ATTR(
"in, out, not_null, throw_if_null, ref") omni::graph::exec::unstable::ExecutionTask* info) noexcept = 0;
//! Acquire internal information about bucketing of instances for vectorized execution
//!
//! Arguments must not be @c nullptr.
virtual void getInstanceInfo_abi(OMNI_ATTR("in, not_null, throw_if_null, ref")
omni::graph::exec::unstable::ExecutionTask const* info,
OMNI_ATTR("out, not_null, ref") omni::graph::core::InstanceIndex* retBaseInstanceIndex,
OMNI_ATTR("out, not_null, ref") size_t* retNumberOfInstances) noexcept = 0;
};
} // namespace unstable
} // namespace core
} // namespace graph
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/graph/core/unstable/IPrivateNodeGraphDef.gen.h>
// custom API declaration
//! @copydoc omni::graph::core::IPrivateNodeGraphDef_abi
class omni::graph::core::unstable::IPrivateNodeGraphDef
: public omni::core::Generated<omni::graph::core::unstable::IPrivateNodeGraphDef_abi>
{
};
// additional headers needed for API implementation
#include <omni/graph/exec/unstable/IGraphBuilder.h>
#include <omni/graph/exec/unstable/INode.h>
// custom API implementation
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/graph/core/unstable/IPrivateNodeGraphDef.gen.h>
| 4,228 | C | 36.096491 | 124 | 0.727294 |
omniverse-code/kit/include/omni/graph/core/cuda/Matrix2d.h | // 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.
//
#pragma once
// CUDA-compatible struct with functions for working with a 2x2 double matrix
#include <float.h>
struct Matrix2d
{
//! Default constructor. Leaves the matrix component values undefined.
Matrix2d() = default;
__device__ explicit Matrix2d(double s)
{
SetDiagonal(s);
}
__device__ Matrix2d& SetDiagonal(double s);
__device__ Matrix2d& SetScale(double s);
__device__ Matrix2d GetInverse() const;
//! Post-multiplies matrix \e m into this matrix.
__device__ Matrix2d& operator*=(const Matrix2d& m);
//! Multiplies matrix \e m1 by \e m2.
__device__ friend Matrix2d operator*(const Matrix2d& m1, const Matrix2d& m2)
{
Matrix2d tmp(m1);
tmp *= m2;
return tmp;
}
//! Matrix storage, in row-major order.
double _mtx[2][2];
};
// Leaves the [2][2] element as 1
inline __device__ Matrix2d& Matrix2d::SetScale(double s)
{
_mtx[0][0] = s;
_mtx[0][1] = 0.0;
_mtx[1][0] = 0.0;
_mtx[1][1] = s;
return *this;
}
inline __device__ Matrix2d& Matrix2d::SetDiagonal(double s)
{
_mtx[0][0] = s;
_mtx[0][1] = 0.0;
_mtx[1][0] = 0.0;
_mtx[1][1] = s;
return *this;
}
inline __device__ Matrix2d Matrix2d::GetInverse() const
{
double x00, x01;
double x10, x11;
// Pickle values for computing determinants into registers
x00 = _mtx[0][0];
x01 = _mtx[0][1];
x10 = _mtx[1][0];
x11 = _mtx[1][1];
// Compute the determinant
double det = x00 * x11 - x01 * x10;
Matrix2d inverse;
double eps = 0;
if (abs(det) > eps)
{
double rcp = 1.0 / det;
// Multiply all 3x3 cofactors by reciprocal & transpose
inverse._mtx[0][0] = x11 * rcp;
inverse._mtx[0][1] = -x01 * rcp;
inverse._mtx[1][0] = -x10 * rcp;
inverse._mtx[1][1] = x00 * rcp;
}
else
{
inverse.SetScale(FLT_MAX);
}
return inverse;
}
inline __device__ Matrix2d& Matrix2d::operator*=(const Matrix2d& m)
{
// Save current values before they are overwritten
Matrix2d tmp = *this;
_mtx[0][0] = tmp._mtx[0][0] * m._mtx[0][0] + tmp._mtx[0][1] * m._mtx[1][0];
_mtx[0][1] = tmp._mtx[0][0] * m._mtx[0][1] + tmp._mtx[0][1] * m._mtx[1][1];
_mtx[1][0] = tmp._mtx[1][0] * m._mtx[0][0] + tmp._mtx[1][1] * m._mtx[1][0];
_mtx[1][1] = tmp._mtx[1][0] * m._mtx[0][1] + tmp._mtx[1][1] * m._mtx[1][1];
return *this;
}
| 2,871 | C | 24.873874 | 80 | 0.58969 |
omniverse-code/kit/include/omni/graph/core/cuda/Matrix4d.h | // 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.
//
#pragma once
// CUDA-compatible struct with functions for working with a 4x4 double matrix
#include <float.h>
struct Matrix4d
{
//! Default constructor. Leaves the matrix component values undefined.
Matrix4d() = default;
__device__ explicit Matrix4d(double s)
{
SetDiagonal(s);
}
__device__ Matrix4d& SetDiagonal(double s);
__device__ Matrix4d& SetScale(double s);
__device__ Matrix4d GetInverse() const;
//! Post-multiplies matrix \e m into this matrix.
__device__ Matrix4d& operator*=(const Matrix4d& m);
//! Multiplies matrix \e m1 by \e m2.
__device__ friend Matrix4d operator*(const Matrix4d& m1, const Matrix4d& m2)
{
Matrix4d tmp(m1);
tmp *= m2;
return tmp;
}
//! Matrix storage, in row-major order.
double _mtx[4][4];
};
// Leaves the [3][3] element as 1
inline __device__ Matrix4d& Matrix4d::SetScale(double s)
{
_mtx[0][0] = s;
_mtx[0][1] = 0.0;
_mtx[0][2] = 0.0;
_mtx[0][3] = 0.0;
_mtx[1][0] = 0.0;
_mtx[1][1] = s;
_mtx[1][2] = 0.0;
_mtx[1][3] = 0.0;
_mtx[2][0] = 0.0;
_mtx[2][1] = 0.0;
_mtx[2][2] = s;
_mtx[2][3] = 0.0;
_mtx[3][0] = 0.0;
_mtx[3][1] = 0.0;
_mtx[3][2] = 0.0;
_mtx[3][3] = 1.0;
return *this;
}
inline __device__ Matrix4d& Matrix4d::SetDiagonal(double s)
{
_mtx[0][0] = s;
_mtx[0][1] = 0.0;
_mtx[0][2] = 0.0;
_mtx[0][3] = 0.0;
_mtx[1][0] = 0.0;
_mtx[1][1] = s;
_mtx[1][2] = 0.0;
_mtx[1][3] = 0.0;
_mtx[2][0] = 0.0;
_mtx[2][1] = 0.0;
_mtx[2][2] = s;
_mtx[2][3] = 0.0;
_mtx[3][0] = 0.0;
_mtx[3][1] = 0.0;
_mtx[3][2] = 0.0;
_mtx[3][3] = s;
return *this;
}
inline __device__ Matrix4d Matrix4d::GetInverse() const
{
double x00, x01, x02, x03;
double x10, x11, x12, x13;
double x20, x21, x22, x23;
double x30, x31, x32, x33;
double y01, y02, y03, y12, y13, y23;
double z00, z10, z20, z30;
double z01, z11, z21, z31;
double z02, z03, z12, z13, z22, z23, z32, z33;
// Pickle 1st two columns of matrix into registers
x00 = _mtx[0][0];
x01 = _mtx[0][1];
x10 = _mtx[1][0];
x11 = _mtx[1][1];
x20 = _mtx[2][0];
x21 = _mtx[2][1];
x30 = _mtx[3][0];
x31 = _mtx[3][1];
// Compute all six 2x2 determinants of 1st two columns
y01 = x00 * x11 - x10 * x01;
y02 = x00 * x21 - x20 * x01;
y03 = x00 * x31 - x30 * x01;
y12 = x10 * x21 - x20 * x11;
y13 = x10 * x31 - x30 * x11;
y23 = x20 * x31 - x30 * x21;
// Pickle last two columns of matrix into registers
x02 = _mtx[0][2];
x03 = _mtx[0][3];
x12 = _mtx[1][2];
x13 = _mtx[1][3];
x22 = _mtx[2][2];
x23 = _mtx[2][3];
x32 = _mtx[3][2];
x33 = _mtx[3][3];
// Compute all 3x3 cofactors for 2nd two columns */
z33 = x02 * y12 - x12 * y02 + x22 * y01;
z23 = x12 * y03 - x32 * y01 - x02 * y13;
z13 = x02 * y23 - x22 * y03 + x32 * y02;
z03 = x22 * y13 - x32 * y12 - x12 * y23;
z32 = x13 * y02 - x23 * y01 - x03 * y12;
z22 = x03 * y13 - x13 * y03 + x33 * y01;
z12 = x23 * y03 - x33 * y02 - x03 * y23;
z02 = x13 * y23 - x23 * y13 + x33 * y12;
// Compute all six 2x2 determinants of 2nd two columns
y01 = x02 * x13 - x12 * x03;
y02 = x02 * x23 - x22 * x03;
y03 = x02 * x33 - x32 * x03;
y12 = x12 * x23 - x22 * x13;
y13 = x12 * x33 - x32 * x13;
y23 = x22 * x33 - x32 * x23;
// Compute all 3x3 cofactors for 1st two columns
z30 = x11 * y02 - x21 * y01 - x01 * y12;
z20 = x01 * y13 - x11 * y03 + x31 * y01;
z10 = x21 * y03 - x31 * y02 - x01 * y23;
z00 = x11 * y23 - x21 * y13 + x31 * y12;
z31 = x00 * y12 - x10 * y02 + x20 * y01;
z21 = x10 * y03 - x30 * y01 - x00 * y13;
z11 = x00 * y23 - x20 * y03 + x30 * y02;
z01 = x20 * y13 - x30 * y12 - x10 * y23;
// compute 4x4 determinant & its reciprocal
double det = x30 * z30 + x20 * z20 + x10 * z10 + x00 * z00;
Matrix4d inverse;
double eps = 0;
if (abs(det) > eps)
{
double rcp = 1.0 / det;
// Multiply all 3x3 cofactors by reciprocal & transpose
inverse._mtx[0][0] = z00 * rcp;
inverse._mtx[0][1] = z10 * rcp;
inverse._mtx[1][0] = z01 * rcp;
inverse._mtx[0][2] = z20 * rcp;
inverse._mtx[2][0] = z02 * rcp;
inverse._mtx[0][3] = z30 * rcp;
inverse._mtx[3][0] = z03 * rcp;
inverse._mtx[1][1] = z11 * rcp;
inverse._mtx[1][2] = z21 * rcp;
inverse._mtx[2][1] = z12 * rcp;
inverse._mtx[1][3] = z31 * rcp;
inverse._mtx[3][1] = z13 * rcp;
inverse._mtx[2][2] = z22 * rcp;
inverse._mtx[2][3] = z32 * rcp;
inverse._mtx[3][2] = z23 * rcp;
inverse._mtx[3][3] = z33 * rcp;
}
else
{
inverse.SetScale(FLT_MAX);
}
return inverse;
}
inline __device__ Matrix4d& Matrix4d::operator*=(const Matrix4d& m)
{
// Save current values before they are overwritten
Matrix4d tmp = *this;
_mtx[0][0] = tmp._mtx[0][0] * m._mtx[0][0] + tmp._mtx[0][1] * m._mtx[1][0] + tmp._mtx[0][2] * m._mtx[2][0] +
tmp._mtx[0][3] * m._mtx[3][0];
_mtx[0][1] = tmp._mtx[0][0] * m._mtx[0][1] + tmp._mtx[0][1] * m._mtx[1][1] + tmp._mtx[0][2] * m._mtx[2][1] +
tmp._mtx[0][3] * m._mtx[3][1];
_mtx[0][2] = tmp._mtx[0][0] * m._mtx[0][2] + tmp._mtx[0][1] * m._mtx[1][2] + tmp._mtx[0][2] * m._mtx[2][2] +
tmp._mtx[0][3] * m._mtx[3][2];
_mtx[0][3] = tmp._mtx[0][0] * m._mtx[0][3] + tmp._mtx[0][1] * m._mtx[1][3] + tmp._mtx[0][2] * m._mtx[2][3] +
tmp._mtx[0][3] * m._mtx[3][3];
_mtx[1][0] = tmp._mtx[1][0] * m._mtx[0][0] + tmp._mtx[1][1] * m._mtx[1][0] + tmp._mtx[1][2] * m._mtx[2][0] +
tmp._mtx[1][3] * m._mtx[3][0];
_mtx[1][1] = tmp._mtx[1][0] * m._mtx[0][1] + tmp._mtx[1][1] * m._mtx[1][1] + tmp._mtx[1][2] * m._mtx[2][1] +
tmp._mtx[1][3] * m._mtx[3][1];
_mtx[1][2] = tmp._mtx[1][0] * m._mtx[0][2] + tmp._mtx[1][1] * m._mtx[1][2] + tmp._mtx[1][2] * m._mtx[2][2] +
tmp._mtx[1][3] * m._mtx[3][2];
_mtx[1][3] = tmp._mtx[1][0] * m._mtx[0][3] + tmp._mtx[1][1] * m._mtx[1][3] + tmp._mtx[1][2] * m._mtx[2][3] +
tmp._mtx[1][3] * m._mtx[3][3];
_mtx[2][0] = tmp._mtx[2][0] * m._mtx[0][0] + tmp._mtx[2][1] * m._mtx[1][0] + tmp._mtx[2][2] * m._mtx[2][0] +
tmp._mtx[2][3] * m._mtx[3][0];
_mtx[2][1] = tmp._mtx[2][0] * m._mtx[0][1] + tmp._mtx[2][1] * m._mtx[1][1] + tmp._mtx[2][2] * m._mtx[2][1] +
tmp._mtx[2][3] * m._mtx[3][1];
_mtx[2][2] = tmp._mtx[2][0] * m._mtx[0][2] + tmp._mtx[2][1] * m._mtx[1][2] + tmp._mtx[2][2] * m._mtx[2][2] +
tmp._mtx[2][3] * m._mtx[3][2];
_mtx[2][3] = tmp._mtx[2][0] * m._mtx[0][3] + tmp._mtx[2][1] * m._mtx[1][3] + tmp._mtx[2][2] * m._mtx[2][3] +
tmp._mtx[2][3] * m._mtx[3][3];
_mtx[3][0] = tmp._mtx[3][0] * m._mtx[0][0] + tmp._mtx[3][1] * m._mtx[1][0] + tmp._mtx[3][2] * m._mtx[2][0] +
tmp._mtx[3][3] * m._mtx[3][0];
_mtx[3][1] = tmp._mtx[3][0] * m._mtx[0][1] + tmp._mtx[3][1] * m._mtx[1][1] + tmp._mtx[3][2] * m._mtx[2][1] +
tmp._mtx[3][3] * m._mtx[3][1];
_mtx[3][2] = tmp._mtx[3][0] * m._mtx[0][2] + tmp._mtx[3][1] * m._mtx[1][2] + tmp._mtx[3][2] * m._mtx[2][2] +
tmp._mtx[3][3] * m._mtx[3][2];
_mtx[3][3] = tmp._mtx[3][0] * m._mtx[0][3] + tmp._mtx[3][1] * m._mtx[1][3] + tmp._mtx[3][2] * m._mtx[2][3] +
tmp._mtx[3][3] * m._mtx[3][3];
return *this;
}
inline __device__ static float3 getTranslation(const Matrix4d& src)
{
return float3{ float(src._mtx[3][0]), float(src._mtx[3][1]), float(src._mtx[3][2]) };
}
inline __device__ static float4 getRotation(const Matrix4d& src)
{
// if (!removeScale(src))
//{
// return carb::Float4{0.0f, 0.0f, 0.0f, 1.0f};
//}
float tr = float(src._mtx[0][0] + src._mtx[1][1] + src._mtx[2][2]);
if (tr >= 0.0)
{
float s = sqrtf(tr + 1.0f); // better use invsqrt, but didn't find the fast API....
float4 result;
result.w = 0.5f * s;
s = 0.5f / s;
result.x = float(src._mtx[1][2] - src._mtx[2][1]) * s;
result.y = float(src._mtx[2][0] - src._mtx[0][2]) * s;
result.z = float(src._mtx[0][1] - src._mtx[1][0]) * s;
return result;
}
else
{
int i = 0;
if (src._mtx[1][1] > src._mtx[0][0])
i = 1;
if (src._mtx[2][2] > src._mtx[i][i])
i = 2;
static constexpr int next[3] = { 1, 2, 0 };
int j = next[i];
int k = next[j];
float s = float(sqrt(src._mtx[i][i] - src._mtx[j][j] - src._mtx[k][k] + 1.0f));
float quat[4];
quat[i] = 0.5f * s;
s = 0.5f / s;
quat[j] = float(src._mtx[i][j] + src._mtx[j][i]) * s;
quat[k] = float(src._mtx[k][i] + src._mtx[i][k]) * s;
quat[3] = float(src._mtx[j][k] - src._mtx[k][j]) * s;
return float4{ quat[0], quat[1], quat[2], quat[3] };
}
}
inline __device__ static float4 quatMultiply(const float4& q0, const float4& q1)
{
float4 result;
result.x = q0.w * q1.x + q0.x * q1.w + q0.y * q1.z - q0.z * q1.y;
result.y = q0.w * q1.y - q0.x * q1.z + q0.y * q1.w + q0.z * q1.x;
result.z = q0.w * q1.z + q0.x * q1.y - q0.y * q1.x + q0.z * q1.w;
result.w = q0.w * q1.w - q0.x * q1.x - q0.y * q1.y - q0.z * q1.z;
return result;
}
inline __device__ static void matrixToDualQuat(float* dst, const Matrix4d& src)
{
float3 trans = getTranslation(src);
float4 quat = getRotation(src);
float invQuatLength = 1 / sqrt(quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w);
dst[0] = quat.x * invQuatLength;
dst[1] = quat.y * invQuatLength;
dst[2] = quat.z * invQuatLength;
dst[3] = quat.w * invQuatLength;
float4 quat2{ trans.x, trans.y, trans.z, 0.0f };
float4 dual = quatMultiply(quat2, float4{ dst[0], dst[1], dst[2], dst[3] });
dst[4] = dual.x * 0.5f;
dst[5] = dual.y * 0.5f;
dst[6] = dual.z * 0.5f;
dst[7] = dual.w * 0.5f;
}
| 10,645 | C | 31.858025 | 112 | 0.487177 |
omniverse-code/kit/include/omni/graph/core/cuda/Matrix3d.h | // 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.
//
#pragma once
// CUDA-compatible struct with functions for working with a 3x3 double matrix
#include <float.h>
struct Matrix3d
{
//! Default constructor. Leaves the matrix component values undefined.
Matrix3d() = default;
__device__ explicit Matrix3d(double s)
{
SetDiagonal(s);
}
__device__ Matrix3d& SetDiagonal(double s);
__device__ Matrix3d& SetScale(double s);
__device__ Matrix3d GetInverse() const;
//! Post-multiplies matrix \e m into this matrix.
__device__ Matrix3d& operator*=(const Matrix3d& m);
//! Multiplies matrix \e m1 by \e m2.
__device__ friend Matrix3d operator*(const Matrix3d& m1, const Matrix3d& m2)
{
Matrix3d tmp(m1);
tmp *= m2;
return tmp;
}
//! Matrix storage, in row-major order.
double _mtx[3][3];
};
// Leaves the [2][2] element as 1
inline __device__ Matrix3d& Matrix3d::SetScale(double s)
{
_mtx[0][0] = s;
_mtx[0][1] = 0.0;
_mtx[0][2] = 0.0;
_mtx[1][0] = 0.0;
_mtx[1][1] = s;
_mtx[1][2] = 0.0;
_mtx[2][0] = 0.0;
_mtx[2][1] = 0.0;
_mtx[2][2] = s;
return *this;
}
inline __device__ Matrix3d& Matrix3d::SetDiagonal(double s)
{
_mtx[0][0] = s;
_mtx[0][1] = 0.0;
_mtx[0][2] = 0.0;
_mtx[1][0] = 0.0;
_mtx[1][1] = s;
_mtx[1][2] = 0.0;
_mtx[2][0] = 0.0;
_mtx[2][1] = 0.0;
_mtx[2][2] = s;
return *this;
}
inline __device__ Matrix3d Matrix3d::GetInverse() const
{
double x00, x01, x02;
double x10, x11, x12;
double x20, x21, x22;
double det00, det01, det02;
double det10, det11, det12;
double det20, det21, det22;
// Pickle values for computing determinants into registers
x00 = _mtx[0][0];
x01 = _mtx[0][1];
x02 = _mtx[0][2];
x10 = _mtx[1][0];
x11 = _mtx[1][1];
x12 = _mtx[1][2];
x20 = _mtx[2][0];
x21 = _mtx[2][1];
x22 = _mtx[2][2];
// Compute the determinants of the transposed matrix
det00 = x11 * x22 - x21 * x12;
det01 = x02 * x21 - x01 * x22;
det02 = x01 * x12 - x02 * x11;
det10 = x12 * x20 - x10 * x22;
det11 = x00 * x22 - x02 * x20;
det12 = x10 * x02 - x00 * x12;
det20 = x10 * x21 - x20 * x11;
det21 = x20 * x01 - x00 * x21;
det22 = x00 * x11 - x10 * x01;
// compute determinant from the first row
double det = x00 * det00 + x01 * det10 + x02 * det20;
Matrix3d inverse;
double eps = 0;
if (abs(det) > eps)
{
double rcp = 1.0 / det;
// Multiply all 3x3 cofactors by reciprocal & transpose
inverse._mtx[0][0] = det00 * rcp;
inverse._mtx[0][1] = det01 * rcp;
inverse._mtx[1][0] = det10 * rcp;
inverse._mtx[0][2] = det02 * rcp;
inverse._mtx[2][0] = det20 * rcp;
inverse._mtx[1][1] = det11 * rcp;
inverse._mtx[1][2] = det12 * rcp;
inverse._mtx[2][1] = det21 * rcp;
inverse._mtx[2][2] = det22 * rcp;
}
else
{
inverse.SetScale(FLT_MAX);
}
return inverse;
}
inline __device__ Matrix3d& Matrix3d::operator*=(const Matrix3d& m)
{
// Save current values before they are overwritten
Matrix3d tmp = *this;
_mtx[0][0] = tmp._mtx[0][0] * m._mtx[0][0] + tmp._mtx[0][1] * m._mtx[1][0] + tmp._mtx[0][2] * m._mtx[2][0];
_mtx[0][1] = tmp._mtx[0][0] * m._mtx[0][1] + tmp._mtx[0][1] * m._mtx[1][1] + tmp._mtx[0][2] * m._mtx[2][1];
_mtx[0][2] = tmp._mtx[0][0] * m._mtx[0][2] + tmp._mtx[0][1] * m._mtx[1][2] + tmp._mtx[0][2] * m._mtx[2][2];
_mtx[1][0] = tmp._mtx[1][0] * m._mtx[0][0] + tmp._mtx[1][1] * m._mtx[1][0] + tmp._mtx[1][2] * m._mtx[2][0];
_mtx[1][1] = tmp._mtx[1][0] * m._mtx[0][1] + tmp._mtx[1][1] * m._mtx[1][1] + tmp._mtx[1][2] * m._mtx[2][1];
_mtx[1][2] = tmp._mtx[1][0] * m._mtx[0][2] + tmp._mtx[1][1] * m._mtx[1][2] + tmp._mtx[1][2] * m._mtx[2][2];
_mtx[2][0] = tmp._mtx[2][0] * m._mtx[0][0] + tmp._mtx[2][1] * m._mtx[1][0] + tmp._mtx[2][2] * m._mtx[2][0];
_mtx[2][1] = tmp._mtx[2][0] * m._mtx[0][1] + tmp._mtx[2][1] * m._mtx[1][1] + tmp._mtx[2][2] * m._mtx[2][1];
_mtx[2][2] = tmp._mtx[2][0] * m._mtx[0][2] + tmp._mtx[2][1] * m._mtx[1][2] + tmp._mtx[2][2] * m._mtx[2][2];
return *this;
}
| 4,641 | C | 29.339869 | 111 | 0.539539 |
omniverse-code/kit/include/omni/graph/core/cuda/CUDAUtils.h | // 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.
//
#pragma once
// Collection of CUDA math utilities
#include "cuda_runtime.h"
using double44 = double[4][4];
using float44 = float[4][4];
// ===============================================================
// Return the dot product of two float4s
inline __host__ __device__ float dot(const float4& a, const float4& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
// ===============================================================
// Return the elementwise sum of two float4s
inline __host__ __device__ float4 operator+(const float4& a, const float4& b)
{
return make_float4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
// ===============================================================
// Return the vector product of two float4s
inline __host__ __device__ float4 operator*(const float4& a, const float& s)
{
return make_float4(a.x * s, a.y * s, a.z * s, a.w * s);
}
// ===============================================================
// Return the product of a float4 vector and a 4x4 matrix
inline __host__ __device__ float4 operator*(const float4& p, const double44& m)
{
float4 result;
result.x = (float)((double)p.x * m[0][0] + (double)p.y * m[1][0] + (double)p.z * m[2][0] + (double)p.w * m[3][0]);
result.y = (float)((double)p.x * m[0][1] + (double)p.y * m[1][1] + (double)p.z * m[2][1] + (double)p.w * m[3][1]);
result.z = (float)((double)p.x * m[0][2] + (double)p.y * m[1][2] + (double)p.z * m[2][2] + (double)p.w * m[3][2]);
result.w = (float)((double)p.x * m[0][3] + (double)p.y * m[1][3] + (double)p.z * m[2][3] + (double)p.w * m[3][3]);
return result;
}
// ===============================================================
// Return the product of a float4 vector and a 4x4 float matrix
inline __host__ __device__ float4 operator*(const float4& p, const float44& m)
{
float4 result;
result.x = p.x * m[0][0] + p.y * m[1][0] + p.z * m[2][0] + p.w * m[3][0];
result.y = p.x * m[0][1] + p.y * m[1][1] + p.z * m[2][1] + p.w * m[3][1];
result.z = p.x * m[0][2] + p.y * m[1][2] + p.z * m[2][2] + p.w * m[3][2];
result.w = p.x * m[0][3] + p.y * m[1][3] + p.z * m[2][3] + p.w * m[3][3];
return result;
}
// ===============================================================
// Return a float4 with it's w-scale applied and set to 1.0
inline __host__ __device__ float4 homogenize(const float4& p)
{
float inv = (abs(p.w)) > 1e-6f ? 1.0f / p.w : 1.0f;
return p * inv;
}
// ===============================================================
// Return the dot product of two float3s
inline __host__ __device__ float dot(const float3& a, const float3& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
// ===============================================================
// Return the elementwise product of two float3s
inline __host__ __device__ float3 hadamard_product(const float3& a, const float3& b)
{
return make_float3(a.x * b.x, a.y * b.y, a.z * b.z);
}
// ===============================================================
// Return the cross product of two float3s
inline __host__ __device__ float3 cross(const float3& a, const float3& b)
{
return make_float3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
}
// ===============================================================
// Return the elementwise sum of two float3s
inline __host__ __device__ float3 operator+(const float3& a, const float3& b)
{
return make_float3(a.x + b.x, a.y + b.y, a.z + b.z);
}
// ===============================================================
// Return the elementwise difference between two float3s
inline __host__ __device__ float3 operator-(const float3& a, const float3& b)
{
return make_float3(a.x - b.x, a.y - b.y, a.z - b.z);
}
// ===============================================================
// Return the product of a float3 and a constant
inline __host__ __device__ float3 operator*(const float3& a, const float& s)
{
return make_float3(a.x * s, a.y * s, a.z * s);
}
// ===============================================================
// Return the dot product of two double4s
inline __host__ __device__ double dot(const double4& a, const double4& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
// ===============================================================
// Return the elementwise sum of two double4s
inline __host__ __device__ double4 operator+(const double4& a, const double4& b)
{
return make_double4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
// ===============================================================
// Return the vector product of two double4s
inline __host__ __device__ double4 operator*(const double4& a, const double& s)
{
return make_double4(a.x * s, a.y * s, a.z * s, a.w * s);
}
// ===============================================================
// Return the product of a double4 vector and a 4x4 matrix
inline __host__ __device__ double4 operator*(const double4& p, const double44& m)
{
double4 result;
result.x = (double)((double)p.x * m[0][0] + (double)p.y * m[1][0] + (double)p.z * m[2][0] + (double)p.w * m[3][0]);
result.y = (double)((double)p.x * m[0][1] + (double)p.y * m[1][1] + (double)p.z * m[2][1] + (double)p.w * m[3][1]);
result.z = (double)((double)p.x * m[0][2] + (double)p.y * m[1][2] + (double)p.z * m[2][2] + (double)p.w * m[3][2]);
result.w = (double)((double)p.x * m[0][3] + (double)p.y * m[1][3] + (double)p.z * m[2][3] + (double)p.w * m[3][3]);
return result;
}
// ===============================================================
// Return a double4 with it's w-scale applied and set to 1.0
inline __host__ __device__ double4 homogenize(const double4& p)
{
double inv = (abs(p.w)) > 1e-6f ? 1.0f / p.w : 1.0f;
return p * inv;
}
// ===============================================================
// Return the dot product of two double3s
inline __host__ __device__ double dot(const double3& a, const double3& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
// ===============================================================
// Return the elementwise product of two double3s
inline __host__ __device__ double3 hadamard_product(const double3& a, const double3& b)
{
return make_double3(a.x * b.x, a.y * b.y, a.z * b.z);
}
// ===============================================================
// Return the cross product of two double3s
inline __host__ __device__ double3 cross(const double3& a, const double3& b)
{
return make_double3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
}
// ===============================================================
// Return the elementwise sum of two double3s
inline __host__ __device__ double3 operator+(const double3& a, const double3& b)
{
return make_double3(a.x + b.x, a.y + b.y, a.z + b.z);
}
// ===============================================================
// Return the elementwise difference between two double3s
inline __host__ __device__ double3 operator-(const double3& a, const double3& b)
{
return make_double3(a.x - b.x, a.y - b.y, a.z - b.z);
}
// ===============================================================
// Return the product of a double3 and a constant
inline __host__ __device__ double3 operator*(const double3& a, const double& s)
{
return make_double3(a.x * s, a.y * s, a.z * s);
}
| 7,778 | C | 38.892307 | 119 | 0.484572 |
omniverse-code/kit/include/omni/graph/core/bundle/IBundleFactory2.h | // 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.
//
#pragma once
#include "IBundleFactory1.h"
namespace omni
{
namespace graph
{
namespace core
{
OMNI_DECLARE_INTERFACE(IBundleFactory2);
//! IBundleFactory version 2.
//!
//! The version 2 allows to retrieve instances of IBundle instances from paths.
class IBundleFactory2_abi
: public omni::core::Inherits<omni::graph::core::IBundleFactory, OMNI_TYPE_ID("omni.graph.core.IBundleFactory2")>
{
protected:
//! Get read only IBundle interface from path.
//!
//! @param contextObj The context where bundles belong to.
//! @param paths Input paths.
//! @param pathCount Length of paths array.
//! @param bundles Output instances of IConstBundle2 interface.
//!
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getConstBundlesFromPaths_abi(
GraphContextObj const* const contextObj OMNI_ATTR("in, not_null"),
omni::fabric::PathC const* const paths OMNI_ATTR("in, not_null"),
size_t pathCount,
IConstBundle2** const bundles OMNI_ATTR("out, *not_null, count=pathCount")) noexcept = 0;
//! Get read write IBundle interface from path.
//!
//! @param contextObj The context where bundles belong to.
//! @param paths Input paths.
//! @param pathCount Length of paths array.
//! @param bundles Output instances of IBundle2 interface.
//!
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getBundlesFromPaths_abi(
GraphContextObj const* const contextObj OMNI_ATTR("in, not_null"),
omni::fabric::PathC const* const paths OMNI_ATTR("in, not_null"),
size_t pathCount,
IBundle2** const bundles OMNI_ATTR("out, *not_null, count=pathCount")) noexcept = 0;
};
}
}
}
#include "IBundleFactory2.gen.h"
//! @cond Doxygen_Suppress
//!
//! API part of the bundle factory interface
OMNI_DEFINE_INTERFACE_API(omni::graph::core::IBundleFactory2)
//! @endcond
{
public:
//! Get read only IBundle interface from path.
//!
//! @param contextObj The context where bundles belong to.
//! @param path Input path.
//!
//! @return Instance of IConstBundle interface.
omni::core::ObjectPtr<omni::graph::core::IConstBundle2> getConstBundleFromPath(
omni::graph::core::GraphContextObj const& contextObj, omni::fabric::PathC path) noexcept
{
omni::core::ObjectPtr<omni::graph::core::IConstBundle2> out;
auto const outPtr = reinterpret_cast<omni::graph::core::IConstBundle2**>(&out);
auto const result = getConstBundlesFromPaths_abi(&contextObj, &path, 1, outPtr);
if (OMNI_FAILED(result))
{
OMNI_LOG_ERROR("unable to get bundle at path: 0x%08X", result);
}
return out;
}
//! Get read write IBundle interface from path.
//!
//! @param contextObj The context where bundles belong to.
//! @param path Input path.
//!
//! @return Instance of IBundle interface.
omni::core::ObjectPtr<omni::graph::core::IBundle2> getBundleFromPath(
omni::graph::core::GraphContextObj const& contextObj, omni::fabric::PathC path) noexcept
{
omni::core::ObjectPtr<omni::graph::core::IBundle2> out;
auto const outPtr = reinterpret_cast<omni::graph::core::IBundle2**>(&out);
auto const result = getBundlesFromPaths_abi(&contextObj, &path, 1, outPtr);
if (OMNI_FAILED(result))
{
OMNI_LOG_ERROR("unable to get bundle at path: 0x%08X", result);
}
return out;
}
//! Get read only IConstBundle2 interfaces from an array of paths.
//!
//! @param contextObj The context where bundles belong to.
//! @param paths Input paths.
//! @param pathCount Length of paths array.
//! @param createdBundles Smart pointers that manage lifetime of IConstBundle2 instances.
//!
//! @return false on failure, true on success.
bool getConstBundlesFromPaths(
omni::graph::core::GraphContextObj const& contextObj,
omni::fabric::PathC const* const paths,
size_t const pathCount,
omni::core::ObjectPtr<omni::graph::core::IConstBundle2>* createdBundles) noexcept
{
static_assert(sizeof(ObjectPtr<omni::graph::core::IConstBundle2>) == sizeof(omni::graph::core::IConstBundle2*),
"ObjectPtr and IConstBundle2 pointer requires to be the same size!");
auto const result = getConstBundlesFromPaths_abi(&contextObj, paths, pathCount, reinterpret_cast<omni::graph::core::IConstBundle2**>(createdBundles));
if (OMNI_FAILED(result))
{
OMNI_LOG_ERROR("unable to get const bundles from path: 0x%08X", result);
return false;
}
return true;
}
};
| 5,371 | C | 37.371428 | 158 | 0.673245 |
omniverse-code/kit/include/omni/graph/core/bundle/IBundleChanges1.h | // 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.
//
#pragma once
#include <omni/core/IObject.h>
#include <omni/graph/core/Handle.h>
namespace omni
{
namespace graph
{
namespace core
{
//! Enumeration representing the type of change that occurred in a bundle.
//!
//! This enumeration is used to identify the kind of modification that has taken place in a bundle or attribute.
//! It's used as the return type for functions that check bundles and attributes, signaling whether those have been
//! modified or not.
enum class BundleChangeType : uint64_t
{
None = 0 << 0, //!< Indicates that no change has occurred in the bundle.
Modified = 1 << 0, //!< Indicates that the bundle has been modified.
};
OMNI_DECLARE_INTERFACE(IBundleChanges);
//! Interface for monitoring and handling changes in bundles and attributes.
//!
//! The IBundleChanges_abi is an interface that provides methods for checking whether bundles and attributes
//! have been modified, and cleaning them if they have been modified. This is particularly useful in scenarios
//! where it's crucial to track changes and maintain the state of bundles and attributes.
//!
//! This interface provides several methods for checking and cleaning modifications, each catering to different
//! use cases such as handling single bundles, multiple bundles, attributes, or specific attributes of a single bundle.
//!
//! The methods of this interface return a BundleChangeType enumeration that indicates whether the checked entity
//! (bundle or attribute) has been modified.
class IBundleChanges_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.IBundleChanges")>
{
protected:
//! @brief Activate tracking for specific bundle on its attributes and children.
//! @param handle to the specific bundles to enable change tracking.
//! @return An omni::core::Result indicating the success of the operation.
virtual omni::core::Result activateChangeTracking_abi(BundleHandle handle) noexcept = 0;
//! @brief Deactivate tracking for specific bundle on its attributes and children.
//! @param handle to the specific bundles to enable change tracking.
//! @return An omni::core::Result indicating the success of the operation.
virtual omni::core::Result deactivateChangeTracking_abi(BundleHandle handle) noexcept = 0;
//! @brief Retrieves the change status of an array of bundles.
//!
//! This method is used to check if any of the bundles in the provided array have been modified.
//!
//! The count parameter indicates the size of the bundles array, as well as the changes output array.
//!
//! @param bundles An array of handles to the specific bundles to check for modifications.
//! @param count The number of bundle handles in the array.
//! @param changes An array that will be filled with BundleChangeType values for each bundle.
//!
//! @returns An omni::core::Result indicating the success of the operation.
OMNI_ATTR("no_py")
virtual omni::core::Result getChangesForBundles_abi(
ConstBundleHandle const* const bundles OMNI_ATTR("in, throw_if_null, count=count"),
size_t count,
BundleChangeType* const changes OMNI_ATTR("out, throw_if_null, count=count")) noexcept = 0;
//! @brief Retrieves the change status of an array of attributes.
//!
//! This method is used to check if any of the attributes in the provided array have been modified.
//!
//! The count parameter indicates the size of the attributes array, as well as the changes output array.
//!
//! @param attributes An array of handles to the attributes to check for modifications.
//! @param count The number of attribute handles in the array.
//! @param changes An array that will be filled with BundleChangeType values for each attribute.
//!
//! @returns An omni::core::Result indicating the success of the operation.
OMNI_ATTR("no_py")
virtual omni::core::Result getChangesForAttributes_abi(
ConstAttributeDataHandle const* const attributes OMNI_ATTR("in, throw_if_null, count=count"),
size_t count,
BundleChangeType* const changes OMNI_ATTR("out, throw_if_null, count=count")) noexcept = 0;
//! @brief Retrieves the change status of specific attributes within a bundle.
//!
//! This method is used to check if any of the specified attributes within a bundle have been modified.
//! It operates by providing a handle to the bundle and an array of attribute names to check for modifications.
//!
//! The count parameter indicates the number of attribute names in the array, as well as the size of the changes
//! output array.
//!
//! @param bundle A handle to the specific bundle for which attribute changes are being checked.
//! @param attributes An array of attribute names (Tokens) to check for modifications.
//! @param count The number of attribute names in the array.
//! @param changes An array that will be filled with BundleChangeType values for each attribute.
//!
//! @returns An omni::core::Result indicating the success of the operation.
OMNI_ATTR("no_py, no_api")
virtual omni::core::Result getChangesForAttributesInBundle_abi(
ConstBundleHandle const bundle,
fabric::TokenC const* const attributes OMNI_ATTR("in, throw_if_null, count=count"),
size_t count,
BundleChangeType* const changes OMNI_ATTR("out, throw_if_null, count=count")) noexcept = 0;
//! Clears all recorded changes.
//!
//! This method is used to clear or reset all the recorded changes of the bundles and attributes.
//! It can be used when the changes have been processed and need to be discarded.
//!
//! An omni::core::Result indicating the success of the operation.
virtual omni::core::Result clearChanges_abi() noexcept = 0;
};
}
}
}
#include "IBundleChanges1.gen.h"
OMNI_DEFINE_INTERFACE_API(omni::graph::core::IBundleChanges)
{
public:
using BundleChangeType = omni::graph::core::BundleChangeType;
using ConstBundleHandle = omni::graph::core::ConstBundleHandle;
using ConstAttributeDataHandle = omni::graph::core::ConstAttributeDataHandle;
//! @brief Retrieves the change status of a specific bundle.
//!
//! This method is used to check if a specific bundle or its contents have been modified.
//!
//! @param bundle The handle to the specific bundle to check for modifications.
//!
//! @returns A BundleChangeType value indicating the type of change (if any) that has occurred to the bundle.
BundleChangeType getChange(ConstBundleHandle bundle)
{
BundleChangeType change;
auto const result = getChangesForBundles_abi(&bundle, 1, &change);
return OMNI_SUCCEEDED(result) ? change : BundleChangeType::None;
}
//! @brief Retrieves the change status of a specific attribute.
//!
//! This method is used to check if a specific attribute has been modified.
//!
//! @param attribute The handle to the specific attribute to check for modifications.
//!
//! @returns A BundleChangeType value indicating the type of change (if any) that has occurred to the attribute.
BundleChangeType getChange(ConstAttributeDataHandle attribute)
{
BundleChangeType change;
auto const result = getChangesForAttributes_abi(&attribute, 1, &change);
return OMNI_SUCCEEDED(result) ? change : BundleChangeType::None;
}
//! @brief Retrieves the change status of multiple bundles.
//!
//! This method is used to check if any of the provided bundles or their contents have been modified.
//!
//! @param bundles An array of handles to the bundles to check for modifications.
//! @param size The number of bundle handles in the array.
//! @param changes An array that will be filled with BundleChangeType values for each bundle.
//!
//! @returns An omni::core::Result indicating the success of the operation.
omni::core::Result getChanges(ConstBundleHandle const* bundles, size_t size, BundleChangeType* changes)
{
return getChangesForBundles_abi(bundles, size, changes);
}
//! @brief Retrieves the change status of multiple attributes.
//!
//! This method is used to check if any of the provided attributes have been modified.
//!
//! @param attributes An array of handles to the attributes to check for modifications.
//! @param size The number of attribute handles in the array.
//! @param changes An array that will be filled with BundleChangeType values for each attribute.
//!
//! @returns An omni::core::Result indicating the success of the operation.
omni::core::Result getChanges(ConstAttributeDataHandle const* attributes, size_t size, BundleChangeType* changes)
{
return getChangesForAttributes_abi(attributes, size, changes);
}
//! @brief Retrieves the change status of multiple attributes within a specific bundle.
//!
//! This method is used to check if any of the specified attributes within a particular bundle have been modified.
//!
//! @param bundle The handle to the specific bundle whose attributes are to be checked for modifications.
//! @param attributes An array of Tokens representing the attributes to check for modifications.
//! @param size The number of attribute tokens in the array.
//! @param changes An array that will be filled with BundleChangeType values for each attribute.
//!
//! @returns An omni::core::Result indicating the success of the operation.
omni::core::Result getChanges(ConstBundleHandle bundle, fabric::TokenC const* attributes, size_t size, BundleChangeType* changes)
{
return getChangesForAttributesInBundle_abi(bundle, attributes, size, changes);
}
};
| 10,252 | C | 48.531401 | 133 | 0.719469 |
omniverse-code/kit/include/omni/graph/core/bundle/PyIBundleChanges1.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
#pragma once
#include <omni/core/ITypeFactory.h>
#include <omni/python/PyBind.h>
#include <omni/python/PyString.h>
#include <omni/python/PyVec.h>
#include <sstream>
auto bindBundleChangeType(py::module& m)
{
py::enum_<omni::graph::core::BundleChangeType> e(
m, "BundleChangeType", R"OMNI_BIND_RAW_(Enumeration representing the type of change that occurred in a bundle.
This enumeration is used to identify the kind of modification that has taken place in a bundle or attribute.
It's used as the return type for functions that check bundles and attributes, signaling whether those have been
modified or not.)OMNI_BIND_RAW_");
e.value("NONE", omni::graph::core::BundleChangeType::None,
R"OMNI_BIND_RAW_(Indicates that no change has occurred in the bundle.)OMNI_BIND_RAW_");
e.value("MODIFIED", omni::graph::core::BundleChangeType::Modified,
R"OMNI_BIND_RAW_(Indicates that the bundle has been modified.)OMNI_BIND_RAW_");
return e;
}
auto bindIBundleChanges(py::module& m)
{
// hack around pybind11 issues with C++17
// - https://github.com/pybind/pybind11/issues/2234
// - https://github.com/pybind/pybind11/issues/2666
// - https://github.com/pybind/pybind11/issues/2856
py::class_<omni::core::Generated<omni::graph::core::IBundleChanges_abi>,
omni::python::detail::PyObjectPtr<omni::core::Generated<omni::graph::core::IBundleChanges_abi>>,
omni::core::IObject>
clsParent(m, "_IBundleChanges");
py::class_<omni::graph::core::IBundleChanges, omni::core::Generated<omni::graph::core::IBundleChanges_abi>,
omni::python::detail::PyObjectPtr<omni::graph::core::IBundleChanges>, omni::core::IObject>
cls(m, "IBundleChanges", R"OMNI_BIND_RAW_(Interface for monitoring and handling changes in bundles and attributes.
The IBundleChanges_abi is an interface that provides methods for checking whether bundles and attributes
have been modified, and cleaning them if they have been modified. This is particularly useful in scenarios
where it's crucial to track changes and maintain the state of bundles and attributes.
This interface provides several methods for checking and cleaning modifications, each catering to different
use cases such as handling single bundles, multiple bundles, attributes, or specific attributes of a single bundle.
The methods of this interface return a BundleChangeType enumeration that indicates whether the checked entity
(bundle or attribute) has been modified.)OMNI_BIND_RAW_");
cls.def(py::init(
[](const omni::core::ObjectPtr<omni::core::IObject>& obj)
{
auto tmp = omni::core::cast<omni::graph::core::IBundleChanges>(obj.get());
if (!tmp)
{
throw std::runtime_error("invalid type conversion");
}
return tmp;
}));
cls.def(py::init(
[]()
{
auto tmp = omni::core::createType<omni::graph::core::IBundleChanges>();
if (!tmp)
{
throw std::runtime_error("unable to create omni::graph::core::IBundleChanges instantiation");
}
return tmp;
}));
cls.def("activate_change_tracking",
[](omni::graph::core::IBundleChanges* self, omni::graph::core::BundleHandle* handle)
{
auto return_value = self->activateChangeTracking(*handle);
return return_value;
},
R"OMNI_BIND_RAW_(@brief Activate tracking for specific bundle on its attributes and children.
@param handle to the specific bundles to enable change tracking.
@return An omni::core::Result indicating the success of the operation.)OMNI_BIND_RAW_",
py::arg("handle"));
cls.def("deactivate_change_tracking",
[](omni::graph::core::IBundleChanges* self, omni::graph::core::BundleHandle* handle)
{
auto return_value = self->deactivateChangeTracking(*handle);
return return_value;
},
R"OMNI_BIND_RAW_(@brief Deactivate tracking for specific bundle on its attributes and children.
@param handle to the specific bundles to enable change tracking.
@return An omni::core::Result indicating the success of the operation.)OMNI_BIND_RAW_",
py::arg("handle"));
cls.def("clear_changes", &omni::graph::core::IBundleChanges::clearChanges, R"OMNI_BIND_RAW_(Clears all recorded changes.
This method is used to clear or reset all the recorded changes of the bundles and attributes.
It can be used when the changes have been processed and need to be discarded.
An omni::core::Result indicating the success of the operation.)OMNI_BIND_RAW_");
return omni::python::PyBind<omni::graph::core::IBundleChanges>::bind(cls);
}
| 5,330 | C | 47.908256 | 124 | 0.683677 |
omniverse-code/kit/include/omni/graph/core/bundle/IBundle1.h | // 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.
//
#pragma once
#include <omni/graph/core/Handle.h>
namespace omni
{
namespace graph
{
namespace core
{
// ======================================================================
/** Interface for bundle attribute data */
struct IBundle
{
//! @private to avoid doxygen problems
CARB_PLUGIN_INTERFACE("omni::graph::core::IBundle", 1, 6);
/**
* Counts the number of attributes contained in the bundle.
*
* @param[in] contextObj The context to which the bundle belongs
* @param[in] bundle The handle to the bundle data
* @return the number of attributes in the bundle
*/
size_t(CARB_ABI* getAttributesCount)(const GraphContextObj& contextObj, ConstBundleHandle bundle);
/**
* Get all of the attributes on the bundle in read-only form.
*
* @param[out] attrsOut Handles to the attributes on the bundle (preallocated to hold "count" members)
* @param[in] contextObj The context to which the bundle belongs
* @param[in] bundle The handle to the bundle data
* @param[in] count The number of attribute slots allocated in attrsOut (should be >= getAttributesCount())
*/
void(CARB_ABI* getAttributesR)(ConstAttributeDataHandle* attrsOut,
const GraphContextObj& contextObj,
ConstBundleHandle bundle,
size_t count);
/**
* Get all of the attributes on the bundle in writable form.
*
* @param[out] attrsOut Handles to the attributes on the bundle (preallocated to hold "count" members)
* @param[in] contextObj The context to which the bundle belongs
* @param[in] bundle The handle to the bundle data
* @param[in] count The number of attribute slots allocated in attrsOut (should be >= getAttributesCount())
*/
void(CARB_ABI* getAttributesW)(AttributeDataHandle* attrsOut,
const GraphContextObj& contextObj,
BundleHandle bundle,
size_t count);
/**
* Get attributes on the bundle whose names appear in "attrNames" in read-only form.
*
* @param[out] attrsOut Handles to the attributes on the bundle (preallocated to hold "count" members)
* @param[in] contextObj The context to which the bundle belongs
* @param[in] bundle The handle to the bundle data
* @param[in] attrNames The list of attribute names to be looked up
* @param[in] count The number of attribute slots allocated in attrsOut (should be >= getAttributesCount())
*/
void(CARB_ABI* getAttributesByNameR)(ConstAttributeDataHandle* attrsOut,
const GraphContextObj& contextObj,
ConstBundleHandle bundle,
const NameToken* attrNames,
size_t count);
/**
* Get attributes on the bundle whose names appear in "attrNames" in writable form.
*
* @param[out] attrsOut Handles to the attributes on the bundle (preallocated to hold "count" members)
* @param[in] contextObj The context to which the bundle belongs
* @param[in] bundle The handle to the bundle data
* @param[in] attrNames The list of attribute names to be looked up
* @param[in] count The number of attribute slots allocated in attrsOut (should be >= getAttributesCount())
*/
void(CARB_ABI* getAttributesByNameW)(AttributeDataHandle* attrsOut,
const GraphContextObj& contextObj,
BundleHandle bundle,
const NameToken* attrNames,
size_t count);
/**
* Get the names and types of all attributes on the bundle.
*
* @param[out] namesOut Handles to the names of attributes on the bundle (preallocated to hold "count" members)
* @param[out] typesOut Handles to the types of attributes on the bundle (preallocated to hold "count" members)
* @param[in] contextObj The context to which the bundle belongs
* @param[in] bundle The handle to the bundle data
* @param[in] count The number of attribute slots allocated in attrsOut (should be >= getAttributesCount())
*/
void (CARB_ABI* getAttributeNamesAndTypes)(NameToken* namesOut,
Type* typesOut,
const GraphContextObj& contextObj,
ConstBundleHandle bundle,
size_t count);
/**
* Create a new attribute and add it to the bundle.
*
* @param[in] contextObj The context to which the bundle belongs
* @param[in] destination The handle to the bundle data
* @param[in] attrName Name for the new attribute
* @param[in] attrType Type for the new attribute
* @return Handle to the newly created attribute
*/
AttributeDataHandle(CARB_ABI* addAttribute)(const GraphContextObj& contextObj,
BundleHandle destination,
NameToken attrName,
Type attrType);
/**
* Create a new attribute and add it to the bundle.
*
* @param[in] contextObj The context to which the bundle belongs
* @param[in] destination The handle to the bundle data
* @param[in] pattern Attribute whose name and type is to be copied for the new attribute
* @return Handle to the newly created attribute
*/
AttributeDataHandle(CARB_ABI* addAttributeLike)(const GraphContextObj& contextObj,
BundleHandle destination,
ConstAttributeDataHandle pattern);
/**
* Create a new array attribute and add it to the bundle.
*
* @param[in] contextObj The context to which the bundle belongs
* @param[in] destination The handle to the bundle data
* @param[in] attrName Name for the new attribute
* @param[in] attrType Type for the new attribute
* @param[in] elementCount Starting element count for the array attribute
* @return Handle to the newly created attribute
*/
AttributeDataHandle(CARB_ABI* addArrayAttribute)(const GraphContextObj& contextObj,
BundleHandle destination,
NameToken attrName,
Type attrType,
size_t elementCount);
/**
* Create a new array-of-arrays attribute and add it to the bundle.
*
* Note: At the moment only arrays and arrays-of-tuples are fully supported so use with caution
*
* @param[in] contextObj The context to which the bundle belongs
* @param[in] destination The handle to the bundle data
* @param[in] attrName Name for the new attribute
* @param[in] baseType Base data type for the new attribute
* @param[in] numComponents Number of tuple elements for the new attribute (e.g. 3 for float[3])
* @param[in] numArrays How many levels of arrays are on the attribute (currently only 1 is supported)
* @param[in] ... Variadic list containing the starting element count for each level of array
* @return Handle to the newly created attribute
*/
AttributeDataHandle(CARB_ABI* addArrayOfArraysAttribute)(const GraphContextObj& contextObj,
BundleHandle destination,
NameToken attrName,
BaseDataType baseType,
size_t numComponents,
size_t numArrays,
...);
/**
* Create a new attribute by copying an existing one, including its data, and renaming and add it to the bundle.
*
* @param[in] contextObj The context to which the bundle belongs
* @param[in] destination The handle to the bundle data
* @param[in] destinationAttrName Name for the new attribute
* @param[in] source Handle to attribute whose data type is to be copied
* @return Handle to the newly created attribute
*/
void(CARB_ABI* copyAttribute)(const GraphContextObj& contextObj,
BundleHandle destination,
NameToken destinationAttrName,
ConstAttributeDataHandle source);
/**
* Get the unique data ID of a bundle.
*
* @param[in] bundle The bundle whose ID is to be found
* @return The unique ID of the bundle
*/
uint64_t(CARB_ABI* getDataID)(ConstBundleHandle bundle);
//! @cond Doxygen_Suppress
//! Deprecated function - do not use
[[deprecated("Use getBundlePath")]] const char*(CARB_ABI* getPrimPath)(ConstBundleHandle);
//! @endcond
/**
* Remove an existing attribute from the bundle.
*
* @param[in] contextObj The context to which the bundle belongs
* @param[in] destination The handle to the bundle data
* @param[in] attrName Name of the attribute to remove
*/
void (*removeAttribute)(const GraphContextObj& contextObj, BundleHandle destination, NameToken attrName);
/**
* Add a batch of attributes to a bundle.
*
* @param[in] contextObj The context to which the bundle belongs
* @param[in] destination The handle to the bundle data
* @param[in] attributeCount Number of attributes to be added
* @param[in] attrNames Array of names for the new attributes
* @param[in] attrTypes Array of types for the new attributes
* @return Whether addition was successful
*/
bool(CARB_ABI* addAttributes)(const GraphContextObj& contextObj,
BundleHandle destination,
size_t attributeCount,
const NameToken* attrNames,
const Type* attrTypes);
/**
* Remove a batch of attributes from a bundle.
*
* @param[in] contextObj The context to which the bundle belongs
* @param[in] destination The handle to the bundle data
* @param[in] attributeCount Number of attributes to be removed
* @param[in] attrNames Array of names to be removed
*/
bool(CARB_ABI* removeAttributes)(const GraphContextObj& contextObj,
BundleHandle destination,
size_t attributeCount,
const NameToken* attrNames);
/**
* Copy a set of attributes from a source bundle/node to another bundle/node
* Attributes taht don't exists on the destination will be created
* The name on the destination can differ from the one on the source
*
* @param[in] contextObj The context object used to find the variable data.
* @param[in] destBundleHandle The destination node/bundle on which to copy/create the the attributes.
* @param[in] sourceBundleHandle The source node/bundle from which to read the data.
* @param[in] srcNames The attributes to copy
* @param[in] dstNames Optional - the name of the destination attribute.
* if nullptr, the name of input will be used
* if not nullptr, lenght must be equal to namesCount
* @param[in] namesCount Length of srcNames array (and dstNames if provided)
*
*/
void(CARB_ABI* copyAttributes)(const GraphContextObj& contextObj,
BundleHandle destBundle,
ConstBundleHandle sourceBundle,
NameToken const* srcNames,
NameToken const* dstNames,
size_t namesCount);
/**
* Retrieves the path to the bundle. It will be part of the node in which it is defined.
*
* @param[in] bundle A handle pointing to a bundle
* @return the bundle path
*/
const char*(CARB_ABI* getBundlePath)(ConstBundleHandle bundle);
};
// Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle
STRUCT_INTEGRITY_CHECK(IBundle, getBundlePath, 17)
}
}
}
| 13,202 | C | 47.540441 | 116 | 0.595289 |
omniverse-code/kit/include/omni/graph/core/bundle/IBundleFactory2.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! IBundleFactory version 2.
//!
//! The version 2 allows to retrieve instances of IBundle instances from paths.
template <>
class omni::core::Generated<omni::graph::core::IBundleFactory2_abi> : public omni::graph::core::IBundleFactory2_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::IBundleFactory2")
//! Get read only IBundle interface from path.
//!
//! @param contextObj The context where bundles belong to.
//! @param paths Input paths.
//! @param pathCount Length of paths array.
//! @param bundles Output instances of IConstBundle2 interface.
//!
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result getConstBundlesFromPaths(const omni::graph::core::GraphContextObj* const contextObj,
const omni::fabric::PathC* const paths,
size_t pathCount,
omni::graph::core::IConstBundle2** const bundles) noexcept;
//! Get read write IBundle interface from path.
//!
//! @param contextObj The context where bundles belong to.
//! @param paths Input paths.
//! @param pathCount Length of paths array.
//! @param bundles Output instances of IBundle2 interface.
//!
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result getBundlesFromPaths(const omni::graph::core::GraphContextObj* const contextObj,
const omni::fabric::PathC* const paths,
size_t pathCount,
omni::graph::core::IBundle2** const bundles) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundleFactory2_abi>::getConstBundlesFromPaths(
const omni::graph::core::GraphContextObj* const contextObj,
const omni::fabric::PathC* const paths,
size_t pathCount,
omni::graph::core::IConstBundle2** const bundles) noexcept
{
return getConstBundlesFromPaths_abi(contextObj, paths, pathCount, bundles);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundleFactory2_abi>::getBundlesFromPaths(
const omni::graph::core::GraphContextObj* const contextObj,
const omni::fabric::PathC* const paths,
size_t pathCount,
omni::graph::core::IBundle2** const bundles) noexcept
{
return getBundlesFromPaths_abi(contextObj, paths, pathCount, bundles);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 3,558 | C | 38.10989 | 115 | 0.67566 |
omniverse-code/kit/include/omni/graph/core/bundle/IBundle2.h | // 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.
//
//! @file IBundle.h
//!
//! @brief Defines Read Write interfaces for recursive bundles.
#pragma once
#include "IConstBundle2.h"
namespace omni
{
namespace graph
{
namespace core
{
//! Declare the IBundle2 interface definition
OMNI_DECLARE_INTERFACE(IBundle2);
//! Provide read write access to recursive bundles.
class IBundle2_abi : public omni::core::Inherits<IConstBundle2, OMNI_TYPE_ID("omni.graph.core.IBundle2")>
{
protected:
//! Return handle to this bundle. Invalid handle is returned if this bundle is invalid.
OMNI_ATTR("no_py")
virtual BundleHandle getHandle_abi() noexcept = 0;
//! Return parent of this bundle, or invalid handle if there is no parent.
OMNI_ATTR("no_py")
virtual BundleHandle getParentBundle_abi() noexcept = 0;
//! @brief Get read-write handles to all attributes in this bundle.
//!
//! @copydetails IConstBundle2_abi::getConstAttributes_abi
OMNI_ATTR("no_py")
virtual omni::core::Result getAttributes_abi(
AttributeDataHandle* const attributes OMNI_ATTR("out, not_null, count=*attributeCount"),
size_t* const attributeCount OMNI_ATTR("in, out, not_null")) noexcept = 0;
//! @brief Searches for read-write handles of the attribute in this bundle by using attribute names.
//!
//! @copydetails IConstBundle2_abi::getConstAttributesByName_abi
OMNI_ATTR("no_py")
virtual omni::core::Result getAttributesByName_abi(
NameToken const* const names OMNI_ATTR("in, not_null, count=nameCount"),
size_t nameCount,
AttributeDataHandle* const attributes OMNI_ATTR("out, not_null, count=nameCount")) noexcept = 0;
//! @brief Get read write handles to all child bundles in this bundle.
//!
//! @copydetails IConstBundle2_abi::getConstChildBundles_abi
OMNI_ATTR("no_py")
virtual omni::core::Result getChildBundles_abi(BundleHandle* const bundles OMNI_ATTR("out, not_null, count=bundleCount"),
size_t* const bundleCount OMNI_ATTR("in, out, not_null")) noexcept = 0;
//! @brief Get read write handle to child bundle by index.
//!
//! @copydetails IConstBundle2_abi::getConstChildBundle_abi
OMNI_ATTR("no_py")
virtual omni::core::Result getChildBundle_abi(size_t bundleIndex,
BundleHandle* const bundle OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Lookup for read write handles to child bundles under specified names.
//!
//! @copydetails IConstBundle2_abi::getConstChildBundlesByName_abi
OMNI_ATTR("no_py")
virtual omni::core::Result getChildBundlesByName_abi(
NameToken const* const names OMNI_ATTR("in, not_null, count=nameCount"),
size_t nameCount,
BundleHandle* const foundBundles OMNI_ATTR("out, not_null, count=nameCount")) noexcept = 0;
//! @brief Create new attributes by copying existing.
//!
//! Source attribute handles' data and metadata are copied. If a handle is invalid,
//! then its source is ignored.
//! Created attributes are owned by this bundle.
//!
//! @param newNames The names for the new attributes, if `nullptr` then names are taken from the source attributes.
//! @param sourceAttributes Handles to attributes whose data type is to be copied.
//! @param attributeCount Number of attributes to be copied.
//! @param overwrite An option to overwrite existing attributes.
//! @param copiedAttributes Output handles to the newly copied attributes. Can be `nullptr` if no output is
//! required.
//! @param copiedCount Number of successfully copied attributes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result copyAttributes_abi(
NameToken const* const newNames OMNI_ATTR("in, count=attributeCount"),
ConstAttributeDataHandle const* const sourceAttributes OMNI_ATTR("in, not_null, count=attributeCount"),
size_t attributeCount,
bool overwrite,
AttributeDataHandle* const copiedAttributes OMNI_ATTR("out, count=attributeCount"),
size_t* const copiedCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Create attributes based on provided names and types.
//!
//! Created attributes are owned by this bundle.
//!
//! @param names The names of the attributes.
//! @param types The types of the attributes.
//! @param elementCount Number of elements in the array, can be `nullptr` if attribute is not an array.
//! @param attributeCount Number of attributes to be created.
//! @param createdAttributes Output handles to the newly created attributes. Can be nullptr if no output is
//! required.
//! @param createdCount Number of successfully created attributes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result createAttributes_abi(
NameToken const* const names OMNI_ATTR("in, not_null, count=attributeCount"),
Type const* const types OMNI_ATTR("in, not_null, count=attributeCount"),
size_t const* const elementCount OMNI_ATTR("in, not_null, count=attributeCount"),
size_t attributeCount,
AttributeDataHandle* const createdAttributes OMNI_ATTR("out, count=attributeCount"),
size_t* const createdCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Use attribute handles as pattern to create new attributes.
//!
//! The name and type for new attributes are taken from pattern attributes, data and metadata is not copied.
//! If pattern handle is invalid, then attribute creation is skipped.
//! Created attributes are owned by this bundle.
//!
//! @param patternAttributes Attributes whose name and type is to be used to create new attributes.
//! @param patternCount Number of attributes to be created.
//! @param createdAttributes Output handles to the newly created attributes. Can be nullptr if no output is
//! required.
//! @param createdCount Number of successfully created attributes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result createAttributesLike_abi(
ConstAttributeDataHandle const* const patternAttributes OMNI_ATTR("in, not_null, count=patternCount"),
size_t patternCount,
AttributeDataHandle* const createdAttributes OMNI_ATTR("out, count=patternCount"),
size_t* const createdCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Create immediate child bundles under specified names in this bundle.
//!
//! Only immediate children are created. This method does not work recursively.
//! If name token is invalid, then child bundle creation is skipped.
//! Created bundles are owned by this bundle.
//!
//! @param names New children names in this bundle.
//! @param nameCount Number of bundles to be created.
//! @param createdBundles Output handles to the newly created bundles. Can be nullptr if no output is required.
//! @param createdCount Number of successfully created child bundles.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result createChildBundles_abi(
NameToken const* const names OMNI_ATTR("in, not_null, count=nameCount"),
size_t nameCount,
BundleHandle* const createdBundles OMNI_ATTR("out, count=nameCount"),
size_t* const createdCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! <b>Feature not implemented yet.</b>
//!
//! @brief Add a set of attributes to this bundle as links.
//!
//! Added attributes are links to other attributes that are part of another bundle.
//! If target handle is invalid, then linking is skipped.
//! The links are owned by this bundle, but targets of the links are not.
//! Removing links from this bundle does not destroy the data links point to.
//!
//! @param linkNames The names for new links.
//! @param targetAttributes Handles to attributes whose data is to be added.
//! @param attributeCount Number of attributes to be added.
//! @param linkedAttributes Output handles to linked attributes. Can be nullptr if no output is required.
//! @param linkedCount Number of attributes successfully linked.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result linkAttributes_abi(
NameToken const* const linkNames OMNI_ATTR("in, count=attributeCount"),
ConstAttributeDataHandle const* const targetAttributes OMNI_ATTR("in, not_null, count=attributeCount"),
size_t attributeCount,
AttributeDataHandle* const linkedAttributes OMNI_ATTR("out, count=attributeCount"),
size_t* const linkedCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Copy bundle data and metadata from the source bundle to this bundle.
//!
//! If source handle is invalid, then operation is skipped.
//!
//! @param sourceBundle Handle to bundle whose data is to be copied.
//! @param overwrite An option to overwrite existing content of the bundle.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result copyBundle_abi(ConstBundleHandle sourceBundle, bool overwrite) noexcept = 0;
//! @brief Create new child bundles by copying existing.
//!
//! Source bundle handles' data and metadata are copied. If a handle is invalid,
//! then its source is ignored.
//! Created bundles are owned by this bundle.
//!
//! @param newNames Names for new children, if `nullptr` then names are taken from the source bundles.
//! @param sourceBundles Handles to bundles whose data is to be copied.
//! @param bundleCount Number of bundles to be copied.
//! @param overwrite An option to overwrite existing child bundles.
//! @param copiedBundles Output handles to the newly copied bundles. Can be `nullptr` if no output is required.
//! @param copiedCount Number of successfully copied child bundles.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result copyChildBundles_abi(
NameToken const* const newNames OMNI_ATTR("in, count=bundleCount"),
ConstBundleHandle const* const sourceBundles OMNI_ATTR("in, not_null, count=bundleCount"),
size_t bundleCount,
bool overwrite,
BundleHandle* const copiedBundles OMNI_ATTR("out, count=bundleCount"),
size_t* const copiedCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! <b>Feature not implemented yet.</b>
//!
//! @brief Link content from the source bundle to this bundle.
//!
//! If source handle is invalid, then operation is skipped.
//!
//! @param sourceBundle Handle to bundle whose data is to be linked.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result linkBundle_abi(
ConstBundleHandle const* const sourceBundle OMNI_ATTR("in, not_null")) noexcept = 0;
//! @brief Add a set of bundles as children to this bundle as links.
//!
//! Created bundles are links to other bundles that are part of another bundle.
//! If target handle is invalid, then operation is skipped.
//! The links are owned by this bundle, but targets of the links are not.
//! Removing links from this bundle does not destroy the targets data.
//!
//! @param linkNames Names for new links.
//! @param targetBundles Handles to bundles whose data is to be added.
//! @param bundleCount Number of bundles to be added.
//! @param linkedBundles Handles to linked bundles. Can be nullptr if no output is required.
//! @param linkedCount Number of child bundles successfully linked.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result linkChildBundles_abi(
NameToken const* const linkNames OMNI_ATTR("in, count=bundleCount"),
ConstBundleHandle const* const targetBundles OMNI_ATTR("in, not_null, count=bundleCount"),
size_t bundleCount,
BundleHandle* const linkedBundles OMNI_ATTR("out, count=bundleCount"),
size_t* const linkedCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Remove attributes based on provided handles.
//!
//! Lookup the attribute handles and if they are part of this bundle then remove attributes' data and
//! metadata. Attribute handles that are not part of this bundle are ignored.
//!
//! @param attributes Handles to attributes whose data is to be removed
//! @param attributeCount Number of attributes to be removed.
//! @param removedCount Number of attributes successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result removeAttributes_abi(ConstAttributeDataHandle const* const attributes
OMNI_ATTR("in, not_null, count=attributeCount"),
size_t attributeCount,
size_t* const removedCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Remove attributes based on provided names.
//!
//! Lookup the attribute names and if they are part of this bundle then remove attributes' data and
//! metadata. Attribute names that are not part of this bundle are ignored.
//!
//! @param names The names of the attributes whose data is to be removed.
//! @param nameCount Number of attributes to be removed.
//! @param removedCount Number of attributes successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result removeAttributesByName_abi(
NameToken const* const names OMNI_ATTR("in, not_null, count=nameCount"),
size_t nameCount,
size_t* const removedCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Remove child bundles based on provided handles.
//!
//! Lookup the bundle handles and if they are children of the bundle then remove them and their metadata.
//! Bundle handles that are not children of this bundle are ignored.
//! Only empty child bundles can be removed.
//!
//! @param childHandles Handles to bundles to be removed.
//! @param childCount Number of child bundles to be removed.
//! @param removedCount Number of child bundles successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result removeChildBundles_abi(
ConstBundleHandle const* const childHandles OMNI_ATTR("in, not_null, count=bundleCount"),
size_t childCount,
size_t* const removedCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Remove child bundles based on provided names.
//!
//! Lookup the bundle names and if the are children of the bundle then remove them and their metadata.
//! Bundle names that are not children of this bundle are ignored.
//! Only empty child bundles can be removed.
//!
//! @param names The names of the child bundles to be removed.
//! @param nameCount Number of child bundles to be removed.
//! @param removedCount Number of child bundles successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result removeChildBundlesByName_abi(
NameToken const* const names OMNI_ATTR("in, not_null, count=nameCount"),
size_t nameCount,
size_t* const removedCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @deprecated Metadata storage is deprecated and invalid handle is returned.
OMNI_ATTR("no_py")
virtual BundleHandle getMetadataStorage_abi() noexcept = 0;
//! @brief Search for bundle metadata fields based on provided names.
//!
//! Invalid attribute handles are returned for not existing names.
//!
//! @param fieldNames Bundle metadata field names to be searched for.
//! @param fieldCount Size of fieldNames and bundleMetadata arrays.
//! @param bundleMetadata Handles to bundle metadata fields in this bundle.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getBundleMetadataByName_abi(
NameToken const* const fieldNames OMNI_ATTR("in, count=fieldCount"),
size_t fieldCount,
AttributeDataHandle* const bundleMetadata OMNI_ATTR("out, count=fieldCount")) noexcept = 0;
//! @brief Create bundle metadata fields in this bundle.
//!
//! @param fieldNames Names of new bundle metadata fields.
//! @param fieldTypes Types of new bundle metadata fields.
//! @param elementCount Number of elements in the array, can be `nullptr` if field is not an array.
//! @param fieldCount Size of fieldNames and fieldTypes arrays.
//! @param bundleMetadata Handles to the newly created bundle metadata fields. Can be `nullptr` if no output is
//! required.
//! @param createdCount Number of child bundles successfully created.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result createBundleMetadata_abi(
NameToken const* const fieldNames OMNI_ATTR("in, count=fieldCount"),
Type const* const fieldTypes OMNI_ATTR("in, count=fieldCount"),
size_t const* const elementCount OMNI_ATTR("in, count=fieldCount"),
size_t fieldCount,
AttributeDataHandle* const bundleMetadata OMNI_ATTR("out, count=fieldCount"),
size_t* const createdCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Remove bundle metadata based on provided field names.
//!
//! @param fieldNames Names of the bundle metadata fields whose data is to be removed.
//! @param fieldCount Number of the bundle metadata fields to be removed.
//! @param removedCount Number of bundle metadata fields successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result removeBundleMetadata_abi(
NameToken const* const fieldNames OMNI_ATTR("in, not_null, count=fieldCount"),
size_t fieldCount,
size_t* const removedCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Search for read write field handles in the attribute by using field names.
//!
//! @copydetails IConstBundle2_abi::getConstAttributeMetadataByName_abi
OMNI_ATTR("no_py")
virtual omni::core::Result getAttributeMetadataByName_abi(
NameToken attribute,
NameToken const* const fieldNames OMNI_ATTR("in, count=fieldCount"),
size_t fieldCount,
AttributeDataHandle* const attributeMetadata OMNI_ATTR("out, count=fieldCount")) noexcept = 0;
//! @brief Create attribute metadata fields.
//!
//! @param attribute Name of the attribute.
//! @param fieldNames Names of new attribute metadata fields.
//! @param fieldTypes Types of new attribute metadata fields.
//! @param elementCount Number of elements in the array, can be `nullptr` if field is not an array.
//! @param fieldCount Size of fieldNames and fieldTypes arrays.
//! @param attributeMetadata Handles to the newly created attribute metadata. Can be `nullptr` if no output is
//! required.
//! @param createdCount Number of attribute metadata fields successfully created.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result createAttributeMetadata_abi(
NameToken attribute,
NameToken const* const fieldNames OMNI_ATTR("in, count=fieldCount"),
Type const* const fieldTypes OMNI_ATTR("in, count=fieldCount"),
size_t const* const elementCount OMNI_ATTR("in, count=fieldCount"),
size_t fieldCount,
AttributeDataHandle* const attributeMetadata OMNI_ATTR("out, count=fieldCount"),
size_t* const createdCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Remove attribute metadata fields.
//!
//! @param attribute Name of the attribute.
//! @param fieldNames Names of the attribute metadata fields to be removed.
//! @param fieldCount Size of fieldNames array.
//! @param removedCount Number of attribute metadata fields successfully removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result removeAttributeMetadata_abi(
NameToken attribute,
NameToken const* const fieldNames OMNI_ATTR("in, count=fieldCount"),
size_t fieldCount,
size_t* const removedCount OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Remove all attributes, child bundles and metadata from this bundle, but keep the bundle itself.
//!
//! @param bundleMetadata Clears bundle metadata in this bundle.
//! @param attributes Clears attributes in this bundle.
//! @param childBundles Clears child bundles in this bundle.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result clearContents_abi(bool bundleMetadata, bool attributes, bool childBundles) noexcept = 0;
};
} // namespace core
} // namespace graph
} // namespace omni
#include "IBundle2.gen.h"
//! @cond Doxygen_Suppress
//!
//! API part of the bundle factory interface
//! @copydoc omni::graph::core::IBundle2_abi
OMNI_DEFINE_INTERFACE_API(omni::graph::core::IBundle2)
//! @endcond
{
public:
//! @copydoc omni::graph::core::IBundle2::getAttributes_abi
omni::core::Result getAttributes(
omni::graph::core::AttributeDataHandle* const attributes, size_t attributeCount) noexcept
{
return getAttributes_abi(attributes, &attributeCount);
}
//! @brief Searches for read-write handle of the attribute in this bundle by using attribute name.
//!
//! @param name The name of the attribute to search for.
//! @return Valid attribute handle if attribute if found, invalid handle otherwise.
omni::graph::core::AttributeDataHandle getAttributeByName(omni::graph::core::NameToken name) noexcept
{
using namespace omni::graph::core;
AttributeDataHandle out{ AttributeDataHandle::invalidValue() };
auto result = getAttributesByName_abi(&name, 1, &out);
return OMNI_SUCCEEDED(result) ? out : AttributeDataHandle{ AttributeDataHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::getChildBundles_abi
omni::core::Result getChildBundles(omni::graph::core::BundleHandle* const bundles, size_t bundleCount) noexcept
{
return getChildBundles_abi(bundles, &bundleCount);
}
//! @brief Get the child bundle handle by index.
//!
//! If bundle index is out of range, then invalid handle is returned.
//!
//! @param bundleIndex Bundle index in range [0, childBundleCount).
//! @return Bundle handle under the index.
omni::graph::core::BundleHandle getChildBundle(size_t bundleIndex) noexcept
{
using namespace omni::graph::core;
BundleHandle out{ BundleHandle::invalidValue() };
auto result = getChildBundle_abi(bundleIndex, &out);
return OMNI_SUCCEEDED(result) ? out : BundleHandle{ BundleHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::copyAttributes_abi
template <typename HANDLE>
omni::core::Result copyAttributes(HANDLE const* const sourceAttributes, size_t attributeCount, bool overwrite = true,
omni::graph::core::NameToken const* const newNames = nullptr,
omni::graph::core::AttributeDataHandle* const copiedAttributes = nullptr,
size_t* const copiedCount = nullptr) noexcept
{
using namespace omni::graph::core;
static_assert(
std::is_same<HANDLE, AttributeDataHandle>::value || std::is_same<HANDLE, ConstAttributeDataHandle>::value,
"Only AttributeDataHandle and ConstAttributeDataHandle can be copied");
return copyAttributes_abi(newNames, reinterpret_cast<ConstAttributeDataHandle const* const>(sourceAttributes),
attributeCount, overwrite, copiedAttributes, copiedCount);
}
//! @brief Create new attribute by copying existing attribute's data and metadata.
//!
//! Created attribute is owned by this bundle.
//!
//! @param sourceAttribute Handle to attribute whose data type is to be copied.
//! @param overwrite Overwrites existing attributes.
//! @param newName The new name for copied attribute.
//! @return Output handle to the newly copied attribute.
omni::graph::core::AttributeDataHandle copyAttribute(
omni::graph::core::ConstAttributeDataHandle const& sourceAttribute, bool overwrite = true,
omni::graph::core::NameToken newName = omni::fabric::kUninitializedToken) noexcept
{
using namespace omni::graph::core;
AttributeDataHandle out{ AttributeDataHandle::invalidValue() };
NameToken* newNamePtr = newName == omni::fabric::kUninitializedToken ? nullptr : &newName;
auto result = copyAttributes_abi(newNamePtr, &sourceAttribute, 1, overwrite, &out, nullptr);
return OMNI_SUCCEEDED(result) ? out : AttributeDataHandle{ AttributeDataHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::createAttributes_abi
omni::core::Result createAttributes(omni::graph::core::NameToken const* const names,
omni::graph::core::Type const* const types, size_t attributeCount,
size_t const* const elementCount = nullptr,
omni::graph::core::AttributeDataHandle* const createdAttributes = nullptr,
size_t* const createdCount = nullptr) noexcept
{
return createAttributes_abi(names, types, elementCount, attributeCount, createdAttributes, createdCount);
}
//! @brief Create attribute based on provided name and type.
//!
//! Created attribute is owned by this bundle.
//!
//! @param name The name of the attribute.
//! @param type The type of the attribute.
//! @param elementCount Number of elements in the array.
//! @return Output handle to the newly created attribute.
omni::graph::core::AttributeDataHandle createAttribute(
omni::graph::core::NameToken name, omni::graph::core::Type const& type, size_t elementCount = 0) noexcept
{
using namespace omni::graph::core;
omni::core::Result result = kResultFail;
AttributeDataHandle out{ AttributeDataHandle::invalidValue() };
size_t* elementCountPtr = type.arrayDepth == 0 ? nullptr : &elementCount;
result = createAttributes_abi(&name, &type, elementCountPtr, 1, &out, nullptr);
return OMNI_SUCCEEDED(result) ? out : AttributeDataHandle{ AttributeDataHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::createAttributesLike_abi
omni::core::Result createAttributesLike(omni::graph::core::ConstAttributeDataHandle const* const patternAttributes,
size_t patternCount,
omni::graph::core::AttributeDataHandle* const createdAttributes = nullptr,
size_t* const createdCount = nullptr) noexcept
{
return createAttributesLike_abi(patternAttributes, patternCount, createdAttributes, createdCount);
}
//! @brief Use input attribute handle as pattern to create attribute in this bundle.
//!
//! The name and type are taken from pattern attribute, data is not copied.
//! Created attribute is owned by this bundle.
//!
//! @param patternAttribute Attribute whose name and type is to be used to create new attribute.
//! @return Output handle to the newly created attribute.
omni::graph::core::AttributeDataHandle createAttributeLike(
omni::graph::core::ConstAttributeDataHandle const& patternAttribute) noexcept
{
using namespace omni::graph::core;
AttributeDataHandle out{ AttributeDataHandle::invalidValue() };
auto result = createAttributesLike_abi(&patternAttribute, 1, &out, nullptr);
return OMNI_SUCCEEDED(result) ? out : AttributeDataHandle{ AttributeDataHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::createChildBundles_abi
omni::core::Result createChildBundles(omni::graph::core::NameToken const* const names, size_t nameCount,
omni::graph::core::BundleHandle* const createdBundles = nullptr,
size_t* const createdCount = nullptr) noexcept
{
return createChildBundles_abi(names, nameCount, createdBundles, createdCount);
}
//! @brief Create immediate child bundle under specified name.
//!
//! Created bundle is owned by this bundle. This method does not work recursively. Only immediate child can be
//! created.
//!
//! @param name New child name in this bundle.
//! @return Output handle to the newly created bundle.
omni::graph::core::BundleHandle createChildBundle(omni::graph::core::NameToken name) noexcept
{
using namespace omni::graph::core;
BundleHandle out{ BundleHandle::invalidValue() };
auto result = createChildBundles_abi(&name, 1, &out, nullptr);
return OMNI_SUCCEEDED(result) ? out : BundleHandle{ BundleHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::linkAttributes_abi
template <typename HANDLE>
omni::core::Result linkAttributes(HANDLE const* const targetAttributes, size_t attributeCount,
omni::graph::core::NameToken const* const linkNames = nullptr,
omni::graph::core::AttributeDataHandle* const linkedAttributes = nullptr,
size_t* const linkedCount = nullptr) noexcept
{
using namespace omni::graph::core;
static_assert(
std::is_same<HANDLE, AttributeDataHandle>::value || std::is_same<HANDLE, ConstAttributeDataHandle>::value,
"Only AttributeDataHandle and ConstAttributeDataHandle can be copied");
auto linkedAttributesPtr = reinterpret_cast<ConstAttributeDataHandle const* const>(targetAttributes);
return linkAttributes_abi(linkNames, linkedAttributesPtr, attributeCount, linkedAttributes, linkedCount);
}
//! < b>Feature not implemented yet.< /b>
//!
//! @brief Add an attribute to this bundle as link with custom name.
//!
//! Added attribute is a link to other attribute that is part of another bundle.
//! The link is owned by this bundle, but target of the link is not.
//! Removing link from this bundle does not destroy the data link points to.
//!
//! @param linkName Name for new link.
//! @param targetAttribute Handle to attribute whose data is to be added.
//! @return Output handle to linked attributes.
omni::graph::core::AttributeDataHandle linkAttribute(
omni::graph::core::ConstAttributeDataHandle const& targetAttribute,
omni::graph::core::NameToken linkName = omni::fabric::kUninitializedToken) noexcept
{
using namespace omni::graph::core;
AttributeDataHandle out{ AttributeDataHandle::invalidValue() };
auto result = linkAttributes_abi(&linkName, &targetAttribute, 1, &out, nullptr);
return OMNI_SUCCEEDED(result) ? out : AttributeDataHandle{ AttributeDataHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::copyBundle_abi
omni::core::Result copyBundle(omni::graph::core::ConstBundleHandle sourceBundle, bool overwrite = true) noexcept
{
return copyBundle_abi(sourceBundle, overwrite);
}
//! @copydoc omni::graph::core::IBundle2_abi::copyChildBundles_abi
template <typename HANDLE>
omni::core::Result copyChildBundles(HANDLE const* const sourceBundles, size_t bundleCount, bool overwrite = true,
omni::graph::core::NameToken const* const newNames = nullptr,
omni::graph::core::BundleHandle* const copiedBundles = nullptr,
size_t* const copiedCount = nullptr) noexcept
{
using namespace omni::graph::core;
static_assert(std::is_same<HANDLE, BundleHandle>::value || std::is_same<HANDLE, ConstBundleHandle>::value,
"Only BundleHandle and ConstBundleHandle can be copied");
auto sourceBundlesPtr = reinterpret_cast<ConstBundleHandle const* const>(sourceBundles);
return copyChildBundles_abi(newNames, sourceBundlesPtr, bundleCount, overwrite, copiedBundles, copiedCount);
}
//! @brief Create new child bundle by copying existing bundle's data and metadata, with possibility of giving child
//! a new name.
//!
//! Created bundle is owned by this bundle.
//!
//! @param sourceBundle Handle to bundle whose data is to be copied.
//! @param overwrite An option to overwrite child bundle.
//! @param newName Name for new child.
//! @return Output handles to the newly copied bundle.
omni::graph::core::BundleHandle copyChildBundle(
omni::graph::core::ConstBundleHandle const& sourceBundle, bool overwrite = true,
omni::graph::core::NameToken newName = omni::fabric::kUninitializedToken) noexcept
{
using namespace omni::graph::core;
BundleHandle out{ BundleHandle::invalidValue() };
NameToken* newNamePtr = newName == omni::fabric::kUninitializedToken ? nullptr : &newName;
auto result = copyChildBundles_abi(newNamePtr, &sourceBundle, 1, overwrite, &out, nullptr);
return OMNI_SUCCEEDED(result) ? out : BundleHandle{ BundleHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::removeAttributes_abi
template <typename HANDLE>
omni::core::Result removeAttributes(
HANDLE const* const attributes, size_t attributeCount, size_t* const removedCount = nullptr) noexcept
{
using namespace omni::graph::core;
static_assert(
std::is_same<HANDLE, AttributeDataHandle>::value || std::is_same<HANDLE, ConstAttributeDataHandle>::value,
"Only AttributeDataHandle and ConstAttributeDataHandle can be copied");
auto attributesPtr = reinterpret_cast<ConstAttributeDataHandle const* const>(attributes);
return removeAttributes_abi(attributesPtr, attributeCount, removedCount);
}
//! @brief Lookup the attribute handle and if it is part of this bundle then remove attributes' data and
//! metadata.
//!
//! Attribute handle that is not part of this bundle is ignored.
//!
//! @param attribute Handle to attribute whose data is to be removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeAttribute(omni::graph::core::ConstAttributeDataHandle const& attribute) noexcept
{
return removeAttributes_abi(&attribute, 1, nullptr);
}
//! @copydoc omni::graph::core::IBundle2_abi::removeAttributesByName_abi
omni::core::Result removeAttributesByName(omni::graph::core::NameToken const* const names, size_t nameCount,
size_t* const removedCount = nullptr) noexcept
{
return removeAttributesByName_abi(names, nameCount, removedCount);
}
//! @brief Lookup the attribute by name and remove its data and metadata.
//!
//! @param name The name of the attribute whose data is to be removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeAttributeByName(omni::graph::core::NameToken name) noexcept
{
return removeAttributesByName_abi(&name, 1, nullptr);
}
//! @copydoc omni::graph::core::IBundle2_abi::removeChildBundles_abi
template <typename HANDLE>
omni::core::Result removeChildBundles(
HANDLE const* const bundles, size_t bundleCount, size_t* const removedCount = nullptr) noexcept
{
using namespace omni::graph::core;
static_assert(std::is_same<HANDLE, BundleHandle>::value || std::is_same<HANDLE, ConstBundleHandle>::value,
"Only BundleHandle and ConstBundleHandle can be copied");
auto bundlesPtr = reinterpret_cast<ConstBundleHandle const* const>(bundles);
return removeChildBundles_abi(bundlesPtr, bundleCount, removedCount);
}
//! @brief Lookup the bundle handle and if it is child of the bundle then remove it and its metadata.
//!
//! Bundle handle that is not child of this bundle is ignored. Only empty bundle can be removed.
//!
//! @param bundle Handle to bundle to be removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeChildBundle(omni::graph::core::ConstBundleHandle const& bundle) noexcept
{
return removeChildBundles_abi(&bundle, 1, nullptr);
}
//! @copydoc omni::graph::core::IBundle2_abi::removeChildBundlesByName_abi
omni::core::Result removeChildBundlesByName(omni::graph::core::NameToken const* const names, size_t nameCount,
size_t* const removedCount = nullptr) noexcept
{
return removeChildBundlesByName_abi(names, nameCount, removedCount);
}
//! @brief Lookup child bundle by name and remove its data and metadata.
//!
//! @param name The name of the child bundle to be removed.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeChildBundleByName(omni::graph::core::NameToken name) noexcept
{
return removeChildBundlesByName_abi(&name, 1, nullptr);
}
//! @brief Lookup for child under specified name.
//!
//! For child that is not found invalid handle is returned.
//!
//! @param name The name of bundle child in this bundle.
//! @return Output handle to the found bundle.
omni::graph::core::BundleHandle getChildBundleByName(omni::graph::core::NameToken name) noexcept
{
using namespace omni::graph::core;
BundleHandle out{ BundleHandle::invalidValue() };
auto result = getChildBundlesByName_abi(&name, 1, &out);
return OMNI_SUCCEEDED(result) ? out : BundleHandle{ BundleHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::getBundleMetadataByName_abi
using omni::core::Generated<omni::graph::core::IBundle2_abi>::getBundleMetadataByName;
//! @brief Search for bundle metadata field based on provided name.
//!
//! Invalid attribute handle is returned for not existing name.
//!
//! @param fieldName Bundle metadata field name to be searched for.
//!
//! @return Valid metadata attribute handle for existing name, or Invalid handle for not existing.
omni::graph::core::AttributeDataHandle getBundleMetadataByName(omni::graph::core::NameToken fieldName) noexcept
{
using namespace omni::graph::core;
AttributeDataHandle out{ AttributeDataHandle::invalidValue() };
auto result = getBundleMetadataByName_abi(&fieldName, 1, &out);
return OMNI_SUCCEEDED(result) ? out : AttributeDataHandle{ AttributeDataHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::createBundleMetadata_abi
omni::core::Result createBundleMetadata(omni::graph::core::NameToken const* const fieldNames,
omni::graph::core::Type const* const fieldTypes, size_t fieldCount,
size_t const* const elementCount = nullptr,
omni::graph::core::AttributeDataHandle* const bundleMetadata = nullptr,
size_t* const createdCount = nullptr) noexcept
{
return createBundleMetadata_abi(fieldNames, fieldTypes, elementCount, fieldCount, bundleMetadata, createdCount);
}
//! @brief Create bundle metadata field in this bundle.
//!
//! @param fieldName Name of new bundle metadata field.
//! @param fieldType Type of new bundle metadata field.
//! @param elementCount Number of elements in the array, if fieldType is an array type.
//!
//! @return Valid metadata attribute handle for existing name, or Invalid handle for not existing.
omni::graph::core::AttributeDataHandle createBundleMetadata(
omni::graph::core::NameToken fieldName, omni::graph::core::Type const& fieldType, size_t elementCount = 0) noexcept
{
using namespace omni::graph::core;
AttributeDataHandle out{ AttributeDataHandle::invalidValue() };
auto result = createBundleMetadata_abi(&fieldName, &fieldType, &elementCount, 1, &out, nullptr);
return OMNI_SUCCEEDED(result) ? out : AttributeDataHandle{ AttributeDataHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::removeBundleMetadata_abi
omni::core::Result removeBundleMetadata(omni::graph::core::NameToken const* const fieldNames, size_t fieldCount,
size_t* const removedCount = nullptr) noexcept
{
return removeBundleMetadata_abi(fieldNames, fieldCount, removedCount);
}
//! @brief Remove bundle metadata based on provided field name.
//!
//! @param fieldName Name of the bundle metadata field whose data is to be removed.
//!
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeBundleMetadata(omni::graph::core::NameToken fieldName) noexcept
{
return removeBundleMetadata_abi(&fieldName, 1, nullptr);
}
//! @copydoc omni::graph::core::IBundle2_abi::getAttributeMetadataByName_abi
using omni::core::Generated<omni::graph::core::IBundle2_abi>::getAttributeMetadataByName;
//! @brief Search for read-write metadata field handle for the attribute by using field name.
//!
//! @param attribute The name of the attribute.
//! @param fieldName The name of attribute metadata field to be searched for.
//!
//! @return Valid metadata attribute handle for existing name, or Invalid handle for not existing.
omni::graph::core::AttributeDataHandle getAttributeMetadataByName(
omni::graph::core::NameToken attribute, omni::graph::core::NameToken fieldName) noexcept
{
using namespace omni::graph::core;
AttributeDataHandle out{ AttributeDataHandle::invalidValue() };
auto result = getAttributeMetadataByName_abi(attribute, &fieldName, 1, &out);
return OMNI_SUCCEEDED(result) ? out : AttributeDataHandle{ AttributeDataHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::createAttributeMetadata_abi
omni::core::Result createAttributeMetadata(
omni::graph::core::NameToken attribute, omni::graph::core::NameToken const* const fieldNames,
omni::graph::core::Type const* const fieldTypes, size_t fieldCount, size_t const* const elementCount = nullptr,
omni::graph::core::AttributeDataHandle* const attributeMetadata = nullptr,
size_t* const createdCount = nullptr) noexcept
{
return createAttributeMetadata_abi(
attribute, fieldNames, fieldTypes, elementCount, fieldCount, attributeMetadata, createdCount);
}
//! @brief Create attribute metadata field.
//!
//! @param attribute Name of the attribute.
//! @param fieldName Name of new attribute metadata field.
//! @param fieldType Type of new attribute metadata field.
//! @param elementCount Number of elements in the array.
//! @return Handle to the newly created attribute metadata field.
omni::graph::core::AttributeDataHandle createAttributeMetadata(
omni::graph::core::NameToken attribute, omni::graph::core::NameToken fieldName,
omni::graph::core::Type const& fieldType, size_t elementCount = 0) noexcept
{
using namespace omni::graph::core;
AttributeDataHandle out{ AttributeDataHandle::invalidValue() };
size_t* elementCountPtr = fieldType.arrayDepth == 0 ? nullptr : &elementCount;
auto result = createAttributeMetadata_abi(attribute, &fieldName, &fieldType, elementCountPtr, 1, &out, nullptr);
return OMNI_SUCCEEDED(result) ? out : AttributeDataHandle{ AttributeDataHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IBundle2_abi::removeAttributeMetadata_abi
omni::core::Result removeAttributeMetadata(omni::graph::core::NameToken attribute,
omni::graph::core::NameToken const* const fieldNames, size_t fieldCount,
size_t* const removedCount = nullptr) noexcept
{
return removeAttributeMetadata_abi(attribute, fieldNames, fieldCount, removedCount);
}
//! @copydoc omni::graph::core::IBundle2_abi::removeAttributeMetadata_abi
using omni::core::Generated<omni::graph::core::IBundle2_abi>::removeAttributeMetadata;
//! @brief Remove attribute metadata field.
//!
//! @param attribute Name of the attribute.
//! @param fieldName Name of the attribute metadata field to be removed.
//!
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result removeAttributeMetadata(
omni::graph::core::NameToken attribute, omni::graph::core::NameToken fieldName) noexcept
{
return removeAttributeMetadata_abi(attribute, &fieldName, 1, nullptr);
}
//! @copydoc omni::graph::core::IBundle2_abi::clearContents_abi
omni::core::Result clearContents(bool bundleMetadata = true, bool attributes = true, bool childBundles = true) noexcept
{
return clearContents_abi(bundleMetadata, attributes, childBundles);
}
}; // IBundle2
| 48,903 | C | 52.446994 | 125 | 0.682289 |
omniverse-code/kit/include/omni/graph/core/bundle/IBundleFactory1.h | // 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.
//
#pragma once
#include <omni/graph/core/IBundle.h>
namespace omni
{
namespace graph
{
namespace core
{
OMNI_DECLARE_INTERFACE(IBundleFactory);
//! Interface to create new bundles
class IBundleFactory_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.IBundleFactory")>
{
protected:
//! Create bundles at given paths and acquire instances of IBundle2 interface.
//!
//! @param contextObj The context where bundles are created.
//! @param paths Locations for new bundles.
//! @param pathCount Length of paths array.
//! @param createdBundles Output instances of IBundle2 interface.
//!
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result createBundles_abi(GraphContextObj const* const contextObj OMNI_ATTR("in, not_null"),
omni::fabric::PathC const* const paths OMNI_ATTR("in, not_null"),
size_t pathCount,
IBundle2** const createdBundles
OMNI_ATTR("out, *not_null, count=pathCount")) noexcept = 0;
//! Acquire instances of IConstBundle2 interface from const bundle handles.
//!
//! @param contextObj The context where bundles belong to.
//! @param bundleHandles The bundle handles.
//! @param bundleCount Length of bundleHandles array.
//! @param bundles Output instances of IConstBundle2 interface.
//!
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getConstBundles_abi(
GraphContextObj const* const contextObj OMNI_ATTR("in, not_null"),
ConstBundleHandle const* const bundleHandles OMNI_ATTR("in, not_null"),
size_t bundleCount,
IConstBundle2** const bundles OMNI_ATTR("out, *not_null, count=bundleCount")) noexcept = 0;
//! Acquire instances of IBundle2 interface from bundle handles.
//!
//! @param contextObj The context where bundles belong to.
//! @param bundleHandles The bundle handles.
//! @param bundleCount Length of bundleHandles array.
//! @param bundles Output instances of IConstBundle2 interface.
//!
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getBundles_abi(GraphContextObj const* const contextObj OMNI_ATTR("in, not_null"),
BundleHandle const* const bundleHandles OMNI_ATTR("in, not_null"),
size_t bundleCount,
IBundle2** const bundles
OMNI_ATTR("out, *not_null, count=bundleCount")) noexcept = 0;
};
} // namespace core
} // namespace graph
} // namespace omni
#include "IBundleFactory1.gen.h"
//! @cond Doxygen_Suppress
//!
//! API part of the bundle factory interface
OMNI_DEFINE_INTERFACE_API(omni::graph::core::IBundleFactory)
//! @endcond
{
public:
//! @brief Create a list of Bundle objects
//!
//! @param contextObj The context where bundles are created.
//! @param paths Locations for new bundles.
//! @param pathCount Length of paths array.
//! @param createdBundles Output instances of IBundle2 interface.
//!
//! @return true if bundles were created
//! @return false if bundle creation failed or arguments were invalid
bool createBundles(omni::graph::core::GraphContextObj const& contextObj,
omni::fabric::PathC const* const paths,
size_t pathCount,
omni::core::ObjectPtr<omni::graph::core::IBundle2>* const createdBundles) noexcept
{
static_assert(sizeof(omni::core::ObjectPtr<omni::graph::core::IBundle2>) == sizeof(omni::graph::core::IBundle2*),
"ObjectPtr and IBundle2 pointer requires to be the same size!");
auto result = createBundles_abi(
&contextObj, paths, pathCount, reinterpret_cast<omni::graph::core::IBundle2**>(createdBundles));
if (OMNI_FAILED(result))
{
OMNI_LOG_ERROR("unable to create bundles: 0x%08X", result);
return false;
}
return true;
}
//! Create bundle at given path and acquire instance of IBundle2 interface.
//!
//! @param contextObj The context where bundle is created.
//! @param path Locations for new bundle.
//!
//! @return Smart pointer that manages lifetime of IBundle2 instance.
omni::core::ObjectPtr<omni::graph::core::IBundle2> createBundle(omni::graph::core::GraphContextObj const& contextObj,
omni::fabric::PathC path) noexcept
{
omni::core::ObjectPtr<omni::graph::core::IBundle2> out;
createBundles(contextObj, &path, 1, &out);
return out;
}
//! Acquire instances of IConstBundle2 interface from constant bundle handles.
//!
//! @param contextObj The context where bundles belong to.
//! @param bundleHandles The bundle handles.
//! @param bundleCount Length of bundleHandles array.
//! @param bundles Smart pointers that manage lifetime of IConstBundle2 instances.
//!
//! @return true if operation was successful, false otherwise.
template <typename HANDLE>
bool getConstBundles(omni::graph::core::GraphContextObj const& contextObj,
HANDLE const* const bundleHandles,
size_t bundleCount,
omni::core::ObjectPtr<omni::graph::core::IConstBundle2>* const bundles) noexcept
{
static_assert(sizeof(omni::core::ObjectPtr<omni::graph::core::IConstBundle2>) ==
sizeof(omni::graph::core::IConstBundle2*),
"ObjectPtr and IBundle2 pointer requires to be the same size!");
auto result = getConstBundles_abi(
&contextObj, bundleHandles, bundleCount, reinterpret_cast<omni::graph::core::IConstBundle2**>(bundles));
if (OMNI_FAILED(result))
{
OMNI_LOG_ERROR("unable to get bundles: 0x%08X", result);
return false;
}
return true;
}
//! Acquire instance of IConstBundle2 interface from constant bundle handle.
//!
//! @param contextObj The context where bundles belong to.
//! @param bundleHandle The bundle handle.
//!
//! @return Smart pointer that manages lifetime of IConstBundle2 instance.
omni::core::ObjectPtr<omni::graph::core::IConstBundle2> getConstBundle(
omni::graph::core::GraphContextObj const& contextObj,
omni::graph::core::ConstBundleHandle const& bundleHandle) noexcept
{
omni::core::ObjectPtr<omni::graph::core::IConstBundle2> out;
getConstBundles(contextObj, &bundleHandle, 1, &out);
return out;
}
//! Acquire instances of IBundle2 interface from bundle handles.
//!
//! @param contextObj The context where bundles belong to.
//! @param bundleHandles The bundle handles.
//! @param bundleCount Length of bundleHandles array.
//! @param createdBundles Smart pointers that manage lifetime of IBundle2 instances.
//!
//! @return true if operation was successful, false otherwise.
bool getBundles(omni::graph::core::GraphContextObj const& contextObj,
omni::graph::core::BundleHandle const* const bundleHandles,
size_t bundleCount,
omni::core::ObjectPtr<omni::graph::core::IBundle2>* const createdBundles) noexcept
{
static_assert(sizeof(omni::core::ObjectPtr<omni::graph::core::IBundle2>) == sizeof(omni::graph::core::IBundle2*),
"ObjectPtr and IBundle2 pointer requires to be the same size!");
auto result = getBundles_abi(
&contextObj, bundleHandles, bundleCount, reinterpret_cast<omni::graph::core::IBundle2**>(createdBundles));
if (OMNI_FAILED(result))
{
OMNI_LOG_ERROR("unable to get bundles: 0x%08X", result);
return false;
}
return true;
}
//! Acquire instance of IBundle2 interface from constant bundle handle.
//!
//! @param contextObj The context where bundles belong to.
//! @param bundleHandle The bundle handle.
//!
//! @return Smart pointer that manages lifetime of IBundle2 instance.
omni::core::ObjectPtr<omni::graph::core::IBundle2> getBundle(omni::graph::core::GraphContextObj const& contextObj,
omni::graph::core::BundleHandle const& bundleHandle) noexcept
{
omni::core::ObjectPtr<omni::graph::core::IBundle2> out;
getBundles(contextObj, &bundleHandle, 1, &out);
return out;
}
};
| 9,600 | C | 44.287736 | 126 | 0.635521 |
omniverse-code/kit/include/omni/graph/core/bundle/IBundleChanges1.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Interface for monitoring and handling changes in bundles and attributes.
//!
//! The IBundleChanges_abi is an interface that provides methods for checking whether bundles and attributes
//! have been modified, and cleaning them if they have been modified. This is particularly useful in scenarios
//! where it's crucial to track changes and maintain the state of bundles and attributes.
//!
//! This interface provides several methods for checking and cleaning modifications, each catering to different
//! use cases such as handling single bundles, multiple bundles, attributes, or specific attributes of a single bundle.
//!
//! The methods of this interface return a BundleChangeType enumeration that indicates whether the checked entity
//! (bundle or attribute) has been modified.
template <>
class omni::core::Generated<omni::graph::core::IBundleChanges_abi> : public omni::graph::core::IBundleChanges_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::graph::core::IBundleChanges")
//! @brief Activate tracking for specific bundle on its attributes and children.
//! @param handle to the specific bundles to enable change tracking.
//! @return An omni::core::Result indicating the success of the operation.
omni::core::Result activateChangeTracking(const omni::graph::core::BundleHandle& handle) noexcept;
//! @brief Deactivate tracking for specific bundle on its attributes and children.
//! @param handle to the specific bundles to enable change tracking.
//! @return An omni::core::Result indicating the success of the operation.
omni::core::Result deactivateChangeTracking(const omni::graph::core::BundleHandle& handle) noexcept;
//! @brief Retrieves the change status of an array of bundles.
//!
//! This method is used to check if any of the bundles in the provided array have been modified.
//!
//! The count parameter indicates the size of the bundles array, as well as the changes output array.
//!
//! @param bundles An array of handles to the specific bundles to check for modifications.
//! @param count The number of bundle handles in the array.
//! @param changes An array that will be filled with BundleChangeType values for each bundle.
//!
//! @returns An omni::core::Result indicating the success of the operation.
omni::core::Result getChangesForBundles(const omni::graph::core::ConstBundleHandle* const bundles,
size_t count,
omni::graph::core::BundleChangeType* const changes);
//! @brief Retrieves the change status of an array of attributes.
//!
//! This method is used to check if any of the attributes in the provided array have been modified.
//!
//! The count parameter indicates the size of the attributes array, as well as the changes output array.
//!
//! @param attributes An array of handles to the attributes to check for modifications.
//! @param count The number of attribute handles in the array.
//! @param changes An array that will be filled with BundleChangeType values for each attribute.
//!
//! @returns An omni::core::Result indicating the success of the operation.
omni::core::Result getChangesForAttributes(const omni::graph::core::ConstAttributeDataHandle* const attributes,
size_t count,
omni::graph::core::BundleChangeType* const changes);
//! Clears all recorded changes.
//!
//! This method is used to clear or reset all the recorded changes of the bundles and attributes.
//! It can be used when the changes have been processed and need to be discarded.
//!
//! An omni::core::Result indicating the success of the operation.
omni::core::Result clearChanges() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundleChanges_abi>::activateChangeTracking(
const omni::graph::core::BundleHandle& handle) noexcept
{
return activateChangeTracking_abi(handle);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundleChanges_abi>::deactivateChangeTracking(
const omni::graph::core::BundleHandle& handle) noexcept
{
return deactivateChangeTracking_abi(handle);
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundleChanges_abi>::getChangesForBundles(
const omni::graph::core::ConstBundleHandle* const bundles,
size_t count,
omni::graph::core::BundleChangeType* const changes)
{
OMNI_THROW_IF_ARG_NULL(bundles);
OMNI_THROW_IF_ARG_NULL(changes);
auto return_ = getChangesForBundles_abi(bundles, count, changes);
return return_;
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundleChanges_abi>::getChangesForAttributes(
const omni::graph::core::ConstAttributeDataHandle* const attributes,
size_t count,
omni::graph::core::BundleChangeType* const changes)
{
OMNI_THROW_IF_ARG_NULL(attributes);
OMNI_THROW_IF_ARG_NULL(changes);
auto return_ = getChangesForAttributes_abi(attributes, count, changes);
return return_;
}
inline omni::core::Result omni::core::Generated<omni::graph::core::IBundleChanges_abi>::clearChanges() noexcept
{
return clearChanges_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 6,257 | C | 43.7 | 119 | 0.715359 |
omniverse-code/kit/include/omni/graph/core/bundle/IConstBundle2.h | // 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.
//
//! @file IConstBundle.h
//!
//! @brief Defines Read only interfaces for recursive bundles.
#pragma once
#include <omni/core/IObject.h>
#include <omni/graph/core/Handle.h>
#include <omni/graph/core/Type.h>
#include <omni/log/ILog.h>
OMNI_LOG_DECLARE_CHANNEL(kBundleChannel)
namespace omni
{
namespace graph
{
namespace core
{
//! Declare the interface definition
OMNI_DECLARE_INTERFACE(IConstBundle2);
//! Provide read only access to recursive bundles.
class IConstBundle2_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.IConstBundle2")>
{
protected:
//! Return true if this bundle is valid, false otherwise.
virtual bool isValid_abi() noexcept = 0;
//! Return the context of this bundle.
OMNI_ATTR("no_py")
virtual GraphContextObj getContext_abi() noexcept = 0;
//! Return Handle to this bundle. Invalid handle is returned if this bundle is invalid.
OMNI_ATTR("no_py")
virtual ConstBundleHandle getConstHandle_abi() noexcept = 0;
//! Return full path of this bundle.
OMNI_ATTR("no_py")
virtual omni::fabric::PathC getPath_abi() noexcept = 0;
//! Return name of this bundle
OMNI_ATTR("no_py")
virtual NameToken getName_abi() noexcept = 0;
//! Return handle to the parent of this bundle. Invalid handle is returned if bundle has no parent.
OMNI_ATTR("no_py")
virtual ConstBundleHandle getConstParentBundle_abi() noexcept = 0;
//! @brief Get the names and types of all attributes in this bundle.
//!
//! This method operates in two modes: **query mode** or **get mode**.
//!
//! **Query mode** is enabled when names and types are `nullptr`. When in this mode, *nameAndTypeCount
//! will be populated with the number of attributes in the bundle.
//!
//! **Get mode** is enabled when names or types is not `nullptr`. Upon entering the function, *nameAndTypeCount
//! stores the number of entries in names and types. In **Get mode** names are not nullptr, names array is populated
//! with attribute names. In **Get mode** types are not nullptr, types array is populated with attribute types.
//!
//! @param names The names of the attributes.
//! @param types The types of the attributes.
//! @param nameAndTypeCount must not be `nullptr` in both modes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getAttributeNamesAndTypes_abi(
NameToken* const names OMNI_ATTR("out, count=*nameAndTypeCount"),
Type* const types OMNI_ATTR("out, count=*nameAndTypeCount"),
size_t* const nameAndTypeCount OMNI_ATTR("in, out, not_null")) noexcept = 0;
//! @brief Get read only handles to all attributes in this bundle.
//!
//! This method operates in two modes: **query mode** or **get mode**.
//!
//! **Query mode** is enabled when attributes is `nullptr`. When in this mode, *attributeCount
//! will be populated with the number of attributes in the bundle.
//!
//! **Get mode** is enabled when attributes is not `nullptr`. Upon entering the function, *attributeCount
//! stores the number of entries in attributes.
//! In **Get mode** attributes are not nullptr, attributes array is populated with attribute handles in the bundle.
//!
//! @param attributes The buffer to store handles of the attributes in this bundle.
//! @param attributeCount Size of attributes buffer. Must not be `nullptr` in both modes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getConstAttributes_abi(
ConstAttributeDataHandle* const attributes OMNI_ATTR("out, not_null, count=*attributeCount"),
size_t* const attributeCount OMNI_ATTR("in, out, not_null")) noexcept = 0;
//! @brief Search for read only handles of the attribute in this bundle by using attribute names.
//!
//! @param names The name of the attributes to be searched for.
//! @param nameCount Size of names buffer.
//! @param attributes The buffer to store handles of the attributes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getConstAttributesByName_abi(
NameToken const* const names OMNI_ATTR("in, not_null, count=nameCount"),
size_t nameCount,
ConstAttributeDataHandle* const attributes OMNI_ATTR("out, not_null, count=nameCount")) noexcept = 0;
//! @brief Get read only handles to all child bundles in this bundle.
//!
//! This method operates in two modes: **query mode** or **get mode**.
//!
//! **Query mode** is enabled when bundles is `nullptr`. When in this mode, *bundleCount
//! will be populated with the number of bundles in the bundle.
//!
//! **Get mode** is enabled when bundles is not `nullptr`. Upon entering the function, *bundleCount
//! stores the number of entries in bundles.
//! In **Get mode** bundles are not nullptr, bundles array is populated with bundle handles in the bundle.
//!
//! @param bundles The buffer to save child bundle handles.
//! @param bundleCount Size of the bundles buffer. Must not be `nullptr` in both modes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getConstChildBundles_abi(
ConstBundleHandle* const bundles OMNI_ATTR("out, not_null, count=*bundleCount"),
size_t* const bundleCount OMNI_ATTR("in, out, not_null")) noexcept = 0;
//! @brief Get read only handle to child bundle by index.
//!
//! @param bundleIndex Bundle index in range [0, childBundleCount).
//! @param bundle Handle under the index. If bundle index is out of range, then invalid handle is returned.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getConstChildBundle_abi(
size_t bundleIndex, ConstBundleHandle* const bundle OMNI_ATTR("out, not_null")) noexcept = 0;
//! @brief Lookup for read only handles to child bundles under specified names.
//!
//! For children that are not found invalid handles are returned.
//!
//! @param names The names of the child bundles in this bundle.
//! @param nameCount The number of child bundles to be searched.
//! @param foundBundles Output handles to the found bundles.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getConstChildBundlesByName_abi(
NameToken const* const names OMNI_ATTR("in, not_null, count=nameCount"),
size_t nameCount,
ConstBundleHandle* const foundBundles OMNI_ATTR("out, not_null, count=nameCount")) noexcept = 0;
//! @deprecated Metadata storage is deprecated and invalid handle is returned.
OMNI_ATTR("no_py")
virtual ConstBundleHandle getConstMetadataStorage_abi() noexcept = 0;
//! @brief Get the names and types of all bundle metadata fields in this bundle.
//!
//! This method operates in two modes: **query mode** or **get mode**.
//!
//! **Query mode** is enabled when fieldNames and fieldTypes are `nullptr`. When in this mode, *fieldCount
//! will be populated with the number of metadata fields in this bundle.
//!
//! **Get mode** is enabled when fieldNames or fieldTypes is not `nullptr`. Upon entering the function,
//! *fieldCount stores the number of entries in fieldNames and @p fieldTypes.
//!
//! In **Get mode** fieldNames are not `nullptr`, fieldNames array is populated with field names.
//! In **Get mode** fieldTypes are not `nullptr`, fieldTypes array is populated with field types.
//!
//! @param fieldNames Output field names in this bundle.
//! @param fieldTypes Output field types in this bundle.
//! @param fieldCount must not be `nullptr` in both modes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getBundleMetadataNamesAndTypes_abi(
NameToken* const fieldNames OMNI_ATTR("out, count=*fieldCount"),
Type* const fieldTypes OMNI_ATTR("out, count=*fieldCount"),
size_t* const fieldCount OMNI_ATTR("in, out, not_null")) noexcept = 0;
//! @brief Search for field handles in this bundle by using field names.
//!
//!@param fieldNames Name of bundle metadata fields to be searched for.
//!@param fieldCount Size of fieldNames and bundleMetadata arrays.
//!@param bundleMetadata Handle to metadata fields in this bundle.
//!@return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getConstBundleMetadataByName_abi(
NameToken const* const fieldNames OMNI_ATTR("in, count=fieldCount"),
size_t fieldCount,
ConstAttributeDataHandle* const bundleMetadata OMNI_ATTR("out, count=fieldCount")) noexcept = 0;
//! @brief Get the names and types of all attribute metadata fields in the attribute.
//!
//! This method operates in two modes: **query mode** or **get mode**.
//!
//! **Query mode** is enabled when fieldNames and @p fieldTypes are `nullptr`. When in this mode, *fieldCount
//! will be populated with the number of metadata fields in the attribute.
//!
//! **Get mode** is enabled when fieldNames or fieldTypes is not `nullptr`. Upon entering the function,
//! *fieldCount stores the number of entries in fieldNames and fieldTypes.
//!
//! In **Get mode** fieldNames are not `nullptr`, fieldNames array is populated with field names.
//! In **Get mode** fieldTypes are not `nullptr`, fieldTypes array is populated with field types.
//!
//! @param attribute Name of the attribute.
//! @param fieldNames Output field names in the attribute.
//! @param fieldTypes Output field types in the attribute.
//! @param fieldCount must not be `nullptr` in both modes.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getAttributeMetadataNamesAndTypes_abi(
NameToken attribute,
NameToken* const fieldNames OMNI_ATTR("out, count=*fieldCount"),
Type* const fieldTypes OMNI_ATTR("out, count=*fieldCount"),
size_t* const fieldCount OMNI_ATTR("in, out, not_null")) noexcept = 0;
//! @brief Search for read only field handles in the attribute by using field names.
//!
//! @param attribute The name of the attribute.
//! @param fieldNames The names of attribute metadata fields to be searched for.
//! @param fieldCount Size of fieldNames and attributeMetadata arrays.
//! @param attributeMetadata Handles to attribute metadata fields in the attribute.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
OMNI_ATTR("no_py")
virtual omni::core::Result getConstAttributeMetadataByName_abi(
NameToken attribute,
NameToken const* const fieldNames OMNI_ATTR("in, count=fieldCount"),
size_t fieldCount,
ConstAttributeDataHandle* const attributeMetadata OMNI_ATTR("out, count=fieldCount")) noexcept = 0;
};
} // namespace core
} // namespace graph
} // namespace omni
#include "IConstBundle2.gen.h"
//! @cond Doxygen_Suppress
//!
//! API part of the bundle factory interface
//! @copydoc omni::graph::core::IConstBundle2_abi
OMNI_DEFINE_INTERFACE_API(omni::graph::core::IConstBundle2)
//! @endcond
{
public:
//! Return number of attributes in this bundle.
size_t getAttributeCount() noexcept
{
size_t attributeCount = 0;
auto result = getConstAttributes_abi(nullptr, &attributeCount);
return OMNI_SUCCEEDED(result) ? attributeCount : 0;
}
//! Return number of child bundles in this bundle.
size_t getChildBundleCount() noexcept
{
size_t bundleCount = 0;
auto result = getConstChildBundles_abi(nullptr, &bundleCount);
return OMNI_SUCCEEDED(result) ? bundleCount : 0;
}
//! @brief Get the names of all attributes in this bundle.
//!
//! @param names Output array of attribute names. Size must be at least nameCount.
//! @param nameCount Length of names array.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result getAttributeNames(omni::graph::core::NameToken* const names, size_t nameCount) noexcept
{
return getAttributeNamesAndTypes_abi(names, nullptr, &nameCount);
}
//! @brief Get the types of all attributes in this bundle.
//!
//! @param types Output array of attribute types. Size must be at least typeCount.
//! @param typeCount Length of types array.
//! @return Success if executed successfully, Fail for unsuccessful execution, InvalidArgument if arguments are
//! invalid.
omni::core::Result getAttributeTypes(omni::graph::core::Type* const types, size_t typeCount) noexcept
{
return getAttributeNamesAndTypes_abi(nullptr, types, &typeCount);
}
//! @copydoc omni::graph::core::IConstBundle2_abi::getConstAttributes_abi
omni::core::Result getConstAttributes(
omni::graph::core::ConstAttributeDataHandle* const attributes, size_t attributeCount) noexcept
{
return getConstAttributes_abi(attributes, &attributeCount);
}
//! @brief Search for attribute handle in this bundle by using attribute name.
//!
//! @param name The name of the attribute to search for.
//! @return Valid attribute handle if attribute if found, invalid handle otherwise.
omni::graph::core::ConstAttributeDataHandle getConstAttributeByName(omni::graph::core::NameToken name) noexcept
{
using namespace omni::graph::core;
ConstAttributeDataHandle out{ ConstAttributeDataHandle::invalidValue() };
auto result = getConstAttributesByName_abi(&name, 1, &out);
return OMNI_SUCCEEDED(result) ? out : ConstAttributeDataHandle{ ConstAttributeDataHandle::invalidValue() };
}
//! @copydoc omni::graph::core::IConstBundle2_abi::getConstChildBundles_abi
omni::core::Result getConstChildBundles(omni::graph::core::ConstBundleHandle* const bundles, size_t bundleCount) noexcept
{
return getConstChildBundles_abi(bundles, &bundleCount);
}
//! @brief @copybrief omni::graph::core::IConstBundle2_abi::getConstChildBundle_abi
//!
//! @param bundleIndex Bundle index in range [0, childBundleCount).
//! @return Valid bundle handle if child bundle is found, invalid handle otherwise.
omni::graph::core::ConstBundleHandle getConstChildBundle(size_t bundleIndex) noexcept
{
using namespace omni::graph::core;
ConstBundleHandle out{ ConstBundleHandle::invalidValue() };
auto result = getConstChildBundle_abi(bundleIndex, &out);
return OMNI_SUCCEEDED(result) ? out : ConstBundleHandle{ ConstBundleHandle::invalidValue() };
}
//! @brief @copybrief omni::graph::core::IConstBundle2_abi::getConstChildBundlesByName_abi
//!
//! @param name The name of the child bundle.
//! @return Valid bundle handle if child bundle is found, invalid handle otherwise.
omni::graph::core::ConstBundleHandle getConstChildBundleByName(omni::graph::core::NameToken name) noexcept
{
using namespace omni::graph::core;
ConstBundleHandle out{ ConstBundleHandle::invalidValue() };
auto result = getConstChildBundlesByName_abi(&name, 1, &out);
return OMNI_SUCCEEDED(result) ? out : ConstBundleHandle{ ConstBundleHandle::invalidValue() };
}
//! Return number of metadata fields in this bundle.
size_t getBundleMetadataCount() noexcept
{
size_t bundleMetadataCount = 0;
auto result = getBundleMetadataNamesAndTypes_abi(nullptr, nullptr, &bundleMetadataCount);
return OMNI_SUCCEEDED(result) ? bundleMetadataCount : 0;
}
//! @copydoc omni::graph::core::IConstBundle2_abi::getBundleMetadataNamesAndTypes_abi
omni::core::Result getBundleMetadataNamesAndTypes(omni::graph::core::NameToken* const fieldNames,
omni::graph::core::Type* const fieldTypes, size_t fieldCount) noexcept
{
return getBundleMetadataNamesAndTypes_abi(fieldNames, fieldTypes, &fieldCount);
}
//! @copydoc omni::graph::core::IConstBundle2_abi::getConstBundleMetadataByName_abi
using omni::core::Generated<IConstBundle2_abi>::getConstBundleMetadataByName;
//! @brief @copybrief omni::graph::core::IConstBundle2_abi::getConstBundleMetadataByName_abi
//!
//! @param fieldName The name of the bundle metadata field.
//! @return Valid attribute handle if bundle metadata is found, invalid handle otherwise.
omni::graph::core::ConstAttributeDataHandle getConstBundleMetadataByName(omni::graph::core::NameToken fieldName) noexcept
{
using namespace omni::graph::core;
ConstAttributeDataHandle out{ ConstAttributeDataHandle::invalidValue() };
Result result = getConstBundleMetadataByName_abi(&fieldName, 1, &out);
return OMNI_SUCCEEDED(result) ? out : ConstAttributeDataHandle{ ConstAttributeDataHandle::invalidValue() };
}
//! @brief Return Number of metadata fields in the attribute.
//!
//! @param attribute The name of the attribute.
size_t getAttributeMetadataCount(omni::graph::core::NameToken attribute) noexcept
{
size_t attributeMetadataCount = 0;
auto result = getAttributeMetadataNamesAndTypes_abi(attribute, nullptr, nullptr, &attributeMetadataCount);
return OMNI_SUCCEEDED(result) ? attributeMetadataCount : 0;
}
//! @copydoc omni::graph::core::IConstBundle2_abi::getAttributeMetadataNamesAndTypes_abi
omni::core::Result getAttributeMetadataNamesAndTypes(
omni::graph::core::NameToken attribute, omni::graph::core::NameToken* const fieldNames,
omni::graph::core::Type* const fieldTypes, size_t fieldCount) noexcept
{
return getAttributeMetadataNamesAndTypes_abi(attribute, fieldNames, fieldTypes, &fieldCount);
}
//! @copydoc omni::graph::core::IConstBundle2_abi::getConstAttributeMetadataByName_abi
using omni::core::Generated<IConstBundle2_abi>::getConstAttributeMetadataByName;
//! @brief @copybrief omni::graph::core::IConstBundle2_abi::getConstAttributeMetadataByName_abi
//!
//! @param attribute The name of the attribute.
//! @param fieldName The name of the field.
//! @return Valid attribute handle if bundle metadata is found, invalid handle otherwise.
omni::graph::core::ConstAttributeDataHandle getConstAttributeMetadataByName(
omni::graph::core::NameToken attribute, omni::graph::core::NameToken fieldName) noexcept
{
using namespace omni::graph::core;
ConstAttributeDataHandle out{ ConstAttributeDataHandle::invalidValue() };
auto result = getConstAttributeMetadataByName_abi(attribute, &fieldName, 1, &out);
return OMNI_SUCCEEDED(result) ? out : ConstAttributeDataHandle{ ConstAttributeDataHandle::invalidValue() };
}
}; // IConstBundle2
| 20,465 | C | 49.285012 | 125 | 0.699243 |
omniverse-code/kit/include/omni/core/IObject.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Defines the base class for ABI-safe interfaces.
#pragma once
#include "Assert.h"
#include "Result.h"
#include "TypeId.h"
#include "OmniAttr.h"
#include <atomic>
#include <climits> // CHAR_BITS
#include <type_traits>
//! Main namespace for Omniverse.
namespace omni
{
//! Core functionality for Omniverse Interfaces.
namespace core
{
// we assume 8-bit chars
static_assert(CHAR_BIT == 8, "non-octet char is not supported");
class IObject_abi;
class IObject;
//! Base class for all @rstref{ABI-safe <abi-compatibility>} interfaces. Provides references counting and an ABI-safe
//! `dynamic_cast` like mechanism.
//!
//! When defining a new interface, use the @ref Inherits template.
//!
//! When implementing one or more interfaces use the @ref omni::core::Implements template.
//!
//! See @oni_overview to understand the overall design of Omniverse Native Interfaces.
//!
//! @thread_safety All methods in this interface are thread safe.
class OMNI_ATTR("no_py") IObject_abi
{
public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
//! Anonymous enum to store the type ID.
enum : TypeId
{
kTypeId = OMNI_TYPE_ID("omni.core.IObject") //!< Uniquely identifies the @ref IObject_abi interface.
};
#endif
protected:
//! Returns a pointer to the interface defined by the given type id if this object implements the type id's
//! interface.
//!
//! Objects can support multiple interfaces, even interfaces that are in different inheritance chains.
//!
//! The returned object will have @ref omni::core::IObject::acquire() called on it before it is returned, meaning it
//! is up to the caller to call @ref omni::core::IObject::release() on the returned pointer.
//!
//! The returned pointer can be safely `reinterpret_cast<>` to the type id's C++ class. For example,
//! "omni.windowing.IWindow" can be cast to `omni::windowing::IWindow`.
//!
//! Do not directly use this method, rather use a wrapper function like @ref omni::core::cast() or @ref
//! omni::core::ObjectPtr::as().
//!
//! @thread_safety This method is thread safe.
virtual void* cast_abi(TypeId id) noexcept = 0;
//! Increments the object's reference count.
//!
//! Objects may have multiple reference counts (e.g. one per interface implemented). As such, it is important that
//! you call @ref omni::core::IObject::release() on the same pointer from which you called @ref
//! omni::core::IObject::acquire().
//!
//! Do not directly use this method, rather use @ref omni::core::ObjectPtr, which will manage calling @ref
//! omni::core::IObject::acquire() and @ref omni::core::IObject::release() for you.
//!
//! @thread_safety This method is thread safe.
virtual void acquire_abi() noexcept = 0;
//! Decrements the objects reference count.
//!
//! Most implementations will destroy the object if the reference count reaches 0 (though this is not a
//! requirement).
//!
//! Objects may have multiple reference counts (e.g. one per interface implemented). As such, it is important that
//! you call @ref omni::core::IObject::release() on the same pointer from which you called @ref
//! omni::core::IObject::acquire().
//!
//! Do not directly use this method, rather use @ref omni::core::ObjectPtr, which will manage calling @ref
//! omni::core::IObject::acquire() and @ref omni::core::IObject::release() for you.
//!
//! @thread_safety This method is thread safe.
virtual void release_abi() noexcept = 0;
};
} // namespace core
} // namespace omni
//! By defining this macro before including a header generated by *omni.bind*, only the declaration of any generated
//! boiler-plate code is included.
//!
//! @see OMNI_BIND_INCLUDE_INTERFACE_IMPL
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include "IObject.gen.h"
namespace omni
{
namespace core
{
//! @copydoc omni::core::IObject_abi
class IObject : public omni::core::Generated<omni::core::IObject_abi>
{
};
//! Helper template for interface inheritance.
//!
//! Using this template defines compile time information used by @ref omni::core::Implements.
//!
//! Expected usage:
//!
//! @code{.cpp}
//!
//! class IMyInterface : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("IMyInterface")
//! { /* ... */ };
//!
//! @endcode
template <typename BASE, TypeId TYPEID>
class Inherits : public BASE
{
public:
#ifndef DOXYGEN_BUILD
//! Anonymous enum to store the type ID.
enum : TypeId
{
kTypeId = TYPEID //!< The unique interface type of this object.
};
using BaseType = BASE; //!< Useful for @ref omni::core::Implements.
#endif
};
#ifndef DOXYGEN_BUILD
namespace detail
{
//! Helper type used by @ref ObjectPtr.
class BorrowPtrType
{
public:
explicit BorrowPtrType() noexcept = default;
};
} // namespace detail
#endif
//! Used to create an @ref ObjectPtr that increments an objects reference count.
//!
//! @code{.cpp}
//!
//! IMyType* raw = /* ... */;
//! auto smart = ObjectPtr<IMyType>(myType, kBorrow);
//!
//! @endcode
//!
//! @ref ObjectPtr's rarely "borrow" raw pointers, rather they usually "steal" them (see @ref kSteal).
//!
//! See @ref omni::core::borrow().
constexpr detail::BorrowPtrType kBorrow{};
#ifndef DOXYGEN_BUILD
namespace detail
{
//! Helper type used by ObjectPtr.
class StealPtrType
{
public:
explicit StealPtrType() noexcept = default;
};
} // namespace detail
#endif
//! Used to create an @ref ObjectPtr that does not increments an objects reference count. The @ref ObjectPtr does
//! decrement the reference count of the raw pointer upon the @ref ObjectPtr's destruction.
//!
//! @code
//!
//! auto smart = ObjectPtr<IMyType>(createMyType, kSteal);
//!
//! @endcode
//!
//! Stealing a raw pointer is quite common when a function returns a raw interface pointer.
//!
//! See @ref omni::core::steal().
constexpr detail::StealPtrType kSteal{};
//! Smart pointer wrapper around interface pointers.
//!
//! This object manages the mundane detail of managing the given objects reference count.
//!
//! There is no implicit raw pointer to @ref ObjectPtr conversion. Such a conversion is ambiguous, as it is unclear if
//! the object's reference count should be immediately incremented. Rather, use @ref omni::core::steal() and @ref
//! omni::core::borrow() to create an @ref ObjectPtr.
//!
//! Use @ref get() to return the raw object pointer. The pointer will still be managed by this wrapper.
//!
//! Use @ref detach() to return and stop managing the raw pointer. When calling @ref detach(), @ref
//! omni::core::IObject::release() will not be called.
//!
//! Use @ref release() to decrement the raw pointer's reference count and stop managing the raw pointer.
//!
//! @rst
//!
//! .. warning::
//! ``ObjectPtr::release()`` does not have the same meaning as ``std::unique_ptr::release()``.
//! ``std::unique_ptr::release()`` is equivalent to ``ObjectPtr::detach()``.
//!
//! @endrst
//!
//! Use @ref as() to cast the pointer to another interface.
//!
//! Unless otherwise stated, the managed pointer can be `nullptr`.
//!
//! @thread_safety All methods are thread safe.
template <typename T>
class ObjectPtr
{
public:
//! Allow implicit conversion from `nullptr` to an @ref ObjectPtr.
constexpr ObjectPtr(std::nullptr_t = nullptr) noexcept
{
}
//! Start managing the given raw pointer. @ref omni::core::IObject::acquire() will be called on the pointer.
//!
//! Prefer using @ref omni::core::borrow() over this constructor.
ObjectPtr(T* other, detail::BorrowPtrType) noexcept : m_ptr(other)
{
addRef();
}
//! Start managing the given raw pointer. @ref omni::core::IObject::acquire() will *not* be called on the pointer.
//!
//! Prefer using @ref omni::core::steal() over this constructor.
constexpr ObjectPtr(T* other, detail::StealPtrType) noexcept : m_ptr(other)
{
}
//! Copy constructor.
ObjectPtr(const ObjectPtr& other) noexcept : m_ptr(other.m_ptr)
{
addRef();
}
//! Copy constructor.
template <typename U>
ObjectPtr(const ObjectPtr<U>& other) noexcept : m_ptr(other.m_ptr)
{
addRef();
}
//! Move constructor.
template <typename U>
ObjectPtr(ObjectPtr<U>&& other) noexcept : m_ptr(std::exchange(other.m_ptr, {}))
{
}
//! Destructor. Calls @ref release() on the managed pointer.
~ObjectPtr() noexcept
{
releaseRef();
}
//! Assignment operator.
ObjectPtr& operator=(const ObjectPtr& other) noexcept
{
copyRef(other.m_ptr);
return *this;
}
//! Move operator.
ObjectPtr& operator=(ObjectPtr&& other) noexcept
{
if (this != &other)
{
releaseRef();
m_ptr = std::exchange(other.m_ptr, {});
}
return *this;
}
//! Assignment operator.
template <typename U>
ObjectPtr& operator=(const ObjectPtr<U>& other) noexcept
{
copyRef(other.m_ptr);
return *this;
}
//! Move operator.
template <typename U>
ObjectPtr& operator=(ObjectPtr<U>&& other) noexcept
{
releaseRef();
m_ptr = std::exchange(other.m_ptr, {});
return *this;
}
//! Returns true if the managed pointer is not `nullptr`.
explicit operator bool() const noexcept
{
return m_ptr != nullptr;
}
//! The managed pointer must not be `nullptr`.
T* operator->() const noexcept
{
return m_ptr;
}
//! The managed pointer must not be `nullptr`.
T& operator*() const noexcept
{
return *m_ptr;
}
//! Returns the raw pointer. The pointer is still managed by this wrapper.
//!
//! This method is useful when having to pass raw pointers to ABI functions.
T* get() const noexcept
{
return m_ptr;
}
//! Returns a pointer to the managed pointer (which must be `nullptr`).
//!
//! The managed pointer must be `nullptr`, otherwise the function results in undefined behavior.
//!
//! Useful when having to manage pointers output via a function argument list.
//!
//! @code{.cpp}
//!
//! void createMyType(MyType** out);
//!
//! // ...
//!
//! ObjectPtr<MyType> ptr;
//! createMyType(ptr.put());
//!
//! @endcode
//!
//! Such methods are rare.
T** put() noexcept
{
OMNI_ASSERT(m_ptr == nullptr);
return &m_ptr;
}
//! Manage the given pointer. @ref omni::core::IObject::acquire() is not called on the pointer.
//!
//! See @ref borrow() for a method that does call @ref omni::core::IObject::acquire().
void steal(T* value) noexcept
{
releaseRef();
*put() = value;
}
//! Returns the managed pointer and no longer manages the pointer.
//!
//! @ref omni::core::IObject::release() is *not* called on the pointer. Use this method to stop managing the
//! pointer.
T* detach() noexcept
{
return std::exchange(m_ptr, {});
}
//! Manage the given pointer. @ref omni::core::IObject::acquire() is called on the pointer.
//!
//! See @ref steal() for a method that does not call @ref omni::core::IObject::acquire().
void borrow(T* value) noexcept
{
releaseRef();
*put() = value;
addRef();
}
//! Cast the managed pointer to a new interface type (@p To).
//!
//! `nullptr` is returned if the pointer does not implement the interface.
template <typename To>
ObjectPtr<To> as() const noexcept
{
if (!m_ptr)
{
return nullptr; // dynamic_cast allows a nullptr, so we do as well
}
else
{
return ObjectPtr<To>(reinterpret_cast<To*>(m_ptr->cast(To::kTypeId)), kSteal);
}
}
//! Cast the managed pointer to the type of the given @ref omni::core::ObjectPtr (e.g. @p To).
//!
//! `nullptr` is written to @p to if the pointer does not implement the interface.
template <typename To>
void as(ObjectPtr<To>& to) const noexcept
{
if (!m_ptr)
{
to.steal(nullptr); // dynamic_cast allows a nullptr, so we do as well
}
else
{
to.steal(reinterpret_cast<To*>(m_ptr->cast(To::kTypeId)));
}
}
//! Calls @ref release() on the managed pointer and sets the internal pointer to `nullptr`.
//!
//! @rst
//!
//! .. warning::
//! ``ObjectPtr::release()`` does not have the same meaning as ``std::unique_ptr::release()``.
//! ``std::unique_ptr::release()`` is equivalent to ``ObjectPtr::detach()``.
//!
//! @endrst
void release() noexcept
{
releaseRef();
}
//! Calls @ref release() on the managed pointer and sets the internal pointer to @p value
//!
//! Equivalent to `std::unique_ptr::reset()`.
//!
//! @param value The new value to assign to `*this`, defaults to `nullptr`.
void reset(T* value = nullptr) noexcept
{
if (value)
{
const_cast<std::remove_const_t<T>*>(value)->acquire();
}
T* oldval = std::exchange(m_ptr, value);
if (oldval)
{
oldval->release();
}
}
private:
void copyRef(T* other) noexcept
{
if (m_ptr != other)
{
releaseRef();
m_ptr = other;
addRef();
}
}
void addRef() const noexcept
{
if (m_ptr)
{
const_cast<std::remove_const_t<T>*>(m_ptr)->acquire();
}
}
void releaseRef() noexcept
{
if (m_ptr)
{
std::exchange(m_ptr, {})->release();
}
}
template <typename U>
friend class ObjectPtr;
T* m_ptr{};
};
// Breathe/Sphinx is unable to handle these overloads and produces warnings. Since we don't like warnings, remove these
// overloads from the docs until Breathe/Sphinx is updated.
#ifndef DOXYGEN_SHOULD_SKIP_THIS
//! @ref ObjectPtr less than operator.
template <typename T>
inline bool operator<(const ObjectPtr<T>& left, const ObjectPtr<T>& right) noexcept
{
return (left.get() < right.get());
}
//! @ref ObjectPtr equality operator.
template <typename T>
inline bool operator==(const ObjectPtr<T>& left, const ObjectPtr<T>& right) noexcept
{
return (left.get() == right.get());
}
//! @ref ObjectPtr equality operator (with raw pointer).
template <typename T>
inline bool operator==(const ObjectPtr<T>& left, const T* right) noexcept
{
return (left.get() == right);
}
//! @ref ObjectPtr equality operator (with raw pointer).
template <typename T>
inline bool operator==(const T* left, const ObjectPtr<T>& right) noexcept
{
return (left == right.get());
}
//! @ref ObjectPtr equality operator (with nullptr).
template <typename T>
inline bool operator==(const ObjectPtr<T>& left, std::nullptr_t) noexcept
{
return (left.get() == nullptr);
}
//! @ref ObjectPtr equality operator (with nullptr).
template <typename T>
inline bool operator==(std::nullptr_t, const ObjectPtr<T>& right) noexcept
{
return (right.get() == nullptr);
}
//! @ref ObjectPtr inequality operator.
template <typename T>
inline bool operator!=(const ObjectPtr<T>& left, const ObjectPtr<T>& right) noexcept
{
return (left.get() != right.get());
}
//! @ref ObjectPtr inequality operator (with raw pointer).
template <typename T>
inline bool operator!=(const ObjectPtr<T>& left, const T* right) noexcept
{
return (left.get() != right);
}
//! @ref ObjectPtr inequality operator (with raw pointer).
template <typename T>
inline bool operator!=(const T* left, const ObjectPtr<T>& right) noexcept
{
return (left != right.get());
}
//! @ref ObjectPtr inequality operator (with nullptr).
template <typename T>
inline bool operator!=(const ObjectPtr<T>& left, std::nullptr_t) noexcept
{
return (left.get() != nullptr);
}
//! @ref ObjectPtr inequality operator (with nullptr).
template <typename T>
inline bool operator!=(std::nullptr_t, const ObjectPtr<T>& right) noexcept
{
return (right.get() != nullptr);
}
#endif // DOXYGEN_SHOULD_SKIP_THIS
//! Returns an @ref ObjectPtr managing the given pointer. @ref omni::core::IObject::acquire() is **not** called on the
//! pointer.
//!
//! `nullptr` is accepted.
template <typename T>
inline ObjectPtr<T> steal(T* ptr) noexcept
{
return ObjectPtr<T>(ptr, kSteal);
}
//! Returns an @ref ObjectPtr managing the given pointer. @ref omni::core::IObject::acquire() is called on the
//! pointer.
//!
//! `nullptr` is accepted.
template <typename T>
inline ObjectPtr<T> borrow(T* ptr) noexcept
{
return ObjectPtr<T>(ptr, kBorrow);
}
//! Casts the given pointer to the given interface (e.g. T).
//!
//! `nullptr` is accepted.
//!
//! @returns A valid pointer is returned if the given pointer implements the given interface. Otherwise, `nullptr` is
//! returned.
template <typename T, typename U>
inline ObjectPtr<T> cast(U* ptr) noexcept
{
static_assert(std::is_base_of<IObject, T>::value, "cast can only be used with classes that derive from IObject");
if (ptr)
{
return ObjectPtr<T>{ reinterpret_cast<T*>(ptr->cast(T::kTypeId)), kSteal };
}
else
{
return { nullptr };
}
}
#ifndef DOXYGEN_BUILD
namespace detail
{
template <typename T>
inline void* cast(T* obj, TypeId id) noexcept; // forward declaration
} // namespace detail
#endif
//! Helper template for implementing the cast function for one or more interfaces.
//!
//! Implementations of interfaces (usually hidden in <i>.cpp</i> files) are well served to use this template.
//!
//! This template provides the following useful feature:
//!
//! - It provides a @ref omni::core::IObject_abi::cast_abi() implementation that supports multiple inheritance.
//!
//! Using @ref omni::core::ImplementsCast is recommended in cases where you want the default implementation
//! of the cast function, but want to override the behavior of @ref omni::core::IObject_abi::acquire_abi() and @ref
//! omni::core::IObject_abi::release_abi(). If the default implementation of cast, acquire, and release functions is
//! desired, then using @ref Implements is recommended.
//!
//! A possible usage implementing your own acquire/release semantics:
//!
//! @code{.cpp}
//!
//! class MyIFooAndIBarImpl : public omni::core::ImplementsCast<IFoo, IBar>
//! {
//! public:
//! //! See @ref omni::core::IObject::acquire.
//! inline void acquire() noexcept
//! {
//! // note: this implementation is needed to disambiguate which `cast` to call when using multiple
//! // inheritance. it has zero-overhead.
//! static_cast<IFoo*>(this)->acquire();
//! }
//!
//! //! See @ref omni::core::IObject::release.
//! inline void release() noexcept
//! {
//! // note: this implementation is needed to disambiguate which `cast` to call when using multiple
//! // inheritance. it has zero-overhead.
//! static_cast<IFoo*>(this)->release();
//! }
//! protected:
//! std::atomic<uint32_t> m_refCount{ 1 }; //!< Reference count.
//!
//! //! @copydoc IObject_abi::acquire_abi
//! virtual void acquire_abi() noexcept override
//! {
//! uint32_t count = m_refCount.fetch_add(1, std::memory_order_relaxed) + 1;
//! CARB_LOG_INFO("Increased count to %u", count);
//! }
//!
//! //! @copydoc IObject_abi::release_abi
//! virtual void release_abi() noexcept override
//! {
//! uint32_t count = m_refCount.fetch_sub(1, std::memory_order_release) - 1;
//! CARB_LOG_INFO("Reduced count to %u", count);
//! if (0 == count)
//! {
//! std::atomic_thread_fence(std::memory_order_acquire);
//! delete this;
//! }
//! }
//!
//! /* ... */
//! };
//!
//! @endcode
template <typename T, typename... Rest>
struct ImplementsCast : public T, public Rest...
{
public:
//! See @ref omni::core::IObject::cast.
inline void* cast(omni::core::TypeId id) noexcept
{
// note: this implementation is needed to disambiguate which `cast` to call when using multiple inheritance. it
// has zero-overhead.
return static_cast<T*>(this)->cast(id);
}
private:
// given a type id, castImpl() check if the type id matches T's typeid. if not, T's parent class type id is
// checked. if T's parent class type id does not match, the grandparent class's type id is check. this continues
// until IObject's type id is checked.
//
// if no type id in T's inheritance chain match, the next interface in Rest is checked.
//
// it's expected the compiler can optimize away the recursion
template <typename U, typename... Args>
inline void* castImpl(TypeId id) noexcept
{
// detail::cast will march down the inheritance chain
void* obj = omni::core::detail::cast<U>(this, id);
if (nullptr == obj)
{
// check the next class (inheritance chain) provide in the inheritance list
return castImpl<Args...>(id);
}
return obj;
}
// this terminates walking across the types in the variadic template
template <int = 0>
inline void* castImpl(TypeId) noexcept
{
return nullptr;
}
protected:
virtual ~ImplementsCast() noexcept = default;
//! @copydoc omni::core::IObject_abi::cast_abi
virtual void* cast_abi(TypeId id) noexcept override
{
return castImpl<T, Rest...>(id);
}
};
//! Helper template for implementing one or more interfaces.
//!
//! Implementations of interfaces (usually hidden in <i>.cpp</i> files) are well served to use this template.
//!
//! This template provides two useful features:
//!
//! - It provides a reference count and reasonable implementations of @ref omni::core::IObject_abi::acquire_abi() and
//! @ref omni::core::IObject_abi::release_abi().
//!
//! - It provides a @ref omni::core::IObject_abi::cast_abi() implementation that supports multiple inheritance.
//!
//! Using @ref omni::core::Implements is recommended in most cases when implementing one or more interfaces.
//!
//! Expected usage:
//!
//! @code{.cpp}
//!
//! class MyIFooAndIBarImpl : public omni::core::Implements<IFoo, IBar>
//! { /* ... */ };
//!
//! @endcode
template <typename T, typename... Rest>
struct Implements : public ImplementsCast<T, Rest...>
{
public:
//! See @ref omni::core::IObject::acquire.
inline void acquire() noexcept
{
// note: this implementation is needed to disambiguate which `cast` to call when using multiple inheritance. it
// has zero-overhead.
static_cast<T*>(this)->acquire();
}
//! See @ref omni::core::IObject::release.
inline void release() noexcept
{
// note: this implementation is needed to disambiguate which `cast` to call when using multiple inheritance. it
// has zero-overhead.
static_cast<T*>(this)->release();
}
protected:
std::atomic<uint32_t> m_refCount{ 1 }; //!< Reference count.
virtual ~Implements() noexcept = default;
//! @copydoc omni::core::IObject_abi::acquire_abi
virtual void acquire_abi() noexcept override
{
m_refCount.fetch_add(1, std::memory_order_relaxed);
}
//! @copydoc omni::core::IObject_abi::release_abi
virtual void release_abi() noexcept override
{
if (0 == m_refCount.fetch_sub(1, std::memory_order_release) - 1)
{
std::atomic_thread_fence(std::memory_order_acquire);
delete this;
}
}
};
#ifndef DOXYGEN_BUILD
namespace detail
{
//! Given a type, this function walks the inheritance chain for the type, checking if the id of the type matches the
//! given id.
//!
//! Implementation detail. Do not call.
template <typename T>
inline void* cast(T* obj, TypeId id) noexcept
{
if (T::kTypeId == id)
{
obj->acquire(); // match! since we return an interface pointer, acquire() must be called.
return obj;
}
else
{
return cast<typename T::BaseType>(obj, id); // call cast again, but with the parent type
}
}
//! Specialization of `cast<T>(T*, TypeId)` for @ref omni::core::IObject. @ref omni::core::IObject always terminates the
//! recursive template since it does not have a base class.
//!
//! Implementation detail. Do not call.
template <>
inline void* cast<IObject>(IObject* obj, TypeId id) noexcept
{
if (IObject::kTypeId == id)
{
obj->acquire();
return obj;
}
else
{
return nullptr;
}
}
} // namespace detail
#endif
} // namespace core
} // namespace omni
//! By defining this macro before including a header generated by *omni.bind*, only the implementations of any
//! generated boiler-plate code is included.
//!
//! @see OMNI_BIND_INCLUDE_INTERFACE_DECL
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include "IObject.gen.h"
| 25,585 | C | 29.101176 | 120 | 0.634747 |
omniverse-code/kit/include/omni/core/TypeId.h | // 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.
//
//! @file
//! @brief Helper functions and macros for generating type identifiers.
#pragma once
#include "../../carb/Defines.h"
#include <cstdint>
namespace omni
{
namespace core
{
//! Base type for an interface type identifier.
using TypeId = uint64_t;
//! Returns the type id of the given type name at compile time.
//!
//! See omni::core::typeId() for a version of this macro that is evaluated at runtime.
#define OMNI_TYPE_ID(str_) CARB_HASH_STRING(str_)
//! Returns the type id of the given type name at run time.
//!
//! If possible, use OMNI_TYPE_ID(), which is evaluated at compile time.
inline TypeId typeId(const char* str)
{
// currently, the user must choose between calling typeId() or OMNI_TYPE_ID() to map a string to an id. the user's
// decision should be based on if the input string is known at compile time or not.
//
// we should be able to have a single constexpr function, typeId(), that will determine if the input string is
// constant or not. the compiler would then be able to evaluate the string correctly at compile time or runtime.
// this would make the user's life easier.
//
// unfortunately, MSVC incorrectly warns when it detects that an unsigned expression will overflow in a constexpr.
// overflowing an unsigned value is well-defined and actually by design in our hashing algorithm.
//
// disabling this warning is even more of a pain, as MSVC doesn't allow you to disable the warning at the
// overflowing expression. rather, you must disable the warning at each call site of the constexpr.
//
// this bug is fixed in late 2019. since customers may be on older compilers, we're stuck with this workaround.
//
// https://developercommunity.visualstudio.com/content/problem/211134/unsigned-integer-overflows-in-constexpr-functionsa.html
// https://stackoverflow.com/questions/57342279/how-can-i-suppress-constexpr-warnings-in-msvc
return carb::hashString(str);
}
} // namespace core
} // namespace omni
| 2,461 | C | 42.192982 | 129 | 0.735067 |
omniverse-code/kit/include/omni/core/Api.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Helper macros to provide API calling convention tags.
#pragma once
#include "Platform.h"
#ifdef __cplusplus
//! Declares a "C" exported external symbol. This uses the "C" name decoration style of
//! adding an underscore to the start of the exported name.
# define OMNI_EXTERN_C extern "C"
#else
//! Declares a "C" exported external symbol. This uses the "C" name decoration style of
//! adding an underscore to the start of the exported name.
# define OMNI_EXTERN_C
#endif
//! \copydoc CARB_EXPORT
#define OMNI_EXPORT CARB_EXPORT
// Functions that wish to be exported from a .dll/.so should be decorated with OMNI_API.
//
// Functions related to modules, such omniGetModuleExports(), should be decorated with OMNI_MODULE_API.
#ifdef OMNI_COMPILE_AS_DYNAMIC_LIBRARY
# if OMNI_PLATFORM_WINDOWS
//! Declares a symbol that is marked as externally exported. The symbol will be exported
//! with C decorations. On Windows, this is expected to be exported from the containing DLL.
//! On Linux, this is exported as having default visibility from the module instead of being
//! hidden. This export tag should only be used when tagging exported symbols from within
//! omni.core itself. Exported symbols in other modules (such as `omniGetModuleExports()`
//! functions in implementation libraries) should use @ref OMNI_MODULE_API instead.
# define OMNI_API OMNI_EXTERN_C __declspec(dllexport)
# elif OMNI_PLATFORM_LINUX || OMNI_PLATFORM_MACOS
//! Declares a symbol that is marked as externally exported. The symbol will be exported
//! with C decorations. On Windows, this is expected to be exported from the containing DLL.
//! On Linux, this is exported as having default visibility from the module instead of being
//! hidden. This export tag should only be used when tagging exported symbols from within
//! omni.core itself. Exported symbols in other modules (such as `omniGetModuleExports()`
//! functions in implementation libraries) should use @ref OMNI_MODULE_API instead.
# define OMNI_API OMNI_EXTERN_C __attribute__((visibility("default")))
# endif
#else
//! Declares a symbol that is marked as externally exported. The symbol will be exported
//! with C decorations. On Windows, this is expected to be exported from the containing DLL.
//! On Linux, this is exported as having default visibility from the module instead of being
//! hidden. This export tag should only be used when tagging exported symbols from within
//! omni.core itself. Exported symbols in other modules (such as `omniGetModuleExports()`
//! functions in implementation libraries) should use @ref OMNI_MODULE_API instead.
# define OMNI_API OMNI_EXTERN_C
#endif
// Functions related to modules should be decorated with OMNI_MODULE_API. Currently, only omniGetModuleExports()
// qualifies.
#ifdef OMNI_COMPILE_AS_MODULE
# ifdef OMNI_COMPILE_AS_DYNAMIC_LIBRARY
# error "OMNI_COMPILE_AS_DYNAMIC_LIBRARY and OMNI_COMPILE_AS_MODULE cannot be both defined"
# endif
# if OMNI_PLATFORM_WINDOWS
//! Declares a function that is marked as externally exported. The symbol will be exported
//! with C decorations. On Windows, this is expected to be exported from the containing DLL.
//! On Linux, this is exported as having default visibility from the module instead of being
//! hidden. This is intended for exported symbols in implementation libraries.
# define OMNI_MODULE_API OMNI_EXTERN_C __declspec(dllexport)
# elif OMNI_PLATFORM_LINUX || OMNI_PLATFORM_MACOS
//! Declares a function that is marked as externally exported. The symbol will be exported
//! with C decorations. On Windows, this is expected to be exported from the containing DLL.
//! On Linux, this is exported as having default visibility from the module instead of being
//! hidden. This is intended for exported symbols in implementation libraries.
# define OMNI_MODULE_API OMNI_EXTERN_C __attribute__((visibility("default")))
# else
CARB_UNSUPPORTED_PLATFORM();
# endif
#else
//! Declares a function that is marked as externally exported. The symbol will be exported
//! with C decorations. On Windows, this is expected to be exported from the containing DLL.
//! On Linux, this is exported as having default visibility from the module instead of being
//! hidden. This is intended for exported symbols in implementation libraries.
# define OMNI_MODULE_API OMNI_EXTERN_C
#endif
| 4,877 | C | 55.068965 | 112 | 0.757023 |
omniverse-code/kit/include/omni/core/Types.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Common data structs and types.
#pragma once
#include "OmniAttr.h"
#include "../../carb/Types.h"
#ifndef DOXYGEN_SHOULD_SKIP_THIS
CARB_IGNOREWARNING_MSC_WITH_PUSH(4201) // nonstandard extension used: nameless struct/union
#endif
namespace omni
{
namespace core
{
/** Helper struct to represent a single 2-space vector of unsigned integers. Each member
* of the struct can be accessed in multiple ways including an array and direct accessors
* known by multiple names. Objects of this struct are guaranteed to be only as large as
* two 32-bit unsigned integers.
*/
union OMNI_ATTR("vec") UInt2
{
/** Access to the value members in this object as an array. */
OMNI_ATTR("no_py") uint32_t data[2]; // must be first for proper { } initialization
/** Structure of unions containing the possible names of the first and second values
* in this object.
*/
struct
{
/** Names for the first data member in this object. This can be used to access
* the value treating it as a Cartesian coordinate (`x`), texture coordinate
* (`u`, `s`), or a dimensional size (`w`). These are all just different names
* for the same value that can be used to help with the semantics of an access.
*/
union
{
/** Provides access to the first data member as a Cartesian X coordinate. */
OMNI_ATTR("init_arg") uint32_t x;
uint32_t u; ///< Provides access to the first data member as a U texture coordinate.
uint32_t s; ///< Provides access to the first data member as an S texture coordinate.
uint32_t w; ///< Provides access to the first data member as a width value.
};
/** Names for the second data member in this object. This can be used to access
* the value treating it as a Cartesian coordinate (`y`), texture coordinate
* (`v`, `t`), or a dimensional size (`h`). These are all just different names
* for the same value that can be used to help with the semantics of an access.
*/
union
{
/** Provides access to the first data member as a Cartesian Y coordinate. */
OMNI_ATTR("init_arg") uint32_t y;
uint32_t v; ///< Provides access to the first data member as a V texture coordinate.
uint32_t t; ///< Provides access to the first data member as an T texture coordinate.
uint32_t h; ///< Provides access to the first data member as a height value.
};
};
};
static_assert(sizeof(UInt2) == (sizeof(uint32_t) * 2), "unexpected UInt2 size");
/** Helper struct to represent a single 2-space vector of signed integers. Each member of
* the struct can be accessed in multiple ways including an array and direct accessors known
* by multiple names. Objects of this struct are guaranteed to be only as large as two
* 32-bit signed integers.
*/
union OMNI_ATTR("vec") Int2
{
/** Access to the value members in this object as an array. */
OMNI_ATTR("no_py") int32_t data[2]; // must be first for proper { } initialization
/** Structure of unions containing the possible names of the first and second values
* in this object.
*/
struct
{
/** Names for the first data member in this object. This can be used to access
* the value treating it as a Cartesian coordinate (`x`), texture coordinate
* (`u`, `s`), or a dimensional size (`w`). These are all just different names
* for the same value that can be used to help with the semantics of an access.
*/
union
{
/** Provides access to the first data member as a Cartesian X coordinate. */
OMNI_ATTR("init_arg") int32_t x;
int32_t u; ///< Provides access to the first data member as a U texture coordinate.
int32_t s; ///< Provides access to the first data member as an S texture coordinate.
int32_t w; ///< Provides access to the first data member as a width value.
};
/** Names for the second data member in this object. This can be used to access
* the value treating it as a Cartesian coordinate (`y`), texture coordinate
* (`v`, `t`), or a dimensional size (`h`). These are all just different names
* for the same value that can be used to help with the semantics of an access.
*/
union
{
/** Provides access to the first data member as a Cartesian Y coordinate. */
OMNI_ATTR("init_arg") int32_t y;
int32_t v; ///< Provides access to the first data member as a V texture coordinate.
int32_t t; ///< Provides access to the first data member as an T texture coordinate.
int32_t h; ///< Provides access to the first data member as a height value.
};
};
};
static_assert(sizeof(Int2) == (sizeof(int32_t) * 2), "unexpected Int2 size");
/** Helper struct to represent a single 2-space vector of floating point values. Each member of
* the struct can be accessed in multiple ways including an array and direct accessors known
* by multiple names. Objects of this struct are guaranteed to be only as large as two
* 32-bit floating point values.
*/
union OMNI_ATTR("vec") Float2
{
/** Access to the value members in this object as an array. */
OMNI_ATTR("no_py") float data[2]; // must be first for proper { } initialization
/** Structure of unions containing the possible names of the first and second values
* in this object.
*/
struct
{
/** Names for the first data member in this object. This can be used to access
* the value treating it as a Cartesian coordinate (`x`), texture coordinate
* (`u`, `s`), or a dimensional size (`w`). These are all just different names
* for the same value that can be used to help with the semantics of an access.
*/
union
{
/** Provides access to the first data member as a Cartesian X coordinate. */
OMNI_ATTR("init_arg") float x;
float u; ///< Provides access to the first data member as a U texture coordinate.
float s; ///< Provides access to the first data member as an S texture coordinate.
float w; ///< Provides access to the first data member as a width value.
};
/** Names for the second data member in this object. This can be used to access
* the value treating it as a Cartesian coordinate (`y`), texture coordinate
* (`v`, `t`), or a dimensional size (`h`). These are all just different names
* for the same value that can be used to help with the semantics of an access.
*/
union
{
/** Provides access to the first data member as a Cartesian Y coordinate. */
OMNI_ATTR("init_arg") float y;
float v; ///< Provides access to the first data member as a V texture coordinate.
float t; ///< Provides access to the first data member as an T texture coordinate.
float h; ///< Provides access to the first data member as a height value.
};
};
};
static_assert(sizeof(Float2) == (sizeof(float) * 2), "unexpected Float2 size");
} // namespace core
} // namespace omni
#ifndef DOXYGEN_SHOULD_SKIP_THIS
CARB_IGNOREWARNING_MSC_POP
#endif
#include "Types.gen.h"
| 7,917 | C | 44.505747 | 97 | 0.644057 |
omniverse-code/kit/include/omni/core/IObject.gen.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/OmniAttr.h>
#include <omni/core/Interface.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <utility>
#include <type_traits>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Base class for all @rstref{ABI-safe <abi-compatibility>} interfaces. Provides references counting and an ABI-safe
//! `dynamic_cast` like mechanism.
//!
//! When defining a new interface, use the @ref Inherits template.
//!
//! When implementing one or more interfaces use the @ref omni::core::Implements template.
//!
//! See @oni_overview to understand the overall design of Omniverse Native Interfaces.
//!
//! @thread_safety All methods in this interface are thread safe.
template <>
class omni::core::Generated<omni::core::IObject_abi> : public omni::core::IObject_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::core::IObject")
//! Returns a pointer to the interface defined by the given type id if this object implements the type id's
//! interface.
//!
//! Objects can support multiple interfaces, even interfaces that are in different inheritance chains.
//!
//! The returned object will have @ref omni::core::IObject::acquire() called on it before it is returned, meaning it
//! is up to the caller to call @ref omni::core::IObject::release() on the returned pointer.
//!
//! The returned pointer can be safely `reinterpret_cast<>` to the type id's C++ class. For example,
//! "omni.windowing.IWindow" can be cast to `omni::windowing::IWindow`.
//!
//! Do not directly use this method, rather use a wrapper function like @ref omni::core::cast() or @ref
//! omni::core::ObjectPtr::as().
//!
//! @thread_safety This method is thread safe.
void* cast(omni::core::TypeId id) noexcept;
//! Increments the object's reference count.
//!
//! Objects may have multiple reference counts (e.g. one per interface implemented). As such, it is important that
//! you call @ref omni::core::IObject::release() on the same pointer from which you called @ref
//! omni::core::IObject::acquire().
//!
//! Do not directly use this method, rather use @ref omni::core::ObjectPtr, which will manage calling @ref
//! omni::core::IObject::acquire() and @ref omni::core::IObject::release() for you.
//!
//! @thread_safety This method is thread safe.
void acquire() noexcept;
//! Decrements the objects reference count.
//!
//! Most implementations will destroy the object if the reference count reaches 0 (though this is not a
//! requirement).
//!
//! Objects may have multiple reference counts (e.g. one per interface implemented). As such, it is important that
//! you call @ref omni::core::IObject::release() on the same pointer from which you called @ref
//! omni::core::IObject::acquire().
//!
//! Do not directly use this method, rather use @ref omni::core::ObjectPtr, which will manage calling @ref
//! omni::core::IObject::acquire() and @ref omni::core::IObject::release() for you.
//!
//! @thread_safety This method is thread safe.
void release() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline void* omni::core::Generated<omni::core::IObject_abi>::cast(omni::core::TypeId id) noexcept
{
return cast_abi(id);
}
inline void omni::core::Generated<omni::core::IObject_abi>::acquire() noexcept
{
acquire_abi();
}
inline void omni::core::Generated<omni::core::IObject_abi>::release() noexcept
{
release_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 4,194 | C | 36.792792 | 120 | 0.691941 |
omniverse-code/kit/include/omni/core/ReplaceCarbAssert.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
// NOTE: This comment is left for historical purposes, but is no longer accurate. The `g_carbAssert` global variable is
// weakly-linked now, so it no longer requires linking against carb.dll.
#if 0
// Include this file (near the top of your includes list) when compiling a DLL which does not depend on any Carbonite
// interfaces.
//
// This file solves the following problem: some inline code in carb::extras uses CARB_ASSERT, which causes a dependency
// on g_carbAssert. When compiling code as a DLL for implicit linking (i.e. not a module/plugin), the linker will not
// be able to find g_carbAssert. The DLL can define g_carbAssert, but no one is likely to set it to a valid value. The
// result is a crash.
//
// This file redefines the CARB_ASSERT macros to the OMNI_ASSERT macros. The OMNI_ASSERT macros do not depend on global
// variables.
# define CARB_ASSERT OMNI_ASSERT
# define CARB_ASSERT_ENABLED OMNI_ASSERT_ENABLED
# define CARB_CHECK OMNI_CHECK
# define CARB_CHECK_ENABLED OMNI_CHECK_ENABLED
# define CARB_FATAL_UNLESS OMNI_FATAL_UNLESS
#endif
#include "../../carb/Defines.h"
#include "Assert.h"
| 1,589 | C | 44.42857 | 120 | 0.758339 |
omniverse-code/kit/include/omni/core/OmniInit.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Core header for starting the Omniverse core.
#pragma once
#include "Omni.h"
#include "../../carb/ClientUtils.h"
#include "../../carb/StartupUtils.h"
//! Initializes the omni library along with Carbonite. Ensures that both libraries will be cleaned up upon exit.
//!
//! This macro should be used in `main()`. It creates some objects which will release the framework when they go out of
//! scope.
//!
//! Use this macro in conjunction with @ref OMNI_APP_GLOBALS().
//!
//! For startup, this function calls \ref carb::acquireFrameworkAndRegisterBuiltins() and \ref carb::startupFramework().
//! At a high level, these functions:
//!
//! - Determines application path from CLI args and env vars (see @ref carb::extras::getAppPathAndName()).
//! - Sets application path as filesystem root.
//! - Loads plugins for settings: *carb.settings.plugin*, *carb.dictionary.plugin*, *carb.tokens.plugins* and any
//! serializer plugin.
//! - Searches for config file, loads it and applies CLI args overrides.
//! - Configures logging with config file.
//! - Loads plugins according to config file.
//! - Configures default plugins according to config file.
//! - Starts the default profiler (if loaded).
//!
//! @param ... May be either \a empty (default initialization), `argc, argv` (command-line arguments), or a const-
//! reference to a \ref carb::StartupFrameworkDesc.
#define OMNI_CORE_INIT(...) \
omni::core::ScopedOmniCore scopedOmniverse_; \
omni::core::ScopedFrameworkStartup scopedFrameworkStartup_{ __VA_ARGS__ };
namespace omni
{
namespace core
{
//! Scoped object which calls @ref OMNI_CORE_START() and @ref OMNI_CORE_STOP().
//!
//! Rather than directly using this object, use @ref OMNI_CORE_INIT().
struct ScopedOmniCore
{
//! Starts the Carbonite @ref carb::Framework and calls @ref omniCoreStart.
ScopedOmniCore(const OmniCoreStartArgs* args = nullptr)
{
if (!carb::getFramework())
{
carb::acquireFrameworkAndRegisterBuiltins(args);
}
}
//! Calls @ref omniCoreStop and tears down the Carbonite @ref carb::Framework.
~ScopedOmniCore()
{
carb::releaseFrameworkAndDeregisterBuiltins();
}
private:
CARB_PREVENT_COPY_AND_MOVE(ScopedOmniCore);
};
//! Scoped object which calls @ref carb::startupFramework() and @ref carb::shutdownFramework().
//!
//! Rather than directly using this object, use @ref OMNI_CORE_INIT().
struct ScopedFrameworkStartup
{
//! Default constructor which does not startup the framework due to a lack of arguments.
//!
//! This constructor is present to make @ref OMNI_CORE_INIT() useful when the application wishes to call @ref
//! carb::startupFramework() explicitly.
ScopedFrameworkStartup() : m_startedFramework{ false }
{
}
//! Constructor which passes @p argc and @p argv to @ref carb::startupFramework().
//!
//! All other parameters passed to @ref carb::startupFramework() are default values.
ScopedFrameworkStartup(int argc, char** argv) : m_startedFramework{ true }
{
carb::StartupFrameworkDesc startupParams = carb::StartupFrameworkDesc::getDefault();
startupParams.argv = argv;
startupParams.argc = argc;
carb::startupFramework(startupParams);
}
//! Constructor which allows specify all parameters to @ref carb::startupFramework().
ScopedFrameworkStartup(const carb::StartupFrameworkDesc& startupParams) : m_startedFramework{ true }
{
carb::startupFramework(startupParams);
}
//! Calls @ref carb::shutdownFramework() if a non-default constructor was called.
~ScopedFrameworkStartup()
{
if (m_startedFramework)
{
carb::shutdownFramework();
}
}
private:
CARB_PREVENT_COPY_AND_MOVE(ScopedFrameworkStartup);
private:
bool m_startedFramework;
};
} // namespace core
} // namespace omni
| 4,525 | C | 35.796748 | 120 | 0.675359 |
omniverse-code/kit/include/omni/core/IWeakObject.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/OmniAttr.h>
#include <omni/core/Interface.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <utility>
#include <type_traits>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Control block to maintain weak and strong reference counts for an object.
//!
//! The @ref IWeakObject interface supports the notion of "weak pointers". Unlike "strong pointers" (e.g. @ref
//! ObjectPtr) weak pointers do not affect the pointee's reference count. While this sounds like a raw pointer (and
//! possibly a bad idea), the magic of a weak pointer is that if the pointee's reference count goes to zero, the weak
//! pointer updates its internal pointer to `nullptr`.
//!
//! @ref IWeakObjectControlBlock is an ABI-safe object used to store a pointer to both the object and the object's
//! reference count (i.e. the "strong count"). This object additionally stores a "weak count", which is a count of
//! objects pointing to the @ref IWeakObjectControlBlock.
//!
//! Both @ref WeakPtr and @ref IWeakObject affect the "weak count".
//!
//! Only @ref ObjectPtr will affect the "strong count".
//!
//! Direct usage of this object should be avoided. See @ref WeakPtr to learn how weak pointers are used in practice.
//!
//! **Advanced: Design Considerations**
//!
//! The design of ONI's weak pointers takes three main design considerations into account:
//!
//! - The user API should work similar to <a href="https://en.cppreference.com/w/cpp/memory/weak_ptr">std::weak_ptr</a>.
//!
//! - Enabling weak pointer support for an object should should not tank performance in hot code paths.
//!
//! - Weak pointers must be able to point to object's whose DLL has been unloaded from memory.
//!
//! Above, the final point has a strong affect on the implementation of weak pointers. In particular, this object (i.e.
//! @ref IWeakObjectControlBlock). Consider:
//!
//! - For a virtual function to be called successfully, the code implementing the virtual function must still be loaded.
//!
//! - An @ref IWeakObjectControlBlock may outlive the DLL that created the object to which it points.
//!
//! Rather than exposing a raw struct with the weak and strong counts (and associated inline code to manipulate them),
//! this interface is used to hide both the counts and the manipulation logic. However, this introduces virtual
//! functions, which could potentially be unloaded. To address the unloading problem, *carb.dll* provides
//! `omni::core::getOrCreateWeakObjectControlBlock()`. This C-ABI returns an implementation of @ref
//! IWeakObjectControlBlock implemented within *carb.dll*. This effectively avoids the DLL unloading problem, since
//! *carb.dll* is considered a core dependency that cannot be unloaded and therefore the virtual function
//! implementations for @ref IWeakObjectControlBlock will always be loaded.
template <>
class omni::core::Generated<omni::core::IWeakObjectControlBlock_abi> : public omni::core::IWeakObjectControlBlock_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::core::IWeakObjectControlBlock")
//! Returns a pointer to the object pointed to by this control block. May return `nullptr`.
//!
//! If the object pointed to by this control block has a strong reference count of zero, `nullptr` is returned.
//! Otherwise, @ref IObject::acquire() is called on the object before being returned.
//!
//! @thread_safety This method is thread safe.
omni::core::ObjectPtr<omni::core::IObject> getObject() noexcept;
};
//! Interface defining a contract for objects which support "weak"/non-owning references.
//!
//! This interface works tightly with @ref WeakPtr to implement weak pointers. Users of weak pointers should focus on
//! @ref WeakPtr rather than this interface, as this interface is an implementation detail of the weak pointer ABI.
//!
//! Developers wishing to add weak pointer support to their objects must implement this interface, which is a
//! non-trivial task. A default implementation is provided in @ref ImplementsWeak.
template <>
class omni::core::Generated<omni::core::IWeakObject_abi> : public omni::core::IWeakObject_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::core::IWeakObject")
//! Returns a control block containing reference count information needed for the implementation of weak pointers.
//!
//! Users of weak pointers must never call this method. Rather, they should focus on exclusively using @ref
//! WeakPtr.
//!
//! Implementers of this method are encouraged to use the implementation found in @ref omni::core::ImplementsWeak.
//!
//! The returns pointer is never `nullptr`.
//!
//! The returned pointer will have @ref IObject::acquire() called on it before being returned.
//!
//! @thread_safety This method is thread safe.
omni::core::ObjectPtr<omni::core::IWeakObjectControlBlock> getWeakObjectControlBlock() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::core::ObjectPtr<omni::core::IObject> omni::core::Generated<omni::core::IWeakObjectControlBlock_abi>::getObject() noexcept
{
return omni::core::steal(getObject_abi());
}
inline omni::core::ObjectPtr<omni::core::IWeakObjectControlBlock> omni::core::Generated<
omni::core::IWeakObject_abi>::getWeakObjectControlBlock() noexcept
{
return omni::core::steal(getWeakObjectControlBlock_abi());
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 6,046 | C | 45.515384 | 134 | 0.739332 |
omniverse-code/kit/include/omni/core/Result.h | // 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.
//
//! \file
//!
//! \brief Result codes form the basics of error handling.
#pragma once
#include "../../carb/Defines.h"
#include "OmniAttr.h"
#include <cstdint>
namespace omni
{
namespace core
{
//! \{
//! Error code for the result of an operation.
//!
//! The numeric encoding for values follows Microsoft's
//! <a
//! href="https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/0642cb2f-2075-4469-918c-4441e69c548a">
//! HRESULT</a> scheme. Many values are direct copies of those from the Windows API, such as \c kResultNotImplemented.
//! Codes which are NVIDIA-provided, will have the mask \c 0xa4310000. This comes from setting the "customer bit" (bit
//! at most-significant index 2) and having a "facility" (bits from index 5-15) of \c 0b10000110001 aka \c 0x431 (which
//! is \c "NVDA" in Morse Code).
using Result OMNI_ATTR("constant, prefix=kResult") = std::int32_t;
//! Returns \c true if the given \ref omni::core::Result is not a failure code.
//!
//! `true` will be returned not only if the given result is \ref omni::core::kResultSuccess, but any other \ref
//! omni::core::Result that is not a failure code (such as warning \ref omni::core::Result codes).
#define OMNI_SUCCEEDED(x_) ((x_) >= 0)
//! Returns `true` if the given @ref omni::core::Result is a failure code.
#define OMNI_FAILED(x_) ((x_) < 0)
//! If the given \ref omni::core::Result is a failure code, calls `return result` to exit the current function.
#define OMNI_RETURN_IF_FAILED(x_) \
do \
{ \
auto result = (x_); \
if (OMNI_FAILED(result)) \
{ \
return result; \
} \
} while (0)
//! Operation successful. No error occurred.
constexpr Result kResultSuccess = 0;
//! The feature or method was not implemented. It might be at some point in the future.
//!
//! * POSIX: \c ENOSYS
//! * Windows: \c E_NOTIMPL
//! * Decimal Value: -2147467263
constexpr Result kResultNotImplemented = 0x80004001;
//! The operation was aborted.
//!
//! * Windows: \c E_ABORT
//! * Decimal Value: -2147467260
constexpr Result kResultOperationAborted = 0x80004004;
//! The operation failed.
//! * Decimal Value: -2147467259
constexpr Result kResultFail = 0x80004005;
//! The item was not found.
//! * Decimal Value: -2147024894
constexpr Result kResultNotFound = 0x80070002;
//! Access has been denied for this operation.
//!
//! * POSIX: \c EACCES
//! * Windows: \c E_ACCESSDENIED
//! * Decimal Value: -2147024891
constexpr Result kResultAccessDenied = 0x80070005;
//! A system is out of memory. This does not necessarily mean resident memory has been exhausted (although it can),
//! as this code can be used to special conditions such as exhausting graphics memory or running out of a specific
//! memory pool. It can also indicate that an allocation would have been too big and failed ahead of time.
//!
//! * POSIX: \c ENOMEM
//! * Windows: \c E_OUTOFMEMORY
//! * Decimal Value: -2147024882
constexpr Result kResultOutOfMemory = 0x8007000E;
//! The operation is not supported.
//! * Decimal Value: -2147024846
constexpr Result kResultNotSupported = 0x80070032;
//! One or more of the arguments passed to a given function was invalid.
//!
//! * POSIX: \c EINVAL
//! * Windows: \c E_INVALIDARG
//! * Decimal Value: -2147024809
constexpr Result kResultInvalidArgument = 0x80070057;
//! The system is in an invalid state to perform the operation. This is distinct from \c kResultInvalidOperation in that
//! it covers situations like "system is not yet started" or "file is closed."
//! * Decimal Value: -2147024892
constexpr Result kResultInvalidState = 0x80070004;
//! Version check failure.
//! * Decimal Value: -2147024253
constexpr Result kResultVersionCheckFailure = 0x80070283;
//! Failed to parse the version.
//! * Decimal Value: -2147024119
constexpr Result kResultVersionParseError = 0x80070309;
//! Insufficient buffer.
//! * Decimal Value: -2147024774
constexpr Result kResultInsufficientBuffer = 0x8007007A;
//! Try the operation again. This is typically emitted in situations where an operation would require blocking, but the
//! system is configured to be non-blocking. For example, attempting to read from a TCP socket when no data has been
//! received would return \c kResultTryAgain.
//!
//! * POSIX: \c EAGAIN, \c EWOULDBLOCK
//! * Windows: \c WMI_TRY_AGAIN
//! * Decimal Value: -2147020693
constexpr Result kResultTryAgain = 0x8007106B; //!< Try the operation again.
//! An operation was interrupted. An "interruption" happens in cases where the operation did not complete successfully
//! due to an outside system (such as a timer) interrupting it. For example, a function `Result wait_for(duration d)`
//! might give \c kResultSuccess when function returns because the duration expired and \c kResultInterrupted if the
//! system is shutting down.
//!
//! * POSIX: \c EINTR
//! * Windows: \c WSAEINTR
//! * Decimal Value: -1540292607
constexpr Result kResultInterrupted = 0xa4310001;
//! Interface not implemented.
//! * Decimal Value: -2147467262
constexpr Result kResultNoInterface = 0x80004002;
//! Pointer is null.
//!
//! * POSIX: covered by \c EINVAL
//! * Decimal Value: -2147467261
constexpr Result kResultNullPointer = 0x80004003;
//! Object already exists.
//!
//! * POSIX: \c EEXIST or \c EBUSY
//! * Decimal Value: -2147286960
constexpr Result kResultAlreadyExists = 0x80030050;
//! The operation was not valid for the target. For example, attempting to perform a write operation on a read-only file
//! would result in this error.
//!
//! * POSIX: \c EPERM
//! * Decimal Value: -2147020579
constexpr Result kResultInvalidOperation = 0x800710DD;
//! No more items to return. This is meant for things like reader queues when they have run out of data and will never
//! have more data. For cases where something like an async queue being temporarily empty, use \c kResultTryAgain.
//! * Decimal Value: -2146893782
constexpr Result kResultNoMoreItems = 0x8009002A;
//! Invalid index.
//!
//! * POSIX: covered by \c EINVAL or \c ENOENT, depending on the situation
//! * Decimal Value: -2146889720
constexpr Result kResultInvalidIndex = 0x80091008;
//! Not enough data.
//! * Decimal Value: -2144796415
constexpr Result kResultNotEnoughData = 0x80290101;
//! Too much data.
//! * Decimal Value: -2144796414
constexpr Result kResultTooMuchData = 0x80290102;
//! Invalid data type. This is used in cases where a specific type of data is requested, but that is not the data which
//! the receiver has.
//! * Decimal Value: -2144272373
constexpr Result kResultInvalidDataType = 0x8031000B;
//! Invalid data size. This arises when the correct type of data is requested, but the requester believes the data size
//! is different from the receiver. The cause of this is typically a version mismatch.
//! * Decimal Value: -2144272372
constexpr Result kResultInvalidDataSize = 0x8031000C;
//! \}
//! \cond DEV
// clang-format off
//! The list of all result codes as a higher-order macro. The provided \c item_ should accept three parameters:
//!
//! * \c symbol -- the PascalCase version of the symbol; e.g.: \c AlreadyExists. Note that this includes neither the
//! \c kResult prefix nor the \c omni::core namespace qualifier, so you need to paste those yourself if desired.
//! * \c snake_symbol -- the snake_case version of the symbol; e.g.: \c try_again
//! * \c message -- a string literal of the associated message for the error; e.g.: `"access denied"`
#define OMNI_RESULT_CODE_LIST(item_) \
/* (symbol, snek_symbol, message) */ \
item_(Success, success, "operation succeeded") \
item_(NotImplemented, not_implemented, "not implemented") \
item_(OperationAborted, operation_aborted, "aborted") \
item_(Fail, fail, "failure") \
item_(NotFound, not_found, "not found") \
item_(AccessDenied, access_denied, "access denied") \
item_(OutOfMemory, out_of_memory, "out of memory") \
item_(NotSupported, not_supported, "not supported") \
item_(InvalidArgument, invalid_argument, "invalid argument") \
item_(InvalidState, invalid_state, "invalid state") \
item_(VersionCheckFailure, version_check_failure, "version check failure") \
item_(VersionParseError, version_parse_error, "version parse error") \
item_(InsufficientBuffer, insufficient_buffer, "insufficient buffer") \
item_(TryAgain, try_again, "try again") \
item_(Interrupted, interrupted, "interrupted") \
item_(NoInterface, no_interface, "no interface") \
item_(NullPointer, null_pointer, "null pointer") \
item_(AlreadyExists, already_exists, "already exists") \
item_(InvalidOperation, invalid_operation, "invalid operation") \
item_(NoMoreItems, no_more_items, "no more items") \
item_(InvalidIndex, invalid_index, "invalid index") \
item_(NotEnoughData, not_enough_data, "not enough data") \
item_(TooMuchData, too_much_data, "too much data") \
item_(InvalidDataType, invalid_data_type, "invalid data type") \
item_(InvalidDataSize, invalid_data_size, "invalid data size")
// clang-format on
//! \endcond
} // namespace core
} // namespace omni
| 11,070 | C | 45.322176 | 120 | 0.620145 |
omniverse-code/kit/include/omni/core/ModuleInfo.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Helper functions for collecting module information.
#pragma once
#include "../../carb/extras/Library.h"
#include "../../carb/Interface.h"
#include "IObject.h"
namespace omni
{
namespace core
{
//! Given an object, returns the name of the module (.dll/.exe) which contains the object's code.
//!
//! @param[in] obj The object to retrieve the module name for. This may not be `nullptr`.
//! @returns The name and path of the library that the given object's owning implementation
//! comes from. Returns an empty string if the object isn't bound to any particular
//! library.
inline std::string getModuleFilename(omni::core::IObject* obj)
{
// getLibraryFilename maps an address to a library.
//
// the first entry in IObject is the vtable pointer on both Windows and Linux. here we use the first virtual
// function address as a function pointer to pass to getLibraryFilename.
//
// Fun fact: everyone loves pointer dereferencing gymnastics: ** **** ******* ****
void** vtbl = *reinterpret_cast<void***>(obj);
return carb::extras::getLibraryFilename(vtbl[0]);
}
} // namespace core
} // namespace omni
//! Provides a list of dependent interfaces for an ONI plugin.
//!
//! @param[in] ... The list of fully qualified interface names that this plugin depends on. This
//! should include any interfaces, Carbonite or ONI, that this plugin will attempt
//! to acquire or create. This allows the Carbonite framework to verify that all
//! dependent modules or interfaces are available for a plugin when attempting to
//! load it, and allows for a more correct shutdown/unload order for plugins.
#define OMNI_PLUGIN_IMPL_DEPS(...) \
template <typename... Types> \
static void getPluginDepsTyped(struct carb::InterfaceDesc** deps, size_t* depsCount) \
{ \
static carb::InterfaceDesc depends[] = { Types::getInterfaceDesc()... }; \
*deps = depends; \
*depsCount = sizeof...(Types); \
} \
\
omni::core::Result omniGetDependencies(carb::InterfaceDesc** deps, size_t* depsCount) \
{ \
getPluginDepsTyped<__VA_ARGS__>(deps, depsCount); \
return omni::core::kResultSuccess; \
}
//! Declares that the calling plugin has no dependencies on any other Carbonite or ONI interfaces.
//!
//! @remarks This lets the Carbonite plugin manager know that the calling plugin does not
//! expect to attempt to acquire any other Carbonite interfaces or create any other
//! ONI objects. This helps the plugin manager determine the most correct unload or
//! shutdown order for all plugins.
#define OMNI_PLUGIN_IMPL_NODEPS() \
omni::core::Result omniGetDependencies(carb::InterfaceDesc** deps, size_t* depsCount) \
{ \
*deps = nullptr; \
*depsCount = 0; \
return omni::core::kResultSuccess; \
}
| 4,924 | C | 61.341771 | 120 | 0.469537 |
omniverse-code/kit/include/omni/core/ITypeFactory.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Provides the ITypeFactory interface declaration.
#pragma once
#include "../../carb/Defines.h"
#include "IObject.h"
#include "ModuleExports.h"
#include "Omni.h"
#include "Result.h"
#include <cstdint>
#include <vector>
namespace omni
{
namespace core
{
//! Forward declares that the ITypeFactory interface is present.
OMNI_DECLARE_INTERFACE(ITypeFactory);
//! Function called by ITypeFactory to instantiate an implementation.
//!
//! This "creation" function is one of the core principles behind @rstref{ABI safety <abi-compatibility>}. By calling
//! this simple function, we're able to instantiate a complex implementation of an Omniverse interface. All of the
//! details to instantiate this implementation are hidden behind this function. Since this function returns a pointer
//! to an interface (IObject), the caller is not exposed to any of the implementation details needed to instantiate the
//! interface.
using InterfaceImplementationCreateFn = IObject*();
//! Describes a mapping from a chunk of code (i.e. implementation) to one or more interfaces.
//!
//! Implementation are concrete classes that implement one or more interfaces.
//!
//! This data structure is essential to the Omniverse type system, as it maps type names (i.e. strings) to chunks of
//! code that can instantiate those types. With this, the Omniverse type system is able to map interface type names to
//! implementations and implementation type names to specific implementations.
struct OMNI_ATTR("no_py") InterfaceImplementation
{
//! Name of the implementation. This must not be the name of an interface.
const char* name;
//! Function that instantiates the implementation.
//!
//! This function can be called concurrently on multiple threads
InterfaceImplementationCreateFn* createFn;
//! Implementations have versions. By default, ITypeFactory will pick the implementation with the highest version
//! number. This behavior can be overridden (see ITypeFactory).
//!
//! This version number is not an "interface" version number. Interfaces are not versioned. Implementations,
//! however, can be versioned. An implementation's version number is used by ITypeFactory to pick the best
//! implementation when instantiating an interface.
uint32_t version;
//! List of interfaces, that when requested to be instantiated by ITypeFactory (e.g. omni::core::createType()),
//! should instantiate this implementation. Not all implemented interfaces should be listed here, only those
//! interfaces you wish to instantiate via omni::core::createType().
//!
//! Said differently, this is a list of interfaces, that when invoked with omni::core::createType(), should
//! instantiate this implementation.
//!
//! Which interfaces should be listed here is subtle topic. See @rstref{omniverse-native-interfaces} for
//! more details.
const char** interfacesImplemented;
//! Number of interfaces implemented (size of interfacesImplemented). Pro-tip: Use
//! CARB_COUNTOF32(interfacesImplemented).
uint32_t interfacesImplementedCount;
};
//! Base type for the flags used when registering plugins or implementations with the type
//! factory. These are used to modify how the plugin or implementation is registered. No
//! flags are currently defined. These flags will all have the prefix `fTypeFactoryFlag`.
using TypeFactoryLoadFlags OMNI_ATTR("flag, prefix=fTypeFactoryFlag") = uint32_t;
//! Flag to indicate that no special change in behavior should be used when registering
//! a plugin or implementation.
constexpr TypeFactoryLoadFlags fTypeFactoryFlagNone = 0x0;
//! A mapping from type id's to implementations.
//!
//! This object maps type id's to concrete implementations. The type id's can represent interface ids or implementation
//! ids.
//!
//! Register types with registerInterfaceImplementationsFromModule() and registerInterfaceImplementations().
//!
//! Instantiate types with omni::core::createType(). This is the primary way Omniverse applications are able to
//! instantiate concrete implementations of @rstref{ABI-safe <abi-compatibility>} interfaces. See
//! omni::core::createType() for a helpful wrapper around omni::core::ITypeFactory::createType().
//!
//! In practice, there will be a single ITypeFactory active in the process space (accessible via
//! omniGetTypeFactoryWithoutAcquire()). However, @ref omni::core::ITypeFactory is not inherently a singleton, and as
//! such multiple instantiations of the interface may exists. This can be used to create private type trees.
//!
//! Unless otherwise noted, all methods in this interface are thread safe.
class ITypeFactory_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.core.ITypeFactory")>
{
protected:
//! Instantiates a concrete type.
//!
//! The given type id can be an interface or implementation id.
//!
//! If the id is an interface id, the following rules are followed:
//!
//! - If the application specified a default implementation, that implementation will be instantiated.
//!
//! - Otherwise, the first registered implementation of the interface is instantiated. If multiple versions of the
//! implementation exist, the highest version is picked.
//!
//! - implVersion must be 0 since interfaces are not versioned (only implementations are versioned). If implVersion
//! is not 0, nullptr is returned.
//!
//! - If a default module name was provided by the app, the rules above will only be applied to implementations from
//! the specified default module.
//!
//! If the id is an implementation id, the followings rules apply:
//!
//! - If version is 0, the highest version of the implementation is returned.
//!
//! - If version is not 0, the returned object is the specified version of the implementation. If such a version
//! does not exists, nullptr is returned. If multiple implementations exists with the same version, the
//! implementation registered first is instantiated.
//!
//! In both cases above, if moduleName given, the rules above are followed by only looking at implementations from
//! the specified module. If no match is found, nullptr is returned.
//!
//! If moduleName has not been loaded, it will be loaded and its implementations registered.
//!
//! If moduleName is nullptr, the rules above are applied across all loaded modules.
//!
//! This method is thread safe.
virtual IObject* OMNI_ATTR("no_py")
createType_abi(TypeId id, OMNI_ATTR("c_str") const char* moduleName, uint32_t implVersion) noexcept = 0;
//! Registers types from the given module.
//!
//! If the module is currently loaded, it will not be reloaded and kResultSuccess is returned.
//!
//! Modules (e.g. .dll or .so) may contain one or many implementations of one or many interfaces. When registering a
//! module with the type factory, a function, whose name is described by 'kModuleGetExportsName', is found and
//! invoked. Let's assume the exported function name is "omniModuleGetExports".
//!
//! "omniModuleGetExports" returns a key/value database of the module's capabilities and the module's requirements.
//! Some things to note about this database:
//!
//! - The module's requirements can be marked as optional.
//!
//! - The module's capabilities can be ignored by ITypeFactory.
//!
//! These properties allow ITypeFactory and the module to find an intersection of desired functionality in a data
//! driven manner. If one party's required needs are not met, the module fails to load (e.g. an appropriate
//! omni::core::Result is returned).
//!
//! It is expected the module has entries in the key/value database describing the functions ITypeFactory should
//! call during the loading process. The most important of these entries is the one defined by
//! OMNI_MODULE_ON_MODULE_LOAD(), which points to the function ITypeFactory should call to get a list of
//! implementations in the module. ITypeFactory invokes exports from the module in the following pattern:
//!
//! .--------------------------------------------------------------------------------------------------------------.
//! | -> Time -> |
//! |--------------------------------------------------------------------------------------------------------------|
//! | omniModuleGetExports | onLoad (req.) | onStarted (optional) | onCanUnload (optional) | onUnload (optional) |
//! | | | impl1->createFn | | |
//! | | | impl2->createFn | | |
//! | | | impl1->createFn | | |
//! \--------------------------------------------------------------------------------------------------------------/
//!
//! Above, functions in the same column can be called concurrently. It's up to the module to make sure such call
//! patterns are thread safe within the module.
//!
//! onCanUnload and createFn can be called multiple times. All other functions are called once during the lifecycle
//! of a module.
//!
//! \see omni/core/ModuleExports.h.
//! \see onModuleLoadFn
//! \see onModuleStartedFn
//! \see onModuleCanUnloadFn
//! \see onModuleUnloadFn
//!
//!
//! The module can be explicitly unloaded with unregisterInterfaceImplementationsFromModule().
//!
//! Upon destruction of this ITypeFactory, unregisterInterfaceImplementationsFromModule is called for each loaded
//! module. If the ITypeFactory destructor's call to unregisterInterfaceImplementationsFromModule fails to safely
//! unload a module (via the module's onModuleCanUnload and onModuleUnload), an attempt will be made to
//! forcefully/unsafely unload the module.
//!
//! The given module name must not be nullptr.
//!
//! This method is thread safe. Modules can be loaded in parallel.
//!
//! \returns Returns kResultSuccess if the module is loaded (either due to this function or a previous call).
//! Otherwise, an error is returned.
virtual Result registerInterfaceImplementationsFromModule_abi(OMNI_ATTR("c_str, not_null") const char* moduleName,
TypeFactoryLoadFlags flags) noexcept = 0;
//! Unregisters all types registered from the given module.
//!
//! Unregistering a module may fail if the module does not belief it can safely be unloaded. This is determined by
//! OMNI_MODULE_ON_MODULE_CAN_UNLOAD().
//!
//! If unregistration does succeed, the given module will be unloaded from the process space.
//!
//! Upon destruction of this ITypeFactory, unregisterInterfaceImplementationsFromModule is called for each loaded
//! module. If the ITypeFactory destructor's call to unregisterInterfaceImplementationsFromModule fails to safely
//! unload a module (via the module's onModuleCanUnload and onModuleUnload), an attempt will be made to
//! forcefully/unsafely unload the module.
//!
//! The given module name must not be nullptr.
//!
//! This method is thread safe.
//!
//! \returns Returns kResultSuccess if the module wasn't already loaded or if this method successfully unloaded the
//! module. Return an error code otherwise.
virtual Result unregisterInterfaceImplementationsFromModule_abi(OMNI_ATTR("c_str, not_null")
const char* moduleName) noexcept = 0;
//! Register the list of types.
//!
//! Needed data from the "implementations" list is copied by this method.
//!
//! This method is thread safe.
virtual OMNI_ATTR("no_py") void registerInterfaceImplementations_abi(
OMNI_ATTR("in, count=implementationsCount, not_null") const InterfaceImplementation* implementations,
uint32_t implementationsCount,
TypeFactoryLoadFlags flags) noexcept = 0;
//! Maps a type id back to its type name.
//!
//! The memory returned is valid for the lifetime of ITypeFactory
//!
//! Returns nullptr if id has never been registered. Types that have been registered, and then unregistered, will
//! still have a valid string returned from this method.
//!
//! This method is thread safe.
virtual const char* getTypeIdName_abi(TypeId id) noexcept = 0;
//! Sets the implementation matching constraints for the given interface id.
//!
//! See omni::core::ITypeFactory_abi::createType_abi() for how these constraints are used.
//!
//! moduleName can be nullptr.
//!
//! if implVersion is 0 and implId is an implementation id, the implementation with the highest version is chosen.
//!
//! This method is thread safe.
virtual void setInterfaceDefaults_abi(TypeId interfaceId,
TypeId implId,
OMNI_ATTR("c_str") const char* moduleName,
uint32_t implVersion) noexcept = 0;
//! Returns the implementation matching constraints for the given interface id.
//!
//! See omni::core::ITypeFactory_abi::createType_abi() for how these constraints are used.
//!
//! If the given output implementation id pointer (outImplid) is not nullptr, it will be populated with the default
//! implementation id instantiated when the interface requested to be created.
//!
//! If the given output implementation version pointer (outImplVersion) is not nullptr, it will be populated with
//! the default implementation version instantiated when the interface is requested to be created.
//!
//! If the output module name pointer (outModuleName) is not nullptr, it will be populated with the name of the
//! module searched when trying to find an implementation of the interface. If there is no current default module
//! name, the output module name will be populated with the empty string. If the output module name's buffer size is
//! insufficient to store the null terminated module name, kResultBufferInsufficient is returned and the module
//! name's buffer size is updated with the needed buffer size.
//!
//! If the output module name is nullptr, the output module name buffer size (inOutModuleNameCount) will be
//! populated with the size of the buffer needed to store the module name.
//!
//! The output module name buffer size pointer (inOutModuleNameCount) must not be nullptr.
//!
//! If the given interface id is not found, kResultNotFound is returned and the output implementation id (outImplId)
//! and version (outImplVersion), if defined, are set to 0. Additionally, the output module name (outModuleName),
//! if defined, is set to the empty string.
//!
//! If kResultInsufficientBuffer and kResultNotFound are both flagged internally, kResultNotFound is returned.
//!
//! See omni::core::getInterfaceDefaults() for a C++ wrapper to this method.
//!
//! This method is thread safe.
virtual OMNI_ATTR("no_py") Result
getInterfaceDefaults_abi(TypeId interfaceId,
OMNI_ATTR("out") TypeId* outImplId, // nullptr accepted
OMNI_ATTR("out" /*count=*inOutModuleNameCount*/) char* outModuleName, // nullptr
// accepted
OMNI_ATTR("in, out, not_null") uint32_t* inOutModuleNameCount, // must not be null
OMNI_ATTR("out") uint32_t* outImplVersion) noexcept = 0; // nullptr accepted
};
//! The version number of a @ref TypeFactoryArgs object being passed around. This is used to
//! manage backward and forward compatibility checks when an implementation receives the
//! object. Newer versions of a type factory implementation are expected to be able to handle
//! the layout and content of any older version of this object.
constexpr uint16_t kTypeFactoryArgsVersion = 1;
//! Arguments passed to omniCreateTypeFactory().
class TypeFactoryArgs
{
public:
//! Version of this structure. The version should be incremented only when removing/rearranging fields. Adding
//! fields (from the reserved space) is allowed without incrementing the version.
uint16_t version;
//! Size of this structure in bytes.
uint16_t byteCount;
//! Four bytes of intentional padding to ensure the following pointers are appropriately aligned and to
//! force the size of this object to a known expected value.
uint8_t padding[4];
//! A pointer to the @ref omni::log::ILog implementation object that should be used by the core for all
//! logging operations. This may be `nullptr` to use the default internal implementation.
omni::log::ILog* log;
//! A pointer to the @ref omni::structuredlog::IStructuredLog implementation object that should be
//! used by the core for all structured logging operations. This may be `nullptr` to use the default
//! implementation.
omni::structuredlog::IStructuredLog* structuredLog;
//! When adding fields, decrement this reserved space. Be mindful of alignment (explicitly add padding fields if
//! needed).
void* reserved[13];
TypeFactoryArgs()
{
std::memset(this, 0, sizeof(*this));
version = kTypeFactoryArgsVersion;
byteCount = sizeof(*this);
}
//! Constructor: initializes a new object explicitly referencing the override objects to use.
//!
//! @param[in] log_ The @ref omni::log::ILog object to use for all operations that go through
//! `ILog`. This may be `nullptr` to use the default internal implementation.
//! @param[in] strucLog_ The @ref omni::structuredlog::IStructuredLog object to use for all operations
//! that go through `IStructuredLog`. This may be `nullptr` to use the default
//! implementation.
//! @returns No Return value.
//!
//! @remarks This initializes a new object with specific override objects. There is currently no way
//! to specify that one of the override objects should be disabled completely - if a `nullptr`
//! object is passed in, the default implementation will be used instead.
//!
TypeFactoryArgs(omni::log::ILog* log_, omni::structuredlog::IStructuredLog* strucLog_) : TypeFactoryArgs()
{
log = log_;
structuredLog = strucLog_;
}
};
CARB_ASSERT_INTEROP_SAFE(TypeFactoryArgs);
static_assert((8 + 15 * sizeof(void*)) == sizeof(TypeFactoryArgs), "TypeFactoryArgs has an unexpected size");
} // namespace core
} // namespace omni
#include "ITypeFactory.gen.h"
#ifdef OMNI_COMPILE_AS_DYNAMIC_LIBRARY
OMNI_API omni::core::ITypeFactory* omniGetTypeFactoryWithoutAcquire();
#else
//! Returns the global ITypeFactory. omni::core::IObject::acquire() is **not** called on the returned pointer.
//!
//! The global omni::core::ITypeFactory instance can be configured by passing an omni::core::ITypeFactory to
//! omniCoreStart(). If an instance is not provided, omniCreateTypeFactory() is called.
inline omni::core::ITypeFactory* omniGetTypeFactoryWithoutAcquire()
{
return static_cast<omni::core::ITypeFactory*>(omniGetBuiltInWithoutAcquire(OmniBuiltIn::eITypeFactory));
}
#endif
//! Creates a default implementation of ITypeFactory.
//!
//! The given TypeFactoryArgs pointer will only be accessed during this call.
//!
//! nullptr is accepted.
OMNI_API omni::core::ITypeFactory* omniCreateTypeFactory(const omni::core::TypeFactoryArgs* args = nullptr);
// clang-format off
OMNI_DEFINE_INTERFACE_API(omni::core::ITypeFactory)
{
public:
//! Instantiates an implementation of interface T.
//!
//! See omni::core::ITypeFactory_abi::createType_abi() for instantiation rules.
template <typename T>
inline ObjectPtr<T> createType(const char* moduleName = nullptr, uint32_t version = 0) noexcept
{
return createType<T>(T::kTypeId, moduleName, version);
}
//! Instantiates the given type and casts it to T.
//!
//! The given type id can be an implementation id.
//!
//! If the interface type T is not implemented by the type id, nullptr is returned.
//!
//! See omni::core::ITypeFactory_abi::createType_abi() for instantiation rules.
template <typename T = IObject>
inline ObjectPtr<T> createType(TypeId id, const char* moduleName = nullptr, uint32_t version = 0) noexcept
{
auto ptr = steal(createType_abi(id, moduleName, version));
return ptr.template as<T>();
}
};
// clang-format on
namespace omni
{
namespace core
{
//! Instantiates an implementation of interface T.
//!
//! See omni::core::ITypeFactory_abi::createType_abi() for instantiation rules.
template <typename T>
inline ObjectPtr<T> createType(const char* moduleName = nullptr, uint32_t version = 0) throw()
{
return omniGetTypeFactoryWithoutAcquire()->createType<T>(moduleName, version);
}
//! Instantiates the given type and casts it to T.
//!
//! The given type id can be an implementation id.
//!
//! If the interface type T is not implemented by the type id, nullptr is returned.
//!
//! \see omni::core::ITypeFactory_abi::createType_abi() for instantiation rules.
template <typename T = IObject>
inline ObjectPtr<T> createType(TypeId id, const char* moduleName = nullptr, uint32_t version = 0) CARB_NOEXCEPT
{
return omniGetTypeFactoryWithoutAcquire()->createType<T>(id, moduleName, version);
}
//! \see ITypeFactory::registerInterfaceImplementationsFromModule().
inline Result registerInterfaceImplementationsFromModule(const char* moduleName, // e.g. omni.scripting-python.dll
TypeFactoryLoadFlags flags = 0) CARB_NOEXCEPT
{
return omniGetTypeFactoryWithoutAcquire()->registerInterfaceImplementationsFromModule(moduleName, flags);
}
//! \see ITypeFactory::registerInterfaceImplementations().
inline void registerInterfaceImplementations(const InterfaceImplementation* implementations,
uint32_t implementationsCount,
TypeFactoryLoadFlags flags = 0) CARB_NOEXCEPT
{
return omniGetTypeFactoryWithoutAcquire()->registerInterfaceImplementations(
implementations, implementationsCount, flags);
}
//! \see ITypeFactory::getTypeIdName().
inline const char* getTypeIdName(TypeId id) CARB_NOEXCEPT
{
return omniGetTypeFactoryWithoutAcquire()->getTypeIdName(id);
}
//! \see ITypeFactory::setInterfaceDefaults().
template <typename T>
inline void setInterfaceDefaults(TypeId implId, const char* moduleName, uint32_t implVersion)
{
omniGetTypeFactoryWithoutAcquire()->setInterfaceDefaults(T::kTypeId, implId, moduleName, implVersion);
}
//! Given an interface id (i.e. T), returns the preferred implementation (if any) instantiated when calling
//! omni::core::ITypeFactory::createType(), the preferred module (if any) searched when calling
//! omni::core::ITypeFactory::createType(), and the preferred implementation version number (if any) required
//! when calling omni::core::ITypeFactory::createType().
//!
//! \see omni::core::ITypeFactory::getInterfaceDefault().
//!
//! Unlike the ABI method, this method returns kResultTryAgain if another thread is actively changing the interface
//! defaults. This method internally retries multiple times to get the defaults, but will eventually give up with
//! kResultTryAgain.
//!
//! Unlike the ABI method, kResultInsufficientBuffer is never returned.
template <typename T>
inline Result getInterfaceDefaults(TypeId* implId, std::string* moduleName, uint32_t* implVersion)
{
if (!moduleName)
{
uint32_t moduleNameCount = 0;
Result result = omniGetTypeFactoryWithoutAcquire()->getInterfaceDefaults(
T::kTypeId, implId, nullptr, &moduleNameCount, implVersion);
return result;
}
else
{
// loop here in case the module name size changes between checking for the size and actually get the string.
std::vector<char> buffer;
for (unsigned i = 0; i < 4; ++i)
{
uint32_t moduleNameCount = uint32_t(buffer.size());
Result result = omniGetTypeFactoryWithoutAcquire()->getInterfaceDefaults(
T::kTypeId, implId, buffer.data(), &moduleNameCount, implVersion);
if (kResultInsufficientBuffer != result)
{
*moduleName = buffer.data();
return result;
}
else
{
buffer.resize(moduleNameCount);
}
}
return kResultTryAgain;
}
}
//! \see ITypeFactory::unregisterInterfaceImplementationsFromModule().
inline Result unregisterInterfaceImplementationsFromModule(const char* moduleName) CARB_NOEXCEPT
{
return omniGetTypeFactoryWithoutAcquire()->unregisterInterfaceImplementationsFromModule(moduleName);
}
} // namespace core
} // namespace omni
| 26,129 | C | 48.395085 | 120 | 0.677982 |
omniverse-code/kit/include/omni/core/Result.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/OmniAttr.h>
#include <omni/core/Interface.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <utility>
#include <type_traits>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 928 | C | 25.542856 | 77 | 0.746767 |
omniverse-code/kit/include/omni/core/Assert.h | // Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//! @brief Helper macros to provide assertion checking macros.
#pragma once
#include "Platform.h"
#include "VariadicMacroUtils.h"
#include <array>
#include <cstdio>
#include <utility>
namespace omni
{
namespace core
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
template <size_t N>
constexpr std::integral_constant<size_t, N - 1> length(const char (&)[N])
{
return {};
}
template <size_t N>
constexpr std::integral_constant<size_t, N - 1> length(std::array<char, N>)
{
return {};
}
template <typename T>
using LengthType = decltype(length(std::declval<T>()));
template <typename ARRAY>
constexpr void constCopyTo(ARRAY& out, size_t dst, const char* in, size_t sz)
{
if (sz)
{
out[dst] = *in;
constCopyTo(out, dst + 1, in + 1, sz - 1);
}
}
template <class T, std::size_t N, std::size_t... I>
constexpr std::array<std::remove_cv_t<T>, N> constToArrayImpl(T (&a)[N], std::index_sequence<I...>)
{
return { { a[I]... } };
}
template <class T, std::size_t N>
constexpr std::array<std::remove_cv_t<T>, N> constToArray(T (&a)[N])
{
return constToArrayImpl(a, std::make_index_sequence<N>{});
}
template <typename T>
constexpr const char* toChars(T& s)
{
return s;
}
template <typename T, size_t N>
constexpr const char* toChars(const std::array<T, N>& s)
{
return &(s[0]);
}
template <typename A, typename B, typename C>
constexpr std::array<char, LengthType<A>::value + LengthType<B>::value + LengthType<C>::value + 1> constConcat(
const A& a, const B& b, const C& c)
{
char o[LengthType<A>::value + LengthType<B>::value + LengthType<C>::value + 1]{};
constCopyTo(o, 0, toChars(a), LengthType<A>::value);
constCopyTo(o, LengthType<A>::value, toChars(b), LengthType<B>::value);
constCopyTo(o, LengthType<A>::value + LengthType<B>::value, toChars(c), LengthType<C>::value);
return constToArray(o);
}
template <typename A, typename B>
constexpr std::array<char, LengthType<A>::value + LengthType<B>::value + 1> constConcat(const A& a, const B& b)
{
return constConcat(a, b, "");
}
template <typename A>
constexpr std::array<char, LengthType<A>::value + 1> constConcat(const A& a)
{
return constConcat(a, "", "");
}
template <bool I>
struct Assertion
{
constexpr static char Message[] = "Assertion (%s) failed:";
};
template <>
struct Assertion<false>
{
constexpr static char Message[] = "Assertion (%s) failed.";
};
constexpr bool hasArg(const char*)
{
return true;
}
constexpr bool hasArg()
{
return false;
}
} // namespace detail
#endif
} // namespace core
} // namespace omni
//! This macro is surprisingly complex mainly because it accepts a variable number of arguments. If a single argument is
//! given, a message in the following form is printed:
//!
//! "Assertion (myCondition) failed.\n"
//!
//! If multiple arguments are given, the message become more dynamic:
//!
//! "Assertion (var == 1) failed: var == 2\n"
//!
//! Where the latter part of the message "var == 2" is provided by the caller.
//!
//! So, if multiple arguments are given, this macro must:
//!
//! - End the first part of the message with a : instead of an .
//!
//! - Concatenate the the fixed format string ("Assertion (%s)..."") with the user supplied format message.
//!
//! - Add a newline.
//!
//! All of this at compile time.
//!
//! We use a couple of tricks to do this (all in portable C++).
//!
//! - Via the preprocessor, we can't detect if __VA_ARGS__ is empty (this is a preprocessor limitation). We can forward
//! the __VA_ARGS__ to a constexpr (hasArg). hasArg is an overloaded constexpr that will return true if an argument
//! was supplied. We can then use the result of this overload to select a template specialization (Assertion<>)
//! containing a constexpr with our format string.
//!
//! - We need to concatenate the first part of the format string with the user provided portion and a newline. We can't
//! do this with the preprocess because the first part of the message is a constexpr, not a string literal. To get
//! around this we use a constexpr (constConcat) to perform the concatenation.
//!
//! - The user format string may be empty. We use the preprocessor's string concatenation in
//! OMNI_VA_FIRST_OR_EMPTY_STRING to make sure a second argument is passed to the constexpr string concatenation
//! function.
//!
//! - When passing the __VA_ARGS__ to fprintf, we need to elide the first argument (since it's the user supplied format
//! we already concatenated) and provide a comma if any additional arguments were given. While the preprocessor cannot
//! detect if __VA_ARGS__ is empty, it can detect if at least two arguments are supplied. OMNI_VA_COMMA_WITHOUT_FIRST
//! uses this to determine if a comma should be added and to elide the first user supplied argument (the user's
//! format string).
//!
//! Some of this code can be simplified with C++20's __VA_OPT__.
//! Checks if the given condition is true, if not, the given optional message is printed to stdout and the program is
//! terminated.
//!
//! Use this macro when an unrecoverable situation has been detected.
#define OMNI_FATAL_UNLESS(cond_, ...) \
do \
{ \
if (!CARB_LIKELY(cond_)) \
{ \
auto constexpr const failMsg_ = omni::core::detail::constConcat( \
omni::core::detail::Assertion<omni::core::detail::hasArg(OMNI_VA_FIRST(__VA_ARGS__))>::Message, \
OMNI_VA_FIRST_OR_EMPTY_STRING(__VA_ARGS__)); \
auto constexpr const fmt_ = \
omni::core::detail::constConcat(__FILE__ ":" CARB_STRINGIFY(__LINE__) ": ", failMsg_, "\n"); \
std::fprintf(stderr, fmt_.data(), #cond_ OMNI_VA_COMMA_WITHOUT_FIRST(__VA_ARGS__)); \
OMNI_BREAK_POINT(); \
} \
} while (0)
//! Indicates whether runtime checking is enabled. For the time being this is always set to `1`
//! indicating that the default implementation should not be overridden. This may change in
//! the future.
#define OMNI_CHECK_ENABLED 1
//! Checks if the given condition is true, if not, the given optional message is printed to stdout and the program is
//! terminated.
//!
//! Unlike OMNI_ASSERT, this macro runs checks in release builds.
//!
//! Use this macro to when you fail to provide adequate test coverage.
#define OMNI_CHECK OMNI_FATAL_UNLESS
#if CARB_DEBUG
//! Like std::assert. Basically OMNI_FATAL_UNLESS, but compiles to a no-op in debug builds.
# define OMNI_ASSERT(cond, ...) OMNI_FATAL_UNLESS(cond, __VA_ARGS__)
//! Set to 1 to indicate that assertion checks are enabled. Set to 0 if assertion checks will
//! just be ignored. This value will always be defined regardless of the current mode.
# define OMNI_ASSERT_ENABLED 1
#else
//! Like std::assert. Basically OMNI_FATAL_UNLESS, but compiles to a no-op in debug builds.
# define OMNI_ASSERT(cond, ...) ((void)0)
//! Set to 1 to indicate that assertion checks are enabled. Set to 0 if assertion checks will
//! just be ignored. This value will always be defined regardless of the current mode.
# define OMNI_ASSERT_ENABLED 0
#endif
| 8,503 | C | 38.18894 | 120 | 0.608021 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.