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/exts/omni.graph.tools/omni/graph/tools/tests/test_internal_extension.py | """Testing for the internal utilities, like extension version management, logging, and .ogn file handling"""
from contextlib import ExitStack
from pathlib import Path
from tempfile import TemporaryDirectory
import omni.graph.tools._internal as ogi
import omni.kit.test
from .internal_utils import CreateHelper, TemporaryPathAddition
# Helper constants shared by many tests
EXT_INDEX = 0
_CLASS_NAME = "OgnTestNode"
_CURRENT_VERSIONS = ogi.GenerationVersions(ogi.Compatibility.FullyCompatible)
# ==============================================================================================================
class ModuleContexts:
def __init__(self, stack: ExitStack):
"""Set up a stack of contexts to use for tests running in individual temporary directory"""
global EXT_INDEX
EXT_INDEX += 1
self.ext_name = f"omni.test.internal.extension{EXT_INDEX}"
# Default extension version is 0.1.0 so create an ID with that
self.ext_id = f"{self.ext_name}-0.1.0"
# Put all temporary files in a temporary directory for easy disposal
self.test_directory = Path(stack.enter_context(TemporaryDirectory())) # pylint: disable=consider-using-with
self.module_root = Path(self.test_directory) / "exts"
self.module_name = self.ext_name
self.module_path = self.module_root / self.ext_name / self.module_name.replace(".", "/")
# Redirect the usual node cache to the temporary directory
self.cache_root = stack.enter_context(ogi.TemporaryCacheLocation(self.test_directory / "cache"))
# Add the import path of the new extension to the system path
self.path_addition = stack.enter_context(TemporaryPathAddition(self.module_root / self.ext_name))
# Uncomment this to dump debugging information while the tests are running
# self.log = stack.enter_context(ogi.TemporaryLogLocation("stdout"))
# ==============================================================================================================
class TestInternalExtension(omni.kit.test.AsyncTestCase):
"""Tests concerned with exercising the information provided by the code generation utilities. For tests related
to the node type registration see omni.graph.core.tests.test_register_python_ogn.py
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.maxDiff = None # Diffs of file path lists can be large so let the full details be seen
# --------------------------------------------------------------------------------------------------------------
async def test_build_tree_constructor(self):
"""Test the CreateHelper utility class"""
with ExitStack() as stack:
ctx = ModuleContexts(stack)
ogn_directory = ctx.module_path / "ogn"
creator = CreateHelper(ctx.ext_name, ctx.module_root, _CURRENT_VERSIONS)
# Create a build tree with one up-to-date version and one out-of-date version to cover both cases
creator.add_standalone_node("OgnTestNode")
creator.add_v1_18_node("OgnBuiltNode")
expected_files = [
ctx.module_path / "nodes" / "OgnTestNode.ogn",
ctx.module_path / "nodes" / "OgnTestNode.py",
ogn_directory / "nodes" / "OgnBuiltNode.ogn",
ogn_directory / "nodes" / "OgnBuiltNode.py",
ogn_directory / "OgnBuiltNodeDatabase.py",
ogn_directory / "tests" / "__init__.py",
ogn_directory / "tests" / "TestOgnBuiltNode.py",
ogn_directory / "tests" / "usd" / "OgnBuiltNodeTemplate.usda",
]
for expected_file in expected_files:
expected_path = ctx.module_root / expected_file
self.assertTrue(expected_path.is_file(), f"Checking existence of {expected_path}")
self.assertTrue(expected_path.stat().st_size > 0, f"Checking size of {expected_path}")
# --------------------------------------------------------------------------------------------------------------
async def test_walk_with_excludes(self):
"""Test the utility that imitates os.walk with directory exclusions"""
with ExitStack() as stack:
ctx = ModuleContexts(stack)
creator = CreateHelper(ctx.ext_name, ctx.module_root, _CURRENT_VERSIONS)
creator.add_standalone_node("OgnTestNode")
creator.add_v1_18_node("OgnBuiltNode")
# Exclude the tests directory and make sure the two files in there didn't get found
files_found = []
for _, _, file_names in ogi.walk_with_excludes(ctx.test_directory, {"tests"}):
files_found += file_names
self.assertCountEqual(
files_found,
[
"OgnTestNode.ogn",
"OgnTestNode.py",
"OgnBuiltNode.ogn",
"OgnBuiltNode.py",
"OgnBuiltNodeDatabase.py",
],
)
# Walk with no exclusions to make sure all files are found
files_found = []
for _, _, file_names in ogi.walk_with_excludes(ctx.test_directory, {}):
files_found += file_names
self.assertCountEqual(
files_found,
[
"OgnTestNode.ogn",
"OgnTestNode.py",
"OgnBuiltNode.ogn",
"OgnBuiltNode.py",
"OgnBuiltNodeDatabase.py",
"TestOgnBuiltNode.py",
"__init__.py",
"OgnBuiltNodeTemplate.usda",
],
)
# --------------------------------------------------------------------------------------------------------------
async def test_scan_extension(self):
"""Test the process of scanning an extension for existing .ogn, .py, and Database.py files"""
with ExitStack() as stack:
ctx = ModuleContexts(stack)
creator = CreateHelper(ctx.ext_name, ctx.module_root, _CURRENT_VERSIONS)
creator.add_v1_18_node(_CLASS_NAME)
ext_contents = ogi.extension_contents_factory(ctx.ext_name, ctx.ext_name, ctx.module_root / ctx.ext_name)
self.assertIsNotNone(ext_contents)
ext_contents.scan_for_nodes()
user_types_expected = [ogi.FileType.OGN, ogi.FileType.PYTHON]
generated_types_expected = [ogi.FileType.PYTHON_DB, ogi.FileType.TEST, ogi.FileType.USD]
file_names = {file_type: ogi.get_ogn_file_name(_CLASS_NAME, file_type) for file_type in ogi.FileType}
definition = ext_contents.node_type_definition(_CLASS_NAME)
self.assertEqual(definition.name, _CLASS_NAME)
self.assertEqual(len(user_types_expected), len(definition.user_files))
self.assertTrue(
all(
info[0] is not None
for info in [definition.user_files[file_type] for file_type in user_types_expected]
)
)
self.assertCountEqual(list(definition.generated_files.keys()), generated_types_expected)
ogn_directory = ctx.module_path / "ogn"
expected_files = {
ogi.FileType.OGN: ogn_directory / "nodes" / file_names[ogi.FileType.OGN],
ogi.FileType.PYTHON: ogn_directory / "nodes" / file_names[ogi.FileType.PYTHON],
ogi.FileType.PYTHON_DB: ogn_directory / file_names[ogi.FileType.PYTHON_DB],
ogi.FileType.TEST: ogn_directory / "tests" / file_names[ogi.FileType.TEST],
ogi.FileType.USD: ogn_directory / "tests" / "usd" / file_names[ogi.FileType.USD],
}
# All of the file types should be in the expected locations
for expected_type, expected_path in expected_files.items():
self.assertEqual(definition.file_path(expected_type), expected_path)
# The files types, in type order, should also be in time order initially
self.assertTrue(definition.file_mtime(ogi.FileType.OGN) <= definition.file_mtime(ogi.FileType.PYTHON))
self.assertTrue(definition.file_mtime(ogi.FileType.PYTHON) <= definition.file_mtime(ogi.FileType.PYTHON_DB))
self.assertTrue(definition.file_mtime(ogi.FileType.PYTHON_DB) <= definition.file_mtime(ogi.FileType.TEST))
self.assertTrue(definition.file_mtime(ogi.FileType.TEST) <= definition.file_mtime(ogi.FileType.USD))
# The files types should have all received the artificially generated version number
self.assertEqual(
definition.generated_versions,
_CURRENT_VERSIONS,
f"Comparing generated version {definition.generated_versions} to"
f" current version {_CURRENT_VERSIONS}",
)
# The node type definitions are up to date by design
self.assertFalse(definition.is_out_of_date(_CURRENT_VERSIONS))
# Touch the .ogn file to make the database out of date.
self.assertTrue(definition.user_files.touch(ogi.FileType.OGN))
self.assertTrue(definition.is_out_of_date(_CURRENT_VERSIONS))
# Check the functionality that walks the available list of generated file types
available_types = list(definition.iter_valid_generated_filetypes())
self.assertCountEqual(available_types, generated_types_expected + [ogi.FileType.DOCS])
# --------------------------------------------------------------------------------------------------------------
async def test_scan_empty(self):
"""Test the utility that scans a directory looking for .ogn files when the directory has none, though it
does have some nodes that look like node files due to their naming.
"""
with ExitStack() as stack:
ctx = ModuleContexts(stack)
ext_contents = ogi.extension_contents_factory(ctx.ext_name, ctx.ext_name, ctx.module_root / ctx.ext_name)
self.assertIsNone(ext_contents)
# --------------------------------------------------------------------------------------------------------------
async def test_scan_standalone(self):
"""Test the utility that scans a directory looking for .ogn files when the directory is structured as a
standalone extension (i.e. no built files)
"""
with ExitStack() as stack:
ctx = ModuleContexts(stack)
creator = CreateHelper(ctx.ext_name, ctx.module_root, _CURRENT_VERSIONS)
creator.add_standalone_node(_CLASS_NAME)
ogn_directory = ctx.module_path / "ogn"
node_directory = ctx.module_path / "nodes"
ext_contents = ogi.extension_contents_factory(ctx.ext_name, ctx.ext_name, ctx.module_root / ctx.ext_name)
self.assertIsNotNone(ext_contents)
ext_contents.scan_for_nodes()
self.assertEqual(ext_contents.node_type_count, 1)
definition = ext_contents.node_type_definition(_CLASS_NAME)
self.assertIsNotNone(definition)
self.assertEqual(definition.name, _CLASS_NAME)
self.assertEqual(2, len(definition.user_files))
self.assertEqual(0, len(definition.generated_files))
self.assertEqual(definition.user_files[ogi.FileType.OGN][0], node_directory / f"{_CLASS_NAME}.ogn")
self.assertEqual(definition.user_files[ogi.FileType.PYTHON][0], node_directory / f"{_CLASS_NAME}.py")
self.assertTrue(definition.is_out_of_date(_CURRENT_VERSIONS))
expected_files = {
ogi.FileType.OGN: node_directory / f"{_CLASS_NAME}.ogn",
ogi.FileType.PYTHON: node_directory / f"{_CLASS_NAME}.py",
ogi.FileType.PYTHON_DB: ogn_directory / f"{_CLASS_NAME}Database.py",
ogi.FileType.TEST: ogn_directory / "tests" / f"Test{_CLASS_NAME}.py",
ogi.FileType.USD: ogn_directory / "tests" / "usd" / f"{_CLASS_NAME}Template.usda",
ogi.FileType.DOCS: ogn_directory / "docs" / f"{_CLASS_NAME}.rst",
}
for file_type, expected_file in expected_files.items():
if file_type in [ogi.FileType.OGN, ogi.FileType.PYTHON]:
self.assertEqual(definition.file_path(file_type), expected_file)
else:
self.assertEqual(definition.file_path(file_type), None)
# --------------------------------------------------------------------------------------------------------------
async def test_exclude_types(self):
"""Test that files excluded by a node do not appear in its outdated list when missing"""
with ExitStack() as stack:
ctx = ModuleContexts(stack)
ogn_directory = ctx.module_path / "ogn"
exclusions = [ogi.FileType.USD, ogi.FileType.DOCS]
creator = CreateHelper(ctx.ext_name, ctx.module_root, _CURRENT_VERSIONS)
creator.add_v1_18_node(_CLASS_NAME, exclusions)
ext_contents = ogi.extension_contents_factory(ctx.ext_name, ctx.ext_name, ctx.module_root / ctx.ext_name)
self.assertIsNotNone(ext_contents)
ext_contents.scan_for_nodes()
self.assertEqual(ext_contents.node_type_count, 1)
definition = ext_contents.node_type_definition(_CLASS_NAME)
self.assertIsNotNone(definition)
self.assertEqual(definition.name, _CLASS_NAME)
self.assertEqual(definition.file_path(ogi.FileType.OGN), ogn_directory / "nodes" / "OgnTestNode.ogn")
self.assertEqual(definition.file_path(ogi.FileType.PYTHON), ogn_directory / "nodes" / "OgnTestNode.py")
self.assertEqual(
{file_type: gen_def[0] for file_type, gen_def in definition.generated_files.items()},
{
ogi.FileType.TEST: ogn_directory / "tests" / "TestOgnTestNode.py",
ogi.FileType.PYTHON_DB: ogn_directory / "OgnTestNodeDatabase.py",
},
)
# The up-to-date database should have been found
self.assertEqual(
definition.generated_versions,
ogi.GenerationVersions(ogi.Compatibility.FullyCompatible),
)
self.assertFalse(definition.is_out_of_date(_CURRENT_VERSIONS))
# --------------------------------------------------------------------------------------------------------------
async def test_out_of_date_versions(self):
"""Test that versions with good timestamps but old versions are flagged for regeneration"""
incompatible = ogi.GenerationVersions(ogi.Compatibility.Incompatible)
with ExitStack() as stack:
ctx = ModuleContexts(stack)
creator = CreateHelper(ctx.ext_name, ctx.module_root, incompatible)
creator.add_v1_18_node(_CLASS_NAME)
ext_contents = ogi.extension_contents_factory(ctx.ext_name, ctx.ext_name, ctx.module_root / ctx.ext_name)
self.assertIsNotNone(ext_contents)
ext_contents.scan_for_nodes()
self.assertEqual(ext_contents.node_type_count, 1)
definition = ext_contents.node_type_definition(_CLASS_NAME)
self.assertIsNotNone(definition)
# The node was generated to be deliberately incompatible with the current versions
self.assertEqual(definition.generated_versions, incompatible)
self.assertTrue(definition.is_out_of_date(_CURRENT_VERSIONS))
# --------------------------------------------------------------------------------------------------------------
async def test_versions_in_build_and_cache(self):
"""Test that the newer version is selected when they exist in both the build and the cache
The structure it generates here is a local directory with the cache/ and ogn/ directories together:
ogn/
OgnSampleNodeDatabase.py
nodes/
OgnSampleNode.py
OgnSampleNode.ogn
tests/
TestOgnSampleNode.py
usd/
OgnSampleNodeTemplate.usda
cache/
ogn_generated/
XX.YY.ZZ/
omni.test.internal.extension/
OgnSampleNodeDatabase.py
docs/
OgnSampleNode.rst
tests/
TestOgnSampleNode.py
usd/
OgnSampleNodeTemplate.usda
"""
with ExitStack() as stack:
ctx = ModuleContexts(stack)
major_compatible_versions = ogi.GenerationVersions(ogi.Compatibility.MajorVersionCompatible)
cache_directory = ogi.full_cache_path(_CURRENT_VERSIONS, ctx.ext_id, ctx.module_name)
creator_major = CreateHelper(ctx.ext_name, ctx.module_root, major_compatible_versions)
creator_major.add_v1_18_node(_CLASS_NAME)
creator = CreateHelper(ctx.ext_name, ctx.module_root, _CURRENT_VERSIONS)
creator.add_cache_for_node(_CLASS_NAME)
ext_contents = ogi.extension_contents_factory(ctx.ext_id, ctx.ext_name, ctx.module_root / ctx.ext_name)
self.assertIsNotNone(ext_contents)
ext_contents.scan_for_nodes()
self.assertEqual(1, ext_contents.node_type_count)
definition = ext_contents.node_type_definition(_CLASS_NAME)
self.assertIsNotNone(definition)
# Different versions should have been found for the cache and the build generated files
self.assertEqual(
definition.generated_versions,
major_compatible_versions,
f"Generated versions {definition.generated_versions} versus major {major_compatible_versions}",
)
self.assertEqual(
definition.cached_versions,
_CURRENT_VERSIONS,
f"Cached versions {definition.cached_versions} versus current {_CURRENT_VERSIONS}",
)
# The cached file is the one that is currently up to date so it should be the one returned when
# asking for the database file.
cached_db_file = cache_directory / ogi.get_ogn_file_name(_CLASS_NAME, ogi.FileType.PYTHON_DB)
self.assertEqual(cached_db_file, definition.database_to_use())
# Test that cached files are flagged for rebuilding when they have the correct version but are
# older than the .ogn from which they are generated.
self.assertTrue(definition.user_files.touch(ogi.FileType.OGN))
self.assertTrue(definition.is_out_of_date(_CURRENT_VERSIONS))
self.assertEqual(None, definition.database_to_use())
# --------------------------------------------------------------------------------------------------------------
async def test_cached_version_old(self):
"""Test that cached files with incompatible versions are ignored"""
with ExitStack() as stack:
ctx = ModuleContexts(stack)
incompatible_versions = ogi.GenerationVersions(ogi.Compatibility.Incompatible)
creator = CreateHelper(ctx.ext_name, ctx.module_root, _CURRENT_VERSIONS)
creator.add_v1_18_node(_CLASS_NAME)
creator_incompatible = CreateHelper(ctx.ext_name, ctx.module_root, incompatible_versions)
creator_incompatible.add_cache_for_node(_CLASS_NAME)
ext_contents = ogi.extension_contents_factory(ctx.ext_name, ctx.ext_name, ctx.module_root / ctx.ext_name)
self.assertIsNotNone(ext_contents)
ext_contents.scan_for_nodes()
self.assertEqual(1, ext_contents.node_type_count)
definition = ext_contents.node_type_definition(_CLASS_NAME)
self.assertIsNotNone(definition)
# Different versions should have been found for the cache and the build generated files
self.assertEqual(
definition.generated_versions,
_CURRENT_VERSIONS,
f"Generated versions {definition.generated_versions} versus current {_CURRENT_VERSIONS}",
)
# The generated file is the one that is currently up to date so it should be the one returned when
# asking for the database file.
generated_db_file = ctx.module_path / "ogn" / ogi.get_ogn_file_name(_CLASS_NAME, ogi.FileType.PYTHON_DB)
self.assertEqual(generated_db_file, definition.database_to_use())
| 20,866 | Python | 53.483029 | 120 | 0.57898 |
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/tests/test_deprecation.py | """Tests that exercise the various types of deprecation"""
import re
import omni.graph.tools as ogt
import omni.kit
# ==============================================================================================================
# Deprecated constructs for testing
CLASS_DEPRECATED = "Use og.NewerClass"
@ogt.DeprecatedClass(CLASS_DEPRECATED)
class OlderClass:
pass
FUNCTION_DEPRECATED = "Use og.newer_function()"
@ogt.deprecated_function(FUNCTION_DEPRECATED)
def older_function():
pass
class NewNameForClass:
pass
RENAME_MESSAGE = "OldNameForClass is now NewNameForClass"
OldNameForClass = ogt.RenamedClass(NewNameForClass, "OldNameForClass", RENAME_MESSAGE)
OLD_STRING = ogt.DeprecatedStringConstant("OLD_STRING", "GARBAGE", "Wipe your memory of it")
OLD_DICTIONARY = ogt.DeprecatedDictConstant("OLD_DICTIONARY", {}, "Wipe your memory of it")
OLD_OBJECT = ogt.deprecated_constant_object(older_function, "Wipe your memory of it")
# ==============================================================================================================
class TestDeprecation(omni.kit.test.AsyncTestCase):
# --------------------------------------------------------------------------------------------------------------
def setUp(self):
"""Messages have to be cleared before the test to avoid spurious success"""
ogt.DeprecateMessage.clear_messages()
self.__were_deprecations_errors = ogt.DeprecateMessage.deprecations_are_errors()
ogt.DeprecateMessage.set_deprecations_are_errors(False)
def tearDown(self):
"""Messages have to be cleared after the test to prevent contamination of the message logs"""
ogt.DeprecateMessage.clear_messages()
ogt.DeprecateMessage.set_deprecations_are_errors(self.__were_deprecations_errors)
# --------------------------------------------------------------------------------------------------------------
def __check_deprecation_messages(self, pattern: str, expected_count: int):
"""Returns True if the pattern appears in the deprecation messages the given number of times"""
actual_count = sum(
match is not None
for match in [
re.search(pattern, message) for message in ogt.DeprecateMessage._MESSAGES_LOGGED # noqa: PLW0212
]
)
self.assertEqual(
actual_count, expected_count, f"Expected {expected_count} messages matching {pattern} - got {actual_count}"
)
# --------------------------------------------------------------------------------------------------------------
async def test_class_deprecation(self):
"""Test deprecation of a class"""
with ogt.DeprecateMessage.NoLogging():
_ = OlderClass()
self.__check_deprecation_messages(CLASS_DEPRECATED, 1)
# --------------------------------------------------------------------------------------------------------------
async def test_function_deprecation(self):
"""Test deprecation of a single function"""
with ogt.DeprecateMessage.NoLogging():
older_function()
expected = f"older_function() is deprecated: {FUNCTION_DEPRECATED}"
self.assertTrue(
expected in ogt.DeprecateMessage.messages_logged(),
f"'{expected}' not found in {ogt.DeprecateMessage.messages_logged()}",
)
# --------------------------------------------------------------------------------------------------------------
async def test_rename_deprecation(self):
"""Test deprecation of a class by giving it a new name"""
with ogt.DeprecateMessage.NoLogging():
_ = OldNameForClass()
self.__check_deprecation_messages(RENAME_MESSAGE, 1)
# --------------------------------------------------------------------------------------------------------------
async def test_string_constant_deprecation(self):
"""Test deprecation of a string constant that is being removed"""
# The deprecation message only happens on conversion to string as that's where it's most relevant.
with ogt.DeprecateMessage.NoLogging():
new_constant = str(OLD_STRING)
expected = "OLD_STRING is deprecated: Wipe your memory of it"
self.assertEqual(new_constant, "GARBAGE")
self.assertTrue(
expected in ogt.DeprecateMessage.messages_logged(),
f"'{expected}' not found in {ogt.DeprecateMessage.messages_logged()}",
)
# --------------------------------------------------------------------------------------------------------------
async def test_dict_constant_deprecation(self):
"""Test deprecation of a dictionary constant that is being removed"""
expected = "OLD_DICTIONARY is deprecated: Wipe your memory of it"
self.assertEqual(dict(OLD_DICTIONARY), {})
self.assertTrue(
expected in ogt.DeprecateMessage.messages_logged(),
f"'{expected}' not found in {ogt.DeprecateMessage.messages_logged()}",
)
# --------------------------------------------------------------------------------------------------------------
async def test_object_constant_deprecation(self):
"""Test deprecation of an object constant that is being removed"""
expected = re.compile(".*older_function.*is deprecated. Wipe your memory of it")
self.assertEqual(OLD_OBJECT.__name__, "older_function")
found_message = False
messages = ogt.DeprecateMessage.messages_logged()
for message in messages:
if expected.match(message):
found_message = True
self.assertTrue(found_message, f"'{expected}' not found in {messages}")
# --------------------------------------------------------------------------------------------------------------
async def test_deprecation_message(self):
"""Test issuing a deprecation message"""
deprecation_message = "This is deprecated"
with ogt.DeprecateMessage.NoLogging():
ogt.DeprecateMessage.deprecated(deprecation_message)
self.assertTrue(deprecation_message in ogt.DeprecateMessage.messages_logged())
# --------------------------------------------------------------------------------------------------------------
async def test_deprecated_import(self):
"""Test deprecation of a module import"""
with ogt.DeprecateMessage.NoLogging():
import omni.graph.tools.tests.deprecated_import as _do_not_export # noqa: F401,PLW0621
expected = "omni.graph.tools.tests.deprecated_import is deprecated: Do Not Import"
self.assertTrue(
expected in ogt.DeprecateMessage.messages_logged(),
f"'{expected}' not found in {ogt.DeprecateMessage.messages_logged()}",
)
# --------------------------------------------------------------------------------------------------------------
async def test_deprecation_error(self):
"""Test escalation of deprecations from warning to error"""
old_setting = ogt.DeprecateMessage.deprecations_are_errors()
try:
ogt.DeprecateMessage.set_deprecations_are_errors(True)
with self.assertRaises(ogt.DeprecationError, msg="Use of hard deprecated class not raising an error"):
_ = OlderClass()
finally:
ogt.DeprecateMessage.set_deprecations_are_errors(old_setting)
| 7,444 | Python | 47.344156 | 119 | 0.536674 |
omniverse-code/kit/exts/omni.graph.tools/docs/ogn_code_samples_cpp.cpp | // This file contains snippets of example C++ code to be imported by the OGN documentation.
// It's not actual running code itself, merely sections of code that illustrate a point
// It uses the reStructuredText code import with begin/end markings to cherry-pick relevant portions.
// The sections of code being referenced are demarqued by "begin-XX" and "end-XX".
// begin-minimal
#include <OgnNoOpDatabase.h>
class OgnNoOp:
{
public:
static bool compute(OgnNoOpDatabase& db)
{
// This logs a warning to the console, once
db.logWarning("This node does nothing");
// These methods provide direct access to the ABI objects, should you need to drop down to direct ABI calls
// for any reason. (You should let us know if this is necessary as we've tried to minimize the cases in which
// it becomes necessary.)
const auto& contextObj = db.abi_context();
const auto& nodeObj = db.abi_node();
if (! contextObj.iAttributeData || ! nodeObj.iNode)
{
// This logs an error to the console and should only be used for compute failure
db.logError("Could not retrieve the ABI interfaces");
return false;
}
return true;
}
};
REGISTER_OGN_NODE()
// end-minimal
// begin-node-metadata
#include <OgnNodeMetadataDatabase.h>
#include <alloca.h>
class OgnNodeMetadata:
{
public:
static bool compute(OgnNodeMetadataDatabase& db)
{
auto nodeTypeObj = db.abi_node().getNodeTypeObj(db.abi_node());
// Specifically defined metadata can be accessed by name
std::cout << "The author of this node is " << nodeTypeObj.iNodeType->getMetadata(nodeTypeObj, "author") << std::endl;
// Some metadata is automatically added; you can see it by iterating over all of the existing metadata
size_t metadataCount = nodeTypeObj.iNodeType->getMetadataCount(nodeTypeObj);
char const** metadataKeyBuffer = reinterpret_cast<char const**>(alloca(sizeof(char*) * metadataCount));
char const** metadataValueBuffer = reinterpret_cast<char const**>(alloca(sizeof(char*) * metadataCount));
size_t found = nodeTypeObj.iNodeType->getAllMetadata(nodeTypeObj, metadataKeyBuffer, metadataValueBuffer, metadataCount);
for (size_t i=0; i<found; ++i)
{
std:: cout << "Metadata for " << metadataKeyBuffer[i] << " = " << metadataValueBuffer[i] << std::endl;
}
return true;
}
};
REGISTER_OGN_NODE()
// end-node-metadata
// begin-node-icon
#include <OgnNodeWithIconDatabase.h>
class OgnNodeWithIcon:
{
public:
static bool compute(OgnNodeWithIconDatabase& db)
{
auto nodeTypeObj = db.abi_node().getNodeTypeObj(db.abi_node());
// The icon properties are just special cases of metadata. The metadata name is made available with the node type
auto path = nodeTypeObj.iNodeType->getMetadata(nodeTypeObj, kOgnMetadataIconPath);
auto color = nodeTypeObj.iNodeType->getMetadata(nodeTypeObj, kOgnMetadataIconColor);
auto backgroundColor = nodeTypeObj.iNodeType->getMetadata(nodeTypeObj, kOgnMetadataIconBackgroundColor);
auto borderColor = nodeTypeObj.iNodeType->getMetadata(nodeTypeObj, kOgnMetadataIconBorderColor);
if (path)
{
std::cout << "Icon found at " << path << std::endl;
if (color)
{
std::cout << "...color override is " << color << std::endl;
}
else
{
std::cout << "...using default color" << std::endl;
}
if (backgroundColor)
{
std::cout << "...backgroundColor override is " << backgroundColor << std::endl;
}
else
{
std::cout << "...using default backgroundColor" << std::endl;
}
if (borderColor)
{
std::cout << "...borderColor override is " << borderColor << std::endl;
}
else
{
std::cout << "...using default borderColor" << std::endl;
}
}
return true;
}
};
REGISTER_OGN_NODE()
// end-node-icon
// begin-node-scheduling
#include <OgnNodeSchedulingHintsDatabase.h>
class OgnNodeSchedulingHints:
{
public:
static bool compute(OgnNodeSchedulingHintsDatabase& db)
{
auto nodeTypeObj = db.abi_node().getNodeTypeObj(db.abi_node());
// Ordinarily you would not need to access this scheduling information as it is mainly for OmniGraph's use,
// however it is available through the ABI so you can access it at runtime if you wish.
auto schedulingHintsObj = nodeTypeObj.getSchedulingHints(nodeTypeObj);
std::string safety;
switch (schedulingHintsObj.getThreadSafety(schedulingHintsObj))
{
case eThreadSafety::eSafe:
safety = "Safe";
break;
case eThreadSafety::eUnsafe:
safety = "Unsafe";
break;
case eThreadSafety::eUnknown:
default:
safety = "Unknown";
break;
}
std::cout << "Is this node threadsafe? " << safety << std::endl;
return true;
}
};
REGISTER_OGN_NODE()
// end-node-scheduling
// begin-node-singleton
#include <OgnNodeSingletonDatabase.h>
class OgnNodeSingleton:
{
public:
static bool compute(OgnNodeSingletonDatabase& db)
{
auto nodeTypeObj = db.abi_node().getNodeTypeObj(db.abi_node());
// The singleton value is just a special case of metadata. The metadata name is made available with the node type
auto singletonValue = nodeTypeObj.iNodeType->getMetadata(nodeTypeObj, kOgnMetadataSingleton);
if (singletonValue && singletonValue[0] != '1')
{
std::cout << "I am a singleton" << std::endl;
}
return true;
}
};
REGISTER_OGN_NODE()
// end-node-singleton
// begin-node-categories
#include <OgnNodeCategoriesDatabase.h>
class OgnNodeCategories:
{
public:
static bool compute(OgnNodeCategoriesDatabase& db)
{
auto nodeTypeObj = db.abi_node().getNodeTypeObj(db.abi_node());
// The categories value is just a special case of metadata. The metadata name is made available with the node type
auto categoriesValue = nodeTypeObj.iNodeType->getMetadata(nodeTypeObj, kOgnMetadataCategories);
if (categoriesValue)
{
std::cout << "I have these categories:";
char const* delimiters = ",";
char *token = std::strtok(categoriesValue, delimiters);
while (token)
{
std::cout << ' ' << std::quoted(token);
token = std::strtok(nullptr, delimiters);
}
std::cout << std::endl;
}
return true;
}
};
REGISTER_OGN_NODE()
// end-node-categories
// begin-node-tags
#include <OgnNodeTagsDatabase.h>
class OgnNodeTags:
{
public:
static bool compute(OgnNodeTagsDatabase& db)
{
auto nodeTypeObj = db.abi_node().getNodeTypeObj(db.abi_node());
// The tags value is just a special case of metadata. The metadata name is made available with the node type
std::cout << "Tagged as " << nodeTypeObj.iNodeType->getMetadata(nodeTypeObj, kOgnMetadataTags) << std::endl;
return true;
}
};
REGISTER_OGN_NODE()
// end-node-tags
// begin-tokens
#include <OgnTokensDatabase.h>
class OgnTokens:
{
public:
static bool compute(OgnTokensDatabase& db)
{
// Tokens are members of the database, by name. When the dictionary-style definition is used in the .ogn
// file the names are the dictionary keys. These members were created, of type omni::graph::core::NameToken:
// db.tokens.red
// db.tokens.green
// db.tokens.blue
// As tokens are just IDs in order to print their values you have to use the utility method "tokenToString"
// on the database to convert them to strings
std::cout << "The name for red is " << db.tokenToString(db.tokens.red) << std::endl;
std::cout << "The name for green is " << db.tokenToString(db.tokens.green) << std::endl;
std::cout << "The name for blue is " << db.tokenToString(db.tokens.blue) << std::endl;
// This confirms that tokens are uniquely assigned and the same for all types.
auto redToken = db.stringToToken("red");
if (redToken != db.tokens.red)
{
std::cout << "ERROR: red token is not consistent" << std::endl;
return false;
}
return true;
}
};
REGISTER_OGN_NODE()
// end-tokens
// begin-node-uiName
#include <OgnNodeUiNameDatabase.h>
class OgnNodeUiName:
{
public:
static bool compute(OgnNodeUiNameDatabase& db)
{
// The uiName value is just a special case of metadata. The special metadata name is available from the ABI
auto nodeTypeObj = db.abi_node().getNodeTypeObj(db.abi_node());
std::cout << "Call me " << nodeTypeObj.iNodeType->getMetadata(nodeTypeObj, kOgnMetadataUiName) << std::endl;
return true;
}
};
REGISTER_OGN_NODE()
// end-node-uiName
// begin-simple
#include <OgnTokenStringLengthDatabase.h>
class OgnTokenStringLength:
{
public:
static bool compute(OgnTokenStringLengthDatabase& db)
{
// Access pattern is "db", the database, "inputs", the attribute's access type, and "token", the name the
// attribute was given in the .ogn file
// Inputs should always be const-references, outputs and state access types can be just plain references.
const auto& tokenToMeasure = db.inputs.token();
// The database has typedefs for all attributes, which can be used if you prefer explicit types
db.outputs.length_t& stringLength = db.outputs.length();
// Use the utility to convert the token to a string first
std::string tokenString{ db.tokenToString(tokenToMeasure) };
// Simple assignment to the output attribute's accessor is all you need to do to set the value, as it is
// pointing directly to that data.
stringLength = tokenString.length();
return true;
}
};
REGISTER_OGN_NODE()
// end-simple
// begin-tuple
#include <OgnVectorMultiplyDatabase.h>
class OgnVectorMultiply:
{
public:
static bool compute(OgnVectorMultiplyDatabase& db)
{
const auto& vector1 = db.inputs.vector1();
const auto& vector2 = db.inputs.vector2();
auto& product = db.outputs.product();
// Use the functionality in the GfVec classes to perform the multiplication.
// You can use your own library functions by casting to appropriate types first.
for (int row=0; row<4; ++row)
{
product.SetRow(row, vector1 * vector2[row]);
}
return true;
}
};
REGISTER_OGN_NODE()
// end-tuple
// begin-role
#include <OgnPointsToVectorDatabase.h>
// Being explicit about the namespaced types you are using is a good balance between namespace pollution and long names
using omni::graph::core::AttributeRole;
class OgnPointsToVector:
{
public:
static bool compute(OgnPointsToVectorDatabase& db)
{
// Validate the roles for the computation. They aren't used in the actual math, though they could be used
// to do something useful (e.g. cast data with a "color" role to a class that handles color spaces)
if (db.inputs.point1.role() != AttributeRole::ePosition)
{
db.logError("The attribute point1 does not have the point role");
return false;
}
if (db.inputs.point2.role() != AttributeRole::ePosition)
{
db.logError("The attribute point2 does not have the point role");
return false;
}
if (db.outputs.vector.role() != AttributeRole::eVector)
{
db.logError("The attribute vector does not have the vector role");
return false;
}
// The GfVec3f type supports simple subtraction for vector calculation
db.outputs.vector() = db.inputs.point2() - db.inputs.point2();
return true;
}
};
REGISTER_OGN_NODE()
// end-role
// begin-array
#include <OgnPartialSumsDatabase.h>
#include <numeric>
class OgnPartialSums:
{
public:
static bool compute(OgnPartialSumsDatabase& db)
{
const auto& inputArray = db.inputs.array();
auto& outputArray = db.outputs.partialSums();
// This is a critical step, setting the size of the output array. Without this the array has no memory in
// which to write.
//
// For convenience the size() and resize() methods are available at the database level and the wrapper level,
// with the latter method only available for writable attributes. This makes initializing an output with the
// same size as an input a one-liner in either of these two forms:
// db.outputs.partialSum.resize( db.inputs.array.size() );
outputArray.resize(inputArray.size());
// The wrapper to arrays behaves like a std::span<>, where the external memory they manage comes from Fabric.
// The wrapper handles the synchronization, and is set up to behave mostly like
// a normal std::array.
//
// for (const auto& inputValue : inputArray)
// inputArray[index]
// inputArray.at(index)
// inputArray.empty()
// rawData = inputArray.data()
// Since the standard range-based for-loop and general iteration is supported you can make use of the wide
// variety of STL algorithms as well.
//
std::partial_sum(inputArray.begin(), inputArray.end(), outputArray.begin());
return true;
}
};
REGISTER_OGN_NODE()
// end-array
// begin-tuple-array
#include <OgnCrossProductDatabase.h>
#include <algorithm>
class OgnCrossProduct:
{
public:
static bool compute(OgnCrossProductDatabase& db)
{
// It usually keeps your code cleaner if you put your attribute wrappers into local variables, avoiding
// the constant use of the "db.inputs" or "db.outputs" namespaces.
const auto& a = db.inputs.a();
const auto& b = db.inputs.b();
auto& crossProduct = db.outputs.crossProduct();
// This node chooses to make mismatched array lengths an error. You could also make it a warning, or just
// simply calculate the result for the minimum number of available values.
if (a.size() != b.size())
{
db.logError("Input array lengths do not match - '%zu' vs. '%zu'", a.size(), b.size());
return false;
}
// As with simple arrays, the size of the output tuple-array must be set first to allocate Fabric memory
crossProduct.resize(a.size());
// Edge case is easily handled
if (a.size() == 0)
{
return true;
}
// Simple cross product - your math library may have a built-in one you can use
auto crossProduct = [](const GfVec3d& a, const GfVec3d& b) -> GfVec3d {
GfVec3d result;
result[0] = a[1] * b[2] - a[2] * b[1];
result[1] = -(a[0] * b[2] - a[2] * b[0]);
result[2] = a[0] * b[1] - a[1] * b[0];
return result;
};
// STL support makes walking the parallel arrays and computing a breeze
std::transform(a.begin(), a.end(), b.begin(), crossProduct.begin(), crossProduct);
return true;
}
};
REGISTER_OGN_NODE()
// end-tuple-array
// begin-string
#include <OgnReverseStringDatabase.h>
class OgnReverseString:
{
public:
static bool compute(OgnReverseStringDatabase& db)
{
// The attribute wrapper for string types provides a conversion to a std::string with pre-allocated memory.
// Constructing a new string based on that gives you a copy that can be modified locally and assigned after.
std::string result(db.inputs.original());
// Other functions provided by the string wrapper include:
// size() - how many characters in the string?
// empty() - is the string empty?
// data() - the raw char* pointer - note that it is not necessarily null-terminated
// comparison operators for sorting
// iterators
// For writable strings (output and state) there are also modification functions:
// resize() - required before writing, unless you use an assigment operator
// clear() - empty out the string
// assignment operators for char const*, std::string, and string wrappers
// The local copy can be reversed in place.
std::reverse(std::begin(result), std::end(result));
// The assignment operator handles resizing the string as well
db.outputs.result() = result;
// Since in this case the length of the output string is known up front the extra copy can be avoided by
// making use of the iterator feature.
// auto& resultString = db.outputs.result();
// resultString.resize(db.inputs.original.size());
// std::reverse(std::begin(resultString), std::end(resultString));
return true;
}
};
REGISTER_OGN_NODE()
// end-string
// begin-any
#include <OgnAddDatabase.h>
class OgnAdd:
{
public:
static bool compute(OgnAddDatabase& db)
{
// The extra work in handling extended types such as "any" or "union" is in checking the resolved types to
// first ensure they are handled and second select appropriate code paths if they differ from one type to
// another.
// Rather than clutter up the C++ code with a lot of type checking to follow the matrix of code paths
// required to handle all types this example will just perform addition on floats or doubles and report
// an error if any other type is encountered. (In practice this type of node is better implemented in Python
// where such flexible types are easily handled.)
const auto& a = db.inputs.a();
const auto& b = db.inputs.b();
auto& sum = db.outputs.sum();
// Unlike the normal type, a resolved type must be retrieved at runtime. Extra functionality is provided on
// the extended attribute type wrappers for this purpose.
//
// resolved() - Does the attribute currently have a resolved type?
// type() - omni::graph::core::Type information describing the resolved type
// typeName() - String identifying the type()
// get<X>() - Templated function to attempt conversion to the resolved type X
//
if (! a.resolved() || ! b.resolved())
{
db.logWarning("Cannot compute with an input type unresolved")
return false;
}
// For now the output type must be resolved by the graph as well, to ensure consistency.
// In future the type UNKNOWN may be acceptable for outputs, and the compute method can provide the
// type resolution itself.
if (! sum.resolved())
{
db.logWarning("Cannot compute with the output type unresolved")
return false;
}
// There are two ways of access the resolved type data. The first is explicit, where you check the type
// and then explicitly access the data, knowing it will correctly resolve. In this case the add will be
// really fussy and not even allow float+double, so the resolved types need to match exactly.
if ((a.type() != b.type()) || (a.type() != sum.type()))
{
db.logError("Can only add identical types - float or double. Got '%s'+'%s'='%s'",
a.typeName().c_str(), b.typeName().c_str(), sum.typeName().c_str());
return false;
}
// The second way is the Pythonic "ask forgiveness, not permission" method, where the get<X>() method is used
// to attempt to cast to a specific type and it moves on if it fails. This is possible because the get<X>()
// methods do not return direct references to the Fabric data, they return a wrapper around the data that
// provides the same types of access that the normal attribute type wrappers provide, plus a cast operator to
// a bool so that you can quickly check if a cast to a resolved type succeeded.
//
// Note the use of the single "=" assignment to keep the code cleaner.
// Also not the return type is just "auto", not "auto&" or "const auto&". That is because the wrapper must be
// created at runtime so it cannot be cached. The wrapper types are simple so copying is fast.
//
if (auto aValue = a.get<float>())
{
// We've guaranteed above that the resolved types are the same so their retrieval can be assumed to succeed
auto sumValue = sum.get<float>();
auto bValue = b.get<float>();
// The tricky part here is that the actual value still has to be retrieved from the wrapper, and that is
// done by dereferencing it.
*sumValue = *aValue + *bValue;
// The type of "sum" is a wrapper class, the type of "*sum" (or "sum->") is a float&
}
else if (auto aValue = a.get<double>())
{
// You can shorten the operation if you're careful about the placement of the dereferences
*(sum.get<double>()) = *aValue + *(b.get<double>());
}
else
{
// If you want a complete node then you'd continue this cascading type check, even including the
// array and tuple types, such as get<double[]>(), get<double[3]>() and get<double[][3]>(). The types
// supported by the get<X>() method are limited to raw data types, not explicit attribute types.
// For example if you wanted a colord[3] attribute you'd have to do a two-step check for both underlying
// type and attribute role like this:
// if ((auto colorValue = a.get<double[3]>()) && (a.role() == AttributeRole::eColor))
db.logError("Input type '%s' not currently supported by the Add node", a.typeName().c_str());
return false;
}
return true;
}
};
REGISTER_OGN_NODE()
// end-any
// begin-union
#include <OgnMultiplyNumbersDatabase.h>
class OgnMultiplyNumbers:
{
public:
static bool compute(OgnMultiplyNumbersDatabase& db)
{
// Full details on handling extended types can be seen in the example for the "any" type. This example
// shows only the necessary parts to handle the two types accepted for this union type (float and double).
// The underlying code is all the same, the main difference is in the fact that the graph only allows
// resolving to types explicitly mentioned in the union, rather than any type at all.
const auto& a = db.inputs.a();
const auto& b = db.inputs.b();
auto& product = db.outputs.product();
bool handledType{ false };
if (auto aValue = a.get<float>())
{
if (auto bValue = b.get<float>())
{
if (auto productValue = product.get<float>())
{
handledType = true;
*productValue = *aValue * *bValue;
}
}
}
else if (auto aValue = a.get<double>())
{
if (auto bValue = b.get<double>())
{
if (auto productValue = product.get<double>())
{
handledType = true;
*productValue = *aValue * *bValue;
}
}
}
if (! handledType)
{
db.logError("Types were not resolved ('%s'*'%s'='%s')",
a.typeName().c_str(), b.typeName().c_str(), product.typeName().c_str());
return false;
}
return true;
}
};
REGISTER_OGN_NODE()
// end-union
// begin-compute-helpers
#include <OgnAddDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnAddDatabase& db)
{
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);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnAddDatabase& db)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result[i] = a[i] + b[i];
};
return ogn::compute::tryComputeWithTupleBroadcasting<T, N>(db.inputs.a(), db.inputs.b(), db.outputs.sum(), functor);
}
} // namespace
class OgnAdd
{
public:
static bool compute(OgnAddDatabase& db)
{
try
{
// All possible types excluding ogn::string and bool
// scalers
auto& aType = db.inputs.a().type();
switch (aType.baseType)
{
case BaseDataType::eDouble:
switch (aType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db);
case 2: return tryComputeAssumingType<double, 2>(db);
case 3: return tryComputeAssumingType<double, 3>(db);
case 4: return tryComputeAssumingType<double, 4>(db);
case 9: return tryComputeAssumingType<double, 9>(db);
case 16: return tryComputeAssumingType<double, 16>(db);
}
case BaseDataType::eFloat:
switch (aType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db);
case 2: return tryComputeAssumingType<float, 2>(db);
case 3: return tryComputeAssumingType<float, 3>(db);
case 4: return tryComputeAssumingType<float, 4>(db);
}
case BaseDataType::eHalf:
switch (aType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db);
}
case BaseDataType::eInt:
switch (aType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db);
case 2: return tryComputeAssumingType<int32_t, 2>(db);
case 3: return tryComputeAssumingType<int32_t, 3>(db);
case 4: return tryComputeAssumingType<int32_t, 4>(db);
}
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db);
}
}
catch (ogn::compute::InputError &error)
{
db.logWarning(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token())
auto b = node.iNode->getAttributeByToken(node, inputs::b.token())
auto sum = node.iNode->getAttributeByToken(node, outputs::sum.token())
auto aType = a.iAttribute->getResolvedType(a);
auto bType = b.iAttribute->getResolvedType(b);
// Require inputs to be resolved before determining sum's type
if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { a, b, sum };
// a, b, and sum should all have the same tuple count
std::array<uint8_t, 3> tupleCounts {
aType.componentCount,
bType.componentCount,
std::max(aType.componentCount, bType.componentCount)
};
std::array<uint8_t, 3> arrayDepths {
aType.arrayDepth,
bType.arrayDepth,
// Allow for a mix of singular and array inputs. If any input is an array, the output must be an array
std::max(aType.arrayDepth, bType.arrayDepth)
};
std::array<AttributeRole, 3> rolesBuf {
aType.role,
bType.role,
// Copy the attribute role from the resolved type to the output type
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
// begin-bundle
#include <OgnMergeBundlesDatabase.h>
class OgnMergeBundle:
{
public:
static bool compute(OgnMergeBundlesDatabase& db)
{
const auto& bundleA = db.inputs.bundleA();
const auto& bundleB = db.inputs.bundleB();
auto& mergedBundle = db.outputs.bundle();
// Bundle assignment means "assign all of the members of the RHS bundle to the LHS bundle". It doesn't
// do a deep copy of the bundle members.
mergedBundle = bundleA;
// Bundle insertion adds the contents of a bundle to an existing bundle. The bundles may not have members
// with the same names
mergedBundle.insertBundle( bundleB );
return true;
}
};
REGISTER_OGN_NODE()
// end-bundle
// begin-bundle-data
#include <OgnCalculateBrightnessDatabase.h>
class OgnCalculateBrightness:
{
public:
// The actual algorithm to run using a well-defined conversion
static float brightnessFromRGB(float r, float g, float b)
{
return (r * (299.f) + (g * 587.f) + (b * 114.f)) / 256.f;
}
static bool compute(OgnCalculateBrightnessDatabase& db)
{
// Retrieve the bundle accessor
const auto& color = db.inputs.color();
// Using the bundle accessor, try to retrieve the RGB color members. In this case the types have to be
// float, though in a more general purpose node you might also allow for double, half, and int types.
const auto r = color.attributeByName(db.tokens.r).get<float>();
const auto g = color.attributeByName(db.tokens.g).get<float>();
const auto b = color.attributeByName(db.tokens.b).get<float>();
// Validity of a member is a boolean
if (r && g && b)
{
db.outputs.brightness() = brightnessFromRGB(r, g, b);
return true;
}
// Having failed to extract RGB members, do the same check for CMYK members
const auto c = color.attributeByName(db.tokens.c).get<float>();
const auto m = color.attributeByName(db.tokens.m).get<float>();
const auto y = color.attributeByName(db.tokens.y).get<float>();
const auto k = color.attributeByName(db.tokens.k).get<float>();
if (c && m && y && k)
{
db.outputs.brightness() = brightnessFromRGB(
(1.f - c/100.f) * (1.f - k/100.f),
(1.f - m/100.f) * (1.f - k/100.f),
(1.f - y/100.f) * (1.f - k/100.f) );
return true;
}
// You could be more verbose about the reason for the problem as there are a few different scenarios:
// - some but not all of r,g,b or c,m,y,k were in the bundle
// - none of the color components were in the bundle
// - some or all of the color components were found but were of the wrong data type
db.logError("Neither the groups (r, g, b) nor (c, m, y, k) are in the color bundle. Cannot compute brightness");
return false;
}
};
REGISTER_OGN_NODE()
// end-bundle-data
// begin-memory-type
#include <OgnMemoryTypeDatabase.h>
class OgnMemoryType:
{
public:
static bool compute(OgnMemoryTypeDatabase& db)
{
// The operation specifies moving the points data onto the GPU for further computation if the size of
// the input data reaches a threshold where that will make the computation more efficient.
// (This particular node just moves data; in practice you would perform an expensive calculation on it.)
if (db.inputs.points.size() > db.inputs.sizeThreshold())
{
// The gpu() methods force the data onto the GPU. They may or may not perform CPU->GPU copies under the
// covers. Fabric handles all of those details so that you don't have to.
db.outputs.points.gpu() = db.inputs.points.gpu();
}
else
{
// The gpu() methods force the data onto the CPU. They may or may not perform GPU->CPU copies under the
// covers. Fabric handles all of those details so that you don't have to.
db.outputs.points.cpu() = db.inputs.points.cpu();
}
return true;
}
};
REGISTER_OGN_NODE()
// end-memory-type
// begin-cuda-pointers
#include <OgnCudaPointersDatabase.h>
extern "C" callCudaFunction(inputs::cudaPoints_t, outputs::cudaPoints_t);
class OgnCudaPointers:
{
public:
static bool compute(OgnCudaPointersDatabase& db)
{
// When the *cudaPointers* keyword is set to *cpu* this wrapped array will contain a CPU pointer that
// references the GPU array data. If not, it would have contained a GPU pointer that references the GPU
// array data and not been able to be dereferenced on the CPU side.
callCudaFunction(db.inputs.cudaPoints(), db.outputs.cudaPoints());
return true;
}
};
REGISTER_OGN_NODE()
// end-cuda-pointers
// begin-attribute-metadata
#include <OgnStarWarsCharactersDatabase.h>
#include <alloca.h>
class OgnStarWarsCharacters:
{
public:
static bool compute(OgnStarWarsCharactersDatabase& db)
{
auto nodeTypeObj = db.abi_node().getNodeTypeObj(db.abi_node());
auto anakinObj = db.abi_node().getAttribute(db.abi_node(), inputs::anakin.token());
// Specifically defined metadata can be accessed by name
std::cout << "Anakin's secret is " << anakinObj->getMetadata(anakinObj, "secret") << std::endl;
// Some metadata is automatically added; you can see it by iterating over all of the existing metadata
size_t metadataCount = anakinObj->getMetadataCount(anakinObj);
char const** metadataKeyBuffer = reinterpret_cast<char const**>(alloca(sizeof(char*) * metadataCount));
char const** metadataValueBuffer = reinterpret_cast<char const**>(alloca(sizeof(char*) * metadataCount));
size_t found = anakinObj->getAllMetadata(anakinObj, metadataKeyBuffer, metadataValueBuffer, metadataCount);
for (size_t i=0; i<found; ++i)
{
std:: cout << "Metadata for " << metadataKeyBuffer[i] << " = " << metadataValueBuffer[i] << std::endl;
}
return true;
}
};
REGISTER_OGN_NODE()
// end-attribute-metadata
// begin-optional
#include <OgnShoesDatabase.h>
#include <string>
#include <stdlib.h>
class OgnShoes:
{
public:
static bool compute(OgnShoesDatabase& db)
{
static std::string[] _shoeTypes{ "Runners", "Slippers", "Oxfords" };
auto shoeIndex = rand() % 3;
std::string shoeTypeName{ _shoeTypes[shoeIndex] };
// If the shoe is a type that has laces then append the lace type name
if (shoeIndex != 1)
{
// As this is an optional value it may or may not be valid at this point.
const auto& shoelaceStyle = db.inputs.shoelaceStyle();
// This happens automatically with required attributes. With optional ones it has to be done when used.
if (db.inputs.shoeLaceStyle.isValid())
{
shoeTypeName += " with ";
shoeTypeName += db.tokenToString(shoelaceStyle);
shoeTypeName += " laces";
}
}
db.outputs.shoeType() = shoeTypeName;
return true;
}
};
REGISTER_OGN_NODE()
// end-optional
// begin-attribute-uiName
#include <OgnAttributeUiNameDatabase.h>
class OgnAttributeUiName:
{
public:
static bool compute(OgnAttributeUiNameDatabase& db)
{
// The uiName value is just a special case of metadata.
// Note the use of the namespace-enabled "inputs" value that provides access to an attribute's static name.
auto attributeObj = db.abi_node().iNode->getAttribute(db.abi_node(), inputs::x.token());
std::cout << "Call me " << attributeObj.iAttribute->getMetadata(attributeObj, kOgnMetadataUiName) << std::endl;
return true;
}
};
REGISTER_OGN_NODE()
// end-attribute-uiName
// begin-attribute-uiType
#include <OgnAttributeUiTypeDatabase.h>
class OgnAttributeUiType:
{
public:
static bool compute(OgnAttributeUiTypeDatabase& db)
{
// The uiType value is just a special case of metadata.
auto attributeObj = db.abi_node().iNode->getAttribute(db.abi_node(), inputs::x.token());
std::cout << "The property panel ui type is " << attributeObj.iAttribute->getMetadata(attributeObj, kOgnMetadataUiType) << std::endl;
return true;
}
};
REGISTER_OGN_NODE()
// end-attribute-uiType
// begin-unvalidated
#include <OgnShoesDatabase.h>
#include <string>
#include <stdlib.h>
class OgnABTest:
{
public:
static bool compute(OgnABTestDatabase& db)
{
auto choice = db.outputs.choice();
auto outType = choice.type();
// Check to see which input is selected and verify that its data type matches the output resolved type
if (db.inputs.selectA())
{
const auto inputA = db.inputs.a();
if (! inputA.isValid() || (inputA.type() != outType))
{
db.logError("Mismatched types at input a - '%s' versus '%s'", inputA.type().getOgnTypeName(), outType.getOgnTypeName());
return false;
}
choice = inputA;
}
else
{
const auto inputF = db.inputs.b();
if (! inputB.isValid() || (inputB.type() != outType))
{
db.logError("Mismatched types at input b - '%s' versus '%s'", inputB.type().getOgnTypeName(), outType.getOgnTypeName());
return false;
}
choice = inputB;
}
return true;
}
};
REGISTER_OGN_NODE()
// end-unvalidated
// begin-state-node
#include <OgnCounterDatabase.h>
class OgnCounter:
{
// Simple state information that counts how many times this node has been evaluated
int m_evaluationCount{ 0 };
public:
static bool compute(OgnCounterDatabase& db)
{
// The state information is on the node so it is the template parameter
auto& state = db.internalState<OgnCounter>();
// This prints the message and updates the state information
std::cout << "This node has been evaluated " << state.m_evaluationCount++ << " times" << std::endl;
return true;
}
};
REGISTER_OGN_NODE()
// end-state-node
// begin-versioned-node
#include <OgnMultiplyDatabase.h>
class OgnMultiply:
{
public:
static bool compute(OgnMultiplyDatabase& db)
{
db.outputs.result() = db.inputs.a() * db.inputs.b() + db.inputs.offset();
return true;
}
// Simply declaring the function is enough to register it as an override to the normal ABI function
static bool updateNodeVersion(const GraphContextObj&, const NodeObj& nodeObj, int oldVersion, int newVersion)
{
if ((oldVersion == 1) && (newVersion == 2))
{
// Version upgrade manually adds the new attribute to the node.
constexpr float zero = 0.0f;
nodeObj.iNode->createAttribute(nodeObj, "inputs:offset", Type(BaseDataType::eFloat), &zero, nullptr, kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr);
return true;
}
// Always good practice to flag unknown version changes so that they are not forgotten
db.logError("Do not know how to upgrade Multiply from version %d to %d", oldVersion, newVersion);
return false;
}
};
REGISTER_OGN_NODE()
// end-versioned-node
| 41,156 | C++ | 37.71778 | 180 | 0.615001 |
omniverse-code/kit/exts/omni.graph.tools/docs/ogn_code_samples_python.rst | .. _ogn_code_samples_py:
OGN Code Samples - Python
=========================
This files contains a collection of examples for using the .ogn generated code from Python. There is no particular flow
to these examples, they are used as reference data for the :ref:`ogn_user_guide`.
In the examples below this import will be assumed when describing names from the OmniGraph API, in the spirit of
common usage for packages such as *numpy* or *pandas*:
.. code-block:: py
import omni.graph.core as og
.. contents::
.. _ogn_python_generated_database:
Python Generated Database
-------------------------
When the .ogn files are processed and the implementation language is set to *python* it generates a database file
through which all of the attribute data can be accessed. It also generates some utility functions that are useful in
the context of a compute function. For the file **OgnMyNode.ogn** the database class will be named **OgnMyNodeDatabase**
and can be imported directly from the generated `ogn` module inside your Python module.
.. code-block:: py
from omni.examples.ogn.OgnMyNodeDatabase import OgnMyNodeDatabase as database
Usually you will not need to import the file though as the compute method is passed an instance to it. The contents
of that database file will include these functions:
.. code-block:: py
db.log_error("Explanation of error") # Log an error in the compute
db.log_warning("Explanation of warning") # Log a warning in the compute
db.log_warn("Explanation of warning") # An alias for log_warning
db.inputs # Object containing accessors for all input attribute data
db.outputs # Object containing accessors for all output attribute data
db.state # Object containing accessors for all state attribute data
database.per_node_internal_state(node) # Class method to get the internal state data attached to a specific node
The attribute members of `db.inputs`, `db.outputs`, and `db.state` are all properties. The input setter can only be
used during node initialization.
.. _ogn_minimal_node_py:
Minimal Python Node Implementation
----------------------------------
Every Python node must contain a node class definition with an implementation of the ``compute`` method that takes the
database as a parameter and returns a boolean indicating if the compute succeeded. To enforce more stringent type
checking on compute calls, import the database definition for the declaration.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-minimal
:end-before: end-minimal
.. note::
For simplicity, the import will be omitted from subsequent examples.
:ref:`[C++ Version]<ogn_minimal_node_cpp>`
.. _ogn_metadata_node_py:
Python Node Type Metadata Access
--------------------------------
When node types have metadata added to them they can be accessed through the Python bindings to the node ABI.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-node-metadata
:end-before: end-node-metadata
:ref:`[C++ Version]<ogn_metadata_node_cpp>`
.. _ogn_node_with_icon_py:
Python Node Icon Location Access
--------------------------------
Specifying the icon location and color information creates consistently named pieces of metadata that the UI can use to
present a more customized visual appearance.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-node-icon
:end-before: end-node-icon
:ref:`[C++ Version]<ogn_node_with_icon_cpp>`
.. _ogn_scheduling_node_python:
Python Node Type Scheduling Hints
---------------------------------
Specifying scheduling hints makes it easier for the OmniGraph scheduler to optimize the scheduling of node evaluation.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-node-scheduling
:end-before: end-node-scheduling
:ref:`[C++ Version]<ogn_scheduling_node_cpp>`
.. _ogn_singleton_node_py:
Python Singleton Node Types
---------------------------
Specifying that a node type is a singleton creates a consistently named piece of metadata that can be checked to see
if multiple instances of that node type will be allowed in a graph or its child graphs. Attempting to create more than
one of such node types in the same graph or any of its child graphs will result in an error.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-node-singleton
:end-before: end-node-singleton
:ref:`[C++ Version]<ogn_singleton_node_cpp>`
.. _ogn_tags_node_py:
Python Node Type Tags
---------------------
Specifying the node tags creates a consistently named piece of metadata that the UI can use to present a more
friendly grouping of the node types to the user.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-node-tags
:end-before: end-node-tags
This example introduces a simple helper data structure ``og.MetadataKeys``, which contains strings set to the key
values of special internal metadata. These are metadata elements managed by the code generator. Using these names
ensures consistent access.
.. code-block:: py
og.MetadataKeys.ALLOWED_TOKENS # On attributes of type token, a CSV formatted comma-separated list of potential legal values for the UI
og.MetadataKeys.CATEGORIES # On node types, contains a comma-separated list of categories to which the node type belongs
og.MetadataKeys.DESCRIPTION # On attributes and node types, contains their description from the .ogn file
og.MetadataKeys.EXTENSION # On node types, contains the extension that owns this node type
og.MetadataKeys.HIDDEN # On attributes and node types, indicating to the UI that they should not be shown
og.MetadataKeys.ICON_PATH # On node types, contains the file path to the node's icon representation in the editor
og.MetadataKeys.ICON_BACKROUND_COLOR # On node types, overrides the background color of the node's icon
og.MetadataKeys.ICON_BORDER_COLOR # On node types, overrides the border color of the node's icon
og.MetadataKeys.SINGLETON # On node types its presence indicates that only one of the node type may be created in a graph
og.MetadataKeys.TAGS # On node types, a comma-separated list of tags for the type
og.MetadataKeys.UI_NAME # On attributes and node types, user-friendly name specified in the .ogn file
:ref:`[C++ Version]<ogn_tags_node_cpp>`
.. _ogn_tokens_node_py:
Python Token Access
-------------------
Python properties are used for convenience in accessing the predefined token values. As tokens are represented
directly as strings in Python there is no need to support translation between strings and tokens as there is in C++.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-tokens
:end-before: end-tokens
:ref:`[C++ Version]<ogn_tokens_node_cpp>`
.. _ogn_uiName_node_py:
Python Node Type UI Name Access
-------------------------------
Specifying the node UI name creates a consistently named piece of metadata that the UI can use to present a more
friendly name of the node type to the user.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-node-uiName
:end-before: end-node-uiName
:ref:`[C++ Version]<ogn_uiName_node_cpp>`
.. _ogn_simple_node_py:
Simple Python Attribute Data Type
---------------------------------
Accessors are created on the generated database class that return Python accessor objects that wrap the underlying
attribute data, which lives in Fabric. As Python does not have the same flexibility with numeric data types there
is some conversion performed. i.e. a Python number is always 64 bits so it must truncate when dealing with smaller
attributes, such as **int** or **uchar**.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-simple
:end-before: end-simple
:ref:`[C++ Version]<ogn_simple_node_cpp>`
.. _ogn_tuple_node_py:
Tuple Python Attribute Data Type
--------------------------------
Tuples, arrays, and combinations of these all use the ``numpy`` array types as return values as opposed to a plain
Python list such as ``List[float, float, float]``. This plays a big part in efficiency as the ``numpy`` arrays can
point directly to the Fabric data to minimize data copying.
Values are returned through the same kind of accessor as for simple data types, only differing in the returned data
types.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-tuple
:end-before: end-tuple
:ref:`[C++ Version]<ogn_tuple_node_cpp>`
.. _ogn_role_node_py:
Role Python Attribute Data Type
-------------------------------
Roles are stored in a parallel structure to the attributes as properties. For example ``db.inputs.color`` will have a
corresponding property ``db.role.inputs.color``. For convenience, the legal role names are provided as constants in
the database class. The list of role names corresponds to the role values in the omni.graph.core.AttributeRole enum:
- ROLE_COLOR
- ROLE_EXECUTION
- ROLE_FRAME
- ROLE_NORMAL
- ROLE_POINT
- ROLE_QUATERNION
- ROLE_TEXCOORD
- ROLE_TIMECODE
- ROLE_TRANSFORM
- ROLE_VECTOR
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-role
:end-before: end-role
:ref:`[C++ Version]<ogn_role_node_cpp>`
.. _ogn_array_node_py:
Array Python Attribute Data Type
--------------------------------
As with tuple values, all array values in Python are represented as ``numpy.array`` types.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-array
:end-before: end-array
:ref:`[C++ Version]<ogn_array_node_cpp>`
.. _ogn_tuple_array_node_py:
Tuple-Array Python Attribute Data Type
--------------------------------------
As with simple tuple values and array values the tuple-array values are also represented as ``numpy.array`` types.
The numpy objects returned use the Fabric memory as their storage so they can be modified directly when computing
outputs. As with regular arrays, you must first set the size required so that the right amount of memory can be
allocated by Fabric.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-tuple-array
:end-before: end-tuple-array
:ref:`[C++ Version]<ogn_tuple_array_node_cpp>`
.. _ogn_string_node_py:
String Python Attribute Data Type
---------------------------------
String attributes are a bit unusual in Python. In Fabric they are implemented as arrays of characters but they are
exposed in Python as plain old ``str`` types. The best approach is to manipulate local copies of the string and then
assign it to the result when you are finished.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-string
:end-before: end-string
.. important::
Although strings are implemented in Fabric as arrays the fact that strings are immutable in Python means you
don't want to use the array method of resizing (i.e. setting the `db.outputs.stringAttribute_size` property).
You can allocate it, but string elements cannot be assigned so there is no way to set the individual values.
:ref:`[C++ Version]<ogn_string_node_cpp>`
.. _ogn_any_node_py:
Extended Python Attribute Data Type - Any
-----------------------------------------
Extended attribute types have extra information that identifies the type they were resolved to at runtime. The access
to this information is achieved by wrapping the attribute value in the same way as :ref:`ogn_bundle_node_py`.
The Python property for the attribute returns an accessor rather than the value itself. This accessor has the
properties **".value"**, **".name"**, and **".type"** so that the type resolution information can be accessed directly.
In addition, variations of the **".value"** method specific to each memory space are provided as the properties
**".cpu_value"** and **".gpu_value"**.
For example, the value for the input named **a** can be found at ``db.inputs.a.value``, and its resolved type is at
``db.inputs.a.type``.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-union
:end-before: end-union
:ref:`[C++ Version]<ogn_any_node_cpp>`
The extended data types must all be resolved before calling into the compute method. The generated code
handles that for you, executing the equivalent of these calls for extended inputs **a** and **b**, and extended
output **sum**, preventing the call to ``compute()`` if any of the types are unresolved.
.. code-block:: python
if db.inputs.a.type.base_type == og.BaseDataType.UNKNOWN:
return False
if db.inputs.b.type.base_type == og.BaseDataType.UNKNOWN:
return False
if db.outputs.sum.type.base_type == og.BaseDataType.UNKNOWN:
return False
.. _ogn_union_node_py:
Extended Python Attribute Data Type - Union
-------------------------------------------
The generated interface for union types is exactly the same as for **any** types. There is just a tacit agreement that
the resolved types will always be one of the ones listed in the union type description.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-union
:end-before: end-union
:ref:`[C++ Version]<ogn_union_node_cpp>`
.. _ogn_bundle_node_py:
Bundle Python Attribute Data Type
---------------------------------
Bundle attribute information is accessed the same way as information for any other attribute type. As an aggregate,
the bundle can be treated as a container for attributes, without any data itself.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-bundle
:end-before: end-bundle
:ref:`[C++ Version]<ogn_bundle_node_cpp>`
.. _ogn_bundle_data_py:
When you want to get at the actual data, you use the bundle API to extract the runtime attribute accessors from the
bundle for those attributes you wish to process.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-bundle-data
:end-before: end-bundle-data
.. tip::
Although you access them in completely different ways the attributes that are bundle members use the same accessors
as the extended attribute types. See further information in :ref:`ogn_any_node_cpp`
This documentation for bundle access is pulled directly from the code. It removes the extra complication in the
accessors required to provide proper typing information for bundle members and shows the appropriate calls in the
bundle attribute API.
.. literalinclude:: ../../../../source/extensions/omni.graph/python/_impl/bundles.py
:language: cpp
:start-after: begin-bundle-interface-description
:end-before: end-bundle-interface-description
:ref:`[C++ Version]<ogn_bundle_data_cpp>`
.. _ogn_attribute_memory_type_py:
Python Attribute Memory Location
--------------------------------
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-memory-type
:end-before: end-memory-type
:ref:`[C++ Version]<ogn_attribute_memory_type_cpp>`
.. _ogn_node_categories_py:
Node Type Categories
--------------------
Categories are added as metadata to the node and can be accessed through the standard metadata interface.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-node-categories
:end-before: end-node-categories
:ref:`[C++ Version]<ogn_node_categories_cpp>`
.. _ogn_node_cudaPointers_py:
Python Attribute CPU Pointers to GPU Data
-----------------------------------------
.. note::
Although this value takes effect at the attribute level the keyword is only valid at the node level. All
attributes in a node will use the same type of CUDA array pointer referencing.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-cuda-pointers
:end-before: end-cuda-pointers
:ref:`[C++ Version]<ogn_node_cudaPointers_cpp>`
.. _ogn_metadata_attribute_py:
Python Attribute Metadata Access
--------------------------------
When attributes have metadata added to them they can be accessed through the ABI attribute interface.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-attribute-metadata
:end-before: end-attribute-metadata
:ref:`[C++ Version]<ogn_metadata_attribute_cpp>`
.. _ogn_optional_py:
Optional Python Attributes
--------------------------
Since Python values are extracted through the C++ ABI bindings they don't have a direct validity check so the validity
of optional attributes must be checked indirectly. If a Python attribute value returns the special **None** value then
the attribute is not valid. It may also raise a *TypeError* or *ValueError* exception, indicating there was a mismatch
between the data available and the type expected.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-optional
:end-before: end-optional
:ref:`[C++ Version]<ogn_optional_cpp>`
.. _ogn_uiName_attribute_py:
Python Attribute UI Name Access
-------------------------------
Specifying the attribute **uiName** creates a consistently named piece of metadata that the UI can use to present a more
friendly version of the attribute name to the user. It can be accessed through the regular metadata ABI, with some
constants provided for easier access.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-attribute-uiName
:end-before: end-attribute-uiName
:ref:`[C++ Version]<ogn_uiName_attribute_cpp>`
.. _ogn_uiType_attribute_py:
Python Attribute UI Type Access
-------------------------------
Specifying the attribute **uiType** tells the property panel that this attribute should be shown with custom widgets.
- For path, string, and token attributes, a ui type of "filePath" will show file browser widgets
- For 3- and 4-component numeric tuples, a ui type of "color" will show the color picker widget
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-attribute-uiType
:end-before: end-attribute-uiType
:ref:`[C++ Version]<ogn_uiType_attribute_cpp>`
.. _ogn_unvalidated_py:
Unvalidated Python Attributes
-----------------------------
For most attributes the generated code will check to see if the attribute is valid before it calls the `compute()`
function. unvalidated attributes will not have this check made. If you end up using their value then you must make the
call to the `is_valid()` method yourself first and react appropriately if invalid values are found. Further, for
attributes with extended types you must verify that they have successfully resolved to a legal type.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-unvalidated
:end-before: end-unvalidated
:ref:`[C++ Version]<ogn_unvalidated_cpp>`
.. _ogn_dynamic_attributes_py:
Dynamic Python Attributes
-------------------------
In addition to attributes statically defined through a .ogn file, you can also dynamically add attributes to a single
node by using the ABI call ``og.Node.create_attribute(...)``. When you do so, the Python database interface will
automatically pick up these new attributes and provide access to their data in exactly the same way as it does for
regular attributes. (i.e. ``db.inputs.X`` for the value, ``db.attributes.input.X`` for the underlying `og.Attribute`,
``db.roles.inputs.X`` for the attribute role, etc.)
The way you test for such an attribute's existence inside a ``compute()`` method is to capture the `AttributeError`
exception.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-dynamic
:end-before: end-dynamic
.. note::
There is no C++ equivalent to this feature. Dynamic attributes will be available on the Python accessors to the
C++ node but the C++ code can only access the attribute data by using the low level ABI.
.. _ogn_state_node_py:
Python Nodes With Internal State
--------------------------------
Unlike C++ classes it is not as easy to determine if a Python class contains data members that should be interpreted as
state information. Instead, the Python node class will look for a method called `internal_state()`, which should return
an object containing state information to be attached to a node. Once the internal state has been constructed it is not
modified by OmniGraph until the node is released, it is entirely up to the node how and when to modify the data.
That information will be in turn made accessible through the database class using the property `db.internal_state`.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-state-node
:end-before: end-state-node
:ref:`[C++ Version]<ogn_state_node_cpp>`
.. _ogn_versioned_node_py:
Python Nodes With Version Upgrades
----------------------------------
To provide code to upgrade a node from a previous version to the current version you must override the ABI function
`update_node_version()`. The current context and node to be upgraded are passed in, as well as the old version at which
the node was created and the new version to which it should be upgraded. Passing both values allows you to upgrade
nodes at multiple versions in the same code.
This example shows how a new attribute is added using the *og.Node* ABI interface.
.. literalinclude:: ogn_code_samples_python.py
:language: python
:start-after: begin-versioned-node
:end-before: end-versioned-node
:ref:`[C++ Version]<ogn_versioned_node_cpp>`
| 21,784 | reStructuredText | 38.111311 | 144 | 0.721126 |
omniverse-code/kit/exts/omni.graph.tools/docs/ogn_code_samples_python.py | # flake8: noqa
# This file contains snippets of example Python code to be imported by the OGN documentation.
# It's not actual running code itself, merely sections of code that illustrate a point
# It uses the reStructuredText code import with begin/end markings to cherry-pick relevant portions.
# The sections of code being referenced are demarqued by "begin-XX" and "end-XX".
# begin-minimal
# This line isn't strictly necessary. It's only useful for more stringent type information of the compute parameter.
# Note how the extra submodule "ogn" is appended to the extension's module to find the database file.
from ogn.examples.ogn.OgnNoOpDatabase import OgnNoOpDatabase
class OgnNoOp:
@staticmethod
def compute(db: OgnNoOpDatabase) -> bool:
"""This comment should describe the compute algorithm.
Running help() on the database class will provide the information from the node type description field in the
.ogn file. The information here should be a supplement to that, consisting of implementation notes.
"""
# This logs a warning to the console, once
db.log_warning("This node does nothing")
# The node is accessible through the database. Normally you don't have to check its validity as it
# will already be checked, it's just done here to illustrate access and error logging.
if db.node is None or not db.node.isValid():
# This logs an error to the console and should only be used for compute failure
db.log_error("The node being computed is not valid")
return False
return True
# end-minimal
# begin-node-metadata
class OgnNodeMetadata:
@staticmethod
def compute(db) -> bool:
# Specifically defined metadata can be accessed by name
print(f"The author of this node is {db.get_metadata('author')}")
# Some metadata is automatically added; you can see it by iterating over all of the existing metadata.
# The Python iteration interfaces with the C++ ABI to make it seem like the metadata is an iterable list.
for metadata_name, metadata_value in db.node.get_all_metadata():
print(f"Metadata for {metadata_name} is {metadata_value}")
return True
# end-node-metadata
# begin-node-icon
import omni.graph.tools.ogn as ogn
class OgnNodeWithIcon:
@staticmethod
def compute(db) -> bool:
# The icon path is just a special case of metadata. The hardcoded key is in the Python namespace
path = db.get_metadata(ogn.MetadataKeys.ICON_PATH)
color = db.get_metadata(ogn.MetadataKeys.ICON_COLOR)
background_color = db.get_metadata(ogn.MetadataKeys.ICON_BACKGROUND_COLOR)
border_color = db.get_metadata(ogn.MetadataKeys.ICON_BORDER_COLOR)
if path is not None:
print(f"Icon found at {path}")
print(f"...color override is {color}" if color is not None else "...using default color")
print(
f"...backgroundColor override is {background_color}"
if background_color is not None
else "...using default backgroundColor"
)
print(
f"...borderColor override is {border_color}"
if border_color is not None
else "...using default borderColor"
)
return True
# end-node-icon
# begin-node-scheduling
class OgnNodeSchedulingHints:
@staticmethod
def compute(db) -> bool:
scheduling_hints = db.abi_node.get_node_type().get_scheduling_hints()
# Ordinarily you would not need to access this scheduling hints as it is mainly for OmniGraph's use,
# however it is available through the ABI so you can access it at runtime if you wish.
print(f"Is this node threadsafe? {scheduling_hints.get_thread_safety()}")
return True
# end-node-scheduling
# begin-node-singleton
import omni.graph.tools.ogn as ogn
class OgnNodeSingleton:
@staticmethod
def compute(db) -> bool:
# The singleton value is just a special case of metadata. The hardcoded key is in the Python namespace
singleton_value = db.get_metadata(ogn.MetadataKeys.SINGLETON)
if singleton_value and singleton_value[0] == "1":
print("I am a singleton")
return True
# end-node-singleton
# begin-node-categories
import omni.graph.tools.ogn as ogn
class OgnNodeCategories:
@staticmethod
def compute(db) -> bool:
# The categories value is just a special case of metadata. The hardcoded key is in the Python namespace
categories_value = db.get_metadata(ogn.MetadataKeys.CATEGORIES)
if categories_value:
print(f"These are my categories {categories_value.split(',')}")
return True
# end-node-categories
# begin-node-tags
import omni.graph.tools.ogn as ogn
class OgnNodeTags:
@staticmethod
def compute(db) -> bool:
# The tags value is just a special case of metadata. The hardcoded key is in the Python namespace
print(f"My tags are {db.get_metadata(ogn.MetadataKeys.TAGS)}")
return True
# end-node-tags
# begin-tokens
class OgnNodeTokens:
@staticmethod
def compute(db) -> bool:
print(f"The name for red is {db.tokens.red}")
print(f"The name for green is {db.tokens.green}")
print(f"The name for blue is {db.tokens.blue}")
return True
# end-tokens
# begin-node-uiName
import omni.graph.core as og
class OgnNodeUiName:
@staticmethod
def compute(db) -> bool:
# The uiName value is just a special case of metadata. The hardcoded key is in the Python namespace
print("Call me ", db.get_metadata(ogn.MetadataKeys.UI_NAME))
return True
# end-node-uiName
# begin-simple
class OgnTokenStringLength:
@staticmethod
def compute(db) -> bool:
# Access pattern is "db", the database, "inputs", the attribute's access type, and "token", the name the
# attribute was given in the .ogn file
#
# Local variables can be used to clarify the intent, but are not necessary. As a matter of consistency we
# use PEP8 conventions for local variables. Attribute names may not exactly follow the naming conventions
# since they are mutually exclusive between C++ and Python (camelCase vs. snake_case)
token_to_measure = db.inputs.token
# Simple assignment to the output attribute's accessor is all you need to do to set the value, as it is
# pointing directly to that data.
db.outputs.length = len(token_to_measure)
return True
# end-simple
# begin-tuple
class OgnVectorMultiply:
@staticmethod
def compute(db) -> bool:
# The fact that everything is in numpy makes this kind of calculation trivial
db.outputs.product = db.inputs.vector1.reshape(4, 1) @ db.inputs.vector2.reshape(1, 4)
# Here db.inputs.vector1.shape = db.inputs.vector1.shape = (4,), db.outputs.product.shape = (4,4)
return True
# end-tuple
# begin-role
class OgnPointsToVector:
@staticmethod
def compute(db) -> bool:
# In Python the wrapper is only a property so the role has to be extracted from a parallel structure
if db.role.inputs.point1 != db.ROLE_POINT:
db.log_error(f"Cannot convert role {db.role.inputs.point1} to {db.ROLE_POINT}")
return False
if db.role.inputs.point2 != db.ROLE_POINT:
db.log_error(f"Cannot convert role {db.role.inputs.point2} to {db.ROLE_POINT}")
return False
if db.role.outputs.vector != db.ROLE_POINT:
db.log_error(f"Cannot convert role {db.role.inputs.vector} to {db.ROLE_VECTOR}")
return False
# The actual calculation is a trivial numpy call
db.outputs.vector = db.inputs.point2 - db.inputs.point1
return True
# end-role
# begin-array
import numpy as np
class OgnPartialSums:
@staticmethod
def compute(db) -> bool:
# This is a critical step, setting the size of the output array. Without this the array has no memory in
# which to write.
#
# As the Python wrapper is a property, in order to get and set the size a secondary property is introduced
# for array data types which have the same name as the attribute with "_size" appended to it. For outputs
# this property also has a setter, which accomplishes the resizing.
#
db.outputs.partialSums_size = db.inputs.array_size
# Always explicitly handle edge cases as it ensures your node doesn't disrupt evaluation
if db.outputs.partialSums_size == 0:
return True
# IMPORTANT:
# The data value returned from accessing the property is a numpy array whose memory location was
# allocated by Fabric. As such you cannot use the numpy functions that resize the arrays as they will
# not use Fabric data.
# However, since the array attribute data is wrapped in a numpy array you can use numpy functions that
# modify data in place to make efficient use of memory.
#
db.inputs.array.cumsum(out=db.outputs.partialSums)
# A second way you can assign array data is to collect the data externally and then do a simple list
# assignment. This is less efficient as it does a physical copy of the entire list, though more flexible as
# you can arbitrarily resize your data before assigning it. If you use this approach you skip the step of
# setting the output array size as the assignment will do it for you.
#
# # Using numpy
# output_list = np.cumsum(db.inputs.array)
# db.outputs.partialSums = output_list
#
# # Using Python lists
# output_list = [value for value in db.inputs.array]
# for index, value in enumerate(output_list[:-1]):
# output_list[index + 1] = output_list[index + 1] + output_list[index]
# db.outputs.partialSum = output_list
#
# # numpy is smart enough to do element-wise copy, but in this case you do have to preset the size
# output_list = np.cumsum(db.inputs.array)
# db.outputs.partialSums_size = db.inputs.array_size
# db.outputs.partialSums[:] = output_list[:]
#
return True
# end-array
# begin-tuple-array
class OgnCrossProducts:
@staticmethod
def compute(db) -> bool:
# It usually keeps your code cleaner if you put your attribute wrappers into local variables, avoiding
# the constant use of the "db.inputs" or "db.outputs" namespaces.
a = db.inputs.a
b = db.inputs.b
crossProduct = db.outputs.crossProduct
# This node chooses to make mismatched array lengths an error. You could also make it a warning, or just
# simply calculate the result for the minimum number of available values.
if db.inputs.a_size != db.inputs.b_size:
db.log_error(f"Input array lengths do not match - '{db.inputs.a_size}' vs. '{db.inputs.b_size}'")
return False
# As with simple arrays, the size of the output tuple-array must be set first to allocate Fabric memory.
db.outputs.crossProduct_size = db.inputs.a_size
# Edge case is easily handled
if db.inputs.a_size == 0:
return False
# The numpy cross product returns the result so there will be a single copy of the result onto the output.
# numpy handles the iteration over the array so this one line does the entire calculation.
crossProduct = np.cross(a, b)
# This common syntax will do exactly the same thing
# crossProduct[:] = np.cross(a, b)[:]
return True
# end-tuple-array
# begin-string
class OgnReverseString:
@staticmethod
def compute(db) -> bool:
# In Python the wrapper to string attributes provides a standard Python string object.
# As the wrapper is a property the assignment of a value uses the setter method to both allocate the
# necessary space in Fabric and copy the values.
db.outputs.result = db.inputs.original[::-1]
return True
# end-string
import numpy as np
# begin-any
import omni.graph.core as og
class OgnAdd:
@staticmethod
def compute(db) -> bool:
# The extra work in handling extended types such as "any" or "union" is in checking the resolved types to
# first ensure they are handled and second select appropriate code paths if they differ from one type to
# another.
# Unlike C++ the loose typing of the Python objects mean that there is no requirement for explicit casting
# of data into the resolve types. Instead, the much more flexible method of letting the numpy library do the
# work for us is employed. The add operation will perform any necessary type conversion, as will the assignment
# operator.
try:
db.outputs.sum.value = np.add(db.inputs.a.value, db.inputs.b.value)
except Exception as error:
# If numpy doesn't handle addition of the two input types, or assignment to the output type, then an
# exception will be thrown and the node can report the error.
db.log_error(f"Addition could not be performed: {error}")
return False
return True
# end-any
# begin-union
class OgnMultiplyNumbers:
@staticmethod
def compute(db) -> bool:
# Full details on handling extended types can be seen in the example for the "any" type. This example
# shows only the necessary parts to handle the two types accepted for this union type (float and double).
# The underlying code is all the same, the main difference is in the fact that the graph only allows
# resolving to types explicitly mentioned in the union, rather than any type at all.
# Use the exception system to implicitly check the resolved types. Unresolved types will not have accessible
# data and raise an exception.
try:
db.outputs.product = np.mult(db.inputs.a, db.inputs.b)
except Exception as error:
db.log_error(f"Multiplication could not be performed: {error}")
return False
return True
# end-union
# begin-bundle
class OgnMergeBundles:
@staticmethod
def compute(db) -> bool:
bundleA = db.inputs.bundleA
bundleB = db.inputs.bundleB
mergedBundle = db.outputs.bundle
# Bundle assignment means "assign all of the members of the RHS bundle to the LHS bundle". It doesn't
# do a deep copy of the bundle members.
mergedBundle = bundleA
# Bundle insertion adds the contents of a bundle to an existing bundle. The bundles may not have members
# with the same names
mergedBundle.insert_bundle(bundleB)
return True
# end-bundle
# begin-bundle-data
import omni.graph.core as og
FLOAT_TYPE = og.Type(og.BaseDataType.FLOAT)
class OgnCalculateBrightness:
def brightness_from_rgb(self, r: float, g: float, b: float) -> float:
"""The actual algorithm to run using a well-defined conversion"""
return (r * (299.0) + (g * 587.0) + (b * 114.0)) / 256.0
@staticmethod
def compute(db) -> bool:
# Retrieve the bundle accessor
color = db.inputs.color
# Using the bundle accessor, try to retrieve the RGB color members. In this case the types have to be
# float, though in a more general purpose node you might also allow for double, half, and int types.
r = color.attribute_by_name(db.tokens.r)
g = color.attribute_by_name(db.tokens.g)
b = color.attribute_by_name(db.tokens.b)
# Validity of a member is a boolean
if r.type == FLOAT_TYPE and g.type == FLOAT_TYPE and b.type == FLOAT_TYPE:
db.outputs.brightness.value = OgnCalculateBrightness.brightness_from_rgb(r.value, g.value, b.value)
return True
# Having failed to extract RGB members, do the same check for CMYK members
c = color.attribute_by_name(db.tokens.c)
m = color.attribute_by_name(db.tokens.m)
y = color.attribute_by_name(db.tokens.y)
k = color.attribute_by_name(db.tokens.k)
if c.type == FLOAT_TYPE and m.type == FLOAT_TYPE and y.type == FLOAT_TYPE and k.type == FLOAT_TYPE:
db.outputs.brightness.value = OgnCalculateBrightness.brightness_from_rgb(
(1.0 - c / 100.0) * (1.0 - k / 100.0),
(1.0 - m / 100.0) * (1.0 - k / 100.0),
(1.0 - y / 100.0) * (1.0 - k / 100.0),
)
return True
# You could be more verbose about the reason for the problem as there are a few different scenarios:
# - some but not all of r,g,b or c,m,y,k were in the bundle
# - none of the color components were in the bundle
# - some or all of the color components were found but were of the wrong data type
db.logError("Neither the groups (r, g, b) nor (c, m, y, k) are in the color bundle. Cannot compute brightness")
return False
# end-bundle-data
# begin-memory-type
class OgnMemoryType:
@staticmethod
def compute(db) -> bool:
# The operation specifies moving the points data onto the GPU for further computation if the size of
# the input data reaches a threshold where that will make the computation more efficient.
# (This particular node just moves data; in practice you would perform an expensive calculation on it.)
if db.inputs.points.size > db.inputs.sizeThreshold:
# The gpu property forces the data onto the GPU. It may or may not perform CPU->GPU copies under the
# covers. Fabric handles all of those details so that you don't have to.
db.outputs.points.gpu = db.inputs.points.gpu
else:
# The cpu property forces the data onto the CPU. It may or may not perform GPU->CPU copies under the
# covers. Fabric handles all of those details so that you don't have to.
db.outputs.points.cpu = db.inputs.points.cpu
return True
# end-memory-type
# begin-cuda-pointers
class OgnCudaPointers:
@staticmethod
def compute(db) -> bool:
# When the *cudaPointers* keyword is set to *cpu* this wrapped array will contain a CPU pointer that
# references the GPU array data. If not, it would have contained a GPU pointer that references the GPU
# array data and not been able to be dereferenced on the CPU side.
callCudaFunction(db.inputs.cudaPoints, db.outputs.cudaPoints)
return True
# end-cuda-pointers
# begin-dynamic
class OgnDynamicDuo:
@staticmethod
def compute(db) -> bool:
try:
# Testing for the existence of the dynamic input boolean attribute "Robin"
db.outputs.batman = "Duo" if db.inputs.robin else "Unknown"
except AttributeError:
db.outputs.batman = "Solo"
return True
# end-dynamic
# begin-optional
import random
from contextlib import suppress
class OgnShoes:
SHOE_TYPES = ["Runners", "Slippers", "Oxfords"]
@staticmethod
def compute(db) -> bool:
shoe_index = random.randint(0, 2)
shoe_type_name = OgnShoes.SHOE_TYPES[shoe_index]
# If the shoe is a type that has laces then append the lace type name
if shoe_index != 1:
# As this is an optional value it may or may not be valid at this point.
# This check happens automatically with required attributes. With optional ones it has to be done when used.
if db.attributes.inputs.shoeLaceStyle.isValid():
# The attribute may be valid but the data retrieval may still fail. In Python this is flagged in one of
# two ways - raising an exception, or returning None. Both indicate the possibility of invalid data.
# In this node we've chosen to silently ignore expected but invalid shoelace style values. We could
# equally have logged an error or a warning.
with suppress(ValueError, TypeError):
shoelace_style = db.inputs.shoelaceStyle
if shoelace_style is not None:
shoe_type_name += f" with {shoelace_style} laces"
db.outputs.shoeType = shoe_type_name
return True
# end-optional
# begin-attribute-uiName
import omni.graph.tools.ogn as ogn
class OgnAttributeUiName:
@staticmethod
def compute(db) -> bool:
# The uiName value is just a special case of metadata
print(f"Call me {db.get_metadata(ogn.MetadataKeys.UI_NAME, db.attributes.inputs.x)}")
return True
# end-attribute-uiName
# begin-attribute-uiType
import omni.graph.tools.ogn as ogn
class OgnAttributeUiType:
@staticmethod
def compute(db) -> bool:
# The uiType value is just a special case of metadata
print(f"The property panel ui type is {db.get_metadata(ogn.MetadataKeys.UI_TYPE, '(default)')}")
return True
# end-attribute-uiType
# begin-unvalidated
import omni.graph.core as og
class OgnABTest:
@staticmethod
def compute(db) -> bool:
choice = db.outputs.choice
out_type = choice.type
# Check to see which input is selected and verify that its data type matches the output resolved type
if db.inputs.selectA:
input_a = db.inputs.a
if not input_a.is_valid() or input_a.type != out_type:
db.log_error(
f"Mismatched types at input a - '{input_a.type.get_ogn_type_name()}' versus '{out_type.get_ogn_type_name()}'"
)
return False
choice.value = input_a.value
else:
input_b = db.inputs.b
if not input_b.is_valid() or input_b.type != out_type:
db.log_error(
f"Mismatched types at input b - '{input_b.type.get_ogn_type_name()}' versus '{out_type.get_ogn_type_name()}'"
)
return False
choice.value = input_b.value
return True
# end-unvalidated
# begin-attribute-metadata
import omni.graph.tools.ogn as ogn
class OgnStarWarsCharacters:
@staticmethod
def compute(db) -> bool:
anakin_attr = db.attributes.inputs.anakin
# Specifically defined metadata can be accessed by name
print(f"Anakin's secret is {db.get_metadata('secret', anakin_attr)}")
# Some metadata is automatically added; you can see it by iterating over all of the existing metadata.
for metadata_name, metadata_value in anakin_attr.get_all_metadata():
print(f"Metadata for {metadata_name} is {metadata_value}")
# You can also access it directly from the database's metadata interface, either from the node type...
print(f"Node UI Name is {db.get_metadata(ogn.MetadataKeys.UI_NAME)}")
# ...or from a specific attribute
print(f"Attribute UI Name is {db.get_metadata(ogn.MetadataKeys.UI_NAME, anakin_attr)}")
return True
# end-attribute-metadata
# begin-state-node
class OgnStateNode:
class State:
"""Container object holding the node's state information"""
def __init__(self):
self.counter = 0
@staticmethod
def internal_state():
"""Returns an object that will contain per-node state information"""
return OgnStateNode.State()
@staticmethod
def compute(db) -> bool:
print(f"This node has been evaluated {db.internal_state.counter} times")
db.internal_state.counter += 1
return True
# end-state-node
# begin-versioned-node
import carb
import omni.graph.core as og
class OgnMultiply:
@staticmethod
def compute(db) -> bool:
db.outputs.result = db.inputs.a * db.inputs.b + db.inputs.offset
return True
@staticmethod
def update_node_version(context, node, old_version, new_version):
if old_version == 1 and new_version == 3:
node.create_attribute("inputs:offset", og.Type(og.BaseDataType.FLOAT))
return True
# Always good practice to flag unknown version changes so that they are not forgotten
carb.log_error(f"Do not know how to upgrade Multiply from version {old_version} to {new_version}")
return False
# end-versioned-node
| 24,580 | Python | 34.937134 | 129 | 0.655167 |
omniverse-code/kit/exts/omni.graph.tools/docs/ogn_user_guide.rst | .. _ogn_user_guide:
OGN User Guide
==============
Now that you are ready to write an OmniGraph node the first thing you must do is create a node definition. The .ogn
format (short for **O** mni **G** raph **N** ode) is a JSON file that describes the node and its attributes.
Links to relevant sections of the :ref:`ogn_reference_guide` are included throughout, where you can find the
detailed syntax and semantics of all of the .ogn file elements.
OmniGraph nodes are best written by creating a .ogn file with a text editor, with the core algorithm
written in a companion C++ or Python file. There is also the :ref:`omnigraph_node_description_editor`, a work in
progress that will give you a user interface assist in populating your node description.
This document walks through the basics for writing nodes, accessing attribute data, and explains how the nodes fit into
the general ecosystem of the OmniGraph. To get a walkthrough of the node writing process by way of examples that build
on each other, from the simplest to most complex node go to the :ref:`ogn_tutorial_nodes`. This document will
reference relevant tutorials when appropriate, but is intended to be more of a one-stop shop for all features of
OmniGraph nodes.
In the interests of clarity the code samples are kept in a separate document for :ref:`C++<ogn_code_samples_cpp>` and
:ref:`Python<ogn_code_samples_py>` and referred to from here, rather than having everything embedded. If you are
reading this from a web browser you probably want to open a new tab for those links when you visit them.
.. contents::
..
.. note::
For the purpose of these examples the extension **ogn.examples** will be assumed, and names will follow the
established naming conventions.
.. warning::
The code referenced is for illustrative purposes only and some necessary elements may have been elided for
clarity. It may not work as-is.
Generated Files
+++++++++++++++
Before you can write any nodes you must first teach your extension how to build them. These instructions
are tailored for building using premake inside Omniverse Kit, with more generic information being provided to
adapt them to any build environment.
The core of the OmniGraph nodes is the .ogn file. Before actually writing a node you must enable processing of these
files in the build of your extension. If your extension doesn't already support it you can follow the steps in
:ref:`ogn_build_conversion` to add it.
What the build process adds is a step that runs the :ref:`OGN Generator Script<ogn_generation_script>` on your .ogn
file to optionally generate several files you will need for building, testing, running, and documenting your node.
Once you have your .ogn file created, with your build .ogn-enabled as described above, you can run the build with
just that file in place. If it all works you should see the following files added to the build directory. (PLATFORM
can be *windows-x86_64* or *linux-x86_64*, and VARIANT can be *debug* or *release*, depending on what you are
building.)
- *_build/ogn/include/OgnMyNodeDatabase.h*
- *_build/PLATFORM/VARIANT/exts/ogn.examples/docs/OgnMyNode.rst*
- *_build/PLATFORM/VARIANT/exts/ogn.examples/ogn/examples/ogn/OgnMyNode.py*
- *_build/PLATFORM/VARIANT/exts/ogn.examples/ogn/examples/tests/TestOgnMyNode.py*
- *_build/PLATFORM/VARIANT/exts/ogn.examples/ogn/examples/tests/data/OgnMyDatabaseTemplate.usda*
If these are not created, go back and check your build logs to confirm that your build is set up correctly and your
.ogn file was processed correctly.
.. note::
If your node is written in Python then the file *_build/ogn/include/OgnMyNodeDatabase.h* is unused and will not
be generated.
.. tip::
If you have an existing node you wish to convert to .ogn format then you can follow along with the detailed
example of a node's conversion found in :ref:`ogn_node_conversion`.
The Split OmniGraph Extension
+++++++++++++++++++++++++++++
Most extensions are implemented atomically, with all code supporting the feature in a single extension. The OmniGraph
core, however, was split into two. `omni.graph.core` is the basic support for nodes and their evaluation, and
`omni.graph` is the added support for Python bindings and scripts. You almost always want your extension to have a
dependency on `omni.graph`. The main reason for just using `omni.graph.core` is if you have a headless evaluation
engine that has no scripting or UI, just raw calculations, and all of your nodes are written in C++.
The Compute
+++++++++++
The primary function of a node is to use a set of attribute values as input to its algorithm, which generates a
set of output values. In its purest form the node compute operation will be purely functional; reading only received
input attributes and writing its defined output attributes. In this form the node is capable of taking advantage of
the maximum performance provided by threading and distributed computing.
However, we recognize that not all interesting calculations can be expressed in that way, and many times should not,
so OmniGraph is set up to handle more complex configurations such as self-contained subgraphs, internal structures,
and persistent state data, as well as combining all types of nodes into arbitrarily complex graphs.
As the node writer, what happens within the compute function is entirely up to you. The examples here are one possible
approach to these algorithms.
.. important::
It is important to note here that you should consider your node to be an island unto itself. It may live on a
different thread, CPU, GPU, or even physical computer than other nodes in the graph. To guarantee correct
functioning in all situations you should never inject or extract data to or from locations outside of your node. It
should behave as a standalone evaluation engine. This includes other nodes, user interfaces, USD data, and
anything else that is not part of the node's input or output attributes. Should your node require access to such
data then you must provide OmniGraph with the :ref:`ogn_keyword_node_scheduling` information.
Mandatory Node Properties
+++++++++++++++++++++++++
There are properties on the node that are required for every legal file. The node must have a name,
a :ref:`ogn_keyword_node_description`, and a :ref:`ogn_keyword_node_version`. Minimal node definition
which includes only those elements.
.. code-block:: json
{
"NoOp" : {
"description": "Minimal node that does nothing",
"version": 1
}
}
.. note::
As described in :ref:`omnigraph_naming_conventions` the actual unique name of this node will include the extension, and
will be ``ogn.examples.NoOp``.
These examples also illustrate some convenience functions added to the database that facilitate the reporting of
warnings or errors encountered during a node's operation. A warning might be something incidental like a deformer
running on an empty set of points. An error is for something serious like a divide-by-zero error in a calculation.
Using this reporting methods makes debugging node operations much easier. Generally speaking a warning will still
return true as the compute is successful, just not useful, whereas an error will return false indicating that the
compute could not be performed.
+---------------------------------------+-----------------------------------------+
| :ref:`C++ Code<ogn_minimal_node_cpp>` | :ref:`Python Code<ogn_minimal_node_py>` |
+---------------------------------------+-----------------------------------------+
Relevant tutorial - :ref:`ogn_tutorial_empty`.
Although it's not mandatory in every file, the keyword :ref:`ogn_keyword_node_language` is required when
you intend to implement your node in Python. For the above, and all subsequent examples, using the Python node
implementation requires this one extra line in your .ogn file. (C++ is the default so it isn't necessary for nodes
written in C++.)
.. code-block:: json
:emphasize-lines: 5
{
"NoOp" : {
"description": "Minimal node that does nothing in Python",
"version": 1,
"language": "python"
}
}
Secondary Node Properties
+++++++++++++++++++++++++
Some other node properties have simple defaults and need not always be specified in the file. These include
:ref:`ogn_keyword_node_exclude`,
:ref:`ogn_keyword_node_memoryType`,
:ref:`ogn_keyword_node_categories`,
:ref:`ogn_keyword_node_cudaPointers`,
:ref:`ogn_keyword_node_metadata`,
:ref:`ogn_keyword_node_scheduling`,
:ref:`ogn_keyword_node_tags`,
:ref:`ogn_keyword_node_tokens`, and
:ref:`ogn_keyword_node_uiName`.
Providing Scheduling Hints
--------------------------
The scheduler will try to schedule execution of the nodes in as efficient a manner as possible while still maintaining
safe evaluation constraints (e.g. by not scheduling two nodes in parallel that are not threadsafe).
Although it's not (yet) mandatory it is a good idea to provide a value for the :ref:`ogn_keyword_node_scheduling`
keyword so that the scheduler has as much information as possible on how to efficiently scheduler your nodes. The
ideal node has *"scheduling": "threadsafe"*, meaning it is safe to schedule that node in parallel with any other
nodes.
Excluding Generated Files
-------------------------
If for some reason you want to prevent any of the normally generated files from being created you can do so within the
.ogn file with the :ref:`ogn_keyword_node_exclude` keyword. For example you might be in a C++-only environment and want
to prevent the Python test scripts and database access file from being created.
.. code-block:: json
:emphasize-lines: 5
{
"NoOp" : {
"description": "Minimal node that does nothing without Python support",
"version": 1,
"exclude": ["python", "tests"]
}
}
In addition to the five generated file types listed above the reference guide shows that you can also exclude
something called **"template"**. This file, if generated, would be a blank implementation of your node, in the
language you've selected. It's not normally generated by the build, though it is useful for manual generation when
you first start implementing a node. The :ref:`omnigraph_node_description_editor` uses this option to give you a
blank node implementation to start with. Adding it to the exclusion list will prevent that.
Relevant tutorial - :ref:`ogn_tutorial_abi`.
.. _ogn_using_gpu_data:
Using GPU Data
--------------
Part of the benefit of using the .ogn format is that it's purely descriptive so it can handle nodes implemented in
different languages and nodes that run on the CPU, the GPU, or both.
The keyword :ref:`ogn_keyword_node_memoryType` is used to specify where the attribute data on a node should live.
By default all of the node data lives on the CPU, however you can use this keyword to tell
:ref:`omnigraph_concept_fabric` that the data instead lives on the GPU, in particular in CUDA format.
.. code-block:: json
:emphasize-lines: 5
{
"NoOp" : {
"description": "Minimal node that does nothing on the GPU",
"version": 1,
"memoryType": "cuda"
}
}
Until you have attributes, though, this keyword has not effect. It is only the attribute's data that lives on
:ref:`omnigraph_concept_fabric`. See :ref:`ogn_overriding_memory_location` for details on how it affects the code
that access the attribute data.
Relevant tutorials - :ref:`ogn_tutorial_cudaData` and :ref:`ogn_tutorial_cpuGpuData`.
By default the memory references of CUDA array data will be GPU-pointer-to-GPU-pointer, for convenience in facilitating
the use of arrays of arrays in an efficient manner. For single arrays, though, this may not be desirable and you might
wish to just use a CPU-pointer-to-GPU-pointer so that it can be dereferenced on the CPU side. To do so you can add
the *cudaPointers* keyword with your memory definition.
.. code-block:: json
:emphasize-lines: 6
{
"NoOp" : {
"description": "Minimal node that does nothing on the GPU",
"version": 1,
"memoryType": "cuda",
"cudaPointers": "cpu"
}
}
Adding Metadata To A Node Type
------------------------------
Node types can have a metadata dictionary associated with them that can be added through the
:ref:`ogn_keyword_node_metadata` keyword.
.. code-block:: json
:emphasize-lines: 5-7
{
"NodeMetadata" : {
"description": "Minimal node that has some metadata",
"version": 1,
"metadata": {
"author": "Bertram P. Knowedrighter"
}
}
}
.. note::
This is not the same as USD metadata. It is only accessible through the OmniGraph node type.
.. tip::
Although all metadata is stored as a string:string mapping in OmniGraph, you can specify a list of strings
in the .ogn file. It will be changed into a single CSV formatted comma-separated string. For example the list
["red", "green", "blue"] results in a single piece of metadata with the value "red,green,blue". The CSV escape
mechanism is used for strings with embedded commas, so the list ["red,green", "blue"] results in the similar but
different metadata "'red,green',blue". Any CSV parser can be used to safely extract the list of values. If your
metadata does not contain commas then a simple tokenizer will also work.
+----------------------------------------+------------------------------------------+
| :ref:`C++ Code<ogn_metadata_node_cpp>` | :ref:`Python Code<ogn_metadata_node_py>` |
+----------------------------------------+------------------------------------------+
Adding Categories To A Node Type
--------------------------------
Node types can have a categories associated with them that can be added through the
:ref:`ogn_keyword_node_categories` keyword. These serve as a common method of grouping similar node types together,
mostly to make the UI easier to navigate.
.. code-block:: json
:emphasize-lines: 5-7
{
"NodeCategories" : {
"description": "Minimal math array conversion node",
"version": 1,
"categories": ["math:array", "math:conversion"]
}
}
For a more detailed example see the :ref:`omnigraph_node_categories` "how-to".
+------------------------------------------+--------------------------------------------+
| :ref:`C++ Code<ogn_node_categories_cpp>` | :ref:`Python Code<ogn_node_categories_py>` |
+------------------------------------------+--------------------------------------------+
Alternative Icon Location
-------------------------
If the node file *OgnMyNode.ogn* has a file in the same directory named *OgnMyNode.svg* then that file will
automatically be promoted to be the node's icon. If you wish to arrange your icons in a different way then you can
specify a different location for the icon file using the :ref:`ogn_keyword_node_icon` keyword.
The icon path will be relative to the directory in which the *.ogn* file lives so be sure to set your path
accordingly. (A common location might be the *icons/* subdirectory.)
.. code-block:: json
:emphasize-lines: 5-7
{
"NodeWithOtherIcon" : {
"description": "Minimal node that uses a different icon",
"version": 1,
"icon": "icons/CompanyLogo.svg"
}
}
.. note::
This file will be installed into the build area in your extension directory, under the subdirectory *ogn/icons/*
so you don't have to install it into the build separately.
When the icon is installed you can get at it by using the extension manager's ability to introspect its own path.
Sometimes you might also wish to change the coloring of the icon. By default all of the colors are the same. Using this
extended syntax for the icon specification lets you override the shape, border, and background color of the icon using
either a **#AABBGGRR** hexadecimal format or a **[R, G, B, A]** decimal format.
.. code-block:: json
:emphasize-lines: 5-10
{
"NodeWithOtherColoredIcon" : {
"description": "Minimal node that uses a different colored icon",
"version": 1,
"icon": {
"path": "icons/CompanyLogo.svg",
"color": "#FF223344",
"backgroundColor": [255, 0, 0, 0],
"borderColor": [255, 128, 0, 128]
}
}
}
+-----------------------------------------+-------------------------------------------+
| :ref:`C++ Code<ogn_node_with_icon_cpp>` | :ref:`Python Code<ogn_node_with_icon_py>` |
+-----------------------------------------+-------------------------------------------+
.. tip::
Although the node type icon information is set through the generated code, it is encoded in metadata and as such
can be modified at runtime if you wish to further customize your look.
Singleton Node Types
--------------------
For some types of nodes it is undesirable to have more than one of them per graph, including any child graphs. To add
this restriction a node can be marked as a "singleton" using the :ref:`ogn_keyword_node_singleton` keyword. It is a
shortcut to defining specially named metadata whose presence will prevent more than one node of that type being
instantiated.
.. code-block:: json
:emphasize-lines: 5-7
{
"SingletonNode" : {
"description": "Minimal node that can only be instantiated once per graph",
"version": 1,
"singleton": true
}
}
.. note::
Node types with this flag set are not true singletons in the programming sense. You can instantiate more than one
of them. The restriction is that they have to be in different graphs.
+-----------------------------------------+---------------------------------------------+
| :ref:`C++ Code<ogn_singleton_node_cpp>` | :ref:`Python Code<ogn_singleton_node_py>` |
+-----------------------------------------+---------------------------------------------+
Node Tags
---------
Nodes can often be grouped in collections orthogonal to their extension owners or names - e.g. you might want the nodes
*Add*, *Multiply*, and *Divide* to appear in a math collection, even though they may have been implemented in three
unrelated extensions. This information appears in the internal metadata value ``tags``.
Since it is so common, a more succinct method of specifying it is available with the :ref:`ogn_keyword_node_tags`
keyword. It is a shortcut to defining that specially named metadata. Also, if it is specified as a list the tags
string will contain the list of names separated by a comma, so these two definitions generate identical code:
.. code-block:: json
:emphasize-lines: 5-7
{
"NodeTagged" : {
"description": "Minimal node with keyword tags",
"version": 1,
"metadata": {
"tags": "cool,new,improved"
}
}
}
.. code-block:: json
:emphasize-lines: 5
{
"NodeTagged" : {
"description": "Minimal node with keyword tags",
"version": 1,
"tags": ["cool", "new", "improved"]
}
}
+------------------------------------+----------------------------------------+
| :ref:`C++ Code<ogn_tags_node_cpp>` | :ref:`Python Code<ogn_tags_node_py>` |
+------------------------------------+----------------------------------------+
Relevant tutorial - :ref:`ogn_tutorial_tupleData`.
String Tokens
-------------
A token is a unique ID that corresponds to an arbitrary string. A lot of the ABI makes use of tokens where the
choices of the string values are limited, e.g. the attribute types, so that fast comparisons can be made. Using tokens
requires accessing a token translation ABI, leading to a lot of duplicated boilerplate code to perform the common
operation of translating a string into a token, and vice-versa. In addition, the translation process could be slow,
so in order to experience the benefits of using a token it should only be done once where possible.
To make this easier, the :ref:`ogn_keyword_node_tokens` keyword is provided in the .ogn file to predefine a set of
tokens that the node will be using. For example if you are going to look up a fixed set of color names at runtime
you can define the color names as tokens.
.. code-block:: json
:emphasize-lines: 5
{
"Tokens" : {
"description": "Minimal node that has some tokens",
"version": 1,
"tokens": ["red", "green", "blue"]
}
}
When you use the alternative token representation you still access the tokens by the simplified name. So this
definition, although the actual token values are different, uses the same code to access those values.
.. code-block:: json
:emphasize-lines: 5
{
"Tokens" : {
"description": "Minimal node that has some tokens",
"version": 1,
"tokens": {"red": "Candy Apple Red", "green": "English Racing Green", "blue": "Sky Blue"}
}
}
As an added simplification, a simple interface to convert between tokens and strings is added to the database code
for nodes in C++. It isn't necessary in Python since Python represents tokens directly as strings.
+--------------------------------------+----------------------------------------+
| :ref:`C++ Code<ogn_tokens_node_cpp>` | :ref:`Python Code<ogn_tokens_node_py>` |
+--------------------------------------+----------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_tokens`, :ref:`ogn_tutorial_bundle_manipulation`,
:ref:`ogn_tutorial_extended_types`, and :ref:`ogn_tutorial_simpleData`.
.. caution::
Although the simplified token access is implemented in Python, ultimately Python string comparisons are all
done as strings, not as token IDs, due to the nature of Python so that code is for convenience, not efficiency.
Providing A User-Friendly Node Type Name
----------------------------------------
While the unique node type name is useful for keeping things well organized it may not be the type of name you would want
to see, e.g. in a dropdown interface when selecting the node type. A specially named metadata value has been reserved
for that purpose, to give a consistent method of specifying a more user-friendly name for the node type.
Since it is so common, a more succinct method of specifying it is available with the :ref:`ogn_keyword_node_uiName`
keyword. It is a shortcut to defining that specially named metadata, so these two definitions generate identical code:
.. code-block:: json
:emphasize-lines: 5-7
{
"NodeUiName" : {
"description": "Minimal node with a UI name",
"version": 1,
"metadata": {
"uiName": "Node With A UI Name"
}
}
}
.. code-block:: json
:emphasize-lines: 5
{
"NodeUiName" : {
"description": "Minimal node with a UI name",
"version": 1,
"uiName": "Node With A UI Name"
}
}
+--------------------------------------+----------------------------------------+
| :ref:`C++ Code<ogn_uiName_node_cpp>` | :ref:`Python Code<ogn_uiName_node_py>` |
+--------------------------------------+----------------------------------------+
Almost every tutorial in :ref:`ogn_tutorial_nodes` make use of this special piece of metadata.
Attribute Definitions
---------------------
Attributes define the data flowing in and out of the node during evaluation. They are divided into three different
locations with different restrictions on each location.
.. code-block:: json
:emphasize-lines: 5-13
{
"NodeWithEmptyAttributes" : {
"description": "Minimal node with empty attribute lists",
"version": 1,
"inputs": {
"NAME": { "ATTRIBUTE_PROPERTY": "PROPERTY_VALUE" }
},
"outputs": {
"NAME": { "ATTRIBUTE_PROPERTY": "PROPERTY_VALUE" }
},
"state": {
"NAME": { "ATTRIBUTE_PROPERTY": "PROPERTY_VALUE" }
}
}
}
Each attribute section contains the name of an attribute in that location. See :ref:`omnigraph_naming_conventions` for a
description of allowable names. The properties in the attribute definitions are described below in the sections on
:ref:`ogn_mandatory_attribute_properties` and :ref:`ogn_secondary_attribute_properties`.
**inputs** are treated as read-only during a compute, and within the database interface to the attribute data. The
input values can only be set through a command, or the ABI. This is intentional, and should not be overridden as it
could cause graph evaluation to become incorrect or unstable.
**outputs** are values the node is to generate during a compute. From one evaluation to another they are not guaranteed
to be valid, or even exist, so it is the node's responsibility to define them and set their values during the compute.
(Optimizations to this process exist, but are beyond the scope of this document.)
**state** attributes persist from one evaluation to the next and are readable and writable. It is the node's
responsibility to ensure that they initialize correctly, either by explicit initialization in the node or through
use of a recognizable default value that indicate an uninitialized state.
Other than the access restrictions described above the attributes are all described in the same way so any
of the keywords descriptions shown for one attribute location type can be used for any of them.
Automatic Test Definitions
--------------------------
It is always a good idea to have test cases for your node to ensure it is and continues to be operating correctly.
The .ogn file helps with this process by generating some simple test scenarios automatically, along with a script
that will exercise them within the test environment.
.. code-block:: json
:emphasize-lines: 5
{
"NodeWithEmptyAttributes" : {
"description": "Minimal node with empty attribute lists",
"version": 1,
"tests": [
{ "TEST_PROPERTY": "TEST_VALUE" }
]
}
}
This subsection will contain a list of such test definitions. More detail on the **TEST_PROPERTY** values is
available in the discussion on :ref:`ogn_defining_automatic_tests`.
.. _ogn_mandatory_attribute_properties:
Mandatory Attribute Properties
++++++++++++++++++++++++++++++
All attributes in any location subsection has certain minimally required properties. The attribute must have a name,
a :ref:`ogn_keyword_attribute_description`, and a :ref:`ogn_keyword_attribute_type`. This is a minimal node definition
with one simple integer value attribute.
.. code-block:: json
{
"Ignore" : {
"description": "Ignore an integer value",
"version": 1,
"inputs": {
"x": {
"description": "Value to be ignored",
"type": "int"
}
}
}
}
The value of the **"type"** property can create very different interfaces to the underlying data. Although the
syntax in the file is the same for every type (with one exception, explained below) the generated access methods are
tuned to be natural for the type of underlying data. See the document on :ref:`ogn_attribute_types` for full details
on the accepted attribute types and how they correspond to C++, Python, JSON, and USD types.
The data types can be divided into categories, explained separately here though there can be any arbitrary amount
of type mixing.
.. note::
The attribute type **"execution"** can also be specified. These attributes do not carry any data, they merely
exist to form connections to trigger node sequences to evaluate based on external conditions. This behavior can
only be seen at the graph level, not at the individual node level.
Simple Data Attribute Types
---------------------------
These denote individual values with a fixed size such as float, int, etc. In Fabric they are stored directly, using
the size of the type to determine how much space to allocate.
This example will illustrate how to access simple data of type float and token. A full set of compatible types and
how they are accessed can be found in :ref:`ogn_attribute_types`.
.. code-block:: json
{
"TokenStringLength" : {
"description": "Compute the length of a tokenized string, in characters",
"version": 1,
"inputs": {
"token": {
"description": "Value whose length is to be calculated",
"type": "token"
}
},
"outputs": {
"length": {
"description": "Number of characters in the input token's string",
"type": "int64"
}
}
}
}
+------------------------------------------+--------------------------------------------+
| :ref:`C++ Code<ogn_simple_node_cpp>` | :ref:`Python Code<ogn_simple_node_py>` |
+------------------------------------------+--------------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_simpleData`, :ref:`ogn_tutorial_simpleDataPy`
.. note::
Tokens are simple data types as they have a fixed size in Fabric, however strings do not. Using them is
a special case described in :ref:`ogn_string_attribute_type`.
Tuple Data Attribute Types
--------------------------
These denote fixed numbers of simple values, such as double[4], vectord[3], etc. Each tuple value can be treated
as a single entity, but also provide access to individual tuple elements. In Fabric they are stored directly, using
the size of the simple type and the tuple count to determine how much space to allocate.
.. code-block:: json
{
"VectorMultiply" : {
"description": "Multiple two mathematical vectors to create a matrix",
"version": 1,
"inputs": {
"vector1": {
"description": "First vector to multiply",
"type": "double[4]"
},
"vector2": {
"description": "Second vector to multiply",
"type": "double[4]"
},
"outputs": {
"product": {
"description": "Matrix equal to the product of the two input vectors",
"type": "matrixd[4]"
}
}
}
}
+------------------------------------------+--------------------------------------------+
| :ref:`C++ Code<ogn_tuple_node_cpp>` | :ref:`Python Code<ogn_tuple_node_py>` |
+------------------------------------------+--------------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_simpleData`,
:ref:`ogn_tutorial_abi`,
:ref:`ogn_tutorial_cudaData`,
:ref:`ogn_tutorial_cpuGpuData`,
:ref:`ogn_tutorial_simpleDataPy`,
:ref:`ogn_tutorial_abi_py`,
:ref:`ogn_tutorial_state_py`,
:ref:`ogn_tutorial_defaults`, and
:ref:`ogn_tutorial_state_attributes_py`.
Role Data Attribute Types
-------------------------
Roles are specially named types that assign special meanings to certain tuple attribute types. See the details of
what types are available in :ref:`ogn_attribute_roles`.
.. code-block:: json
{
"PointsToVector" : {
"description": "Calculate the vector between two points",
"version": 1,
"inputs": {
"point1": {
"description": "Starting point of the vector",
"type": "pointf[4]"
},
"point2": {
"description": "Ending point of the vector",
"type": "pointf[4]"
}
},
"outputs": {
"vector": {
"description": "Vector from the starting point to the ending point",
"type": "vectorf[4]"
}
}
}
}
+------------------------------------+--------------------------------------+
| :ref:`C++ Code<ogn_role_node_cpp>` | :ref:`Python Code<ogn_role_node_py>` |
+------------------------------------+--------------------------------------+
Relevant tutorial - :ref:`ogn_tutorial_roleData`.
Array Data Attribute Types
--------------------------
These denote variable numbers of simple values, such as double[], bool[], etc. Although the number of elements they
contain is flexible they do not dynamically resize as a ``std::vector`` might, the node writer is responsible for
explicitly setting the size of outputs and the size of inputs is fixed when the compute is called. In Fabric they
are stored in two parts - the array element count, indicating how many of the simple values are contained within the
array, and as a flat piece of memory equal in size to the element count times the size of the simple value.
.. code-block:: json
{
"PartialSum" : {
"description": [
"Calculate the partial sums of an array. Element i of the output array",
"is equal to the sum of elements 0 through i of the input array"
],
"version": 1,
"inputs": {
"array": {
"description": "Array whose partial sum is to be computed",
"type": "float[]"
}
},
"outputs": {
"partialSums": {
"description": "Partial sums of the input array",
"type": "float[]"
}
}
}
}
.. important::
There is no guarantee in Fabric that the array data and the array size information are stored together, or even
in the same memory space. The generated code takes care of this for you, but if you decide to access any of the
data directly through the ABI you should be aware of this.
+------------------------------------------+--------------------------------------------+
| :ref:`C++ Code<ogn_array_node_cpp>` | :ref:`Python Code<ogn_array_node_py>` |
+------------------------------------------+--------------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_arrayData`,
:ref:`ogn_tutorial_cudaData`,
:ref:`ogn_tutorial_cpuGpuData`,
:ref:`ogn_tutorial_complexData_py`,
:ref:`ogn_tutorial_defaults`, and
:ref:`ogn_tutorial_tokens`.
Tuple-Array Data Attribute Types
--------------------------------
These denote variable numbers of a fixed number of simple values, such as pointd[3][], int[2][], etc. In principle
they are accessed the same as regular arrays, with the added capability of accessing the individual tuple values on
the array elements. In Fabric they are stored in two parts - the array element count, indicating how many of the
tuple values are contained within the array, and as a flat piece of memory equal in size to the element count times the
tuple count times the size of the simple value. The tuple elements appear contiguously in the data so for example the
memory layout of a **float[3][]** named `t` implemented with a struct containing x, y, z, would look like this:
+--------+--------+--------+--------+--------+--------+--------+------+
| t[0].x | t[0].y | t[0].z | t[1].x | t[1].y | t[1].z | t[2].x | etc. |
+--------+--------+--------+--------+--------+--------+--------+------+
.. code-block:: json
{
"CrossProducts" : {
"description": "Calculate the cross products of an array of vectors",
"version": 1,
"inputs": {
"a": {
"description": "First set of vectors in the cross product",
"type": "vectord[3][]",
"uiName": "First Vectors"
}
"b": {
"description": "Second set of vectors in the cross product",
"type": "vectord[3][]",
"uiName": "Second Vectors"
}
},
"outputs": {
"crossProduct": {
"description": "Cross products of the elements in the two input arrays",
"type": "vectord[3][]"
}
}
}
}
+-------------------------------------------+---------------------------------------------+
| :ref:`C++ Code<ogn_tuple_array_node_cpp>` | :ref:`Python Code<ogn_tuple_array_node_py>` |
+-------------------------------------------+---------------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_tupleArrays`,
:ref:`ogn_tutorial_cudaData`,
:ref:`ogn_tutorial_cpuGpuData`, and
:ref:`ogn_tutorial_complexData_py`.
.. _ogn_string_attribute_type:
String Attribute Type
---------------------
String data is slightly different from the others. Although it is conceptually simple data, being a single string
value, it is treated as an array in Fabric due to its size allocation requirements. Effort has been made to make
the data accessed from string attributes to appear as much like a normal string as possible, however there is a
restriction on modifications that can be made to them as they have to be resized in Fabric whenever they change
size locally. For that reason, when modifying output strings it is usually best to do all string operations on a local
copy of the string and then assign it to the output once.
.. code-block:: json
{
"ReverseString" : {
"description": "Output the string in reverse order",
"version": 1,
"inputs": {
"original": {
"description": "The string to be reversed",
"type": "string"
}
},
"outputs": {
"reversed": {
"description": "Reversed string",
"type": "string"
}
}
}
}
.. caution::
At this time there is no support for string arrays. Use tokens instead for that purpose.
+--------------------------------------+----------------------------------------+
| :ref:`C++ Code<ogn_string_node_cpp>` | :ref:`Python Code<ogn_string_node_py>` |
+--------------------------------------+----------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_simpleData` and :ref:`ogn_tutorial_simpleDataPy`.
.. _ogn_extended_attribute_types:
Extended Attribute Type - Any
-----------------------------
Sometimes you may want to create a node that can accept a wide variety of data types without the burden of
implementing a different attribute for every acceptable type. For this case the **any** type was introduced.
When an attribute has this type it means "allow connections to any type and resolve the type at runtime".
Practically speaking this type resolution can occur in a number of ways. The main way it resolves now is to create
a connection from an **any** type to a concrete type, such as **float**. Once the connection is made the **any**
attribute type will be resolved and then behave as a **float**.
The implication of this flexibility is that the data types of the **any** attributes cannot be assumed at build time,
only at run time. To handle this flexibility, an extra wrapper layer is added to such attributes to handle
identification of the resolved type and retrieval of the attribute data as that specific data type.
.. code-block:: json
{
"Add" : {
"description": "Compute the sum of two arbitrary values",
"version": 1,
"inputs": {
"a": {
"description": "First value to be added",
"type": "any"
},
"b": {
"description": "Second value to be added",
"type": "any"
}
},
"outputs": {
"sum": {
"description": "Sum of the two inputs",
"type": "any"
}
}
}
}
.. caution::
At this time the extended attribute types are not allowed to resolve to :ref:`ogn_bundle_attribute_types`.
+-----------------------------------+-------------------------------------+
| :ref:`C++ Code<ogn_any_node_cpp>` | :ref:`Python Code<ogn_any_node_py>` |
+-----------------------------------+-------------------------------------+
Relevant tutorial - :ref:`ogn_tutorial_extended_types`.
Extended Attribute Type - Union
-------------------------------
The **union** type is similar to the **any** type in that its actual data type is only decided at runtime. It has the
added restriction of only being able to accept a specific subset of data types, unlike the **any** type that can
literally be any of the primary attribute types.
The way this is specified in the .ogn file is, instead of using the type name **"union"**, you specify the list of
allowable attribute types. Here's an example that can accept either double or float values, but nothing else.
.. code-block:: json
{
"MultiplyNumbers" : {
"description": "Compute the product of two float or double values",
"version": 1,
"inputs": {
"a": {
"description": "First value to be added",
"type": ["double", "float"]
},
"b": {
"description": "Second value to be added",
"type": ["double", "float"]
}
},
"outputs": {
"product": {
"description": "Product of the two inputs",
"type": ["double", "float"]
}
}
}
}
Other than this restriction, which the graph will attempt to enforce, the **union** attributes behave exactly the
same way as the **any** attributes.
+-------------------------------------+---------------------------------------+
| :ref:`C++ Code<ogn_union_node_cpp>` | :ref:`Python Code<ogn_union_node_py>` |
+-------------------------------------+---------------------------------------+
Relevant tutorial - :ref:`ogn_tutorial_extended_types`.
.. _ogn_bundle_attribute_types:
Bundle Attribute Types
----------------------
A bundle doesn't describe an attribute with a specific type of data itself, it is a container for a runtime-curated
set of attributes that do not have definitions in the .ogn file.
.. code-block:: json
{
"MergeBundles" : {
"description": [
"Merge the contents of two bundles together.",
"It is an error to have attributes of the same name in both bundles."
],
"version": 1,
"inputs": {
"bundleA": {
"description": "First bundle to be merged",
"type": "bundle",
},
"bundleB": {
"description": "Second bundle to be merged",
"type": "bundle",
}
},
"outputs": {
"bundle": {
"description": "Result of merging the two bundles",
"type": "bundle",
}
}
}
}
+--------------------------------------+----------------------------------------+
| :ref:`C++ Code<ogn_bundle_node_cpp>` | :ref:`Python Code<ogn_bundle_node_py>` |
+--------------------------------------+----------------------------------------+
.. code-block:: json
"CalculateBrightness": {
"version": 1,
"description": "Calculate the brightness value for colors in various formats",
"tokens": ["r", "g", "b", "c", "m", "y", "k"],
"inputs": {
"color": {
"type": "bundle",
"description": [
"Color value, in a variety of color spaces. The bundle members can either be floats",
"named 'r', 'g', 'b', and 'a', or floats named 'c', 'm', 'y', and 'k'."
]
}
},
"outputs": {
"brightness": {
"type": "float",
"description": "The calculated brightness value"
}
}
}
+--------------------------------------+----------------------------------------+
| :ref:`C++ Code<ogn_bundle_data_cpp>` | :ref:`Python Code<ogn_bundle_data_py>` |
+--------------------------------------+----------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_bundle_manipulation`
:ref:`ogn_tutorial_bundle_data`, and
:ref:`ogn_tutorial_bundle_add_attributes`.
.. _ogn_secondary_attribute_properties:
Secondary Attribute Properties
++++++++++++++++++++++++++++++
Some other attribute properties have simple defaults and need not always be specified in the file. These include
:ref:`ogn_keyword_attribute_default`,
:ref:`maximum <ogn_keyword_attribute_range>`, and
:ref:`ogn_keyword_attribute_memoryType`,
:ref:`ogn_keyword_attribute_metadata`,
:ref:`minimum <ogn_keyword_attribute_range>`, and
:ref:`ogn_keyword_attribute_optional`,
:ref:`ogn_keyword_attribute_unvalidated`,
:ref:`ogn_keyword_attribute_uiName`.
Setting A Default
-----------------
If you don't set an explicit default then the attributes will go to their "natural" default. This is False for a
boolean, zeroes for numeric values including tuples, an empty array for all array types, an empty string for string
and token types, and the identity matrix for matrix, frame, and transform types. Attributes whose types are resolved
at runtime (any, union, and bundle) have no defaults and start in an unresolved state instead.
Sometimes you need a different default though, like setting a scale value to (1.0, 1.0, 1.0), or a token to be used
as an enum to one of the enum values. To do that you simply use the :ref:`ogn_keyword_attribute_default` keyword in
the attribute definition. When it is created it will automatically assume the specified default value.
.. code-block:: json
:emphasize-lines: 5
{
"HairColors": {
"version": 1,
"description": "Collect hair colors for various characters",
"inputs": {
"sabine": {
"type": "token",
"description": "Color of Sabine's hair",
"default": "red"
}
}
}
}
As there is no direct way to access the default values on an attribute yet, no example is necessary.
Relevant tutorials - :ref:`ogn_tutorial_defaults`, :ref:`ogn_tutorial_simpleData` and :ref:`ogn_tutorial_tupleData`.
.. _ogn_overriding_memory_location:
Overriding Memory Location
--------------------------
As described in the :ref:`ogn_using_gpu_data` section, attribute memory can be allocated on the CPU or on the GPU. If
all attributes are in the same location then the node :ref:`ogn_keyword_node_memoryType` keyword specifies where all
of the attribute memory resides. If some attributes are to reside in a different location then those attributes can
override the memory location with their :ref:`ogn_keyword_attribute_memoryType` keyword.
.. code-block:: json
:emphasize-lines: 5,10,21
{
"GpuSwap" : {
"description": "Node that optionally moves data from the GPU to the CPU",
"version": 1,
"memoryType": "any",
"inputs": {
"sizeThreshold": {
"type": "int",
"description": "The number of points at which the computation should be moved to the GPU",
"memoryType": "cpu"
},
"points": {
"type": "pointf[3][]",
"description": "Data to move"
}
},
"outputs": {
"points": {
"type": "pointf[3][]",
"description": "Migrated data, values unchanged"
}
}
}
}
In this description the `inputs:sizeThreshold` data will live on the CPU due to the override, the `inputs:points` data
and the `outputs:points` data will be decided at runtime.
+------------------------------------------------+--------------------------------------------------+
| :ref:`C++ Code<ogn_attribute_memory_type_cpp>` | :ref:`Python Code<ogn_attribute_memory_type_py>` |
+------------------------------------------------+--------------------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_cudaData` and :ref:`ogn_tutorial_cpuGpuData`.
Attribute Metadata
------------------
Attributes have a metadata dictionary associated with them in the same way that node types do. Some values are
automically generated. Others can be added manually through the :ref:`ogn_keyword_attribute_metadata` keyword.
.. code-block:: json
:emphasize-lines: 6-8
{
"StarWarsCharacters": {
"version": 1,
"description": "Database of character information",
"inputs" : {
"anakin": {
"description": "Jedi Knight",
"type": "token",
"metadata": {
"secret": "He is actually Darth Vader"
}
}
}
}
}
.. note::
This is not the same as USD metadata. It is only accessible through the OmniGraph attribute type.
One special metadata item with the keyword ``allowedTokens`` can be attached to attributes of type ``token``.
It will be automatically be added to the USD Attribute's metadata. Like regular tokens, if the token string
contains any special characters it must be specified as a dictionary whose key is a legal code variable name
name and whose value is the actual string.
+---------------------------------------------+-----------------------------------------------+
| :ref:`C++ Code<ogn_metadata_attribute_cpp>` | :ref:`Python Code<ogn_metadata_attribute_py>` |
+---------------------------------------------+-----------------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_abi_py`
Suggested Minimum/Maximum Range
-------------------------------
Numeric values can specify a suggested legal range using the keywords :ref:`minimum <ogn_keyword_attribute_range>` and
:ref:`maximum <ogn_keyword_attribute_range>`. These are not used at runtime at the moment, only within the .ogn file to
verify legality of the default values, or values specified in tests.
Default values can be specified on simple values, tuples (as tuples), arrays (as simple values applied to all array
elements), and tuple-arrays (as tuple values applied to all array elements).
.. code-block:: json
:emphasize-lines: 8-9,14-15,20-21,26-27
"MinMax": {
"version": 1,
"description": "Attribute test exercising the minimum and maximum values to verify defaults",
"inputs": {
"simple": {
"description": "Numeric value in [0.0, 1.0]",
"type": "double",
"minimum": 0.0,
"maximum": 1.0
},
"tuple": {
"description": "Tuple[2] value whose first value is in [-1.0, 1.0] with second value in [0.0, 255.0]",
"type": "double[2]",
"minimum": [-1.0, 0.0],
"maximum": [1.0, 255.0]
},
"array": {
"description": "Array value where every element is in [0, 255]",
"type": "uint",
"minimum": 0,
"maximum": 255
},
"tupleArray": {
"description": "Array of tuple[2] values whose first value is in [5, 10] and second value is at least 12",
"type": "uchar[2][]",
"minimum": [5, 12],
"maximum": [10, 255]
}
}
}
Relevant tutorials - :ref:`ogn_node_conversion`.
Optional Attributes
-------------------
Usually an attribute value must exist and be legal in order for a node's compute to run. This helps the graph avoid
executing nodes that cannot compute their outputs due to missing or illegal inputs. Sometimes a node is capable of
computing an output without certain inputs being present. Those inputs can use the :ref:`ogn_keyword_attribute_optional`
keyword to indicate to OmniGraph that it's okay to compute without it.
.. code-block:: json
:emphasize-lines: 5
{
"Shoes": {
"version": 1,
"description": "Create a random shoe type",
"inputs": {
"shoelaceStyle": {
"type": "token",
"description": "If the shoe type needs shoelaces this will contain the style of shoelace to use",
"optional": true
}
},
"outputs": {
"shoeType": {
"type": "string",
"description": "Name of the randomly generated shoe"
}
}
}
}
It is up to the node to confirm that such optional attributes have legal values before they use them.
+-----------------------------------+-------------------------------------+
| :ref:`C++ Code<ogn_optional_cpp>` | :ref:`Python Code<ogn_optional_py>` |
+-----------------------------------+-------------------------------------+
Unvalidated Attributes For Compute
----------------------------------
Above you can see how attributes may optionally not be required to exist depending on your node function. There is also
a slightly weaker requirement whereby the attributes will exist but they need not have valid values in order for
``compute()`` to be called. Those attributes can use the :ref:`ogn_keyword_attribute_unvalidated`
keyword to indicate to OmniGraph that it's okay to compute without verifying it.
The most common use of this is to handle the case of attributes whose values will only be used under certain
circumstances, especially :ref:`ogn_extended_attribute_types`.
.. code-block:: json
:emphasize-lines: 13,18
{
"ABTest": {
"version": 1,
"description": "Choose one of two inputs based on some input criteria",
"inputs": {
"selectA": {
"type": "bool",
"description": "If true then pass through input a, else pass through input b"
},
"a": {
"type": "any",
"description": "First choice for the a/b test",
"unvalidated": true
},
"b": {
"type": "any",
"description": "Second choice for the a/b test",
"unvalidated": true
}
},
"outputs": {
"choice": {
"type": "any",
"description": "Result from the a/b test choice"
}
}
}
}
It is up to the node to confirm that such attributes have legal values before they use them. Notice here that the output
will be validated. In particular, it will have its resolved type validated before calling ``compute()``. After that the
node will have to confirm that the selected input, a or b, has a type that is compatible with that resolved type.
+--------------------------------------+----------------------------------------+
| :ref:`C++ Code<ogn_unvalidated_cpp>` | :ref:`Python Code<ogn_unvalidated_py>` |
+--------------------------------------+----------------------------------------+
Providing A User-Friendly Attribute Name
----------------------------------------
While the unique attribute name is useful for keeping things well organized it may not be the type of name you would want
to see, e.g. in a dropdown interface when selecting the attribute. A specially named metadata value has been reserved
for that purpose, to give a consistent method of specifying a more user-friendly name for the attribute.
Since it is so common, a more succinct method of specifying it is available with the :ref:`ogn_keyword_attribute_uiName`
keyword. It is a shortcut to defining that specially named metadata, so these two definitions generate identical code:
.. code-block:: json
:emphasize-lines: 6-8
{
"AttributeUiName": {
"version": 1,
"description": "No-op node showing how to use the uiName metadata on an attribute",
"inputs" : {
"x": {
"description": "X marks the spot",
"type": "pointf[3]",
"metadata": {
"uiName": "Treasure Location"
}
}
}
}
}
.. code-block:: json
:emphasize-lines: 6
{
"AttributeUiName": {
"version": 1,
"description": "No-op node showing how to use the uiName metadata on an attribute",
"inputs" : {
"x": {
"description": "X marks the spot",
"type": "pointf[3]",
"uiName": "Treasure Location"
}
}
}
}
+-------------------------------------------+---------------------------------------------+
| :ref:`C++ Code<ogn_uiName_attribute_cpp>` | :ref:`Python Code<ogn_uiName_attribute_py>` |
+-------------------------------------------+---------------------------------------------+
Almost every tutorial in :ref:`ogn_tutorial_nodes` make use of this special piece of metadata.
.. _ogn_defining_automatic_tests:
Defining Automatic Tests
++++++++++++++++++++++++
It is good practice to always write tests that exercise your node's functionality. Nodes that are purely
functional, that is their outputs can be calculated using only their inputs, can have simple tests written that
set certain input values and compare the outputs against expected results.
To make this process easier the **"tests"** section of the .ogn file was created. It generates a Python test
script in the Kit testing framework style from a set of input, output, and state values on the node.
The algorithm is simple. For each test in the list it sets input and state attributes to the values given in the test
description, using default values for any unspecified attributes, runs the compute on the node, then gathers the
computed outputs and compares them against the expected ones in the test description, ignoring any that did not
appear there.
There are two ways of specifying test data. They are both equivalent so you can choose the one that makes your
particular test data the most readable. The first is to have each test specify a dictionary of
*ATTRIBUTE* : *VALUE*. This is a simple node that negates an input value. The tests run a number of example values
to ensure the correct results are obtained. Four tests are run, each independent of each other.
.. code-block:: json
:emphasize-lines: 17-22
{
"NegateValue": {
"version": 1,
"description": "Testable node that negates an input value",
"inputs" : {
"value": {
"description": "Value to negate",
"type": "float"
}
},
"outputs": {
"result": {
"description": "Negated value of the input",
"type": "float"
}
},
"tests": [
{ "inputs:value": 5.0, "outputs:result": -5.0 },
{ "inputs:value": 0.0, "outputs:result": 0.0 },
{ "inputs:value": -5.0, "outputs:result": 5.0 },
{ "outputs:result": 0.0 }
]
}
}
Note how the last test relies on using the default input value, which for floats is 0.0 unless otherwise specified.
The tests illustrate a decent coverage of the different possible types of inputs.
The other way of specifying tests is to use the same type of hierarchical dictionary structure as the attribute
definitions. The attribute names are thus shorter. This .ogn file generates exactly the same test code as the one
above, with the addition of test descriptions to add more information at runtime.
.. code-block:: json
:emphasize-lines: 17-51
{
"NegateValue": {
"version": 1,
"description": "Testable node that negates an input value",
"inputs" : {
"value": {
"description": "Value to negate",
"type": "float"
}
},
"outputs": {
"result": {
"description": "Negated value of the input",
"type": "float"
}
},
"tests": [
{
"description": "Negate a positive number",
"inputs": {
"value": 5.0
},
"outputs": {
"result": -5.0
}
},
{
"description": "Negate zero",
"inputs": {
"value": 0.0
},
"outputs": {
"result": 0.0
}
},
{
"description": "Negate a negative number",
"inputs": {
"value": -5.0
},
"outputs": {
"result": 5.0
}
},
{
"description": "Negate the default value",
"outputs": {
"result": 0.0
}
}
]
}
}
For this type of simple node you'd probably use the first, abbreviated, version of the test description. The second
type is more suited to nodes with many inputs and outputs.
In addition, if you require more than one node to properly set up your test you can use this format to add in a special
section defining the state of the graph before the tests start. For example if you want to test two nodes chained
together you could do this:
.. code-block:: json
:emphasize-lines: 24-42
{
"AddTwoValues": {
"version": 1,
"description": "Testable node that adds two input values",
"inputs" : {
"a": {
"description": "First value to add",
"type": "float"
},
"b": {
"description": "Second value to add",
"type": "float"
}
},
"outputs": {
"result": {
"description": "Sum of the two inputs",
"type": "float"
}
},
"tests": [
{
"description": "Sum a constant and a connected value",
"setup": {
"nodes": [
["TestNode", "omni.examples.AddTwoValues"],
["InputNode", "omni.examples.AddTwoValues"]
],
"prims": [
["InputPrim", {"value": ["float", 5.0]}]
],
"connections": [
["InputPrim", "value", "TestNode", "inputs:a"]
]
},
"outputs": {
"result": 5.0
}
},
{
"inputs:b": 7.0, "outputs:result": 12.0
}
]
}
}
When there is more than one test the setup that happened in the previous test will still be applied. It will be as
though the tests are run on live data in sequence. To reset the setup configuration put a new one in your test,
including simply *{}* if you wish to start with an empty scene.
There is no C++ or Python code that access the test information directly, it is only used to generate the test script.
In addition to your defined tests, extra tests are added to verify the template USD file, if it was generated, and
the import of the Python database module, if it was generated. The test script itself will be installed into a
subdirectory of your Python import directory, e.g. ``ogn.examples/ogn/examples/ogn/tests/TestNegateValue.py``
Relevant tutorials -
:ref:`ogn_tutorial_simpleDataPy`,
:ref:`ogn_tutorial_complexData_py`,
:ref:`ogn_tutorial_abi_py`,
:ref:`ogn_tutorial_state_py`,
:ref:`ogn_tutorial_defaults`,
:ref:`ogn_tutorial_state_attributes_py`,
:ref:`ogn_tutorial_state`,
:ref:`ogn_tutorial_simpleData`,
:ref:`ogn_tutorial_tokens`,
:ref:`ogn_tutorial_tokens`,
:ref:`ogn_tutorial_abi`,
:ref:`ogn_tutorial_tupleData`,
:ref:`ogn_tutorial_arrayData`,
:ref:`ogn_tutorial_tupleArrays`,
:ref:`ogn_tutorial_roleData`,
:ref:`ogn_tutorial_cudaData`,
:ref:`ogn_tutorial_cpuGpuData`, and
:ref:`ogn_tutorial_cpu_gpu_extended`.
Internal State
++++++++++++++
In addition to having state attributes you may also need to maintain state information that is not representable as a
set of attributes; e.g. binary data, arbitrary C++ structures, etc. Per-node internal state is the mechanism that
accommodates this need.
The approach is slightly different in C++ and Python but the intent is the same. The internal state data is a
node-managed piece of data that persists on the node from one evaluation to the next (though not across file load and
save).
There is nothing to do in the .ogn file to indicate that internal state of this kind is being used. The ABI function
``hasState()`` will return true when it is being used, or when state attributes exist on the node.
.. code-block:: json
{
"Counter" : {
"description": "Count the number of times the node executes",
"version": 1
}
}
+------------------------------------------+--------------------------------------------+
| :ref:`C++ Code<ogn_state_node_cpp>` | :ref:`Python Code<ogn_state_node_py>` |
+------------------------------------------+--------------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_state` and :ref:`ogn_tutorial_state_py`.
Versioning
++++++++++
Over time your node type will evolve and you will want to change things within it. When you do that you want all of the
old versions of that node type to continue working, and update themselves to the newer version automatically. The
ABI allows for this by providing a callback to the node that happens whenever a node with a version number lower than
the current version number. (Recall the version number is encoded in the .ogn property **"version"** and in the USD
file as the property **custom int node:typeVersion**.)
The callback provides the version it was attempting to create and the version to which it should be upgraded and lets
the node decide what to do about it. The exact details depend greatly on what changes were made from one version to
the next. This particular node is in version 2, where the second version has added the attribute *offset* because
the node function has changed from ``result = a * b`` to ``result = a * b + offset``.
.. code-block:: json
:emphasize-lines: 3,14-17
{
"Multiply": {
"version": 2,
"description": "Node that multiplies two values and adds an offset",
"inputs" : {
"a": {
"description": "First value",
"type": "float"
},
"b": {
"description": "Second value",
"type": "float"
},
"offset": {
"description": "Offset value",
"type": "float"
}
},
"outputs": {
"result": {
"description": "a times b plus offset",
"type": "float"
}
}
}
}
+------------------------------------------+--------------------------------------------+
| :ref:`C++ Code<ogn_versioned_node_cpp>` | :ref:`Python Code<ogn_versioned_node_py>` |
+------------------------------------------+--------------------------------------------+
Relevant tutorials - :ref:`ogn_tutorial_abi` and :ref:`ogn_tutorial_abi_py`.
Other References
++++++++++++++++
- :ref:`Naming and File Conventions<omnigraph_naming_conventions>`
- :ref:`Setting Up Your Build<ogn_extension_tutorial>`
- :ref:`OGN Reference Guide<ogn_reference_guide>`
- :ref:`Feature-Based Tutorials<ogn_tutorial_nodes>`
- :ref:`Attribute Type Details<ogn_attribute_types>`
- :ref:`OmniGraph Python API<omnigraph_python_api>`
| 69,544 | reStructuredText | 40.469887 | 123 | 0.582509 |
omniverse-code/kit/exts/omni.graph.tools/docs/ogn_generation_script.rst | .. _ogn_generation_script:
Generating OmniGraph Nodes
==========================
The OmniGraph nodes consist of code that is automatically generated from a .ogn file and one or more methods
defined by the node class. These interfaces consist of C++ code, Python code, a USDA file, and Python test scripts
For full details of what is generated automatically see the :ref:`ogn_user_guide`.
.. contents::
.. toctree::
ogn_user_guide
ogn_reference_guide
attribute_types
Running The Script
------------------
The script to run to perform the conversion is *generate_node.py*. It is run with the
same version of Python included with the build in *tools/packman/python.bat* or *tools/packman.python.sh*.
The script `generate_node.py` reads in a node description file in order to automatically generate documentation,
tests, template files, anda simplified interface the node can use to implement its algorithm.
.. note::
Although not required for using the .ogn format, if you are interested in what kind of code is generated from the
descriptions see :ref:`ogn_node_architects_guide`.
Run *generate_node.py --help* to see all of the arguments that can be passed to the script, reproduced here. Each
flag has both a short and long form that are equivalent.
.. code-block:: text
usage: generate_node.py [-h] [-cd DIR] [-c [DIR]] [-d [DIR]]
[-e EXTENSION_NAME] [-i [DIR]]
[-in [INTERMEDIATE_DIRECTORY]]
[-m [PYTHON_IMPORT_MODULE]] [-n [FILE.ogn]] [-p [DIR]]
[-s SETTING_NAME] [-t [DIR]] [-td FILE.json]
[-tp [DIR]] [-u] [-usd [DIR]] [-uw [DIR]] [-v]
Parse a node interface description file and generate code or documentation
optional arguments:
-h, --help show this help message and exit
-cd DIR, --configDirectory DIR
the directory containing the code generator configuration files (default is current)
-c [DIR], --cpp [DIR]
generate the C++ interface class into the specified directory (default is current)
-d [DIR], --docs [DIR]
generate the node documentation into the specified directory (default is current)
-e EXTENSION_NAME, --extension EXTENSION_NAME
name of the extension requesting the generation
-i [DIR], --icons [DIR]
directory into which to install the icon, if one is found
-in [INTERMEDIATE_DIRECTORY], --intermediate [INTERMEDIATE_DIRECTORY]
directory into which temporary build information is stored
-m [PYTHON_IMPORT_MODULE], --module [PYTHON_IMPORT_MODULE]
Python module where the Python node files live
-n [FILE.ogn], --nodeFile [FILE.ogn]
file containing the node description (use stdin if file name is omitted)
-p [DIR], --python [DIR]
generate the Python interface class into the specified directory (default is current)
-s SETTING_NAME, --settings SETTING_NAME
define one or more build-specific settings that can be used to change the generated code at runtime
-t [DIR], --tests [DIR]
generate a file containing basic operational tests for this node
-td FILE.json, --typeDefinitions FILE.json
file name containing the mapping to use from OGN type names to generated code types
-tp [DIR], --template [DIR]
generate an annotated template for the C++ node class into the specified directory (default is current)
-u, --unitTests run the unit tests on this file
-usd [DIR], --usdPath [DIR]
generate a file containing a USD template for nodes of this type
-uw [DIR], --unwritable [DIR]
mark the generated directory as unwritable at runtime
-v, --verbose output the steps the script is performing as it performs them
Available attribute types:
any
bool, bool[]
bundle
colord[3], colord[4], colord[3][], colord[4][]
colorf[3], colorf[4], colorf[3][], colorf[4][]
colorh[3], colorh[4], colorh[3][], colorh[4][]
double, double[2], double[3], double[4], double[], double[2][], double[3][], double[4][]
execution
float, float[2], float[3], float[4], float[], float[2][], float[3][], float[4][]
frame[4], frame[4][]
half, half[2], half[3], half[4], half[], half[2][], half[3][], half[4][]
int, int[2], int[3], int[4], int[], int[2][], int[3][], int[4][]
int64, int64[]
matrixd[2], matrixd[3], matrixd[4], matrixd[2][], matrixd[3][], matrixd[4][]
normald[3], normald[3][]
normalf[3], normalf[3][]
normalh[3], normalh[3][]
objectId, objectId[]
path
pointd[3], pointd[3][]
pointf[3], pointf[3][]
pointh[3], pointh[3][]
quatd[4], quatd[4][]
quatf[4], quatf[4][]
quath[4], quath[4][]
string
texcoordd[2], texcoordd[3], texcoordd[2][], texcoordd[3][]
texcoordf[2], texcoordf[3], texcoordf[2][], texcoordf[3][]
texcoordh[2], texcoordh[3], texcoordh[2][], texcoordh[3][]
timecode, timecode[]
token, token[]
transform[4], transform[4][]
uchar, uchar[]
uint, uint[]
uint64, uint64[]
vectord[3], vectord[3][]
vectorf[3], vectorf[3][]
vectorh[3], vectorh[3][]
["A", "B", "C"... = Any one of the listed types]
The main argument of interest is *--nodeFile MyFile.ogn*. That is how you specify the file for which interfaces are
to be generated. Another one of interest is *--verbose* which, when included, will dump debugging information
describing the operations being performed. Several other options describe which of the available outputs will be
generated.
.. note::
There is also an environment variable controlling build flags. If you set **OGN_DEBUG** then the .ogn
generator will use its *--verbose* option to dump information about the parsing of the file and generation
of the code - worth remembering if you are running into code generation errors.
The usual method of running the script is through the build process, described in :ref:`ogn_tutorial_nodes`.
Other uses of the script are the following:
.. code-block:: bash
# Generate the node using an alternate code path controlled by the value of CODE_SETTING
python generate_node.py --nodeFile MYNODE.ogn --setting CODE_SETTING
# Validate a .ogn file but do not produce any output
python generate_node.py --schema --nodeFile MYNODE.ogn
# Generate all of the interfaces
python generate_node.py --cpp INCLUDE_DIR --python PYTHON_DIR --schema --namespace omni.MY.FEATURE --nodeFile MYNODE.ogn
.. note::
Normally the generated directory is set up to regenerate its files on demand when the .ogn or .py implementation
files change to facilitate hot reloading. When the nodes are installed from an extension through a distribution
this is disabled by using the `--unwritable` flag to tag the generated directory to prevent that. This speeds up
the extension loading and avoids potential write permission problems with installed directories.
.. note::
The script is written to run on Python 3.6 or later. Earlier 3.x versions may work but are untested. It will always
be guaranteed to run on the same version of Python as Kit.
| 7,821 | reStructuredText | 49.141025 | 131 | 0.619742 |
omniverse-code/kit/exts/omni.graph.tools/docs/CHANGELOG.md | # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.17.2] - 2023-02-14
### Fixed
- Made test file pattern account for node files not beginning with Ogn
## [1.17.1] - 2023-02-08
### Changed
- Modified lookup of target extension version to account for the modified path names
## [1.17.0] - 2022-10-03
### Fixed
- Changed code emission to avoid defining interface that will not be used
## [1.16.3] - 2022-09-28
### Added
- Better documentation for categories
### Removed
- Testing for obsolete transform data type
## [1.16.2] - 2022-08-30
### Fixed
- Linting errors
## [1.16.1] - 2022-08-16
### Changed
- Refactored checking for legal extension name as Python import
## [1.16.0] - 2022-08-25
### Added
- Support for new setting that turns deprecations into errors
- Tests for deprecation code
- Access to deprecation message logs to use for testing
## [1.15.2] - 2022-08-09
### Fixed
- Applied formatting to all of the Python files
## [1.15.1] - 2022-08-05
### Fixed
- All of the lint errors reported on the Python files in this extension
## [1.15.0] - 2022-08-01
###
- Change `m_primHandle` to `m_bundleHandle` in `BundleAttributeManager`
## [1.14.1] - 2022-07-25
###
- Added ALLOW_MULTI_INPUTS metadata key
## [1.14.0] - 2022-07-13
###
- Added UI_TYPE metadata key, added class method to MetadataKeys to get all the metadata key strings
## [1.13.0] - 2022-07-08
### Added
- Support for 'deprecation' attribute keyword in .ogn files.
## [1.12.0] - 2022-07-07
### Changed
- Refactored import of non-public API to emit a deprecation warning
- Moved node_generator/ into the _impl section
### Added
- Support for fully defined Python API at the omni.graph.tools level
- Support for fully defined Python API at the omni.graph.tools.ogn level
- Support for public API consistency test
## [1.11.0] - 2022-06-28
### Changed
- Merged to USD and import generated tests and added enhanced generated code coverage
## [1.10.0] - 2022-06-23
### Removed
- Support for the deprecated Autograph functionality, now in omni.graph.core.autonode
## [1.9.1] - 2022-06-17
### Fixed
- Corrected bad API documentation formatting
### Added
- Documentation links for Python API
## [1.9.0] - 2022-06-13
### Added
- Check to see if values are already set before initializing defaults in Python nodes
## [1.8.1] - 2022-06-08
### Fixed
- Add stdint include when constructing node database files.
## [1.8.0] - 2022-06-07
### Added
- Support for generator settings to alter the generated code
- Generator setting for Python output optimization
- Build flag to modify generator settings
- Generator script support for generator settings being passed around
## [1.7.0] - 2022-05-27
### Added
- Ability for the controller to take an attribute description as the first parameter instead of only attributes
## [1.6.2] - 2022-05-17
### Fixed
- Improved node description formatting by using newlines to indicate paragraph breaks
## [1.6.1] - 2022-05-11
### Added
- Category for UI nodes
## [1.6.0] - 2022-05-10
### Added
- Ability to use @deprecated_function with property getters and setters.
## [1.5.4] - 2022-05-06
### Fixed
- Fixed the emission of the CPU to GPU pointer information for output bundles
## [1.5.3] - 2022-04-29
### Fixed
- Fixed incorrect line highlighting in user guide
## [1.5.2] - 2022-04-25
### Fixed
- Stopped generating bundle handle extraction in situations where the handle will not be used
## [1.5.1] - 2022-04-05
### Fixed
- Removed regeneration warning until such time as the regeneration actually happens
## [1.5.0] - 2022-03-24
### Fixed
- Fixed generated contents of tests/__init__.py to be constant
- Refactored generation to use standard import pattern
- ### Added
- Ability to create generated directories on the fly rather than insisting they already exist
## [1.4.0] - 2022-03-14
### Added
- *ensure_nodes_in_toml.py* to add the **[[omnigraph]]** section to the extension.toml file
## [1.3.2] - 2022-03-14
### Added
- examples category
## [1.3.1] - 2022-03-09
### Added
- Added literalOnly to the list of metadata keys
- Added some explanation for the literalOnly metadata key to the OGN reference guide
## [1.3.0] - 2022-03-08
### Changed
- Changed the naming of the generated tests to be shorter for easier use in TestRunner
- Changed the generated USD to use the schema prims
- Changed the generated test scripts to use the schema prims
- Removed unused USD metadata from generated code
## [1.2.4] - 2022-03-08
### Changed
- Modified C++ generated code node registration to match *omni.graph.core 2.23.3*
## [1.2.3] - 2022-02-15
### Added
- script node category
## [1.2.1] - 2022-02-10
### Added
- Unset the useSchemaPrims setting for tests until they are working
## [1.2.0] - 2022-02-09
### Changed
- Moved autograph to omni.graph.core, retained imports for backward compatibility
## [1.1.1] - 2021-08-30
### Breaking Changes
- Type names have changed. `Float32` is now `Float` and `Int32` is now `Int`.
### Improvements and Bugfixes
- *BUGFIX* Fixed type initializers in autograph
- *PERF IMPROVEMENT* Functions using Autofunc now use code generated at read time instead of runtime lookups.
- *UI IMPROVEMENT* Nodes no longer have extra connections with the node name.
## [1.1.0] - 2021-08-19
### Adds Autograph
Added Autograph tools and types
## [1.0.0] - 2021-03-01
### Initial Version
- Started changelog with initial released version of the OmniGraph core
| 5,628 | Markdown | 27.573604 | 111 | 0.714819 |
omniverse-code/kit/exts/omni.graph.tools/docs/attribute_types.rst | .. _ogn_attribute_types:
Attribute Data Types
====================
The attribute data type is the most important part of the attribute. It describes the type of data the attribute
references, and the type of generated interface the node writer will use to access that data.
Attribute data at its core consists of a short list of data types, called `Base Data Types`_. These types encapsulate
a single value, such as a float or integer.
.. warning::
Not all attribute types may be supported by the code generator. For a list of currently supported types
use the command ``generate_node.py --help``.
.. note::
The information here is for the default type definitions. You can override the type definitions using a
configuration file whose format is show in `Type Definition Overrides`_.
.. important::
When extracting bundle members in C++ you'll be passing in a template type to get the value. That is not the type
shown here, these are the types you'll get as a return value. (e.g. pass in _OgnToken_ to get a return value of
_NameToken_, or _float[]_ to get a return value of _ogn::array<float>_.)
Base Data Types
---------------
This table shows the conversion of the **Type Name**, which is how the attribute type appears in the .ogn file
*type* value of the attribute, to the various data types of the other locations the attribute might be referenced:
+-----------+--------+--------------+--------------+--------+------------------------------------------------------------+
| Type Name | USD | C++ | CUDA | Python | JSON | Description |
+===========+========+==============+==============+========+=========+==================================================+
| bool | bool | bool | bool* | bool | bool | True/False value |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| double | double | double | double* | float | float | 64 bit floating point |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| float | float | float | float* | float | float | 32 bit floating point |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| half | half | pxr::GfHalf | __half* | float | float | 16 bit floating point |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| int | int | int32_t | int* | int | integer | 32-bit signed integer |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| int64 | int64 | int64_t | longlong* | int | integer | 64-bit signed integer |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| path | path | ogn::string | ogn::string | str | string | Path to another node or attribute |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| string | string | ogn::string | ogn::string | str | string | Standard string |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| token | token | NameToken | NameToken* | str | string | Interned string with fast comparison and hashing |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| uchar | uchar | uchar_t | uchar_t* | int | integer | 8-bit unsigned integer |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| uint | uint | uint32_t | uint32_t* | int | integer | 32-bit unsigned integer |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
| uint64 | uint64 | uint64_t | uint64_t* | int | integer | 64-bit unsigned integer |
+-----------+--------+--------------+--------------+--------+---------+--------------------------------------------------+
.. note::
For C++ types on input attributes a `const` is prepended to the simple types.
Here are samples of base data type values in the various languages:
**USD Type**
++++++++++++
The type of data as it would appear in a .usd file
.. code-block:: usd
custom int inputs:myInt = 1
custom float inputs:myFloat = 1
**C++ Type**
++++++++++++
The value type a C++ node implementation uses to access the attribute's data
.. code-block:: c++
static bool compute(OgnMyNodeDatabase& db)
{
const int& iValue = db.inputs.myInt();
const float& fValue = db.inputs.myFloat();
}
**CUDA Type**
+++++++++++++
The value type a C++ node implementation uses to pass the attribute's data to CUDA code. Note the use of attribute
type definitions to make the function declarations more consistent.
.. code-block:: c++
extern "C" void runCUDAcompute(inputs::myInt_t*, inputs::myFloat_t*);
static bool compute(OgnMyNodeDatabase& db)
{
const int* iValue = db.inputs.myInt();
const float* fValue = db.inputs.myFloat();
runCUDAcompute( iValue, fValue );
}
.. code-block:: c++
extern "C" void runCUDAcompute(inputs::myInt_t* intValue, inputs::myFloat_t* fValue)
{
}
**Python Type Hint**
++++++++++++++++++++
The value used by the Python typing system to provide a hint about the expected data type
.. code-block:: python
@property
def myInt(self) -> int:
return attributeValues.myInt
**JSON Type**
+++++++++++++
The value type that the .ogn file expects from test or default data from the attribute
.. code-block:: json
{
"myNode" : {
"description" : ["This is my node with one integer and one float input"],
"version" : 1,
"inputs" : {
"myInt" : {
"description" : ["This is an integer attribute"],
"type" : "int",
"default" : 0
},
"myFloat" : {
"description" : ["This is a float attribute"],
"type" : "float",
"default" : 0.0
}
}
}
}
Array Data Types
----------------
An array type is a list of another data type with indeterminate length, analagous to a ``std::vector`` in C++ or a
``list`` type in Python.
Any of the base data types can be made into array types by appending square brackets (`[]`) to the type name. For
example an array of integers would have type `int[]` and an array of floats would have type `float[]`.
The JSON schema type is "array" with the type of the array's "items" being the base type, although in the file it will
just look like ``[VALUE, VALUE, VALUE]``.
Python uses the _numpy_ library to return both tuple and array data types.
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
| Type Name | USD | C++ | CUDA | Python | JSON |
+===========+==========+=========================+===================+==============================+===========+
| bool[] | bool[] | ogn::array<bool> | bool*,size_t | numpy.ndarray[numpy.bool] | bool[] |
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
| double[] | double[] | ogn::array<double> | double*,size_t | numpy.ndarray[numpy.float64] | float[] |
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
| float[] | float[] | ogn::array<float> | float*,size_t | numpy.ndarray[numpy.float64] | float[] |
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
| half[] | half[] | ogn::array<pxr::GfHalf> | __half*,size_t | numpy.ndarray[numpy.float64] | float[] |
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
| int[] | int[] | ogn::array<int32_t> | int*,size_t | numpy.ndarray[numpy.int32] | integer[] |
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
| int64[] | int64[] | ogn::array<int64_t> | longlong*,size_t | numpy.ndarray[numpy.int32] | integer[] |
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
| token[] | token[] | ogn::array<NameToken> | NameToken*,size_t | numpy.ndarray[numpy.str] | string[] |
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
| uchar[] | uchar[] | ogn::array<uchar_t> | uchar_t*,size_t | numpy.ndarray[numpy.int32] | integer[] |
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
| uint[] | uint[] | ogn::array<uint32_t> | uint32_t*,size_t | numpy.ndarray[numpy.int32] | integer[] |
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
| uint64[] | uint64[] | ogn::array<uint64_t> | uint64_t*,size_t | numpy.ndarray[numpy.int32] | integer[] |
+-----------+----------+-------------------------+-------------------+------------------------------+-----------+
.. note::
For C++ types on input attributes the array type is `ogn::const_array`.
Here are samples of array data type values in the various languages:
**USD Array Type**
++++++++++++++++++
.. code-block:: usd
custom int[] inputs:myIntArray = [1, 2, 3]
custom float[] inputs:myFloatArray = [1.0, 2.0, 3.0]
**C++ Array Type**
++++++++++++++++++
.. code-block:: c++
static bool compute(OgnMyNodeDatabase& db)
{
const ogn::const_array& iValue = db.inputs.myIntArray();
const auto& fValue = db.inputs.myFloatArray();
}
**CUDA Array Type**
+++++++++++++++++++
.. code-block:: c++
extern "C" runCUDAcompute(inputs::myIntArray_t*, size_t, inputs::myFloatArray_t*, size_t);
static bool compute(OgnMyNodeDatabase& db)
{
const int* iValue = db.inputs.myIntArray();
auto iSize = db.inputs.myIntArray.size();
const auto fValue = db.inputs.myFloatArray();
auto fSize = db.inputs.myFloatArray.size();
runCUDAcompute( iValue, iSize, fValue, fSize );
}
.. code-block:: c++
extern "C" void runCUDAcompute(inputs::myIntArray_t* iArray, size_t iSize, inputs::myFloat_t* fArray, size_t fSize)
{
// In here it is true that the number of elements in iArray = iSize
}
**Python Array Type Hint**
++++++++++++++++++++++++++
.. code-block:: python
import numpy as np
@property
def myIntArray(self) -> np.ndarray[np.int32]:
return attributeValues.myIntArray
**JSON Array Type**
+++++++++++++++++++
.. code-block:: json
{
"myNode" : {
"description" : ["This is my node with one integer array and one float array input"],
"version" : 1,
"inputs" : {
"myIntArray" : {
"description" : ["This is an integer array attribute"],
"type" : "int[]",
"default" : [1, 2, 3]
},
"myFloatArray" : {
"description" : ["This is a float array attribute"],
"type" : "float[]",
"default" : [1.0, 2.0, 3.0]
}
}
}
}
Tuple Data Types
----------------
An tuple type is a list of another data type with fixed length, analagous to a ``std::array`` in C++ or a
``tuple`` type in Python. Not every type can be a tuple, and the tuple count is restricted to a small subset of those
supported by USD. They are denoted with by appending square brackets containing the tuple count to the
type name. For example a tuple of two integers would have type `int[2]` and a tuple of three floats would have type
`float[3]`.
Since tuple types are implemented in C++ as raw data there is no differentiation between the types returned by input
versus output attributes, just a *const* clause.
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| Type Name | USD | C++ | CUDA | Python | JSON |
+===========+===============================+==============+==========+==================================+==============================+
| double[2] | (double,double) | pxr::GfVec2d | double2* | numpy.ndarray[numpy.float64](2,) | [float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| double[3] | (double,double,double) | pxr::GfVec3d | double3* | numpy.ndarray[numpy.float64](3,) | [float, float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| double[4] | (double,double,double,double) | pxr::GfVec4d | double4* | numpy.ndarray[numpy.float64](4,) | [float, float, float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| float[2] | (float,float) | pxr::GfVec2f | float2* | numpy.ndarray[numpy.float](2,) | [float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| float[3] | (float,float,float) | pxr::GfVec3f | float3* | numpy.ndarray[numpy.float](3,) | [float, float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| float[4] | (float,float,float,float) | pxr::GfVec4f | float4* | numpy.ndarray[numpy.float](4,) | [float, float, float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| half[2] | (half,half) | pxr::GfVec2h | __half2* | numpy.ndarray[numpy.float16](2,) | [float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| half[3] | (half,half,half) | pxr::GfVec3h | __half3* | numpy.ndarray[numpy.float16](3,) | [float, float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| half[4] | (half,half,half,half) | pxr::GfVec4h | __half4* | numpy.ndarray[numpy.float16](4,) | [float, float, float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| int[2] | (int,int) | pxr::GfVec2i | int2* | numpy.ndarray[numpy.int32](2,) | [float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| int[3] | (int,int,int) | pxr::GfVec3i | int3* | numpy.ndarray[numpy.int32](3,) | [float, float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
| int[4] | (int,int,int,int) | pxr::GfVec4i | int4* | numpy.ndarray[numpy.int32](4,) | [float, float, float, float] |
+-----------+-------------------------------+--------------+----------+----------------------------------+------------------------------+
.. note::
Owing to this implementation of a wrapper around raw data all of these types can also be safely
cast to other types that have an equivalent memory layout. For example:
``MyFloat3& f3 = reinterpret_cast<MyFloat3&>(db.inputs.myFloat3Attribute());``
Here's an example of how the class, typedef, USD, and CUDA types relate:
.. code-block:: c++
const GfVec3f& fRaw = db.inputs.myFloat3();
const ogn::float3& fOgn = reinterpret_cast<const ogn::float3&>(fRaw);
const carb::Float3& fCarb = reinterpret_cast<const carb::Float3>(fOgn);
vectorOperation( fCarb.x, fCarb.y, fCarb.z );
callCUDAcode( fRaw );
.. code-block:: c++
extern "C" void callCUDAcode(float3 myFloat3) {...}
Here are samples of tuple data type values in the various languages:
**USD Tuple Type**
++++++++++++++++++
.. code-block:: usd
custom int2 inputs:myIntTuple = (1, 2)
custom float3 inputs:myFloatTuple = (1.0, 2.0, 3.0)
**C++ Tuple Type**
++++++++++++++++++
.. code-block:: c++
static bool compute(OgnMyNodeDatabase& db)
{
const GfVec2i& iValue = db.inputs.myIntTuple();
const GfVec3f& fValue = db.inputs.myFloatTuple();
}
**CUDA Tuple Type**
+++++++++++++++++++
.. code-block:: c++
// Note how the signatures are not identical between the declaration here and the
// definition in the CUDA file. This is possible because the data types have identical
// memory layouts, in this case equivalent to int[2] and float[3].
extern "C" runCUDAcompute(pxr::GfVec2i* iTuple, pxr::GfVec3f* fTuple);
static bool compute(OgnMyNodeDatabase& db)
{
runCUDAcompute( db.inputs.myIntTuple(), db.inputs.myFloatTuple() );
}
.. code-block:: c++
extern "C" void runCUDAcompute(float3* iTuple, float3* fTuple)
{
// In here it is true that the number of elements in iArray = iSize
}
**Python Tuple Type Hint**
++++++++++++++++++++++++++
.. code-block:: python
import numpy as np
@property
def myIntTuple(self) -> np.ndarray[nd.int]:
return attributeValues.myIntTuple
@property
def myFloatTuple(self) -> np.ndarray[nd.float]:
return attributeValues.myFloatTuple
**JSON Tuple Type**
+++++++++++++++++++
.. code-block:: json
{
"myNode" : {
"description" : ["This is my node with one integer tuple and one float tuple input"],
"version" : 1,
"inputs" : {
"myIntTuple" : {
"description" : ["This is an integer tuple attribute"],
"type" : "int[2]",
"default" : [1, 2]
},
"myFloatTuple" : {
"description" : ["This is a float tuple attribute"],
"type" : "float[3]",
"default" : [1.0, 2.0, 3.0]
}
}
}
}
Arrays of Tuple Data Types
--------------------------
Like base data types, there can also be arrays of tuples by appending '[]' to the data type. For now the only
ones supported are the above special types, supported natively in USD. Once the USD conversions are sorted out,
all tuple types can be arrays using these rules.
The type names will have the tuple specification followed by the array specification, e.g. *float[3][]* for an
array of three-floats. This will also extend to arrays of arrays in the future by appending another '[]'.
JSON makes no distinction between arrays and tuples so it will be a multi-dimensional list.
USD uses parentheses **()** for tuples and square brackets **[]** for arrays so both are used to specify the
data values. The types are specified according to the USD Type column in the table above with square brackets appended.
Both the Python and C++ tuple and array types nest for arrays of tuple types.
+-------------+--------------------------------------+--------------------------+--------------------------------------------------+----------------------------+-----------+
| Type Name | C++ | CUDA | Python | JSON | Direction |
+=============+======================================+==========================+==================================================+============================+===========+
| TYPE[N][] | ogn::array<TUPLE_TYPE> | TUPLE_TYPE*,size_t | numpy.ndarray[numpy.TUPLE_TYPE](N,TUPLE_COUNT,) | array of array of JSONTYPE | Output |
+-------------+--------------------------------------+--------------------------+--------------------------------------------------+----------------------------+-----------+
Here are samples of arrays of tuple data type values in the various languages:
**USD Tuple Array Type**
++++++++++++++++++++++++
.. code-block:: usd
custom int2[] inputs:myIntTuple = [(1, 2), (3, 4), (5, 6)]
custom float3[] inputs:myFloatTuple = [(1.0, 2.0, 3.0)]
**C++ Tuple Array Type**
++++++++++++++++++++++++
.. code-block:: c++
static bool compute(OgnMyNodeDatabase& db)
{
const ogn::const_array<GfVec2i>& iValue = db.inputs.myIntTupleArray();
const ogn::const_array<GfVec3f> &fValue = db.inputs.myFloatTupleArray();
// or const auto& fValue = db.inputs.myFloatTupleArray();
}
**CUDA Tuple Array Type**
+++++++++++++++++++++++++
.. code-block:: c++
extern "C" runCUDAcompute(inputs::myIntTupleArray_t* iTuple, size_t iSize,
inputs::myFloatTupleArray_t* fTuple, size_t fSize);
static bool compute(OgnMyNodeDatabase& db)
{
runCUDAcompute( db.inputs.myIntTupleArray(), db.inputs.myIntTupleArray.size(),
db.inputs.myFloatTupleArray(), db.inputs.myFloatTupleArray.size() );
}
.. code-block:: c++
extern "C" void runCUDAcompute(float3** iTuple, size_t iSize, float3** fTuple, size_t fSize)
{
}
**Python Tuple Array Type Hint**
++++++++++++++++++++++++++++++++
.. code-block:: python
import numpy as np
@property
def myIntTupleArray(self) -> np.ndarray:
return attributeValues.myIntTupleArray
@property
def myFloatTupleArray(self) -> np.ndarray:
return attributeValues.myFloatTupleArray
**JSON Tuple Array Type**
+++++++++++++++++++++++++
.. code-block:: json
{
"myNode" : {
"description" : ["This is my node with one integer tuple array and one float tuple array input"],
"version" : 1,
"inputs" : {
"myIntTuple" : {
"description" : ["This is an integer tuple array attribute"],
"type" : "int[2][]",
"default" : [[1, 2], [3, 4], [5, 6]]
},
"myFloatTuple" : {
"description" : ["This is a float tuple array attribute"],
"type" : "float[3][]",
"default" : []
}
}
}
}
.. _ogn_attribute_roles:
Attribute Types With Roles
--------------------------
Some attributes have specific interpretations that are useful for determining how to use them at runtime. These
roles are encoded into the names for simplicity.
.. note::
The fundamental data in the attributes when an AttributeRole is set are unchanged. Adding the role just allows
the interpretation of that data as a first class object of a non-trivial type. The "C++ Type" column in the
table below shows how the underlying data is represented.
For simplicity of specification, the type of base data is encoded in the type name, e.g. *colord* for colors
using double values and *colorf* for colors using float values.
+--------------+------------+------------+----------+-----------------------------------------------------------+
| Type Name | USD | C++ | CUDA | Description |
+==============+============+============+==========+===========================================================+
| colord[3] | color3d | GfVec3d | double3 | Color value with 3 members of type double |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| colorf[3] | color3f | GfVec3f | float3 | Color value with 3 members of type float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| colorh[3] | color3h | GfVec3h | __half3 | Color value with 3 members of type 16 bit float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| colord[4] | color4d | GfVec4d | double4 | Color value with 4 members of type double |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| colorf[4] | color4f | GfVec4f | float4 | Color value with 4 members of type float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| colorh[4] | color4h | GfVec4h | __half4 | Color value with 4 members of type 16 bit float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| normald[3] | normal3d | GfVec3d | double3 | Normal vector with 3 members of type double |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| normalf[3] | normal3f | GfVec3f | float3 | Normal vector with 3 members of type float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| normalh[3] | normal3h | GfVec3h | __half3 | Normal vector with 3 members of type 16 bit float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| pointd[3] | pointd | GfVec3d | double3 | Cartesian point value with 3 members of type double |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| pointf[3] | pointf | GfVec3f | float3 | Cartesian point value with 3 members of type float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| pointh[3] | pointh | GfVec3h | __half3 | Cartesian point value with 3 members of type 16 bit float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| quatd[4] | quat4d | GfQuatd | double3 | Quaternion with 4 members of type double as IJKR |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| quatf[4] | quat4f | GfQuatf | float3 | Quaternion with 4 members of type float as IJKR |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| quath[4] | quat4h | GfQuath | __half3 | Quaternion with 4 members of type 16 bit float as IJKR |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| texcoordd[2] | texCoord2d | GfVec2d | double2 | Texture coordinate with 2 members of type double |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| texcoordf[2] | texCoord2f | GfVec2f | float2 | Texture coordinate with 2 members of type float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| texcoordh[2] | texCoord2h | GfVec2h | __half2 | Texture coordinate with 2 members of type 16 bit float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| texcoordd[3] | texCoord3d | GfVec3d | double3 | Texture coordinate with 3 members of type double |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| texcoordf[3] | texCoord3f | GfVec3f | float3 | Texture coordinate with 3 members of type float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| texcoordh[3] | texCoord3h | GfVec3h | __half3 | Texture coordinate with 3 members of type 16 bit float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| timecode | timecode | double | double | Double value representing a timecode |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| vectord[3] | vector3d | GfVec3d | double3 | Vector with 3 members of type double |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| vectorf[3] | vector3f | GfVec3f | float3 | Vector with 3 members of type float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| vectorh[3] | vector3h | GfVec3h | __half3 | Vector with 3 members of type 16 bit float |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| matrixd[2] | matrix2d | GfMatrix2d | Matrix2d | Transform matrix with 4 members of type double |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| matrixd[3] | matrix3d | GfMatrix3d | Matrix3d | Transform matrix with 9 members of type double |
+--------------+------------+------------+----------+-----------------------------------------------------------+
| matrixd[4] | matrix4d | GfMatrix4d | Matrix4d | Transform matrix with 16 members of type double |
+--------------+------------+------------+----------+-----------------------------------------------------------+
Python and JSON do not have special types for role-based attributes, although that may change for Python once its
interface is fully defined.
The roles are all tuple types so the Python equivalents will all be of the form **Tuple[TYPE, TYPE...]**, and JSON data
will be of the form **[TYPE, TYPE, TYPE]**. The types corresponding to the *Equivalent* column base types are seen above
in `Base Data Types`_.
The color role will serve for our example types here:
**USD Color Role Attribute**
+++++++++++++++++++++++++++++
.. code-block:: usd
custom color3d inputs:myColorRole = (1.0, 0.5, 1.0)
**C++ Color Role Attribute**
+++++++++++++++++++++++++++++
.. code-block:: c++
static bool compute(OgnMyNodeDatabase& db)
{
const GfVec3d& colorValue = db.inputs.myColorRole();
// or const auto& colorValue = db.inputs.myColorRole();
}
**CUDA Color Role Type**
++++++++++++++++++++++++
.. code-block:: c++
extern "C" runCUDAcompute(pxr::GfVec3d* color);
static bool compute(OgnMyNodeDatabase& db)
{
runCUDAcompute( db.inputs.myColorRole() );
}
.. code-block:: c++
extern "C" void runCUDAcompute(double3* color)
{
}
**Python Color Role Attribute Hint**
+++++++++++++++++++++++++++++++++++++
.. code-block:: python
import numpy as np
@property
def myColorRole(self) -> np.ndarray:
return attributeValues.myColorRole
**JSON Color Role Attribute**
++++++++++++++++++++++++++++++
.. code-block:: json
{
"myNode" : {
"description" : ["This is my node with one color role input"],
"version" : 1,
"inputs" : {
"myColorRole" : {
"description" : ["This is color role attribute"],
"type" : "colord[3]",
"default" : [0.0, 0.5, 1.0]
}
}
}
}
Bundle Type Attributes
----------------------
There is a special type of attribute whose type is *bundle*. This attribute represents a set of attributes whose
contents can only be known at runtime. It can still be in a tuple, array, or both. In itself it has no data in Fabric.
Its purpose is to be a container to a description of other attributes of any of the above types, or even
other bundles.
**USD Bundled Attribute**
++++++++++++++++++++++++++
.. code-block:: usd
custom rel inputs:inBundle (
doc="""The input bundle is a relationship, which could come from a prim or another bundle attribute""")
def Output "outputs_outBundle" (
doc="""Output bundles are represented as empty prims, with any namespace colons replaced by underscores""")
{
}
**C++ Bundled Attribute**
++++++++++++++++++++++++++
.. code-block:: c++
static bool compute(OgnMyNodeDatabase& db)
{
// The simplest method of breaking open a bundle is to get an attribute by name
const auto& inBundle = db.inputs.inBundle();
auto myFloat3Attribute = inBundle.attributeByName(db.stringToToken("myFloat3"));
if (auto asFloat3Array = myFloat3Attribute.get<float[][3]>())
{
handleFloat3Array(asFloat3Array); // The data is of type float[][3]
}
// The bundle has iteration capabilities
for (auto& bundledAttribute : inBundle)
{
// Use the type information to find the actual data type and then cast it
if ((bundledAttribute.type().baseType == BaseDataType::eInt)
&& (bundledAttribute.type().componentCount == 1)
&& (bundledAttribute.type().arrayDepth == 0))
{
CARB_ASSERT( nullptr != bundledAttribute.get<int>() );
}
}
}
See the tutorials on :ref:`ogn_tutorial_bundle_manipulation` and :ref:`ogn_tutorial_bundle_data` for more
details on manipulating the bundle and its attributes.
**CUDA Bundled Attribute**
+++++++++++++++++++++++++++
.. code-block:: c++
extern "C" runCUDAcompute(float3* value, size_t iSize);
static bool compute(OgnMyNodeDatabase& db)
{
const auto& myBundle = db.inputs.myBundle();
auto myFloat3Attribute = myBundle.attributeByName(db.stringToToken("myFloat3"));
if (auto asFloat3Array = myFloat3Attribute.get<float[][3]>())
{
runCUDAcompute(asFloat3Array.data(), asFloat3Array.size());
}
}
.. code-block:: c++
extern "C" void runCUDAcompute(float3** value, size_t iSize)
{
}
**Python Bundled Attribute Hint**
++++++++++++++++++++++++++++++++++
.. code-block:: python
from typing import Union
from omni.graph.core.types import AttributeTypes, Bundle, BundledAttribute
@property
def myBundle(self) -> Bundle:
return attributeValues.myBundle
attribute_count = myNode.myBundle.attribute_count()
for bundled_attribute in myNode.myBundle.attributes():
if bundled_attribute.type.base_type == AttributeTypes.INT:
deal_with_integers(bundled_attribute.value)
See the tutorials on :ref:`ogn_tutorial_bundle_manipulation` and :ref:`ogn_tutorial_bundle_data` for more
details on manipulating the bundle and its attributes.
**JSON Bundled Attribute**
++++++++++++++++++++++++++
.. code-block:: json
{
"myNode" : {
"description" : ["This is my node with one bundled input"],
"version" : 1,
"inputs" : {
"myBundle" : {
"description" : ["This is input bundle attribute"],
"type" : "bundle"
}
}
}
}
It's worth noting here that as a bundle does not represent actual data these attributes are not allowed to have a
default value.
If a bundle attribute is defined to live on the GPU, either at all times or as a decision at runtime, this is
equivalent to stating that any attributes that exist inside the bundle will be living on the GPU using the same
criteria.
Extended Attribute Types
------------------------
Some attribute types are only determined at runtime by the data they receive. These types include the "any" type, which
is a single attribute that can be any of the above types, and the "union" type, which specifies a subset of the above
types it can take on. (The astute will notice that "union" is a subset of "any".)
Extended attribute types allow a single node to handle several different attribute-type configurations. For example a
generic 'Cos' node may be able to compute the cosine of any decimal type.
**USD Extended Attribute**
++++++++++++++++++++++++++
.. code-block:: usd
custom token inputs:floatOrInt
custom token inputs:floatArrayOrIntArray
custom token inputs:anyType
**C++ Extended Attribute**
++++++++++++++++++++++++++
.. code-block:: c++
static bool compute(OgnMyNodeDatabase& db)
{
// Casting can be used to find the actual data type the attribute contains
const auto& floatOrInt = db.inputs.floatOrInt();
bool isFloat = (nullptr != floatOrInt.get<float>());
bool isInt = (nullptr != floatOrInt.get<int>());
// Different types are cast in the same way as bundle attributes
const auto& floatOrIntArray = db.inputs.floatOrIntArray();
bool isFloatArray = (nullptr != floatOrIntArray.get<float[]>());
bool isIntArray = (nullptr != floatOrIntArray.get<int[]>());
const auto& anyType = db.inputs.anyType();
std::cout << "Any type is " << anyType.type() << std::endl;
// Like bundled attributes, use the type information to find the actual data type and then cast it
if ((anyType.type().baseType == BaseDataType::eInt)
&& (anyType.type().componentCount == 1)
&& (anyType.type().arrayDepth == 0))
{
CARB_ASSERT( nullptr != anyType.get<int>() );
}
}
**CUDA Extended Attribute**
+++++++++++++++++++++++++++
.. code-block:: c++
extern "C" runCUDAcomputeFloat(float3* value, size_t iSize);
extern "C" runCUDAcomputeInt(int3* value, size_t iSize);
static bool compute(OgnMyNodeDatabase& db)
{
const auto& float3OrInt3Array = db.inputs.float3OrInt3Array();
if (auto asFloat3Array = float3OrInt3Array.get<float[][3]>())
{
runCUDAcomputeFloat(asFloat3Array.data(), asFloat3Array.size());
}
else if (auto asInt3Array = float3OrInt3Array.get<int[][3]>())
{
runCUDAcomputeint(asInt3Array.data(), asInt3Array.size());
}
}
.. code-block:: c++
extern "C" void runCUDAcomputeFloat(float3** value, size_t iSize)
{
}
extern "C" void runCUDAcomputeInt(int3** value, size_t iSize)
{
}
**Python Extended Attribute Hint**
++++++++++++++++++++++++++++++++++
.. code-block:: python
from typing import Union
@property
def myIntOrFloatArray(self) -> List[Union[int, float]]:
return attributeValues.myIntOrFloatArray
**JSON Extended Attribute**
+++++++++++++++++++++++++++
.. code-block:: json
{
"myNode" : {
"description" : "This is my node with some extended inputs",
"version" : 1,
"inputs" : {
"anyType" : {
"description" : "This attribute accepts any type of data, determined at runtime",
"type" : "any"
},
"someNumber": {
"description": "This attribute accepts either float, double, or half values",
"type": ["float", "double", "half"]
},
"someNumberArray": {
"description": ["This attributes accepts an array of float, double, or half values.",
"All values in the array must be of the same type, like a regular array attribute."],
"type": ["float[]", "double[]", "half[]"],
},
}
}
}
**Extended Attribute Union Groups**
+++++++++++++++++++++++++++++++++++
As described above, union extended types are specified by providing a list of types in the OGN definition. These lists can become
quite long if a node can handle a large subset of the possible types. For convenience there are special type names that can be
used inside the JSON list to denote groups of types. For example:
.. code-block:: json
{
"myNode" : {
"description" : "This is my node using union group types",
"version" : 1,
"inputs" : {
"decimal" : {
"description" : "This attribute accepts double, float and half",
"type" : ["decimal_scalers"]
}
}
}
}
**List of Attribute Union Groups**
++++++++++++++++++++++++++++++++++
+-------------------------+------------------------------------------------------------------------------------------+
| Group Type Name | Type Members |
+=========================+==========================================================================================+
| integral_scalers | uchar, int, uint, uint64, int64, timecode |
+-------------------------+------------------------------------------------------------------------------------------+
| integral_tuples | int[2], int[3], int[4] |
+-------------------------+------------------------------------------------------------------------------------------+
| integral_array_elements | integral_scalers, integral_tuples |
+-------------------------+------------------------------------------------------------------------------------------+
| integral_arrays | arrays of integral_array_elements |
+-------------------------+------------------------------------------------------------------------------------------+
| integrals | integral_array_elements, integral_arrays |
+-------------------------+------------------------------------------------------------------------------------------+
| matrices | matrixd[3], matrixd[4], transform[4], frame[4] |
+-------------------------+------------------------------------------------------------------------------------------+
| decimal_scalers | double, float, half |
+-------------------------+------------------------------------------------------------------------------------------+
| decimal_tuples | double[2], double[3], double[4], float[2], float[3], float[4], half[2], half[3], half[4] |
| | |
| | colord[3], colord[4], colorf[3], colorf[4], colorh[3], colorh[4] |
| | |
| | normald[3], normalf[3], normalh[3] |
| | |
| | pointd[3], pointf[3], pointh[3] |
| | |
| | texcoordd[2], texcoordd[3], texcoordf[2], texcoordf[3], texcoordh[2], texcoordh[3] |
| | |
| | quatd[4], quatf[4], quath[4] |
| | |
| | vectord[3], vectorf[3], vectorh[3] |
+-------------------------+------------------------------------------------------------------------------------------+
| decimal_array_elements | decimal_scalers, decimal_tuples |
+-------------------------+------------------------------------------------------------------------------------------+
| decimal_arrays | arrays of decimal_array_elements |
+-------------------------+------------------------------------------------------------------------------------------+
| decimals | decimal_array_elements, decimal_arrays |
+-------------------------+------------------------------------------------------------------------------------------+
| numeric_scalers | integral_scalers, decimal_scalers |
+-------------------------+------------------------------------------------------------------------------------------+
| numeric_tuples | integral_tuples, decimal_tuples |
+-------------------------+------------------------------------------------------------------------------------------+
| numeric_array_elements | numeric_scalers, numeric_tuples, matrices |
+-------------------------+------------------------------------------------------------------------------------------+
| numeric_arrays | arrays of numeric_array_elements |
+-------------------------+------------------------------------------------------------------------------------------+
| numerics | numeric_array_elements, numeric_arrays |
+-------------------------+------------------------------------------------------------------------------------------+
| array_elements | numeric_array_elements, token |
+-------------------------+------------------------------------------------------------------------------------------+
| arrays | numeric_arrays, token[] |
+-------------------------+------------------------------------------------------------------------------------------+
**Extended Attribute Resolution**
+++++++++++++++++++++++++++++++++
Extended attributes are useful to improve the usability of nodes with different types. However the node author has an
extra responsibility to resolve the extended type attributes when possible in order to resolve possible ambiguity
in the graph. If graph connections are unresolved at execution, the node's computation will be skipped.
There are various helpful Python APIs for type resolution, including :py:func:`omni.graph.core.resolve_base_coupled` and
:py:func:`omni.graph.core.resolve_fully_coupled` which allow you to match unresolved inputs to resolved inputs.
.. code-block:: python
@staticmethod
def on_connection_type_resolve(node) -> None:
aattr = node.get_attribute("inputs:a")
resultattr = node.get_attribute("outputs:result")
og.resolve_fully_coupled([aattr, resultattr])
You can also define your own semantics for custom type resolution. The following node takes two decimals, a and b,
and returns their product. If one input is at a lower "significance" than the other, the less significant will be "promoted"
to prevent loss of precision. For example, if inputs are `float` and `double`, the output will be a `double`.
See :class:`omni.graph.core.Type` for more information about creating custom types.
.. code-block:: python
@staticmethod
def on_connection_type_resolve(node) -> None:
atype = node.get_attribute("inputs:a").get_resolved_type()
btype = node.get_attribute("inputs:b").get_resolved_type()
productattr = node.get_attribute("outputs:product")
producttype = productattr.get_resolved_type()
# we can only infer the output given both inputs are resolved and they are the same.
if (atype.base_type != og.BaseDataType.UNKNOWN and btype.base_type != og.BaseDataType.UNKNOWN
and producttype.base_type == og.BaseDataType.UNKNOWN):
if atype.base_type == btype.base_type:
base_type = atype.base_type
else:
decimals = [og.BaseDataType.HALF, og.BaseDataType.FLOAT, og.BaseDataType.DOUBLE]
try:
a_ix = decimals.index(atype.base_type)
except ValueError:
a_ix = -1
try:
b_ix = decimals.index(btype.base_type)
except ValueError:
b_ix = -1
if a_ix >= 0 or b_ix >= 0:
base_type = atype.base_type if a_ix > b_ix else btype.base_type
else:
base_type = og.BaseDataType.DOUBLE
productattr.set_resolved_type(og.Type(base_type, max(atype.tuple_count, btype.tuple_count),
max(atype.array_depth, btype.array_depth)))
See :ref:`ogn_tutorial_extended_types` for more examples on how to perform attribute resolution in C++ and Python.
.. _ogn_type_definition_overrides:
Type Definition Overrides
-------------------------
The generated types provide a default implementation you can use out of the box. Sometimes you might have your own
favorite library for type manipulation so you can provide a type definition configuration file that modifies the
return types used by the generated code.
There are four ways you can implement type overrides.
1. Use the `typeDefinitions` flag on the `generate_node.py` script to point to the file containing the configuration.
2. Use the `"typeDefinitions": "ConfigurationFile.json"` keyword in the .ogn file to point a single node to a configuration.
3. Use the `"typeDefintitions": {TypeConfigurationDictionary}` keyword in the .ogn file to implement simple targeted overrides in a single node.
4. Add the name of the type definitions file to your premake5.lua file in `get_ogn_project_informat("omni/test", "ConfigurationFile.json")` to modify the types for every node in your extension.
The format used for the type definition information is the same for all methods. Here is a sample, with an embedded
explanation on how it is formatted.
.. literalinclude:: ../../../../source/extensions/omni.graph.tools/ogn_config/TypeConfigurationPod.json
:language: json
| 52,242 | reStructuredText | 49.089166 | 193 | 0.439397 |
omniverse-code/kit/exts/omni.graph.tools/docs/node_architects_guide.rst | .. _ogn_node_architects_guide:
OmniGraph Node Architects Guide
===============================
This outlines the code that will be generated behind the scenes by the node generator from a .ogn file.
This includes the API presented to the node that is outlined in :ref:`ogn_user_guide`.
As the details of the generated code are expected to change rapidly this guide does not go into specific details,
it only provides the broad strokes, expecting the developer to go to the either the generated code or the code
generation scripts for the current implementation details.
Helper Templates
----------------
A lot of the generated C++ code relies on templates defined in the helper files ``omni/graph/core/Ogn*.h``,
which contains code that assists in the registration and running of the node, classes to wrap the internal data used
by the node for evaluation, and general type conversion assistance.
None of the code in there is compiled so there is no ABI compatibility problem. This is a critical feature of these
wrappers.
See the files themselves for full documentation on what they handle.
C ABI Interface
---------------
The key piece of generated code is the one that links the external C ABI for the compute node with the
class implementing a particular node's evaluation algorithm. This lets the node writer focus on their business
logic rather than boilerplate ABI conformity details.
The actual ABI implementation for the *INodeType* interface is handled by the templated helper class
*OmniGraphNode_ABI* from ``OgnHelpers.h``. It implements all of the functions required by the ABI, then uses the
"tag-dispatching" technique to selectively call either the default implementation, or the one provided by the
node writer.
In turn, that class has a derived class of *RegisterOgnNode* (defined in ``OgnHelpers.h``).
It adds handling of the automatic registration and deregistration of node types.
Instantiation of the ABI helper class for a given node type is handled by the *REGISTER_OGN_NODE()* macro, required
at the end of every node implementation file.
Attribute Information Caching
-----------------------------
ABI accesss requires attribute information be looked up by name, which can cause a lot of inefficiency. To prevent
this, a templated helper class *IAttributeOgnInfo* is created for every attribute. It contains the attribute's
information, such as its name, its unique handle token, and default value (if any). This is information that is the
same for the attribute in every instance of the node so there is only one static instance of it.
Fabric Access
-------------
This is the core of the benefit provided by the .ogn generated interface. Every node has a *OgnMyNodeDatabase* class
generated for it, which contains accessors to all of the Fabric data in an intuitive form. The base class
*OmniGraphDatabase*, from ``OgnHelpers.h``, provides the common functionality for that access, including token
conversion, and access to the context and node objects provided by the ABI.
The attribute data access is accomplished with two or three pieces of data for every attribute.
1. A raw pointer to the data for that attribute residing in the Fabric
2. (optional, for arrays only) A raw pointer to the element count for the Fabric array data
3. A wrapper class, which will return a reference object from its *operator()* function
The data accessors are put inside structs names *inputs* and *outputs* so that data can be accessed by the actual
attribute's name, e.g. *db.inputs.myInputAttribute()*.
Accessing Data
++++++++++++++
The general approach to accessing attribute data on a node is to wrap the Fabric data in a class that is suited
to handle the movement of data between Fabric and the node in a way that is more natural to the node writer.
For consistency of access, the accessors all override the call operator (``operator()``) to return a wrapper class
that provides access to the data in a natural form. For example, simple POD data will return a direct reference to
the underlying Fabric data (e.g. a ``float&``) for manipulation.
Inputs typically provide const access only. The declaration of the return values can always be simplified by
using ``const auto&`` for inputs and ``auto&`` for outputs and state attributes.
More complex types will return wrappers tailored towards their own access. Where it gets tricky is with variable
sized attributes, such as arrays or bundles. We cannot rely on standard data types to manage them as Fabric is
the sole arbiter of memory management.
Such classes are returned as wrappers that operate as though they are standard types but are actually intermediates
for translating those operations into Fabric manipulation.
For example instead of retrieving arrays as raw ``float*`` or ``std::vector<float>`` they will be retrieved as the
wrapper class ``ogn::array`` or ``ogn::const_array``. This allows all the same manipulations as a ``std::vector<float>``
including iteration for use in the STL algorithm library, through Fabric interfaces.
If you are familiar with the concept of ``std::span`` an array can be thought of in the same way, where the raw data
is managed by Fabric.
Data Initialization
+++++++++++++++++++
All of this data must be initialized before the *compute()* method can be called. This is done in the constructor
of the generated database class, which is constructed by the ABI wrapper to the node's compute method.
Here's a pseudocode view of the calls that would result from a node compute request:
.. code-block:: text
OmniGraphNode_ABI<MyNode, MyNodeDatabase>::compute(graphContext, node);
OgnMyNodeDatabase db(graphContext, node);
getAttributesR for all input attributes
getAttributesW for all output attributes
getDataR for all input attributes
getElementCount for all input array attributes
getDataW for all output attributes
getElementCount for all output array attributes
return db.validate() ? OgnMyNode::compute(db) : false;
Input Validation
----------------
The node will have specified certain conditions required in order for the compute function to be valid. In the
simplest form it will require that a set of input and output attributes exist on the node. Rather than forcing every
node writer to check these conditions before they run their algorithm this is handled by a generated *validate()*
function.
This function checks the underlying Fabric data to make sure it conforms to the conditions required by the node.
In future versions this validation will perform more sophisticated tasks, such as confirming that two sets of input
arrays have the same size, or that attribute values are within the legal ranges the node can recognize.
Python Support
--------------
Python support comes in two forms - support for C++ nodes, and ABI definition for Python node implementations.
For any node written in C++ there is a Python accessor class created that contains properties for accessing the
attribute data on the node. The evaluation context is passed to the accessor class so it can only be created when
one is available.
The accessor is geared for getting and setting values on the attributes of a node.
.. code-block:: python
import omni.graph.core as og
from my.extension.ogn import OgnMyNodeDatabase
my_node = og.get_graph_by_path("/World/PushGraph").get_node("/World/PushGraph/MyNode")
my_db = OgnMyNodeDatabase(og.ContextHelper(), my_node)
print(f"The current value of my float attribute is {my_db.inputs.myFloat}")
my_db.inputs.myFloat = 5.0
.. important::
For Python node implementations the registration process is performed automatically when you load your extension by
looking for the ``ogn/`` subdirectory of your Python import path. The generated Python class performs all of the
underlying management tasks such as registering the ABI methods, providing forwarding for any methods you might have
overridden, creating attribute accessors, and initializing attributes and metadata.
In addition, all of your nodes will be automatically deregistered when the extension is disabled.
| 8,183 | reStructuredText | 51.461538 | 120 | 0.766834 |
omniverse-code/kit/exts/omni.graph.tools/docs/README.md | # OmniGraph Tools [omni.graph.tools]
This is where the functionality of the Omniverse Graph node generator lives. These are the scripts responsible for parsing .ogn files.
| 173 | Markdown | 42.499989 | 134 | 0.803468 |
omniverse-code/kit/exts/omni.graph.tools/docs/index.rst | OmniGraph Tools And .ogn Node Generator
#######################################
.. tabularcolumns:: |L|R|
.. csv-table::
:width: 100%
**Extension**: omni.graph.tools,**Documentation Generated**: |today|
The OmniGraph Tools extension contains general purpose scripts for dealing with OmniGraph, mostly through the .ogn
file format.
If you are interested in writing nodes the best places to start are the :ref:`ogn_user_guide` or the
:ref:`ogn_reference_guide`.
.. toctree::
:maxdepth: 2
:caption: Contents
node_architects_guide.rst
ogn_user_guide.rst
ogn_reference_guide.rst
attribute_types.rst
ogn_code_samples_cpp.rst
ogn_code_samples_python.rst
ogn_generation_script.rst
CHANGELOG.md
| 733 | reStructuredText | 23.466666 | 114 | 0.683492 |
omniverse-code/kit/exts/omni.graph.tools/docs/ogn_code_samples_cpp.rst | .. _ogn_code_samples_cpp:
OGN Code Samples - C++
======================
This files contains a collection of examples for using the .ogn generated code from C++. There is no particular flow
to these examples, they are used as reference data for the :ref:`ogn_user_guide`.
.. contents::
.. _ogn_minimal_node_cpp:
Minimal C++ Node Implementation
-------------------------------
Every C++ node must contain an include of the file containing the generated database definition, and an implementation
of the ``compute`` method that takes the database as a parameter and returns a boolean indicating if the compute
succeeded.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-minimal
:end-before: end-minimal
:ref:`[Python Version]<ogn_minimal_node_py>`
.. _ogn_metadata_node_cpp:
Node Type Metadata Access
-------------------------
When node types have any metadata added to them they can be accessed through the ABI node type interface.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-node-metadata
:end-before: end-node-metadata
:ref:`[Python Version]<ogn_metadata_node_py>`
.. _ogn_node_with_icon_cpp:
Node Icon Location Access
-------------------------
Specifying the icon location and color information creates consistently named pieces of metadata that the UI can use to
present a more customized visual appearance.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-node-icon
:end-before: end-node-icon
:ref:`[Python Version]<ogn_node_with_icon_py>`
.. _ogn_scheduling_node_cpp:
Node Type Scheduling Hints
--------------------------
Specifying scheduling hints makes it easier for the OmniGraph scheduler to optimize the scheduling of node evaluation.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-node-scheduling
:end-before: end-node-scheduling
:ref:`[Python Version]<ogn_scheduling_node_python>`
.. _ogn_singleton_node_cpp:
C++ Singleton Node Types
------------------------
Specifying that a node type is a singleton creates a consistently named piece of metadata that can be checked to see
if multiple instances of that node type will be allowed in a graph or its child graphs. Attempting to create more than
one of such node types in the same graph or any of its child graphs will result in an error.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-node-singleton
:end-before: end-node-singleton
:ref:`[Python Version]<ogn_singleton_node_py>`
.. _ogn_tags_node_cpp:
Node Type Tags
--------------
Specifying the node tags creates a consistently named piece of metadata that the UI can use to present a more
friendly grouping of the node types to the user.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-node-tags
:end-before: end-node-tags
This example introduces some helper constants which contain strings set to the key values of special internal metadata.
These are metadata elements managed by the code generator. Using these name accessors ensures consistent access.
.. code-block:: text
kOgnMetadataAllowedTokens # On attributes of type token, a CSV formatted comma-separated list of potential legal values for the UI
kOgnMetadataCategories # On node types, contains a comma-separated list of categories to which the node type belongs
kOgnMetadataDescription # On attributes and node types, contains their description from the .ogn file
kOgnMetadataExtension # On node types, contains the extension that owns this node type
kOgnMetadataHidden # On attributes and node types, indicating to the UI that they should not be shown
kOgnMetadataIconPath # On node types, contains the file path to the node's icon representation in the editor
kOgnMetadataIconBackgroundColor # On node types, overrides the background color of the node's icon
kOgnMetadataIconBorderColor # On node types, overrides the border color of the node's icon
kOgnMetadataSingleton # On node types its presence indicates that only one of the node type may be created in a graph
kOgnMetadataTags # On node types, a comma-separated list of tags for the type
kOgnMetadataUiName # On attributes and node types, user-friendly name specified in the .ogn file
kOgnMetadataUiType # On certain attribute types, customize how the attribute is displayed on the property panel
:ref:`[Python Version]<ogn_tags_node_py>`
.. _ogn_tokens_node_cpp:
Token Access
------------
There are two accelerators for dealing with tokens. The first is the tokens that are predefined in the generated
code. The second include a couple of methods on the database that facilitate translation between strings and
tokens.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-tokens
:end-before: end-tokens
:ref:`[Python Version]<ogn_tokens_node_py>`
.. _ogn_uiName_node_cpp:
Node Type UI Name Access
------------------------
Specifying the node UI name creates a consistently named piece of metadata that the UI can use to present a more
friendly name of the node type to the user.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-node-uiName
:end-before: end-node-uiName
:ref:`[Python Version]<ogn_uiName_node_py>`
.. _ogn_simple_node_cpp:
Simple Attribute Data Type
--------------------------
Accessors are created on the generated database class that return a reference to the underlying attribute data, which
lives in Fabric. You can use ``auto&` and ``const auto&`` type declarations to provide local names to clarify your
code, or you can specify the exact types that are referenced, so long as they are compatible. e.g. if you have a local
typedef ``Byte`` that is a ``uint8_t`` then you can use that type to get a reference to the data. This will be more
useful with more complex data types later.
.. tip::
For convenience in debugging the actual typedefs for the data are included in the database. They can be found
in the same location as the attributes, but with a *_t* suffix. For example the attribute ``db.outputs.length``
will have a corresponding typedef of ``db.outputs.length_t``, which resolves to ``int64_t``.
References to Fabric are actually done through lightweight accessor classes, which provide extra functionality
such as the ability to check if an attribute value is valid or not - ``compute()`` will not be called if any of
the required attributes are invalid. For example with the simple data types the accessor implements
``operator()`` to directly return a reference to the Fabric memory, as seen in the example.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-simple
:end-before: end-simple
.. tip::
As these accessor types may be subject to change it's best to avoid exposing their types (i.e. the data type of
``db.inputs.token``). If you must pass around attribute data, use the direct references returned from ``operator()``.
:ref:`[Python Version]<ogn_simple_node_py>`
.. _ogn_tuple_node_cpp:
Tuple Attribute Data Type
-------------------------
The wrappers for tuple-types are largely the same as for simple types. The main difference is the underlying data type
that they are wrapping. By default, the ``pxr::GfVec`` types are the types returned from ``operator()`` on tuple types.
Their memory layout is the same as their equivalent POD types, e.g. ``pxr::GfVec3f`` -> ``float[3]`` so you can cast
them to any other equivalent types from your favourite math library.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-tuple
:end-before: end-tuple
:ref:`[Python Version]<ogn_tuple_node_py>`
.. _ogn_role_node_cpp:
Role Attribute Data Type
------------------------
The wrappers for role-types are identical to their underlying tuple types. The only distinction between the types is
the value that will be returned from the wrapper's ``role()`` method.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-role
:end-before: end-role
:ref:`[Python Version]<ogn_role_node_py>`
.. _ogn_array_node_cpp:
Array Attribute Data Type
-------------------------
Array attributes are stored in a wrapper that mirrors the functionality of ``std::span``. The memory being managed
belongs to Fabric, with the wrapper providing the functionality to seamlessly manage the memory when the array size
changes (on writable attributes only).
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-array
:end-before: end-array
:ref:`[Python Version]<ogn_array_node_py>`
.. _ogn_tuple_array_node_cpp:
Tuple-Array Attribute Data Type
-------------------------------
The wrappers for tuple-array types are largely the same as for simple array types. The main difference is the
underlying data type that they are wrapping. See the :ref:`ogn_tuple_node_cpp` section for details on accessing
tuple data.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-tuple-array
:end-before: end-tuple-array
:ref:`[Python Version]<ogn_tuple_array_node_py>`
.. _ogn_string_node_cpp:
String Attribute Data Type
--------------------------
As the normal operations applied to strings involve size changes, and Fabric requires new allocations every time an
array's size changes, it is best to use a local variable for string manipulations rather than modifying the string
directly. Doing so also gives you the ability to access the wealth of string manipulation library functions.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-string
:end-before: end-string
:ref:`[Python Version]<ogn_string_node_py>`
.. _ogn_any_node_cpp:
Extended Attribute Data Type - Any
----------------------------------
Extended attributes, of type "any" and union, have data types that are resolved at runtime. This requires extra
information that identifies the resolved types and provides methods for extracting the actual data from the wrapper
around the extended attribute.
In C++ this is accomplished with prudent use of templated methods and operator overloads. The wrapper around the
extended attribute types uses this to provide access to a layered wrapper for the resolved data type, which in turn
provides wrapped access to the underlying Fabric functionality.
This is the documentation for the interface of the extended attribute wrapper class, taken directly from the
implementation file:
.. literalinclude:: ../../../../include/omni/graph/core/ogn/RuntimeAttribute.h
:language: cpp
:start-after: begin-extended-attribute-interface-description
:end-before: end-extended-attribute-interface-description
The first extended type, **any**, is allowed to resolve to any other attribute type.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-union
:end-before: end-union
:ref:`[Python Version]<ogn_any_node_py>`
.. _ogn_union_node_cpp:
Extended Attribute Data Type - Union
------------------------------------
The access pattern for the union attribute types is exactly the same as for the **any** type. There is just a tacit
agreement that the resolved types will always be one of the ones listed in the union type description.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-union
:end-before: end-union
:ref:`[Python Version]<ogn_union_node_py>`
.. _ogn_bundle_node_cpp:
Extended Attribute Type Resolution using `ogn::compute`
-------------------------------------------------------
As you might see, resolving attributes manually in c++ results in a lot of repeated code that is difficult to read.
the `ogn::compute` api, defined in `<omni/graph/core/ogn/ComputeHelpers.h>` aims to make this easier for developers.
.. literalinclude:: ../../../../include/omni/graph/core/ogn/ComputeHelpers.h
:language: cpp
:start-after: begin-compute-helpers-interface-description
:end-before: end-compute-helpers-interface-description
For a complete code sample, see the implementation of the `OgnAdd` node:
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-compute-helpers
:end-before: end-compute-helpers
Bundle Attribute Data Type
--------------------------
Bundle attribute information is accessed the same way as information for any other attribute type. As an aggregate,
the bundle can be treated as a container for attributes, without any data itself.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-bundle
:end-before: end-bundle
:ref:`[Python Version]<ogn_bundle_node_py>`
.. _ogn_bundle_data_cpp:
When you want to get at the actual data, you use the bundle API to extract the runtime attribute accessors from the
bundle for those attributes you wish to process.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-bundle-data
:end-before: end-bundle-data
.. tip::
Although you access them in completely different ways the attributes that are bundle members use the same accessors
as the extended attribute types. See further information in :ref:`ogn_any_node_cpp`
This documentation for bundle access is pulled directly from the code. It removes the extra complication in the
accessors required to provide proper typing information for bundle members and shows the appropriate calls in the
bundle attribute API.
.. literalinclude:: ../../../../include/omni/graph/core/ogn/Bundle.h
:language: cpp
:start-after: begin-bundle-interface-description
:end-before: end-bundle-interface-description
:ref:`[Python Version]<ogn_bundle_data_py>`
.. _ogn_attribute_memory_type_cpp:
Attribute Memory Location
-------------------------
In C++ nodes the GPU calculations will typically be done by CUDA code. The important thing to remember for this code
is that the CPU, where the node ``compute()`` method lives, cannot dereference pointers in the GPU memory space.
For this reason, all of the APIs that provide access to attribute data values return pointers to the actual data
when it lives on the GPU.
For example, if an attribute has a float value
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-memory-type
:end-before: end-memory-type
:ref:`[Python Version]<ogn_attribute_memory_type_py>`
.. _ogn_node_cudaPointers_cpp:
Attribute CPU Pointers to GPU Data
----------------------------------
.. note::
Although this value takes effect at the attribute level the keyword is only valid at the node level. All
attributes in a node will use the same type of CUDA array pointer referencing.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-cuda-pointers
:end-before: end-cuda-pointers
:ref:`[Python Version]<ogn_node_cudaPointers_py>`
.. _ogn_node_categories_cpp:
Node Type Categories
--------------------
Categories are added as metadata to the node and can be accessed through the standard metadata interface.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-node-categories
:end-before: end-node-categories
:ref:`[Python Version]<ogn_node_categories_py>`
.. _ogn_metadata_attribute_cpp:
Attribute Metadata Access
-------------------------
When attributes have metadata added to them they can be accessed through the ABI attribute interface. This works
basically the same as with metadata on node types, just with different accessors.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-attribute-metadata
:end-before: end-attribute-metadata
:ref:`[Python Version]<ogn_metadata_attribute_py>`
.. _ogn_optional_cpp:
Required vs. Optional Attributes
--------------------------------
For most attributes the generated code will check to see if the attribute is valid before it calls the `compute()`
function. Optional attributes will not have this check made. If you end up using their value then you must make the
call to the `isValid()` method yourself first and react appropriately if invalid values are found. Further, the
existence of these attributes within the compute method is not guaranteed.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-optional
:end-before: end-optional
:ref:`[Python Version]<ogn_optional_py>`
.. caution::
Optional attributes may not even appear on the node. This puts the onus on the node writer to completely validate
the attributes, and provide their own ABI-based access to the attribute data. Use of such attributes should be rare.
.. _ogn_uiName_attribute_cpp:
Attribute UI Name Access
------------------------
Specifying the attribute **uiName** creates a consistently named piece of metadata that the UI can use to present a more
friendly version of the attribute name to the user. It can be accessed through the regular metadata ABI, with some
constants provided for easier access.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-attribute-uiName
:end-before: end-attribute-uiName
Another access point is shown here. As the attribute patterns defined in the .ogn are unchanging the generated code
provides access to the name of the attribute through a data member so that you don't have to replicate the string.
The access is through local namespaces **inputs::**, **outputs::**, and **state::**, mirroring the database structure.
.. code-block:: cpp
inputs::x.token() // The name of the input attribute "x" as a token
inputs::x.name() // The name of the input attribute "x" as a static string
:ref:`[Python Version]<ogn_uiName_attribute_py>`
.. _ogn_uiType_attribute_cpp:
Attribute Type UI Type Access
-----------------------------
Specifying the attribute **uiType** tells the property panel that this attribute should be shown with custom widgets.
- For path, string, and token attributes, a ui type of "filePath" will show file browser widgets
- For 3- and 4-component numeric tuples, a ui type of "color" will show the color picker widget
in the property panel.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-attribute-uiType
:end-before: end-attribute-uiType
:ref:`[Python Version]<ogn_uiType_attribute_py>`
.. _ogn_unvalidated_cpp:
Unvalidated Attributes
----------------------
For most attributes the generated code will check to see if the attribute is valid before it calls the `compute()`
function. unvalidated attributes will not have this check made. If you end up using their value then you must make the
call to the `isValid()` method yourself first and react appropriately if invalid values are found. Further, for
attributes with extended types you must verify that they have successfully resolved to a legal type.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-unvalidated
:end-before: end-unvalidated
:ref:`[Python Version]<ogn_unvalidated_py>`
.. _ogn_state_node_cpp:
Nodes With Internal State
-------------------------
The easiest way to add internal state information is by adding data members to your node class. The presence of any
member variables automatically marks the node as having internal state information, allocating and destroying it
when the node itself is initialized and released. Once the internal state has been constructed it is not modified by
OmniGraph until the node is released, it is entirely up to the node how and when to modify the data.
The data can be easily retrieved with the templated method *internalState<>* on the database class.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-state-node
:end-before: end-state-node
.. note::
As access to internal state data is templated you can also store your state data in some external structure,
however when you do so you must also be sure to override the `setHasState()` ABI method to always return true.
Unless absolutely necessary it's always easier to make the state a member variable of your node.
:ref:`[Python Version]<ogn_state_node_py>`
.. _ogn_versioned_node_cpp:
Nodes With Version Upgrades
---------------------------
To provide code to upgrade a node from a previous version to the current version you must override the ABI function
`updateNodeVersion()`. The current context and node to be upgraded are passed in, as well as the old version at which
the node was created and the new version to which it should be upgraded. Passing both values allows you to upgrade
nodes at multiple versions in the same code.
This example shows how a new attribute is added using the *INode* ABI interface.
.. literalinclude:: ogn_code_samples_cpp.cpp
:language: cpp
:start-after: begin-versioned-node
:end-before: end-versioned-node
:ref:`[Python Version]<ogn_versioned_node_py>`
| 21,114 | reStructuredText | 38.615385 | 139 | 0.729469 |
omniverse-code/kit/exts/omni.graph.tools/docs/ogn_reference_guide.rst | .. _ogn_reference_guide:
OGN Reference Guide
===================
This is a detailed guide to the syntax of the .ogn file. All of the keywords supported are described in detail, and a
simplified JSON schema file is provided for reference.
Each of the described elements contains an example of its use in a .ogn file to illustrate the syntax.
For a more detailed guide on how each of the elements are used see the :ref:`ogn_user_guide`.
.. contents::
..
..
==================================== ====
Node Level Keywords Attribute Level Keywords
==================================== ====
:ref:`ogn_keyword_node_description` :ref:`ogn_keyword_attribute_description`
:ref:`ogn_keyword_node_exclude` :ref:`ogn_keyword_attribute_default`
:ref:`ogn_keyword_node_icon` :ref:`ogn_keyword_attribute_deprecated`
:ref:`ogn_keyword_node_memoryType` :ref:`ogn_keyword_attribute_memoryType`
:ref:`ogn_keyword_node_cudaPointers` :ref:`ogn_keyword_attribute_metadata`
:ref:`ogn_keyword_node_metadata` :ref:`maximum <ogn_keyword_attribute_range>`
:ref:`ogn_keyword_node_singleton` :ref:`minimum <ogn_keyword_attribute_range>`
:ref:`ogn_keyword_node_tags` :ref:`ogn_keyword_attribute_optional`
:ref:`ogn_keyword_node_tokens` :ref:`ogn_keyword_attribute_type`
:ref:`ogn_keyword_node_uiName` :ref:`ogn_keyword_attribute_uiName`
:ref:`ogn_keyword_node_version` :ref:`ogn_keyword_attribute_uiType`
:ref:`ogn_keyword_node_language` :ref:`ogn_keyword_attribute_unvalidated`
:ref:`ogn_keyword_node_scheduling`
:ref:`ogn_keyword_node_categories`
==================================== ====
------------
Basic Structure
---------------
See the :ref:`omnigraph_naming_conventions` for guidance on how to name your files, nodes, and attributes.
.. code-block:: json
{
"NodeName": {
"NODE_PROPERTY": "NODE_PROPERTY_VALUE",
"inputs": "ATTRIBUTE_DICTIONARY",
"outputs": "ATTRIBUTE_DICTIONARY",
"state": "ATTRIBUTE_DICTIONARY",
"tests": "TEST_DATA"
}
}
The :ref:`NODE_PROPERTY<ogn_node_property_keywords>` values are keywords recognized at the node level. The values
in ``NODE_PROPERTY_VALUE`` will vary based on the specific keyword to which they pertain.
The :ref:`ATTRIBUTE_DICTIONARY<ogn_attribute_dictionaries>` sections contain all of the information required to
define the subset of attributes, each containing a set of :ref:`ogn_attribute_property_keywords` that describe the
attribute.
Lastly the :ref:`TEST_DATA<ogn_test_data>` section contains information required to construct one or more Python
tests that exercise the basic node operation.
Comments
--------
JSON files do not have a syntax for adding comments, however in order to allow for adding descriptions or
disabled values to a .ogn file the leading character "$" will treat the key in any key/value pair as a
comment. So while ``"description":"Hello"`` will be treated as a value to be added to the node definition,
``"$description":"Hello"`` will be ignored and not parsed.
Comments can appear pretty much anywhere in your file. They are used extensively in the :ref:`ogn_tutorial_nodes` to
describe the file contents.
.. literalinclude:: ogn_example.json
:language: json
:lines: 1-4
:emphasize-lines: 3
.. _ogn_node_property_keywords:
Node Property Keywords
----------------------
These are the elements that can appear in the `NODE_PROPERTY` section. The values they describe pertain to the node
type as a whole.
.. _ogn_keyword_node_description:
.. rubric:: description
The *description* key value is required on all nodes and will be used in the generated documentation of the node.
You can embed reStructuredText code in the string to be rendered in the final node documentation, though it will
appear as-is in internal documentation such as Python docstrings.
The value can be a string or a list of strings. If it is a list, they will be concatenated as appropriate in the
locations they are used. (Linefeeds preserved in Python docstrings, turned into a single space for text documentation,
prepended with comment directives in code...)
.. tip::
This mandatory string should inform users exactly what function the node performs, as concisely as possible.
.. literalinclude:: ogn_example.json
:language: json
:lines: 1-8
:emphasize-lines: 4-7
.. _ogn_keyword_node_version:
.. rubric:: version
The integer value *version* defines the version number of the current node definition. It is up to the node writer
how to manage the encoding of version levels in the integer value. (For example a node might encode a major version
of 3, a minor version of 6, and a patch version of 12 in two digit groups as the integer 30612, or it might simply
use monotonic increasing values for versions 1, 2, 3...)
.. tip::
This mandatory value can be anything but by convention should start at 1.
.. literalinclude:: ogn_example.json
:language: json
:lines: 4-9
:emphasize-lines: 5
.. _ogn_keyword_node_exclude:
.. rubric:: exclude
Some node types will not be interested in all generated files, e.g. if the node is a Python node it will not need the
C++ interface. Any of the generated files can be skipped by including it in a list of strings whose key is *exclude*.
Here is a node which excludes all generated output, something you might do if you are developing the description of a
new node and just want the node syntax to validate without generating code.
Legal values to include in the exclusion list are **"c++"**, **"docs"**, **"icon"**, **"python"**, **"template"**,
**"tests"**, or **"usd"**, in any combination.
.. note::
C++ is automatically excluded when the implementation language is Python, however when the implementation language
is C++ there will still be a Python interface class generated for convenience. It will have less functionality
than for nodes implemented in Python and is mainly intended to provide an easy interface to the node from Python
scripts.
.. literalinclude:: ogn_example.json
:language: json
:lines: 8-10
:emphasize-lines: 2
.. _ogn_keyword_node_icon:
.. rubric:: icon
A string value that represents the path, relative to the .ogn file, of the icon file that represents the node. This
icon should be a square SVG file. If not specified then it will default to the file with the same name as the *.ogn*
file with the *.svg* extension (e.g. *OgnMyNode.ogn* looks for the file *OgnMyNode.svg*). When no icon file exists the
UI can choose a default for it. The icon will be installed into the extension's generated *ogn/* directory
.. literalinclude:: ogn_example.json
:language: json
:lines: 85-87
:dedent: 4
:emphasize-lines: 2
The extended syntax for the icon description adds the ability to specify custom coloring. Instead of just a string path,
the icon is represented by a dictionary of icon properties. Allowed values are **"path"**, the icon location as with
the simple syntax, **"color"**, a color representation for the draw part of the icon's shape, **"backgroundColor"**,
a color representation for the part of the icon not containing its shape, and **"borderColor"**, a color
representation for the outline of the icon.
Colors are represented in one of two ways - as hexadecimal in the form **#AABBGGRR**, or as a decimal list of
**[R, G, B, A]**, both using the value range [0, 255].
.. literalinclude:: ogn_example.json
:language: json
:lines: 90-97
:dedent: 4
:emphasize-lines: 2-7
.. note::
Unspecified colors will use the defaults. An unspecified path will look for the icon in the default location.
.. _ogn_keyword_node_language:
.. rubric:: language
A string value that represents the language of implementation. The default when not specified is **"c++"**. The
other legal value is **"python"**. This value indicates the language in which the node compute algorithm is
written.
.. literalinclude:: ogn_example.json
:language: json
:lines: 9-11
:emphasize-lines: 2
.. _ogn_keyword_node_memoryType:
.. rubric:: memoryType
Nodes can be written to work on the CPU, GPU via CUDA, or both. For each case the data access has to take this into
account so that the data comes from the correct memory store. The valid values for the *memoryType* property are
*cpu*, *cuda*, and *any*. The first two mean that by default all attribute values on the node are exclusively in either
CPU or CUDA-specific GPU memory. *any* means that the node could run on either CPU or GPU, where the decision of which
to use happens at runtime. The default value is *cpu*.
.. literalinclude:: ogn_example.json
:language: json
:lines: 10-12
:emphasize-lines: 2
.. _ogn_keyword_node_categories:
.. rubric:: categories
Categories provide a way to group similar node types, mostly so that they can be managed easier in the UI.
.. literalinclude:: ogn_example.json
:language: json
:lines: 305-306
:emphasize-lines: 2
For a more detailed example see the :ref:`omnigraph_node_categories` "how-to".
.. _ogn_keyword_node_cudaPointers:
.. rubric:: cudaPointers
Usually when the memory type is set to *cuda* or *any* the CUDA memory pointers for array types are returned as a
GPU pointer to GPU data, so when passing the data to CUDA code you have to pass pointers-to-pointers, since the
CPU code cannot dereference them. Sometimes it is more efficient to just pass the GPU pointer directly though,
pointed at by a CPU pointer. (It's still a pointer to allow for null values.) You can do this by specifying *"cpu"*
as your *cudaPointers* property.
.. literalinclude:: ogn_example.json
:language: json
:lines: 230-234
:emphasize-lines: 4
.. note::
You can also specify *"cuda"* for this value, although as it is the default this has no effect.
.. _ogn_keyword_node_metadata:
.. rubric:: metadata
Node types can have key/value style metadata attached to them by adding a dictionary of them using the *metadata*
property. The key and value are any arbitrary string, though it's a good idea to avoid keywords starting with
with underscore (**_**) as they may have special meaning to the graph. Lists of strings can also be used as metadata
values, though they will be transformed into a single comma-separated string.
A simple example of useful metadata is a human readable format for your node type name. UI code can then read the
consistently named metadata to provide a better name in any interface requiring node type selection. In the example
the keyword *author* is used.
.. literalinclude:: ogn_example.json
:language: json
:lines: 11-15
:emphasize-lines: 2-4
.. tip::
There are several hardcoded metadata values, described in this guide. The keywords under which these are stored
are available as constants for consistency, and can be found in Python in the og.MetadataKeys object and in C++
in the file *omni/graph/core/ogn/Database.h*.
.. _ogn_keyword_node_scheduling:
.. rubric:: scheduling
A string or list of string values that represent information for the scheduler on how nodes of this type may be safely
scheduled. The string values are fixed, and say specific things about the kind of data the node access when
computing.
.. literalinclude:: ogn_example.json
:language: json
:lines: 182-184
:emphasize-lines: 2
.. literalinclude:: ogn_example.json
:language: json
:lines: 187-189
:emphasize-lines: 2
The strings accepted as values in the .ogn file are described below (extracted directly from the code)
.. literalinclude:: ../../../../source/extensions/omni.graph.tools/python/_impl/node_generator/parse_scheduling.py
:language: python
:start-after: begin-scheduling-hints
:end-before: end-scheduling-hints
.. _ogn_keyword_node_singleton:
.. rubric:: singleton
**singleton** is metadata with special meaning to the node type, so as a shortcut it can also be specified as its own
keyword at the node level. The meaning is the same; associate a piece of metadata with the node type. This piece of
metadata indicates the quality of the node type of only being able to instantiate a single node of that type in a graph
or its child graphs. The value is specified as a boolean, though it is stored as the string "1". (If the boolean is
false then nothing is stored, as that is the default.)
.. literalinclude:: ogn_example.json
:language: json
:lines: 111-113
:emphasize-lines: 2
:dedent: 4
.. _ogn_keyword_node_tags:
.. rubric:: tags
**tags** is a very common piece of metadata, so as a shortcut it can also be specified as its own keyword at the
node level. The meaning is the same; associate a piece of metadata with the node type. This piece of
metadata can be used by the UI to better organize sets of nodes into common groups.
.. literalinclude:: ogn_example.json
:language: json
:lines: 15-17
:emphasize-lines: 2
.. tip::
Tags can be either a single string, a comma-separated string, or a list of strings. They will all be represented
as a comma-separated string in the metadata.
.. _ogn_keyword_node_tokens:
.. rubric:: tokens
Token types are more efficient than string types for comparison, and are fairly common. For that reason the .ogn
file provides this shortcut to predefine some tokens for use in your node implementation code.
The simplest method of adding tokens is to add a single token string.
.. literalinclude:: ogn_example.json
:language: json
:lines: 12-16
:emphasize-lines: 4
If you have multiple tokens then you can instead specify a list:
.. literalinclude:: ogn_example.json
:language: json
:lines: 71-75
:emphasize-lines: 4
:dedent: 4
The lookup is the same:
Lastly, if the token value contains illegal names for C++ or Python variables you can specify tokens in a dictionary,
where the key is the name through which it will be accessed and the value is the actual token string:
.. literalinclude:: ogn_example.json
:language: json
:lines: 78-82
:emphasize-lines: 4
:dedent: 4
See the :ref:`ogn_user_guide` for information on how to access the different sets of token in your code.
.. _ogn_keyword_node_uiName:
.. rubric:: uiName
**uiName** is a very common piece of metadata, so as a shortcut it can also be specified as its own keyword at the
node level. The meaning is the same; associate a piece of metadata with the node type. This piece of
metadata can be used by the UI to present a more human-readable name for the node type.
.. literalinclude:: ogn_example.json
:language: json
:lines: 16-17
:emphasize-lines: 2
.. tip::
Unlike the actual name, the uiName has no formatting or uniqueness requirements. Choose a name that will make
its function obvious to a user selecting it from a list.
.. _ogn_attribute_dictionaries:
Attribute Dictionaries
----------------------
Each of the three attribute sections, denoted by the keywords `inputs`, `outputs`, and `state`, contain a list of
attributes of each respective location and their properties.
:**inputs**:
Attributes that are read-only within the node's compute function. These form the collection of data used to run
the node's computation algorithm.
:**outputs**:
Attributes whose values are generated as part of the computation algorithm. Until the node computes their values
they will be undefined. This data is passed on to other nodes in the graph, or made available for inspection.
:**state**:
Attributes that persist between one evaluation and the next. They are both readable and writable. The primary
difference between **state** attributes and **output** attributes is that when you set the value on a **state**
attribute that value is guaranteed to be there the next time the node computes. Its data is entirely owned by
the node.
.. literalinclude:: ogn_example.json
:language: json
:lines: 19-25
:emphasize-lines: 2,4,6
:dedent: 4
.. note::
If there are no attributes of a specific location then that section can simply be omitted.
.. _ogn_attribute_property_keywords:
Attribute Property Keywords
---------------------------
The top level keyword of the attribute is always the unique name. It is always namespaced within the section it
resides and only need be unique within that section. For example, the attribute ``mesh`` can appear in both the
``inputs`` and ``outputs`` sections, where it will be named ``inputs:mesh`` and ``outputs:mesh`` respectively.
Attribute Properties
++++++++++++++++++++
Like the outer node level, each of the attributes has a set of mandatory and optional attributes.
.. _ogn_keyword_attribute_description:
.. rubric:: description
As with the node, the *description* field is a multi-line description of the attribute, optionally with reStructuredText
formatting. The description should contain enough information for the user to know how that attribute will be used
(as an input), computed (as an output), or updated (as state).
.. tip::
This mandatory string should inform users exactly what data the attribute contains, as concisely as possible.
.. literalinclude:: ogn_example.json
:language: json
:lines: 27-30
:emphasize-lines: 3
.. _ogn_keyword_attribute_type:
.. rubric:: type
The *type* property is one of several hard-coded values that specify what type of data the attribute contains. As we
ramp up not all type combinations are supported; run `generate_node.py --help` to see the currently supported list
of attribute types. For a full list of supported types and the data types they generate see :ref:`ogn_attribute_types`.
.. tip::
This field is mandatory, and will help determine what type of interface is generated for the node.
.. literalinclude:: ogn_example.json
:language: json
:lines: 28-31
:emphasize-lines: 3
.. _ogn_keyword_attribute_default:
.. rubric:: default
The *default* property on inputs contains the value of the attribute that will be used when the user has not explicitly
set a value or provided an incoming connection to it. For outputs the default value is optional and will only be used
when the node compute method cannot be run.
The value type of the *default* property will be the JSON version of the type of data, shown in
:ref:`ogn_attribute_types`.
.. literalinclude:: ogn_example.json
:language: json
:lines: 30-32
:emphasize-lines: 2
.. tip::
Although input attributes should all have a default, concrete data types need not have a default set if the intent
is for them to have their natural default. It will be assigned to them automatically. e.g. 0 for "int",
[0.0, 0.0, 0.0] for "float[3]", false for "bool", and "[]" for any array types.
.. warning::
Some attribute types, such as "any" and "bundle", have no well-defined data types and cannot have a default set.
.. _ogn_keyword_attribute_deprecated:
.. rubric:: deprecated
The *deprecated* property is used to indicate that the attribute is being phased out and should no longer be used.
The value of the property is a string or array of strings providing users with information on
how they should change their graphs to accommodate the eventual removal of the attribute.
.. literalinclude:: ogn_example.json
:language: json
:lines: 272-289
:emphasize-lines: 7,14-17
.. _ogn_keyword_attribute_optional:
.. rubric:: optional
The *optional* property is used to tell the node whether the attribute's value needs to be present in order for the
compute function to run. If it is set to `true` then the value is not checked before calling compute. The default
value `false` will not call the compute function if the attribute does not have a valid value.
.. literalinclude:: ogn_example.json
:language: json
:lines: 31-33
:emphasize-lines: 2
.. _ogn_keyword_attribute_memoryType:
.. rubric:: memoryType
By default every attribute in a node will use the *memoryType* defined
:ref:`at the node level<ogn_keyword_node_memoryType>`. It's possible for attributes
to override that choice by adding that same keyword in the attribute properties.
Here's an example of an attribute that overrides the node level memory type to force the attribute onto
the CPU. You might do this to keep cheap POD values on the CPU while the expensive data arrays go directly to the GPU.
.. literalinclude:: ogn_example.json
:language: json
:lines: 32-34
:emphasize-lines: 2
.. _ogn_keyword_attribute_range:
.. rubric:: minimum/maximum
When specified, these properties represent the minimum and maximum allowable value for the attribute. For arrays the
values are applicable to every array element. For tuples the values will themselves be tuples with the same size.
.. literalinclude:: ogn_example.json
:language: json
:lines: 33-36
:emphasize-lines: 2-3
.. note::
These properties are only valid for the numeric attribute types, including tuples and arrays.
At present they are not applied at runtime, only for validating test and default values within the .ogn file,
however in the future they may be saved so it is always a good idea to specify values here when applicable.
.. _ogn_keyword_attribute_metadata:
.. rubric:: metadata
Attributes can also have key/value style metadata attached to them by adding a dictionary of them using the
*metadata* property. The key and value are any arbitrary string, though it's a good idea to avoid keywords starting
with underscore (**_**) as they may have special meaning to the graph. Lists of strings can also be used as metadata
values, though they will be transformed into a single comma-separated string.
.. literalinclude:: ogn_example.json
:language: json
:lines: 35-39
:emphasize-lines: 2-4
There are a number of attribute metadata keys with special meanings:
============= ====
allowedTokens Used only for attributes of type *token* and contains a list of the values that token is allowed to take.
.. literalinclude:: ogn_example.json
:language: json
:lines: 192-200
:emphasize-lines: 5-7
Sometimes you may wish to have special characters in the list of allowed tokens. The generated code uses the token
name for easy access to its values so in these cases you will have to also supply a corresponding safe name for the
token value through which the generated code will access it.
.. literalinclude:: ogn_example.json
:language: json
:lines: 203-215
:emphasize-lines: 5-11
In both cases you would access the token values through the database members ``db.tokens.lt``,
``db.tokens.gt``, and ``db.tokens.ne``.
hidden This is a hint to the application that the attribute should be hidden from the user.
.. literalinclude:: ogn_example.json
:language: json
:lines: 248-257
:emphasize-lines: 6-8
Less commonly used attributes are often hidden to declutter the UI and the application may provide a
mechanism to allow the user to display them on request. For example, in the Create application hidden
attributes are not displayed in its Graph windows but do appear in its Property window from where their
hidden state can be toggled off and on.
internal Marks an attribute which is for internal use only. An application would not normally display the
attribute to users or allow them to interact with it through its UI.
.. literalinclude:: ogn_example.json
:language: json
:lines: 260-269
:emphasize-lines: 6-8
literalOnly Indicates that the value of the attribute can only be set to a literal. In other words, if an attribute
has **literalOnly** set to 1, then it cannot be connected to other attributes, so the only way to modify
the value of the attribute is to set its value to a literal. A typical use case is the input attributes
of event source nodes. Since the action evaluator does not evaluate nodes upstream of an event source
node, the input attributes of event source nodes should not be allowed to connect to upstream nodes, so
they should be declared as **literalOnly**.
.. literalinclude:: ogn_example.json
:language: json
:lines: 237-245
:emphasize-lines: 5-7
outputOnly Used with an input attribute which can be the source of output connections but should not be the
target of input connections. Typically an application will allow input attributes to take their value
from an incoming connection or to be set by the user through the UI if they don't have an incoming
connection. The application may also disallow outbound connections. Setting **outputOnly** to 1 is a
hint to the application that it should continue to allow the user to set the attribute's value through
its UI but disallow incoming connections and enable outgoing connections. A typical use for this is with
a "constant" node which allows the user to enter a constant value which can then be passed on to other
nodes via output connections.
.. literalinclude:: ogn_example.json
:language: json
:lines: 218-227
:emphasize-lines: 6-8
============= ====
.. _ogn_keyword_attribute_uiName:
.. rubric:: uiName
**uiName** is a very common piece of metadata, so as a shortcut it can also be specified as its own keyword at the
attribute level. The meaning is the same; associate a piece of metadata with the attribute. This piece of
metadata can be used by the UI to present a more human-readable name for the attribute.
.. literalinclude:: ogn_example.json
:language: json
:lines: 37-40
:emphasize-lines: 3
.. tip::
Unlike the actual name, the uiName has no formatting or uniqueness requirements. Choose a name that will make
its function obvious to a user selecting it from a list. The UI may or may not include the namespace when
displaying it so if that distinction is critical, include it in the uiName.
.. _ogn_keyword_attribute_uiType:
.. rubric:: uiType
**uiType** is used to provide a hint to the property panel as to how the property should bre displayed. When "filePath"
is specified, string and token fields will create file browser widgets in the property panel. When "color" is
specified, 3- and 4-component tuples will use a color picker widget in the property panel.
.. literalinclude:: ogn_example.json
:language: json
:lines: 298-300
:emphasize-lines: 1
.. _ogn_keyword_attribute_unvalidated:
.. rubric:: unvalidated
**unvalidated** is similar to the **optional** keyword, in that it is used to tag attributes that may not take part
in a ``compute()``. The difference is that these attributes will always exists, they just may not have valid data
when the compute is invoked. For such attributes the onus is on the node writer to check validity of such attributes
if they do end up being used for the compute.
.. literalinclude:: ogn_example.json
:language: json
:lines: 164-179
:emphasize-lines: 9,14
:dedent: 4
.. _ogn_test_data:
Test Definitions
----------------
The node generator is also capable of automatically generating some unit tests on the operation of the node's
algorithm through the **tests** property. This property contains a list of dictionaries, where each entry in the
list is a dictionary of `attribute name : attribute value`.
The test runs by setting all of the input attributes to their corresponding values in the dictionary, executing the
node's compute algorithm, and then comparing the computed values of the outputs against their corrsponding values in
the dictionary.
.. note::
When input attributes do not have a value in the tests their default is used. When output attributes do not have a
value in the test they are not checked against the computed result.
There are two methods of specifying test data. They are equivalent so you can use the one that makes the most sense
for your particular test cases. They can coexist if you have different types of test data.
The first method is using a single dictionary to specify any non-default attribute values.
.. literalinclude:: ogn_example.json
:language: json
:lines: 44-47
:emphasize-lines: 2-3
This example shows test cases to exercise a simple node that adds two integers together. The first test says *if the
node has inputs 1 and 2 the output should be 3* and the second one says *if the node has an input of 5 and a default
valued input the output should be 5* (the defaults have been set to 0).
For a more complex text you can specify the data involved in the test by location instead of all in a single
dictionary. Here's a similar example for an 8 dimensional polynomial solver.
.. literalinclude:: ogn_example.json
:language: json
:lines: 46-61
:emphasize-lines: 2-15
CPU/GPU Data Switch
+++++++++++++++++++
There is one special piece of test configuration that applies when you have output data that switches at runtime
between CPU and GPU (usually through some sort of input information, such as a boolean switch, or a limit on data
size). This information tells the test generator that an output should be expected on the GPU instead of the default
CPU location.
.. literalinclude:: ogn_example.json
:language: json
:lines: 61-67
:emphasize-lines: 6
This example illustrates testing of an output on GPU, where the GPU location is selected at runtime based on the
attribute *inputs:isGpu*.
Extended Type Test Data
+++++++++++++++++++++++
If your node has extended-type attributes, you will have to specify which type you want to use for your test. This is
necessary to distinguish between types which aren't support by json. For example double, float and half.
.. literalinclude:: ogn_example.json
:language: json
:lines: 68-72
:emphasize-lines: 3-4
This example has one input "multiplier" which is a specific decimal type, input "element" and output "tuple" which
are extended-types. "element" and "tuple" are related by the logic of the node in that their base types must match, so
the test is specifying the same type for those attributes.
For tests that deal with extended data types you must also specify the data type with the value to be set so that it
can properly resolve. (The other way of resolving data types is by connection. These simple tests only involve a single
node so resolution can only be done by setting values directly.)
.. literalinclude:: ogn_example.json
:language: json
:lines: 105-108
:emphasize-lines: 2-3
State Test Data
+++++++++++++++
In the special case of tests that need to exercise state data extra syntax is added to differentiate between values
that should be set on state attributes before the test starts and values that are checked on them after the test is
completed. The special suffix *_set* is appended to the state namespace to signify that a value is to be initialized
before a test runs. You may optionally add the suffix *_get* to the state namespace to clarify which values are to be
checked after the test runs but that is the default so it is not necessary.
.. literalinclude:: ogn_example.json
:language: json
:lines: 116-135
:emphasize-lines: 2-19
Test Graph Setup
++++++++++++++++
For more complex situations you may need more than just a single node to test code paths properly. For these situations
there is a pre-test setup section you can add, in the form of the :ref:`Controller.edit<ogn_omnigraph_controller>`
function parameters. Only the creation directives are accepted, not the destructive ones such as *disconnections*.
These creation directives are all executed by the test script before it starts to run, providing you with a known
starting graph configuration consisting of any nodes, prims, and connections needed to run the test.
.. literalinclude:: ogn_example.json
:language: json
:lines: 138-162
:emphasize-lines: 9-23
.. note::
If you define the graph in this way then the first node in your *"nodes"* directives must refer to the node
being tested. If there is no graph specified then a single node of the type being tested will be the sole
contents of the stage when running the test.
Simplified Schema
=================
This schema outlines the relationships between all of the values in the .ogn file. It is simplified in that it does
not include schema information that validates data types in *default*, *minimum*, *maximum*, and test section fields.
(It's possible to include such information in a schema, it just makes it very difficult to follow.)
.. literalinclude:: ogn_schema.json
:linenos:
:language: json
| 33,306 | reStructuredText | 42.199741 | 131 | 0.720801 |
omniverse-code/kit/exts/omni.graph.tools/docs/Overview.md | # OmniGraph Tools And .ogn Node Generator
```{csv-table}
**Extension**: omni.graph.tools,**Documentation Generated**: {sub-ref}`today`
```
The OmniGraph Tools extension contains general purpose scripts for dealing with OmniGraph, mostly through the .ogn file format.
If you are interested in writing nodes the best places to start are the {ref}`ogn_user_guide` or the {ref}`ogn_reference_guide`.
- {doc}`node_architects_guide`
- {doc}`ogn_user_guide`
- {doc}`ogn_reference_guide`
- {doc}`attribute_types`
- {doc}`ogn_code_samples_cpp`
- {doc}`ogn_code_samples_python`
- {doc}`ogn_generation_script`
| 604 | Markdown | 30.842104 | 128 | 0.730132 |
omniverse-code/kit/exts/omni.kit.manipulator.viewport/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "104.0.7"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarly for displaying extension info in UI
title = "Viewport Manipulator Manager"
description="Viewport Manipulator Manager"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Scene"
# Keywords for the extension
keywords = ["kit", "manipulator", "viewport"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
[dependencies]
"omni.ui.scene" = {}
"omni.kit.window.viewport" = { optional = true }
# Main python module this extension provides, it will be publicly available as "import omni.example.hello".
[[python.module]]
name = "omni.kit.manipulator.viewport"
[[test]]
dependencies = [
"omni.kit.renderer.core",
"omni.kit.window.viewport"
]
waiver = "Part of the extension features (single viewport 1.0 scene overlay) is tested by omni.kit.manipulator.prim."
| 1,659 | TOML | 32.199999 | 118 | 0.743822 |
omniverse-code/kit/exts/omni.kit.manipulator.viewport/omni/kit/manipulator/viewport/viewport_manipulator.py | # 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.
#
import inspect
from typing import Type
import carb
class ViewportManipulator:
"""
ViewportManipulator is a generic wrapper class on top of normal Manipulator Object. It contains all "instances" of the
Manipulators exist in each Viewports.
When setting an attribute to the ViewportManipulator Object, it forwards the value to all instances.
Do NOT initialize ViewportManipulator directly. Instead using ManipulatorFactory.create_manipulator(...) instead.
It adds the functionality to automatically track viewport and create or destory "instance" of Manipulator into
ViewportManipulator.
"""
def __init__(self, manipulator_class: Type, **kwargs):
self._manipulator_class = manipulator_class
self._properties = {}
signature = inspect.signature(manipulator_class.__init__)
for arg, val in signature.parameters.items():
if val.default is not inspect.Parameter.empty:
self._properties[arg] = val.default
self._properties.update(kwargs)
for k, v in self._properties.items():
setattr(self, k, v)
self._instances = []
def add_instance(self, instance):
for k, v in self._properties.items():
if hasattr(instance, k):
setattr(instance, k, getattr(self, k))
else:
carb.log_verbose(f"{k} is not an attribute of {type(instance)}")
self._instances.append(instance)
def get_all_instances(self):
return self._instances
def clear_all_instances(self):
self._instances.clear()
@property
def manipulator_class(self):
return self._manipulator_class
def __setattr__(self, name, value):
super().__setattr__(name, value)
if hasattr(self, "_instances"):
for instance in self._instances:
if hasattr(instance, name):
setattr(instance, name, value)
else:
carb.log_verbose(f"{name} is not an attribute of {type(instance)}")
| 2,491 | Python | 33.611111 | 122 | 0.662385 |
omniverse-code/kit/exts/omni.kit.manipulator.viewport/omni/kit/manipulator/viewport/manipulator_factory.py | # 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.
#
from typing import List, Type
import carb.events
import omni.kit.app
import omni.ui as ui
from omni.ui import scene as sc
from .viewport_manipulator import ViewportManipulator
DRAW_ON_VP1 = True
SUPPORT_MULTI_VP1 = True
class ManipulatorPool:
"""
A ManipulatorPool allows omni.ui.scene items in released Manipulator to be reused for a newly created Manipulator,
instead having to rebuild them in the scene view.
"""
def __init__(self, manipulator_class, scene_view: sc.SceneView):
self._manipulator_class = manipulator_class
self._scene_view = scene_view
self._pool = []
def create(self):
if self._pool:
manipulator = self._pool.pop()
else:
with self._scene_view.scene:
manipulator = self._manipulator_class()
return manipulator
def release(self, manipulator):
manipulator.enabled = False
manipulator.model = None
# Put the released manipulator back into the pool
self._pool.append(manipulator)
class _ViewportWindowObject:
def __init__(self, ui_window, ui_scene_view, draw_sub):
self.window = ui_window
self.scene_view = ui_scene_view
self.draw_sub = draw_sub
def __del__(self):
self.draw_sub = None
self.scene_view.destroy()
self.window.destroy()
class ManipulatorFactory:
_instance = None
@classmethod
def create_manipulator(cls, manipulator_class: Type, **kwargs):
"""
Creates a ViewportManipulator object.
Args: Arguments need to match manipulator_type's constructor
"""
return cls._instance._create_manipulator(manipulator_class, **kwargs)
@classmethod
def destroy_manipulator(cls, *args, **kwargs):
"""
Destroys a ViewportManipulator object.
Args @see `_destroy_manipulator`
"""
cls._instance._destroy_manipulator(*args, **kwargs)
def startup(self):
self._instances = dict()
self._manipulators = set()
self._pools = {} # Each manipulator type needs a pool for each viewport.
self._vp1_overlay_windows = {}
self._viewport = None
ManipulatorFactory._instance = self
global DRAW_ON_VP1, SUPPORT_MULTI_VP1
try:
import omni.kit.viewport_legacy
self._viewport = omni.kit.viewport_legacy.acquire_viewport_interface()
except ImportError:
DRAW_ON_VP1, SUPPORT_MULTI_VP1 = False, False
if not DRAW_ON_VP1:
return
self._dead_vp1_overlay_windows = []
self._vp1_instances = []
self._update_sub = (
omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update)
)
def shutdown(self):
if DRAW_ON_VP1:
self._vp1_overlay_windows.clear()
self._dead_vp1_overlay_windows.clear()
self._update_sub = None
ManipulatorFactory._instance = None
def _create_vp1_scene_view(self, instance):
name = self._viewport.get_viewport_window_name(instance)
window = self._viewport.get_viewport_window(instance)
vp1_scene_window = ui.Window(name, visible=window.is_visible(), detachable=False)
with vp1_scene_window.frame:
vp1_scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
draw_event_stream = window.get_ui_draw_event_stream()
draw_sub = draw_event_stream.create_subscription_to_pop(
lambda event, instance=instance: self._on_vp_draw(event, instance)
)
self._vp1_overlay_windows[instance] = _ViewportWindowObject(vp1_scene_window, vp1_scene_view, draw_sub)
return vp1_scene_view
def _create_manipulator(self, manipulator_class: Type, **kwargs) -> ViewportManipulator:
"""
This function creates a TransformManipulator object that has instances in ALL existing viewports and future created viewports.
Args: Arguments need to match manipulator_type's constructor
Return:
ViewportManipulator object.
"""
manipulator = ViewportManipulator(manipulator_class, **kwargs)
pools = self._get_or_create_pools_for_manipulator_class(manipulator_class)
for pool in pools:
instance = pool.create()
self._instances[instance] = pool
manipulator.add_instance(instance)
self._manipulators.add(manipulator)
return manipulator
def _destroy_manipulator(self, manipulator: ViewportManipulator):
"""
Destroy the TransformManipulator and all its instances.
"""
instances = manipulator.get_all_instances()
for instance in instances:
self._instances.pop(instance).release(instance)
manipulator.clear_all_instances()
self._manipulators.remove(manipulator)
def _get_or_create_pools_for_manipulator_class(self, manipulator_class: Type) -> List[ManipulatorPool]:
if manipulator_class not in self._pools:
self._pools[manipulator_class] = [
ManipulatorPool(manipulator_class, vp_obj.scene_view) for vp_obj in self._vp1_overlay_windows.values()
]
return self._pools[manipulator_class]
def _on_update(self, e: carb.events.IEvent):
if DRAW_ON_VP1:
# The visible state between vp 1.0 and the dummy ui.scene overlay window needs to be in sync.
vp_instances_to_remove = []
for vp_instance, vp_obj in self._vp1_overlay_windows.items():
vp_window = self._viewport.get_viewport_window(vp_instance)
if vp_window:
visible = vp_window.is_visible()
if visible != vp_obj.window.visible:
vp_obj.window.visible = visible
vp_obj.scene_view.visible = visible
else:
# Destroy the draw_sub not, its what's caling this method
vp_obj.draw_sub = None
# Hide all ui as well
vp_obj.window.visible = False
vp_obj.scene_view.visible = False
vp_instances_to_remove.append(vp_instance)
# Clear any pending dead Windows and Scenes
self._dead_vp1_overlay_windows.clear()
# Gather all the newly dead Windows and stash them for destruction later
for vp_instance in vp_instances_to_remove:
self._dead_vp1_overlay_windows.append(self._vp1_overlay_windows[vp_instance])
del self._vp1_overlay_windows[vp_instance]
self._vp1_instances.remove(vp_instance)
# Since there's no callback for new VP1 creation, we check for change in update
if SUPPORT_MULTI_VP1:
vp1_instances = self._viewport.get_instance_list()
if vp1_instances != self._vp1_instances:
# assuming Kit can only add viewport.
diff = list(set(vp1_instances) - set(self._vp1_instances))
for instance in diff:
scene_view = self._create_vp1_scene_view(instance)
# make a new pool for the manipulators
for manipulator_class, pools in self._pools.items():
pools.append(ManipulatorPool(manipulator_class, scene_view))
# create a new instance in the new viewport for each existing manipulators
for manipulator in self._manipulators:
manipulator_class = manipulator.manipulator_class
pools = self._get_or_create_pools_for_manipulator_class(manipulator_class)
pool = pools[-1]
instance = pool.create()
self._instances[instance] = pool
manipulator.add_instance(instance)
self._vp1_instances = vp1_instances
def _on_vp_draw(self, event: carb.events.IEvent, vp_instance):
vp_obj = self._vp1_overlay_windows.get(vp_instance)
if not vp_obj:
return
vm = event.payload["viewMatrix"]
pm = event.payload["projMatrix"]
if pm[15] == 0.0:
# perspective matrix matrix
proj_matrix = sc.Matrix44(pm[0], pm[1], pm[2], pm[3], pm[4], pm[5], pm[6], pm[7], pm[8], pm[9], pm[10], pm[11], pm[12], pm[13], pm[14], pm[15])
compensation = sc.Matrix44(1.0, 0.0, -0.0, 0.0, 0.0, 1.0, 0.0, -0.0, -0.0, 0.0, 1.0, -1.0, 0.0, -0.0, 0.0, -2.0)
proj_matrix = proj_matrix * compensation
# Flatten into list for model
pm = [proj_matrix[0], proj_matrix[1], proj_matrix[2], proj_matrix[3],
proj_matrix[4], proj_matrix[5], proj_matrix[6], proj_matrix[7],
proj_matrix[8], proj_matrix[9], proj_matrix[10], proj_matrix[11],
proj_matrix[12], proj_matrix[13], proj_matrix[14], proj_matrix[15]]
scene_view = vp_obj.scene_view
scene_view.model.set_floats("projection", pm)
scene_view.model.set_floats("view", vm)
| 9,726 | Python | 38.54065 | 155 | 0.604874 |
omniverse-code/kit/exts/omni.kit.manipulator.viewport/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [104.0.7] - 2022-05-25
### Changed
- Fix issue with crash when a legacy Viewport is destroyed.
## [104.0.6] - 2022-05-04
### Changed
- Imported to kit repro and bump version to match Kit SDK
## [1.0.6] - 2022-04-20
### Changed
- Delay omni.ui.scene.SceneView creation until app is updating
## [1.0.5] - 2022-04-07
### Added
- Added test waiver.
## [1.0.4] - 2022-04-06
### Changed
- Use omni.ui.SceneView.model to set view and projection
## [1.0.3] - 2021-12-07
### Fixed
- Fixed dangling draw event subscription.
## [1.0.2] - 2021-12-01
### Removed
- Move omni.kit.viewport import to omni.kit.viewport_legacy
## [1.0.1] - 2021-12-01
### Removed
- Made omni.kit.window.viewport an optional dependency.
## [1.0.0] - 2021-09-23
### Added
- Init commit.
| 861 | Markdown | 18.590909 | 80 | 0.659698 |
omniverse-code/kit/exts/omni.kit.manipulator.viewport/docs/README.md | # Viewport Manipulator Extension [omni.kit.manipulator.viewport]
This is the extension providing a way to create managed manipulator in Viewport.
| 148 | Markdown | 28.799994 | 80 | 0.817568 |
omniverse-code/kit/exts/omni.kit.test_app_full_nonrtx/omni/kit/test_app_full_nonrtx/__init__.py | from .app_dev_test import *
| 28 | Python | 13.499993 | 27 | 0.714286 |
omniverse-code/kit/exts/omni.kit.test_app_full_nonrtx/omni/kit/test_app_full_nonrtx/app_dev_test.py | import os
import sys
import inspect
import importlib
import carb
import carb.settings
import carb.tokens
import omni.kit.app
import omni.kit.test
#import omni.kit.test_helpers_gfx
import omni.kit.renderer.bind
from omni.kit.test.teamcity import teamcity_publish_image_artifact
OUTPUTS_DIR = omni.kit.test.get_test_output_path()
USE_TUPLES = True
class AppDevCompatTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.acquire_settings_interface()
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
self._module_test_helpers_gfx = importlib.import_module('omni.kit.test_helpers_gfx')
self._captured_buffer = []
self._captured_buffer_w = 0
self._captured_buffer_h = 0
self._captured_buffer_fmt = 0
def __test_name(self) -> str:
return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}"
async def tearDown(self):
self._renderer = None
self._app_window_factory = None
self._settings = None
def _capture_callback(self, buf, buf_size, w, h, fmt):
if USE_TUPLES:
self._captured_buffer = omni.renderer_capture.convert_raw_bytes_to_rgba_tuples(buf, buf_size, w, h, fmt)
else:
self._captured_buffer = omni.renderer_capture.convert_raw_bytes_to_list(buf, buf_size, w, h, fmt)
self._captured_buffer_w = w
self._captured_buffer_h = h
self._captured_buffer_fmt = fmt
async def test_1_capture_variance(self):
test_name = self.__test_name()
import omni.renderer_capture
app_window = self._app_window_factory.get_default_window()
capture_interface = omni.renderer_capture.acquire_renderer_capture_interface()
capture_interface.capture_next_frame_swapchain_callback(self._capture_callback, app_window)
await omni.kit.app.get_app().next_update_async()
capture_interface.wait_async_capture(app_window)
if "PIL" not in sys.modules.keys():
# Checking if we have Pillow imported
try:
from PIL import Image
except ImportError:
# Install Pillow if it's not installed
import omni.kit.pipapi
omni.kit.pipapi.install("Pillow", module="PIL")
from PIL import Image
from PIL import ImageStat
image = Image.new('RGBA', [self._captured_buffer_w, self._captured_buffer_h])
if USE_TUPLES:
image.putdata(self._captured_buffer)
else:
buf_channel_it = iter(self._captured_buffer)
captured_buffer_tuples = list(zip(buf_channel_it, buf_channel_it, buf_channel_it, buf_channel_it))
image.putdata(captured_buffer_tuples)
# Only compare the standard deviation, since the test failing because of the UI elements shifting around is
# no good. Generally, it is enough to test that:
# 1. the test doesn't crash on iGPUs,
# 2. the test produces anything other than the black screen (the std dev of which is 0.0)
image_stats = ImageStat.Stat(image)
avg_std_dev = sum(image_stats.stddev) / 3.0
# Save image for user verification
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
image.save(TEST_IMG_PATH)
# The full app.dev has a std dev ~30.0, and the version with broken layout has a std dev of ~18.0
STD_DEV_THRESHOLD = 10.0
if avg_std_dev < STD_DEV_THRESHOLD:
teamcity_publish_image_artifact(TEST_IMG_PATH, "results", "Generated")
carb.log_error("Standard deviation of the produced image is lower than the threshold!")
self.assertTrue(False)
| 3,894 | Python | 36.095238 | 116 | 0.643297 |
omniverse-code/kit/exts/omni.kit.test_app_full_nonrtx/docs/index.rst | omni.kit.test_app_full_nonrtx
#############################
Test app.full in PXR mode.
| 89 | reStructuredText | 13.999998 | 29 | 0.494382 |
omniverse-code/kit/exts/omni.kit.widget.spinner/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.4"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarly for displaying extension info in UI
title = "Spinner widgets"
description="A Spinner widget includes a value field and a set of arrow (up/down or left/right) to change field value."
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "ui", "widget", "spinner", "field"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
category = "Internal"
# We only depend on testing framework currently:
[dependencies]
"omni.ui" = {}
"omni.kit.widget.examples" = { optional = true }
# Main python module this extension provides, it will be publicly available as "import omni.kit.widget.spinner".
[[python.module]]
name = "omni.kit.widget.spinner"
[settings]
| 1,548 | TOML | 35.023255 | 119 | 0.744186 |
omniverse-code/kit/exts/omni.kit.widget.spinner/omni/kit/widget/spinner/spinner.py | import abc
from typing import Optional, Union, Dict
import omni.ui as ui
import omni.kit.app
import carb.events
from .style import UI_STYLE
# First delay time to start a long click (in seconds)
SPINNER_LONG_CLICK_DELAY = 0.6
# Long click interval (in seconds)
SPINNER_LONG_CLICK_INTERVAL = 0.2
class AbstractSpinner:
"""
A Spinner widget includes a value field and a set of arrow (up/down or left/right) to change field value.
Kwargs:
model (ui.AbstractValueModel): Value model for value field. Default None.
step (Union[float, int]): Step value. Default 1.
min (Union[float, int, None]): Min value. Default None means no min value.
max (Union[float, int, None]): Max value. Default None means no max value.
vertical (bool): Vertical spinner (with up/down arrows) if True. Otherwise horizontal spinner (with left/right arrows). Default True.
width (ui.Length): Widget width. Default ui.Fraction(1).
"""
def __init__(
self,
model: ui.AbstractValueModel = None,
step: Union[float, int] = 1,
min: Union[float, int, None] = None,
max: Union[float, int, None] = None,
vertical: bool = True,
width: ui.Length = ui.Fraction(1),
style: Dict = None,
precision: int = 7
):
self._model = model
self._step = step
self._width = width
self._min = min
self._max = max
self._vertical = vertical
self._precision = precision
self._arrow_size = 6
ui_style = UI_STYLE.copy()
if style is not None:
ui_style.update(style)
self._build_ui(ui_style)
def destroy(self) -> None:
self._sub = None
@abc.abstractclassmethod
def _create_field_widget(self, model: Optional[ui.AbstractValueModel], **kwargs) -> ui.AbstractField:
pass
@property
def enabled(self) -> bool:
return self._container.enabled
@enabled.setter
def enabled(self, value: bool) -> None:
self._container.enabled = value
def _build_ui(self, style: Dict):
self._container = ui.HStack(width=self._width, height=0, style=style)
with self._container:
if self._vertical:
self._build_vertical_ui()
else:
self._build_horizontal_ui()
def _build_vertical_ui(self):
self._field = self._create_field_widget(self._model, style_type_name_override="Spinner.Field")
ui.Spacer(width=5)
with ui.ZStack(width=self._arrow_size):
ui.Rectangle(style_type_name_override="Spinner.Arrow.Background")
with ui.VStack(width=0, spacing=0):
ui.Spacer()
ui.Triangle(
width=self._arrow_size,
height=self._arrow_size,
alignment=ui.Alignment.CENTER_TOP,
style_type_name_override="Spinner.Arrow",
mouse_pressed_fn=(lambda x, y, key, m: self._begin_change(key, self._step)),
mouse_released_fn=(lambda *_: self._end_change()),
)
ui.Spacer(height=4)
ui.Triangle(
width=self._arrow_size,
height=self._arrow_size,
alignment=ui.Alignment.CENTER_BOTTOM,
style_type_name_override="Spinner.Arrow",
mouse_pressed_fn=(lambda x, y, key, m: self._begin_change(key, -self._step)),
mouse_released_fn=(lambda *_: self._end_change()),
)
ui.Spacer()
def _build_horizontal_ui(self):
with ui.VStack(width=0):
ui.Spacer()
ui.Triangle(
width=self._arrow_size,
height=self._arrow_size,
alignment=ui.Alignment.LEFT_CENTER,
style_type_name_override="Spinner.Arrow",
mouse_pressed_fn=(lambda x, y, key, m: self._begin_change(key, -self._step)),
mouse_released_fn=(lambda *_: self._end_change()),
)
ui.Spacer()
ui.Spacer(width=4)
self._field = self._create_field_widget(self._model, style_type_name_override="Spinner.Field")
ui.Spacer(width=4)
with ui.VStack(width=0, spacing=0):
ui.Spacer()
ui.Triangle(
width=self._arrow_size,
height=self._arrow_size,
alignment=ui.Alignment.RIGHT_CENTER,
style_type_name_override="Spinner.Arrow",
mouse_pressed_fn=(lambda x, y, key, m: self._begin_change(key, self._step)),
mouse_released_fn=(lambda *_: self._end_change()),
)
ui.Spacer()
def _begin_change(self, button: int, step: int):
if not self._container.enabled:
return
if button != 0:
return
self._delta = step
self._action_time = 0.0
self._current_time = 0.0
self._update_value()
self._register_update()
def _end_change(self):
self._deregister_update()
def _register_update(self):
self._sub = (
omni.kit.app.get_app()
.get_update_event_stream()
.create_subscription_to_pop(self._on_update, name="spinner update")
)
def _deregister_update(self):
self._sub = None
def _on_update(self, event: carb.events.IEvent):
dt = event.payload["dt"]
self._current_time += dt
if self._action_time == 0.0:
self._action_time = self._current_time + SPINNER_LONG_CLICK_DELAY
elif self._current_time > self._action_time:
self._update_value()
self._action_time += SPINNER_LONG_CLICK_INTERVAL
def _update_value(self):
new_value = round(self._field.model.as_float + self._delta, self._precision)
if self._min is not None:
new_value = max(new_value, self._min)
if self._max is not None:
new_value = min(new_value, self._max)
self._field.model.set_value(new_value)
class FloatSpinner(AbstractSpinner):
def _create_field_widget(self, model: Optional[ui.AbstractValueModel], **kwargs) -> ui.AbstractField:
return ui.FloatField(model, **kwargs)
class IntSpinner(AbstractSpinner):
def _create_field_widget(self, model: Optional[ui.AbstractValueModel], **kwargs) -> ui.AbstractField:
return ui.IntField(model, **kwargs)
class IntDragSpinner(AbstractSpinner):
def _create_field_widget(self, model: Optional[ui.AbstractValueModel], **kwargs) -> ui.AbstractField:
return ui.IntDrag(model, **kwargs)
| 6,714 | Python | 34.909091 | 141 | 0.573131 |
omniverse-code/kit/exts/omni.kit.widget.spinner/omni/kit/widget/spinner/style.py | from omni.ui import color as cl
UI_STYLE = {
"Spinner.Field": {},
"Spinner.Arrow": {"background_color": cl.shade(cl("#D6D6D6"))},
"Spinner.Arrow:disabled": {"background_color": cl.shade(cl("#A0A0A0"))},
"Spinner.Arrow.Background": {"background_color": 0},
}
| 275 | Python | 29.666663 | 76 | 0.632727 |
omniverse-code/kit/exts/omni.kit.widget.spinner/omni/kit/widget/spinner/__init__.py | from .spinner import AbstractSpinner, FloatSpinner, IntSpinner, IntDragSpinner
from .example import *
| 102 | Python | 33.333322 | 78 | 0.833333 |
omniverse-code/kit/exts/omni.kit.widget.spinner/omni/kit/widget/spinner/example/spinner.py | from omni import ui
from omni.kit.widget.spinner import FloatSpinner, IntSpinner
from omni.kit.widget.examples import ExamplePage
from typing import List, Optional
class SpinnerPage(ExamplePage):
def __init__(self):
super().__init__("Spinner")
def destroy(self):
self._h_float_spinner.destroy()
self._float_spinner.destroy()
self._int_spinner.destroy()
def build_page(self):
with ui.VStack(spacing=5):
with ui.HStack(height=20, spacing=10):
ui.Label("Float spinner:", width=100)
self._float_spinner = FloatSpinner(width=60)
with ui.HStack(height=20, spacing=10):
ui.Label("Int spinner:", width=100)
self._int_spinner = IntSpinner(width=60)
with ui.HStack(height=20, spacing=10):
ui.Label("Horizontal:", width=100)
self._h_float_spinner = FloatSpinner(vertical=False, width=60)
with ui.HStack(height=20, spacing=10):
ui.Label("Disabled:", width=100)
self._disbled_spinner = FloatSpinner(width=60)
self._disbled_spinner.enabled = False
| 1,186 | Python | 32.914285 | 78 | 0.596965 |
omniverse-code/kit/exts/omni.kit.widget.spinner/omni/kit/widget/spinner/example/__init__.py | import carb
try:
from omni.kit.widget.examples import register_page
from .spinner import SpinnerPage
register_page(SpinnerPage())
except Exception as e:
carb.log_info(f"Failed to add example for spinner: {str(e)}")
pass
| 243 | Python | 19.333332 | 65 | 0.711934 |
omniverse-code/kit/exts/omni.kit.widget.spinner/omni/kit/widget/spinner/tests/__init__.py | from .test_spinner import *
| 28 | Python | 13.499993 | 27 | 0.75 |
omniverse-code/kit/exts/omni.kit.widget.spinner/omni/kit/widget/spinner/tests/test_spinner.py | import omni.kit.test
from omni.kit.widget.spinner import FloatSpinner, IntSpinner, IntDragSpinner
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.app
import asyncio
import carb
import copy
import omni.ui as ui
from omni.ui import color as cl
import asyncio
SPINNER_STYLE = {
"Spinner.Field": {"background_color": 0, "color": cl.viewport_menubar_light},
"Spinner.Field:disabled": {"color": cl.viewport_menubar_medium},
"Spinner.Arrow": {"background_color": cl.viewport_menubar_light},
"Spinner.Arrow:disabled": {"background_color": cl.viewport_menubar_medium},
}
class TestSpinner(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_sliderbar(self):
float_spinner = FloatSpinner(step=0.1, min=0, max=10, style=SPINNER_STYLE)
self.assertEqual(float_spinner._field.model.as_float, 0.0)
float_spinner._begin_change(0, 0.1)
self.assertEqual(float_spinner._field.model.as_float, 0.1)
float_spinner._end_change()
# Test this change is reduced to value + 0.1
float_spinner._begin_change(0, 0.10000001)
self.assertEqual(float_spinner._field.model.as_float, 0.2)
float_spinner._end_change()
float_spinner._begin_change(1, 0.10000001)
self.assertEqual(float_spinner._field.model.as_float, 0.2)
float_spinner._end_change()
# Test for no change
float_spinner._begin_change(0, 0.100001)
self.assertEqual(float_spinner._field.model.as_float, 0.300001)
float_spinner._end_change()
float_spinner.enabled = False
self.assertFalse(float_spinner.enabled)
float_spinner._begin_change(0, 0.100001)
self.assertEqual(float_spinner._field.model.as_float, 0.300001)
float_spinner._end_change()
int_spinner = IntSpinner(step=1, min=0, max=10, vertical=False)
self.assertEqual(int_spinner._field.model.as_int, 0)
int_spinner._begin_change(0, 1)
self.assertEqual(int_spinner._field.model.as_int, 1)
int_spinner._end_change()
int_drag_spinner = IntDragSpinner(step=1, min=0, max=10)
self.assertEqual(int_drag_spinner._field.model.as_int, 0)
int_drag_spinner._begin_change(0, 1)
self.assertEqual(int_drag_spinner._field.model.as_int, 1)
# Check for long click
await asyncio.sleep(0.7)
self.assertEqual(int_drag_spinner._field.model.as_int, 2)
int_drag_spinner._end_change() | 2,615 | Python | 38.044776 | 82 | 0.668834 |
omniverse-code/kit/exts/omni.kit.widget.spinner/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``omni.kit.widget.spinner`` extension.
This project adheres to `Semantic Versioning <https://semver.org/>`_.
## [1.0.4] - 2022-07-25
### Added
- Add precision to reduced floating point precision issues.
## [1.0.3] - 2022-04-08
### Added
- Add test
## [1.0.2] - 2022-03-07
### Changed
- Donot change value when disabled
## [1.0.1] - 2022-03-07
### Changed
- Widget height
## [1.0.0] - 2022-03-04
### Added
- Initial version implementation
| 502 | Markdown | 18.346153 | 83 | 0.669323 |
omniverse-code/kit/exts/omni.kit.widget.spinner/docs/README.md | # Spinner widget
To use:
```
from omni.kit.widget.spinner import FloatSpinner, IntSpinner
float_model = ui.SimpleFloatModel()
float_spinner = FloatSpinner(model=float_model)
int_model = ui.SimpleIntModel()
int_spinner = IntSpinner(model=int_model)
```
Cleanup:
```
float_spinner.destroy()
int_spinner.destroy()
``` | 320 | Markdown | 15.049999 | 60 | 0.740625 |
omniverse-code/kit/exts/omni.kit.widget.stage_icons/config/extension.toml | [package]
version = "1.0.2"
authors = ["NVIDIA"]
title = "Icons for Stage Widget"
description = "Default Set of Icons for the Stage Window."
readme = "docs/README.md"
repository = ""
category = "Stage"
keywords = ["kit", "example"]
changelog = "docs/CHANGELOG.md"
icon = "data/icon.png"
[[python.module]]
name = "omni.kit.widget.stage_icons"
# Additional python module with tests, to make them discoverable by test system.
[[python.module]]
name = "omni.kit.widget.stage_icons.tests"
[[test]]
dependencies = [
"omni.kit.widget.stage",
]
| 544 | TOML | 21.708332 | 80 | 0.696691 |
omniverse-code/kit/exts/omni.kit.widget.stage_icons/omni/kit/widget/stage_icons/stage_icons_extension.py | # Copyright (c) 2018-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.
#
from pathlib import Path
import carb.settings
import omni.ext
class StageIconsExtension(omni.ext.IExt):
_icons_registered = None
@staticmethod
def get_registered_icons():
return StageIconsExtension._icons_registered
def register_icons(self):
StageIconsExtension._icons_registered = []
import omni.kit.widget.stage
stage_icons = omni.kit.widget.stage.StageIcons()
current_path = Path(__file__).parent
icon_path = current_path.parent.parent.parent.parent.joinpath("icons")
style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
# Read all the svg files in the directory
icons = {icon.stem: str(icon) for icon in icon_path.joinpath(style).glob("*.svg")}
for prim_type, filename in icons.items():
stage_icons.set(prim_type, filename)
StageIconsExtension._icons_registered.append(prim_type)
def on_startup(self, ext_id):
StageIconsExtension._icons_registered = None
manager = omni.kit.app.get_app().get_extension_manager()
self._hook = manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self.register_icons(),
ext_name="omni.kit.widget.stage",
hook_name="omni.kit.widget.stage_icons",
)
def on_shutdown(self):
if StageIconsExtension._icons_registered:
try:
import omni.kit.widget.stage
except ImportError as e:
return
stage_icons = omni.kit.widget.stage.StageIcons()
for prim_type in StageIconsExtension._icons_registered:
stage_icons.set(prim_type, None)
| 2,153 | Python | 36.13793 | 108 | 0.672085 |
omniverse-code/kit/exts/omni.kit.widget.stage_icons/omni/kit/widget/stage_icons/tests/stage_icons_test.py | ## 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.
##
from ..stage_icons_extension import StageIconsExtension
import omni.kit.test
class TestStageIcons(omni.kit.test.AsyncTestCase):
async def test_registry(self):
icons = StageIconsExtension.get_registered_icons()
self.assertIsInstance(icons, list)
self.assertIn("Camera", icons)
self.assertIn("GeomSubset", icons)
self.assertIn("Instance", icons)
self.assertIn("Light", icons)
self.assertIn("Material", icons)
self.assertIn("Prim", icons)
self.assertIn("Reference", icons)
self.assertIn("Scope", icons)
self.assertIn("Shader", icons)
self.assertIn("SkelJoint", icons)
self.assertIn("Xform", icons)
async def test_disable_extension(self):
manager = omni.kit.app.get_app().get_extension_manager()
ext_id = "omni.kit.widget.stage_icons"
self.assertTrue(ext_id)
self.assertTrue(manager.is_extension_enabled(ext_id))
manager.set_extension_enabled(ext_id, False)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertTrue(not manager.is_extension_enabled(ext_id))
manager.set_extension_enabled(ext_id, True)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertTrue(manager.is_extension_enabled(ext_id))
| 1,969 | Python | 41.826086 | 77 | 0.687659 |
omniverse-code/kit/exts/omni.kit.widget.stage_icons/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``omni.kit.widget.stage_icons`` extension.
This project adheres to `Semantic Versioning <https://semver.org/>`.
## [1.0.2] - 2021-07-29
### Changes
- Added payload icon
## [1.0.1] - 2021-02-10
### Changes
- Updated StyleUI handling
## [1.0.0] - 2020-10-22
### Added
- The initial extension
| 354 | Markdown | 16.749999 | 87 | 0.677966 |
omniverse-code/kit/exts/omni.kit.widget.stage_icons/docs/README.md | # Default Set of Icons for the Stage Window [omni.kit.widget.stage_icons]
To add an icon, just name it with the type of USD Prim and place it to the icons folder.
| 164 | Markdown | 40.24999 | 88 | 0.756098 |
omniverse-code/kit/exts/omni.kit.raycast.query/omni/kit/raycast/query/__init__.py | from ._omni_kit_raycast_query import *
from .scripts import *
__all__ = []
| 76 | Python | 14.399997 | 38 | 0.644737 |
omniverse-code/kit/exts/omni.kit.raycast.query/omni/kit/raycast/query/_omni_kit_raycast_query.pyi | """pybind11 omni.kit.raycast.query.IRaycastQuery bindings"""
from __future__ import annotations
import omni.kit.raycast.query._omni_kit_raycast_query
import typing
__all__ = [
"IRaycastQuery",
"Ray",
"RayQueryResult",
"Result",
"acquire_raycast_query_interface"
]
class IRaycastQuery():
def add_raycast_sequence(self) -> int: ...
def get_latest_result_from_raycast_sequence(self, arg0: int) -> typing.Tuple[Ray, RayQueryResult]: ...
def remove_raycast_sequence(self, arg0: int) -> Result: ...
def set_raycast_sequence_array_size(self, arg0: int, arg1: int) -> Result: ...
def submit_ray_to_raycast_sequence(self, arg0: int, arg1: Ray) -> Result: ...
def submit_raycast_query(self, ray: Ray, callback: typing.Callable[[Ray, RayQueryResult], None]) -> None: ...
pass
class Ray():
def __init__(self, origin: object, direction: object, min_t: float = 0.0, max_t: float = inf, adjust_for_section: bool = True) -> None:
"""
Create a new Ray
"""
def __repr__(self) -> str: ...
def __str__(self) -> str: ...
@property
def forward(self) -> object:
"""
direction of the ray
:type: object
"""
@forward.setter
def forward(self, arg1: object) -> None:
"""
direction of the ray
"""
@property
def max_t(self) -> float:
"""
t value at end of ray
:type: float
"""
@max_t.setter
def max_t(self, arg1: float) -> None:
"""
t value at end of ray
"""
@property
def min_t(self) -> float:
"""
t value of start of ray
:type: float
"""
@min_t.setter
def min_t(self, arg1: float) -> None:
"""
t value of start of ray
"""
@property
def origin(self) -> object:
"""
origin of the ray
:type: object
"""
@origin.setter
def origin(self, arg1: object) -> None:
"""
origin of the ray
"""
pass
class RayQueryResult():
def __init__(self) -> None:
"""
Create a new RayQueryResult
"""
def __repr__(self) -> str: ...
def __str__(self) -> str: ...
def get_target_usd_path(self) -> str:
"""
This function returns the usd path of geometry that was hit.
Return:
Usd path of object that is the target, or an empty string if nothing was hit
"""
@property
def hit_position(self) -> object:
"""
position of hit
:type: object
"""
@property
def hit_t(self) -> float:
"""
t value of hit position
:type: float
"""
@property
def instance_id(self) -> int:
"""
instance id
:type: int
"""
@property
def normal(self) -> object:
"""
normal of geometry at hit point
:type: object
"""
@property
def primitive_id(self) -> int:
"""
primitive id
:type: int
"""
@property
def valid(self) -> bool:
"""
indicates whether result is valid
:type: bool
"""
pass
class Result():
"""
Result.
Members:
SUCCESS
INVALID_PARAMETER
PARAMETER_IS_NULL
RAYCAST_SEQUENCE_DOES_NOT_EXIST
RAYCAST_QUERY_MANAGER_DOES_NOT_EXIT
RAYCAST_SEQUENCE_ADDITION_FAILED
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
INVALID_PARAMETER: omni.kit.raycast.query._omni_kit_raycast_query.Result # value = <Result.INVALID_PARAMETER: 1>
PARAMETER_IS_NULL: omni.kit.raycast.query._omni_kit_raycast_query.Result # value = <Result.PARAMETER_IS_NULL: 2>
RAYCAST_QUERY_MANAGER_DOES_NOT_EXIT: omni.kit.raycast.query._omni_kit_raycast_query.Result # value = <Result.RAYCAST_QUERY_MANAGER_DOES_NOT_EXIT: 4>
RAYCAST_SEQUENCE_ADDITION_FAILED: omni.kit.raycast.query._omni_kit_raycast_query.Result # value = <Result.RAYCAST_SEQUENCE_ADDITION_FAILED: 5>
RAYCAST_SEQUENCE_DOES_NOT_EXIST: omni.kit.raycast.query._omni_kit_raycast_query.Result # value = <Result.RAYCAST_SEQUENCE_DOES_NOT_EXIST: 3>
SUCCESS: omni.kit.raycast.query._omni_kit_raycast_query.Result # value = <Result.SUCCESS: 0>
__members__: dict # value = {'SUCCESS': <Result.SUCCESS: 0>, 'INVALID_PARAMETER': <Result.INVALID_PARAMETER: 1>, 'PARAMETER_IS_NULL': <Result.PARAMETER_IS_NULL: 2>, 'RAYCAST_SEQUENCE_DOES_NOT_EXIST': <Result.RAYCAST_SEQUENCE_DOES_NOT_EXIST: 3>, 'RAYCAST_QUERY_MANAGER_DOES_NOT_EXIT': <Result.RAYCAST_QUERY_MANAGER_DOES_NOT_EXIT: 4>, 'RAYCAST_SEQUENCE_ADDITION_FAILED': <Result.RAYCAST_SEQUENCE_ADDITION_FAILED: 5>}
pass
def acquire_raycast_query_interface(*args, **kwargs) -> typing.Any:
pass
| 5,306 | unknown | 27.842391 | 418 | 0.563513 |
omniverse-code/kit/exts/omni.kit.raycast.query/omni/kit/raycast/query/scripts/__init__.py | from .utils import * | 20 | Python | 19.99998 | 20 | 0.75 |
omniverse-code/kit/exts/omni.kit.raycast.query/omni/kit/raycast/query/scripts/utils.py | __all__ = ["raycast_from_mouse_ndc"]
import omni.kit.raycast.query as rq
from typing import Sequence, Callable
def raycast_from_mouse_ndc(
mouse_ndc: Sequence[float],
viewport_api: "ViewportAPI",
on_complete_fn: Callable
):
ndc_near = (mouse_ndc[0], mouse_ndc[1], -1)
ndc_far = (mouse_ndc[0], mouse_ndc[1], 1)
view_proj_inv = (viewport_api.view * viewport_api.projection).GetInverse()
origin = view_proj_inv.Transform(ndc_near)
dir = (view_proj_inv.Transform(ndc_far) - origin).GetNormalized()
ray = rq.Ray(origin, dir)
rqi = rq.acquire_raycast_query_interface()
rqi.submit_raycast_query(ray, on_complete_fn)
| 658 | Python | 28.954544 | 78 | 0.673252 |
omniverse-code/kit/exts/omni.kit.raycast.query/omni/kit/raycast/query/tests/test_raycast.py | # 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.
#
import asyncio
from pathlib import Path
import carb
import carb.settings
import omni.kit.app
import omni.kit.commands
import omni.kit.raycast.query
from omni.kit.raycast.query import utils as rq_utils
import omni.kit.test
import omni.usd
from omni import ui
import omni.kit.ui_test as ui_test
from omni.kit.viewport.utility import get_active_viewport
from pxr import Gf, UsdGeom
SETTING_SECTION_ENABLED = "/rtx/sectionPlane/enabled"
SETTING_SECTION_PLANE = "/rtx/sectionPlane/plane"
DATA_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.raycast.query}/data"))
USD_FILES = DATA_PATH.joinpath("tests").joinpath("usd")
class TestRaycast(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.get_settings()
self._app = omni.kit.app.get_app()
self._context = omni.usd.get_context()
self._raycast = omni.kit.raycast.query.acquire_raycast_query_interface()
async def tearDown(self):
pass
async def _setup_simple_scene(self):
await self._context.new_stage_async()
stage = self._context.get_stage()
self.assertTrue(stage)
CUBE_PATH = "/Cube"
cube = UsdGeom.Cube.Define(stage, CUBE_PATH)
UsdGeom.XformCommonAPI(cube.GetPrim()).SetTranslate(Gf.Vec3d(123.45, 0, 0))
return cube
async def test_single_raycast_query(self):
await self._setup_simple_scene()
viewport_api = get_active_viewport()
await viewport_api.wait_for_rendered_frames(5)
ray = omni.kit.raycast.query.Ray((1000, 0, 0), (-1, 0, 0))
future = asyncio.Future()
def callback(ray, result):
future.set_result(result)
self._raycast.submit_raycast_query(ray, callback)
result = await future
self.assertTrue(result.valid)
self.assertTrue(Gf.IsClose(Gf.Vec3d(*result.hit_position), Gf.Vec3d(124.45, 0, 0), 1e-4))
self.assertTrue(Gf.IsClose(result.hit_t, 875.551, 1e-4))
self.assertTrue(Gf.IsClose(Gf.Vec3d(*result.normal), Gf.Vec3d(1, 0, 0), 1e-4))
self.assertEqual(result.get_target_usd_path(), "/Cube")
async def test_ray_with_section_tool(self):
"""Test if raycast section plane awareness"""
await self._context.new_stage_async()
# Set up a scene with 2 large flattened cubes as floors, one is 3m higher the other
cube_bottom_path = "/World/Cube_bottom"
omni.kit.commands.create(
"CreatePrim",
prim_type="Cube",
prim_path=cube_bottom_path,
select_new_prim=False,
).do()
omni.kit.commands.create(
"TransformPrimSRTCommand",
path=cube_bottom_path,
new_scale=Gf.Vec3d(1000, 1, 1000)
).do()
cube_top_path = "/World/Cube_top"
cube_top_height = 300.0
omni.kit.commands.create(
"CreatePrim",
prim_type="Cube",
prim_path=cube_top_path,
select_new_prim=False,
).do()
omni.kit.commands.create(
"TransformPrimSRTCommand",
path=cube_top_path,
new_scale=Gf.Vec3d(1000, 1, 1000),
new_translation=Gf.Vec3d(0, cube_top_height, 0)
).do()
await self._app.next_update_async()
section_plane_height = 150
self._settings.set(SETTING_SECTION_ENABLED, True)
self._settings.set(SETTING_SECTION_PLANE, [0, -1, 0, section_plane_height])
async def submit_ray_and_wait_for_result(ray):
future = asyncio.Future()
def callback(ray, result):
future.set_result(result)
self._raycast.submit_raycast_query(ray, callback)
return await future
#### Test 1, ray origin is culled, and direction points away from section plane ####
ray = omni.kit.raycast.query.Ray((0, section_plane_height + 10, 0), (0, 1, 0))
result = await submit_ray_and_wait_for_result(ray)
# no valid result should return
self.assertFalse(result.valid)
#### Test 1.1, ray origin is culled, and direction points away from section plane, but no section awareness ####
ray = omni.kit.raycast.query.Ray((0, section_plane_height + 10, 0), (0, 1, 0), adjust_for_section=False)
result = await submit_ray_and_wait_for_result(ray)
# ray should hit Top Cube even though it's culled
self.assertTrue(result.valid)
self.assertAlmostEqual(result.hit_position[1], cube_top_height - 1.0)
#### Test 2, ray origin is culled, but direction points towards section plane ####
ray = omni.kit.raycast.query.Ray((0, cube_top_height + 20, 0), (0, -1, 0))
result = await submit_ray_and_wait_for_result(ray)
# ray should skip top Cube and hit bottom Cube
self.assertTrue(result.valid)
self.assertAlmostEqual(result.hit_position[1], 1.0)
#### Test 2.1, ray origin is culled, but direction points towards section plane, but no section awareness ####
ray = omni.kit.raycast.query.Ray((0, cube_top_height + 20, 0), (0, -1, 0), adjust_for_section=False)
result = await submit_ray_and_wait_for_result(ray)
# ray should hit top Cube even though it's culled
self.assertTrue(result.valid)
self.assertAlmostEqual(result.hit_position[1], cube_top_height + 1.0)
#### Test 3, ray origin is not culled, but direction points towards section plane ####
ray = omni.kit.raycast.query.Ray((0, section_plane_height - 10, 0), (0, 1, 0))
result = await submit_ray_and_wait_for_result(ray)
# no valid result should return
self.assertFalse(result.valid)
#### Test 4, ray origin is not culled, and direction points away from section plane ####
ray = omni.kit.raycast.query.Ray((0, section_plane_height - 10, 0), (0, -1, 0))
result = await submit_ray_and_wait_for_result(ray)
# ray should hit bottom Cube
self.assertTrue(result.valid)
self.assertAlmostEqual(result.hit_position[1], 1.0)
self._settings.set(SETTING_SECTION_ENABLED, False)
async def test_raycast_from_mouse_ndc(self):
await self._context.new_stage_async()
omni.kit.commands.create(
"CreatePrim",
prim_type="Cube",
prim_path="/World/Cube",
select_new_prim=False,
).do()
omni.kit.commands.create(
"TransformPrimSRTCommand",
path="/World/Cube",
new_scale=Gf.Vec3d(1000, 1, 1000)
).do()
viewport_api = get_active_viewport()
await viewport_api.wait_for_rendered_frames(5)
future = asyncio.Future()
def callback(ray, result):
future.set_result(result)
rq_utils.raycast_from_mouse_ndc(
(0, 0),
viewport_api,
callback,
)
result = await future
self.assertTrue(result.valid)
self.assertTrue(Gf.IsClose(Gf.Vec3d(*result.hit_position), Gf.Vec3d(1, 1, 1), 1e-4))
self.assertTrue(Gf.IsClose(result.hit_t, 863.2943, 1e-4))
self.assertTrue(Gf.IsClose(Gf.Vec3d(*result.normal), Gf.Vec3d(0, 1, 0), 1e-4))
self.assertEqual(result.get_target_usd_path(), "/World/Cube")
async def test_viewport_drag_and_drop(self):
await self._context.new_stage_async()
stage = self._context.get_stage()
# Create a floor
floor = UsdGeom.Cube.Define(stage, "/World/floor")
UsdGeom.XformCommonAPI(floor.GetPrim()).SetTranslate(Gf.Vec3d(0, 100, 0))
UsdGeom.XformCommonAPI(floor.GetPrim()).SetScale(Gf.Vec3f(500, 1, 500))
await ui_test.wait_n_updates(10)
# Create an area in test window as drag source
drag_window_size = 80
drag_source_window = ui.Window(
"TestDrag",
width=drag_window_size,
height=drag_window_size
)
with drag_source_window.frame:
stack = ui.ZStack()
with stack:
ui.Rectangle(width=drag_window_size, height=drag_window_size)
def on_drag():
return str(USD_FILES.joinpath("test_drag_drop.usda"))
stack.set_drag_fn(on_drag)
# Layout window
app_window = omni.appwindow.get_default_app_window()
window_width = app_window.get_width()
window_height = app_window.get_height()
vp_window = ui.Workspace.get_window("Viewport Next")
vp_width = int(window_width / 2)
vp_height = int(window_height / 2)
vp_window.position_x = 0
vp_window.position_y = 0
vp_window.width = vp_width
vp_window.height = vp_height
drag_source_window.position_x = 0
drag_source_window.position_y = vp_height +10
drag_source_window.focus()
await ui_test.wait_n_updates(10)
# Drag and drop
rect = ui_test.find("TestDrag//Frame/**/Rectangle[*]")
await ui_test.human_delay(20)
vp_center = ui_test.Vec2(
int(vp_window.position_x + vp_window.width/2),
int(vp_window.position_y + vp_window.height/2)
)
await rect.drag_and_drop(vp_center)
await ui_test.human_delay(20)
# Check dropped prim
dropped_path = "/test_drag_drop"
droped_prim = stage.GetPrimAtPath(dropped_path)
self.assertTrue(droped_prim)
world_mtx = omni.usd.get_world_transform_matrix(droped_prim)
dropped_pos = world_mtx.ExtractTranslation()
# Expected height = floor height + floor thickess
self.assertTrue(Gf.IsClose(dropped_pos[1], 101.0, 1e-2))
await ui_test.human_delay(20)
if drag_source_window:
drag_source_window.destroy()
del drag_source_window
| 10,261 | Python | 35.781362 | 120 | 0.621869 |
omniverse-code/kit/exts/omni.kit.raycast.query/omni/kit/raycast/query/tests/__init__.py | from .test_raycast import *
| 28 | Python | 13.499993 | 27 | 0.75 |
omniverse-code/kit/exts/omni.kit.raycast.query/docs/index.rst | omni.kit.raycast.query
###########################
RTX Raycast Query extension:
.. toctree::
:maxdepth: 1
README.md
CHANGELOG.md
| 144 | reStructuredText | 12.181817 | 28 | 0.541667 |
omniverse-code/kit/exts/omni.kit.window.script_editor/config/extension.toml | [package]
version = "1.7.2"
authors = ["NVIDIA"]
title = "Script Editor"
description = "Window to edit and run python scripts."
repository = ""
category = "Internal"
feature = true
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui" = {}
"omni.kit.actions.core" = {}
"omni.kit.hotkeys.core" = {}
"omni.kit.widget.filebrowser" = {}
"omni.kit.window.filepicker" = {}
[[native.library]]
path = "bin/${lib_prefix}omni.kit.window.script_editor.plugin${lib_ext}"
[[python.module]]
name = "omni.kit.window.script_editor"
[settings]
# Folder to look for snippets. Snippets are just .py files, where first line is a comment with snippet name. Snippet
# name can contain one '/' to define category. E.g. # Settings/Get Setting
exts."omni.kit.window.script_editor".snippetFolders = [
"${kit}/snippets",
"${shared_documents}/snippets"
]
# Clear text from the editor tab after it has been executed?
persistent.exts."omni.kit.window.script_editor".clearAfterExecute = false
# Color palette to use. Can be "Dark", "Light" or "Retro Blue".
persistent.exts."omni.kit.window.script_editor".editorPalette = "Dark"
# If you open or reload a script file, should it be automatically executed?
persistent.exts."omni.kit.window.script_editor".executeOnReload = false
# Size, in points, of font used in the log window and editor tabs.
# If the exact size is not supported the nearest one will be used.
persistent.exts."omni.kit.window.script_editor".fontSize = 14
# Set the path to the font of the bottom part of the window
persistent.exts."omni.kit.window.script_editor".font = ""
# Write to temp file before executing. That allows inspect and ast std modules to be able to get sources and work correctly.
exts."omni.kit.window.script_editor".executeInTempFile = true
[[test]]
dependencies = [
"omni.kit.ui_test",
]
stdoutFailPatterns.exclude = [
"*SyntaxError*" # We have syntax error produced on purpose during testing
]
| 1,962 | TOML | 29.671875 | 124 | 0.726809 |
omniverse-code/kit/exts/omni.kit.window.script_editor/omni/kit/window/script_editor/__init__.py | from ._script_editor import *
from .scripts import * | 53 | Python | 16.999994 | 29 | 0.735849 |
omniverse-code/kit/exts/omni.kit.window.script_editor/omni/kit/window/script_editor/scripts/__init__.py | from .script_editor_extension import ScriptEditorExtension, ScriptEditorWindow | 78 | Python | 77.999922 | 78 | 0.897436 |
omniverse-code/kit/exts/omni.kit.window.script_editor/omni/kit/window/script_editor/scripts/script_editor_extension.py | # Copyright (c) 2018-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.
#
__all__ = ["ScriptEditorExtension"]
import asyncio
import omni.ext
import omni.kit.ui
import omni.ui as ui
from functools import partial
from .script_editor_window import ScriptEditorWindow
class ScriptEditorExtension(omni.ext.IExt):
"""The entry point for Script Editor Window"""
WINDOW_NAME = "Script Editor"
MENU_PATH = f"Window/{WINDOW_NAME}"
def on_startup(self, ext_id):
self._ext_name = omni.ext.get_extension_name(ext_id)
ui.Workspace.set_show_window_fn(ScriptEditorExtension.WINDOW_NAME, partial(self.show_window, None))
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
# off by default
self._menu = editor_menu.add_item(ScriptEditorExtension.MENU_PATH, self.show_window, toggle=True, value=False)
self._window = None
def on_shutdown(self):
self._menu = None
asyncio.ensure_future(self._destroy_window_async())
ui.Workspace.set_show_window_fn(ScriptEditorExtension.WINDOW_NAME, None)
def _set_menu(self, value):
"""Set the menu to create this window on and off"""
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(ScriptEditorExtension.MENU_PATH, value)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.deregister_hotkeys(self._ext_name)
self._window.deregister_actions(self._ext_name)
self._window.destroy()
self._window = None
def _visibility_changed_fn(self, visible):
self._set_menu(visible)
def show_window(self, menu, value):
if value:
if self._window:
# If we already have the window hidden, just show it, rather than creating a new one
self._window.visible = True
else:
self._window = ScriptEditorWindow()
self._window.set_visibility_changed_listener(self._visibility_changed_fn)
self._window.register_actions(self._ext_name)
self._window.register_hotkeys(self._ext_name)
elif self._window:
self._window.visible = False
| 2,778 | Python | 35.565789 | 122 | 0.660907 |
omniverse-code/kit/exts/omni.kit.window.script_editor/omni/kit/window/script_editor/scripts/script_editor_menu.py | import carb
import omni.client
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.filepicker import FilePickerDialog
import os
def _encode_content(content):
if type(content) == str:
payload = bytes(content.encode("utf-8"))
elif type(content) != type(None):
payload = bytes(content)
else:
payload = bytes()
return payload
class MenuOptions:
def __init__(self, **kwargs):
self._dialog = None
self._current_filename = None
self._current_dir = None
self.load_data = kwargs.pop("load_data", None)
self.save_data = kwargs.pop("save_data", None)
self.get_file_path = kwargs.pop("get_file_path", None)
def destroy(self):
if self._dialog:
self._dialog.destroy()
def __on_apply_save(self, filename: str, dir: str):
"""Called when the user press "Export" in the pick filename dialog"""
# don't accept as long as no filename is selected
if not filename or not dir:
return
self._dialog.hide()
# add the file extension if missing
if self._dialog.current_filter_option == 0 and not filename.lower().endswith(".py"):
filename += ".py"
self._current_filename = filename
self._current_dir = dir
# add a trailing slash for the client library
if dir[-1] != os.sep:
dir = dir + os.sep
current_export_path = omni.client.combine_urls(dir, filename)
self.save(current_export_path)
def __on_apply_load(self, filename: str, dir: str):
"""Called when the user press "Export" in the pick filename dialog"""
# don't accept as long as no filename is selected
if not filename or not dir:
return
self._dialog.hide()
# add a trailing slash for the client library
if dir[-1] != os.sep:
dir = dir + os.sep
# OM-93082: Fix issue with omni.client.combine_urls will eat up the subfolder path for omniverse urls if
# the dirname is ending with "\" on windows
dir = dir.replace("\\", "/")
current_path = omni.client.combine_urls(dir, filename)
if omni.client.stat(current_path)[0] != omni.client.Result.OK:
# add the file extension if missing
if self._dialog.current_filter_option == 0 and not filename.lower().endswith(".py"):
filename += ".py"
current_path = omni.client.combine_urls(dir, filename)
if omni.client.stat(current_path)[0] != omni.client.Result.OK:
# Still can't find
return
self._current_filename = filename
self._current_dir = dir
self.open(current_path)
def __menu_filter_files(self, item: FileBrowserItem) -> bool:
"""Used by pick folder dialog to hide all the files"""
if not item or item.is_folder:
return True
if self._dialog.current_filter_option == 0:
# Show only files with listed extensions
if item.path.endswith(".py"):
return True
else:
return False
else:
# Show All Files (*)
return True
def menu_open(self):
"""Open "Open" dialog"""
if self._dialog:
self._dialog.destroy()
self._dialog = FilePickerDialog(
"Open...",
allow_multi_selection=False,
apply_button_label="Open",
click_apply_handler=self.__on_apply_load,
item_filter_options=["Python Files (*.py)", "Any file (*.*)"],
item_filter_fn=self.__menu_filter_files,
current_filename=self._current_filename,
current_directory=self._current_dir,
)
def menu_save(self):
file_path = self.get_file_path()
if file_path:
self.save(file_path)
else:
self.menu_save_as()
def menu_save_as(self):
"""Open "Save As" dialog"""
if self._dialog:
self._dialog.destroy()
self._dialog = FilePickerDialog(
"Save As...",
allow_multi_selection=False,
apply_button_label="Save",
click_apply_handler=self.__on_apply_save,
item_filter_options=["Python Files (*.py)", "Any file (*.*)"],
item_filter_fn=self.__menu_filter_files,
current_filename=self._current_filename,
current_directory=self._current_dir,
)
def save(self, filename: str):
"""Save the current model to external file"""
data = self.save_data(filename)
if not data:
return
# Save to the file
result = omni.client.write_file(filename, _encode_content(data))
if result != omni.client.Result.OK:
carb.log_error(f"[omni.kit.window.script_editor] Cannot write to {filename}, error code: {result}")
return
carb.log_info(f"[omni.kit.window.script_editor] The scripts have saved to {filename}")
def open(self, filename: str):
"""Load the model from the file"""
result, _, content = omni.client.read_file(filename)
if result != omni.client.Result.OK:
carb.log_error(f"[omni.kit.window.script_editor] Can't read file {filename}, error code: {result}")
return
data = memoryview(content).tobytes().decode("utf-8")
self.load_data(filename, data)
| 5,522 | Python | 32.676829 | 112 | 0.573886 |
omniverse-code/kit/exts/omni.kit.window.script_editor/omni/kit/window/script_editor/scripts/script_editor_window.py | # Copyright (c) 2018-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.
#
__all__ = ["ScriptEditorWindow"]
import omni.ui as ui
from .._script_editor import ScriptEditorWidget
from .script_editor_menu import MenuOptions
from omni.kit.actions.core import get_action_registry
import omni.kit.hotkeys.core as hotkeys
_DEFAULT_HOTKEY_MAP = {
"Open": "ALT+O",
"Save": "ALT+S",
"Save As": "SHIFT+ALT+S",
}
class ScriptEditorWindow(ui.Window):
"""The Script Editor window"""
def __init__(self):
self._title = "Script Editor"
super().__init__(
self._title,
width=800,
height=600,
flags=ui.WINDOW_FLAGS_MENU_BAR,
raster_policy=ui.RasterPolicy.NEVER
)
self._visiblity_changed_listener = None
self.set_visibility_changed_fn(self._visibility_changed_fn)
with self.frame:
self._script_editor_widget = ScriptEditorWidget()
with self.menu_bar:
self._menu_option = MenuOptions(
load_data=self.load_data,
save_data=self.save_data,
get_file_path=self.get_file_path,
)
with ui.Menu("File"):
ui.MenuItem("Open", hotkey_text="Alt + O", triggered_fn=self._menu_option.menu_open)
ui.MenuItem("Save", hotkey_text="Alt + S", triggered_fn=self._menu_option.menu_save)
ui.MenuItem("Save As...", hotkey_text="Shift + Alt + S", triggered_fn=self._menu_option.menu_save_as)
def register_actions(self, extension_id: str):
action_registry = get_action_registry()
actions_tag = "Script Editor File Actions"
action_registry.register_action(
extension_id,
"Open",
self._menu_option.menu_open,
display_name="Open",
description="Open a script",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"Save",
self._menu_option.menu_save,
display_name="Save",
description="Save the script from the current tab to a file",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"Save As",
self._menu_option.menu_save_as,
display_name="Save As...",
description="Save the script from the current tab as a file",
tag=actions_tag,
)
def deregister_actions(self, extension_id):
action_registry = get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
def register_hotkeys(self, extension_id: str):
hotkey_registry = hotkeys.get_hotkey_registry()
action_registry = get_action_registry()
ext_actions = action_registry.get_all_actions_for_extension(extension_id)
for action in ext_actions:
key = _DEFAULT_HOTKEY_MAP.get(action.id, None)
# Not all Actions will have default hotkeys
if not key:
continue
hotkey_registry.register_hotkey(
hotkey_ext_id=extension_id,
key=key,
action_ext_id=action.extension_id,
action_id=action.id,
filter=None,
)
def deregister_hotkeys(self, extension_id: str):
hotkey_registry = hotkeys.get_hotkey_registry()
hotkey_registry.deregister_all_hotkeys_for_extension(extension_id)
def load_data(self, filename, data):
self._script_editor_widget.load_script(filename, data)
def save_data(self, filename):
return self._script_editor_widget.save_script(filename)
def clear_data(self):
self._script_editor_widget.clear_script()
def get_file_path(self):
return self._script_editor_widget.get_script_path()
def _visibility_changed_fn(self, visible):
if self._visiblity_changed_listener:
self._visiblity_changed_listener(visible)
def set_visibility_changed_listener(self, listener):
self._visiblity_changed_listener = listener
def destroy(self):
"""
Called by extension before destroying this object. It doesn't happen automatically.
Without this hot reloading doesn't work.
"""
if self._script_editor_widget:
self._script_editor_widget.destroy()
self._script_editor_widget = None
self._visiblity_changed_listener = None
super().destroy()
| 4,914 | Python | 33.612676 | 117 | 0.613553 |
omniverse-code/kit/exts/omni.kit.window.script_editor/omni/kit/window/script_editor/tests/test_script_editor.py | ## 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.
##
import omni.kit.test
import omni.kit.app
from omni.kit.test import AsyncTestCase
import omni.kit.ui_test as ui_test
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from omni.kit.window.script_editor.scripts import ScriptEditorWindow
import omni.ui as ui
CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data")
# Use it to receive extraterrestrial messages from executing script
public_mailbox = ""
class TestScriptEditor(AsyncTestCase):
# Before running each test
async def setUp(self):
global public_mailbox
public_mailbox = ""
window = ScriptEditorWindow()
await ui_test.wait_n_updates(2)
self.editor = ui_test.find("Script Editor")
await self.editor.focus()
# Close tab and clear script
await ui_test.emulate_key_combo("CTRL+W")
window.clear_data()
# Focus on text field
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(700, 500))
async def test_script_run(self):
await ui_test.emulate_char_press("import omni.kit.window.script_editor.tests.test_script_editor as editor\n")
await ui_test.emulate_char_press("editor.public_mailbox = 'who is there?'\n")
await ui_test.wait_n_updates(2)
await ui_test.emulate_key_combo("CTRL+ENTER")
self.assertEqual(public_mailbox, "who is there?")
# Add another line
await ui_test.emulate_char_press("editor.public_mailbox = 123\n")
await ui_test.wait_n_updates(2)
await ui_test.emulate_key_combo("CTRL+ENTER")
self.assertEqual(public_mailbox, 123)
# New tab
await ui_test.emulate_key_combo("CTRL+N")
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(700, 500))
await ui_test.emulate_char_press("import omni.kit.window.script_editor.tests.test_script_editor as editor\n")
await ui_test.emulate_char_press("editor.public_mailbox = 'yellow'\n")
await ui_test.wait_n_updates(2)
await ui_test.emulate_key_combo("CTRL+ENTER")
self.assertEqual(public_mailbox, "yellow")
async def test_script_fail(self):
await ui_test.emulate_char_press("import omni.kit.window.script_editor.tests.test_script_editor as editor\n")
await ui_test.emulate_char_press("editor.public_mailbox = 555\n")
await ui_test.emulate_char_press("x = \n") # typo
await ui_test.wait_n_updates(2)
await ui_test.emulate_key_combo("CTRL+ENTER")
self.assertEqual(public_mailbox, "")
# fix it
await ui_test.emulate_key_combo("BACKSPACE")
await ui_test.emulate_key_combo("BACKSPACE")
await ui_test.emulate_char_press("3")
await ui_test.wait_n_updates(2)
await ui_test.emulate_key_combo("CTRL+ENTER")
self.assertEqual(public_mailbox, 555)
async def test_script_get_source(self):
# That tests: exts."omni.kit.window.script_editor".executeInTempFile = true
# If we are not writing to a temp file ast/inspect doesn't work and throws error that it can't find source.
await ui_test.emulate_char_press("""
import ast
import inspect
import omni.kit.window.script_editor.tests.test_script_editor as editor
foo = lambda y: y
lines = inspect.getsource(foo)
r = ast.parse(lines)
editor.public_mailbox = r is not None
""")
await ui_test.wait_n_updates(2)
await ui_test.emulate_key_combo("CTRL+ENTER")
self.assertEqual(public_mailbox, True)
async def test_close_and_reopen_window(self):
"""Tests to make sure that content remains in the window even after it has been closed and reopened."""
global public_mailbox
await ui_test.emulate_char_press("import omni.kit.window.script_editor.tests.test_script_editor as editor\n")
await ui_test.emulate_char_press("editor.public_mailbox = 'Hello World'\n")
await ui_test.wait_n_updates(2)
await ui_test.emulate_key_combo("CTRL+ENTER")
self.assertEqual(public_mailbox, "Hello World")
await ui_test.wait_n_updates(2)
self.editor._widget.visible = False
await ui_test.wait_n_updates(2)
public_mailbox = ""
self.editor._widget.visible = True
await ui_test.wait_n_updates(2)
await ui_test.emulate_key_combo("CTRL+ENTER")
self.assertEqual(public_mailbox, "Hello World")
| 4,815 | Python | 39.813559 | 117 | 0.681412 |
omniverse-code/kit/exts/omni.kit.window.script_editor/omni/kit/window/script_editor/tests/__init__.py | from .test_script_editor import *
| 34 | Python | 16.499992 | 33 | 0.764706 |
omniverse-code/kit/exts/omni.kit.test_suite.context_browser/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
category = "Internal"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "omni.kit.test_suite.viewport"
description="omni.kit.test_suite.viewport"
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "ui", "test"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog = "docs/CHANGELOG.md"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
[[python.module]]
name = "omni.kit.test_suite.context_browser"
[dependencies]
"omni.kit.test" = {}
"omni.kit.test_helpers_gfx" = {}
"omni.kit.renderer.capture" = {}
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/file/ignoreUnsavedOnExit=true",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/persistent/app/omniverse/filepicker/options_menu/show_details=false",
"--/persistent/app/stage/dragDropImport='reference'",
"--no-window"
]
dependencies = [
"omni.kit.mainwindow",
"omni.usd",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers",
"omni.kit.window.stage",
"omni.kit.window.file",
"omni.kit.property.bundle",
"omni.kit.window.status_bar",
"omni.hydra.pxr",
"omni.kit.window.viewport",
"omni.kit.material.library",
"omni.kit.window.content_browser",
]
stdoutFailPatterns.exclude = [
"*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop
"*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available
]
| 2,211 | TOML | 29.301369 | 122 | 0.695613 |
omniverse-code/kit/exts/omni.kit.test_suite.context_browser/omni/kit/test_suite/context_browser/tests/__init__.py | from .test_content_browser_settings import *
from .test_file_picker_settings import *
| 86 | Python | 27.999991 | 44 | 0.790698 |
omniverse-code/kit/exts/omni.kit.test_suite.context_browser/omni/kit/test_suite/context_browser/tests/test_content_browser_settings.py | # 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.
#
import omni.usd
import carb
import omni.ui as ui
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, arrange_windows
class TestContentBrowserSettings(AsyncTestCase):
# Before running each test
async def setUp(self):
super().setUp()
await arrange_windows()
async def test_content_browser_settings(self):
from omni.kit.window.content_browser import get_content_window
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
async with ContentBrowserTestHelper() as content_browser_helper:
path = get_test_data_path(__name__, "folder1/")
async def get_files():
return sorted([c.name for c in await content_browser_helper.select_items_async(path, "*")])
# all off
await content_browser_helper.set_config_menu_settings({'hide_unknown': False, 'hide_thumbnails': False, 'show_udim_sequence': False, 'show_details': False})
menu_state = await content_browser_helper.get_config_menu_settings()
self.assertEqual(menu_state, {'hide_unknown': False, 'hide_thumbnails': False, 'show_details': False, 'show_udim_sequence': False})
self.assertEqual(await get_files(), ['.thumbs', 'badfile.cheese', 'cheese.1041.png', 'file.9999.xxx.png', 'tile.1001.png', 'tile.1200.png', 'udim.1001.jpg', 'udim.1200.jpg'])
# unknown enabled
await content_browser_helper.set_config_menu_settings({'hide_unknown': True, 'hide_thumbnails': False, 'show_udim_sequence': False, 'show_details': False})
menu_state = await content_browser_helper.get_config_menu_settings()
self.assertEqual(menu_state, {'hide_unknown': True, 'hide_thumbnails': False, 'show_details': False, 'show_udim_sequence': False})
self.assertEqual(await get_files(), ['.thumbs', 'cheese.1041.png', 'file.9999.xxx.png', 'tile.1001.png', 'tile.1200.png', 'udim.1001.jpg', 'udim.1200.jpg'])
# thumbs enabled
await content_browser_helper.set_config_menu_settings({'hide_unknown': False, 'hide_thumbnails': True, 'show_udim_sequence': False, 'show_details': False})
menu_state = await content_browser_helper.get_config_menu_settings()
self.assertEqual(menu_state, {'hide_unknown': False, 'hide_thumbnails': True, 'show_details': False, 'show_udim_sequence': False})
self.assertEqual(await get_files(), ['badfile.cheese', 'cheese.1041.png', 'file.9999.xxx.png', 'tile.1001.png', 'tile.1200.png', 'udim.1001.jpg', 'udim.1200.jpg'])
# udim enabled
await content_browser_helper.set_config_menu_settings({'hide_unknown': False, 'hide_thumbnails': False, 'show_udim_sequence': True, 'show_details': False})
menu_state = await content_browser_helper.get_config_menu_settings()
self.assertEqual(menu_state, {'hide_unknown': False, 'hide_thumbnails': False, 'show_details': False, 'show_udim_sequence': True})
self.assertEqual(await get_files(), ['.thumbs', 'badfile.cheese', 'cheese.<UDIM>.png', 'file.9999.xxx.png', 'tile.<UDIM>.png', 'udim.<UDIM>.jpg'])
# all enabled
await content_browser_helper.set_config_menu_settings({'hide_unknown': True, 'hide_thumbnails': True, 'show_udim_sequence': True, 'show_details': False})
menu_state = await content_browser_helper.get_config_menu_settings()
self.assertEqual(menu_state, {'hide_unknown': True, 'hide_thumbnails': True, 'show_details': False, 'show_udim_sequence': True})
self.assertEqual(await get_files(), ['cheese.<UDIM>.png', 'file.9999.xxx.png', 'tile.<UDIM>.png', 'udim.<UDIM>.jpg'])
| 4,230 | Python | 67.241934 | 186 | 0.678487 |
omniverse-code/kit/exts/omni.kit.test_suite.context_browser/omni/kit/test_suite/context_browser/tests/test_file_picker_settings.py | # 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.
#
import omni.usd
import carb
from functools import partial
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit.window.file_importer import get_file_importer
from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, arrange_windows
from omni.kit import ui_test
class TestFilePickerSettings(AsyncTestCase):
# Before running each test
async def setUp(self):
super().setUp()
await arrange_windows()
async def test_file_picker_settings(self):
from omni.kit.window.content_browser import get_content_window
from omni.kit.window.file_importer.test_helper import FileImporterTestHelper
async with FileImporterTestHelper() as file_import_helper:
path = get_test_data_path(__name__, "folder1/")
async def get_files():
return sorted([c.name for c in await file_import_helper.select_items_async(path, "*")])
file_importer = get_file_importer()
file_importer.show_window(
title="File Picker Test",
import_button_label="Ok",
file_extension_types=[('*.*', 'All Files')],
filename_url=path,
)
await ui_test.human_delay(50)
# all off
await file_import_helper.set_config_menu_settings({'hide_thumbnails': False, 'show_udim_sequence': False, 'show_details': False})
menu_state = await file_import_helper.get_config_menu_settings()
self.assertEqual(menu_state, {'hide_thumbnails': False, 'show_details': False, 'show_udim_sequence': False})
self.assertEqual(await get_files(), ['.thumbs', 'badfile.cheese', 'cheese.1041.png', 'file.9999.xxx.png', 'tile.1001.png', 'tile.1200.png', 'udim.1001.jpg', 'udim.1200.jpg'])
# thumbs enabled
await file_import_helper.set_config_menu_settings({'hide_thumbnails': True, 'show_udim_sequence': False, 'show_details': False})
menu_state = await file_import_helper.get_config_menu_settings()
self.assertEqual(menu_state, {'hide_thumbnails': True, 'show_details': False, 'show_udim_sequence': False})
self.assertEqual(await get_files(), ['badfile.cheese', 'cheese.1041.png', 'file.9999.xxx.png', 'tile.1001.png', 'tile.1200.png', 'udim.1001.jpg', 'udim.1200.jpg'])
# udim enabled
await file_import_helper.set_config_menu_settings({'hide_thumbnails': False, 'show_udim_sequence': True, 'show_details': False})
menu_state = await file_import_helper.get_config_menu_settings()
self.assertEqual(menu_state, {'hide_thumbnails': False, 'show_details': False, 'show_udim_sequence': True})
self.assertEqual(await get_files(), ['.thumbs', 'badfile.cheese', 'cheese.<UDIM>.png', 'file.9999.xxx.png', 'tile.<UDIM>.png', 'udim.<UDIM>.jpg'])
# all enabled
await file_import_helper.set_config_menu_settings({'hide_thumbnails': True, 'show_udim_sequence': True, 'show_details': False})
menu_state = await file_import_helper.get_config_menu_settings()
menu_state = await file_import_helper.get_config_menu_settings()
self.assertEqual(menu_state, {'hide_thumbnails': True, 'show_details': False, 'show_udim_sequence': True})
self.assertEqual(await get_files(), ['badfile.cheese', 'cheese.<UDIM>.png', 'file.9999.xxx.png', 'tile.<UDIM>.png', 'udim.<UDIM>.jpg'])
file_importer.hide_window()
await ui_test.human_delay(50)
| 3,972 | Python | 56.579709 | 186 | 0.660624 |
omniverse-code/kit/exts/omni.kit.test_suite.context_browser/docs/index.rst | omni.kit.test_suite.context_browser
###################################
viewport tests
.. toctree::
:maxdepth: 1
CHANGELOG
| 132 | reStructuredText | 12.299999 | 35 | 0.515152 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/_scene.pyi | from __future__ import annotations
import omni.ui_scene._scene
import typing
import carb._carb
import omni.ui._ui
__all__ = [
"AbstractContainer",
"AbstractGesture",
"AbstractItem",
"AbstractManipulatorItem",
"AbstractManipulatorModel",
"AbstractShape",
"Arc",
"ArcGesturePayload",
"AspectRatioPolicy",
"CameraModel",
"ClickGesture",
"Color4",
"Cross",
"Culling",
"Curve",
"CurveGesturePayload",
"Dot",
"DoubleClickGesture",
"DragGesture",
"GestureManager",
"GestureState",
"HoverGesture",
"Image",
"Label",
"Line",
"LineGesturePayload",
"Manipulator",
"ManipulatorGesture",
"Matrix44",
"MouseInput",
"Points",
"PointsGesturePayload",
"PolygonMesh",
"PolygonMeshGesturePayload",
"Rectangle",
"RectangleGesturePayload",
"Scene",
"SceneView",
"Screen",
"ScreenGesturePayload",
"ScrollGesture",
"ShapeGesture",
"Space",
"TexturedMesh",
"TexturedMeshGesturePayload",
"Transform",
"TransformBasis",
"Vector2",
"Vector3",
"Vector4",
"Widget"
]
class AbstractContainer(AbstractItem):
"""
Base class for all the items that have children.
"""
def __enter__(self) -> None: ...
def __exit__(self, arg0: object, arg1: object, arg2: object) -> None: ...
def clear(self) -> None:
"""
Removes the container items from the container.
"""
pass
class AbstractGesture():
"""
The base class for the gestures to provides a way to capture mouse events in 3d scene.
"""
class GesturePayload():
@typing.overload
def __init__(self, arg0: object, arg1: object, arg2: float) -> None: ...
@typing.overload
def __init__(self, arg0: AbstractGesture.GesturePayload) -> None: ...
@property
def item_closest_point(self) -> object:
"""
:type: object
"""
@property
def ray_closest_point(self) -> object:
"""
:type: object
"""
@property
def ray_distance(self) -> float:
"""
:type: float
"""
pass
def __repr__(self) -> str: ...
@typing.overload
def get_gesture_payload(self) -> AbstractGesture.GesturePayload:
"""
Shortcut for sender.get_gesturePayload.
OMNIUI_SCENE_API const*
Shortcut for sender.get_gesturePayload.
OMNIUI_SCENE_API const*
"""
@typing.overload
def get_gesture_payload(self, arg0: GestureState) -> AbstractGesture.GesturePayload: ...
def process(self) -> None:
"""
Process the gesture and call callbacks if necessary.
"""
@property
def gesture_payload(self) -> AbstractGesture.GesturePayload:
"""
Shortcut for sender.get_gesturePayload.
OMNIUI_SCENE_API const*
:type: AbstractGesture.GesturePayload
"""
@property
def manager(self) -> GestureManager:
"""
The Manager that controld this gesture.
:type: GestureManager
"""
@manager.setter
def manager(self, arg1: GestureManager) -> None:
"""
The Manager that controld this gesture.
"""
@property
def name(self) -> str:
"""
The name of the object. It's used for debugging.
:type: str
"""
@name.setter
def name(self, arg1: str) -> None:
"""
The name of the object. It's used for debugging.
"""
@property
def state(self) -> GestureState:
"""
Get the internal state of the gesture.
:type: GestureState
"""
@state.setter
def state(self, arg1: GestureState) -> None:
"""
Get the internal state of the gesture.
"""
pass
class AbstractItem():
"""
"""
def compute_visibility(self) -> bool:
"""
Calculate the effective visibility of this prim, as defined by its most ancestral invisible opinion, if any.
"""
def transform_space(self, arg0: Space, arg1: Space, arg2: handle) -> object:
"""
Transform the given point from the coordinate system fromspace to the coordinate system tospace.
"""
@property
def scene_view(self) -> omni::ui::scene::SceneView:
"""
The current SceneView this item is parented to.
:type: omni::ui::scene::SceneView
"""
@property
def visible(self) -> bool:
"""
This property holds whether the item is visible.
:type: bool
"""
@visible.setter
def visible(self, arg1: bool) -> None:
"""
This property holds whether the item is visible.
"""
pass
class AbstractManipulatorItem():
def __init__(self) -> None: ...
pass
class CameraModel(AbstractManipulatorModel):
"""
A model that holds projection and view matrices
"""
def __init__(self, arg0: object, arg1: object) -> None:
"""
Initialize the camera with the given projection/view matrices.
`kwargs : dict`
See below
### Keyword Arguments:
`projection : `
The camera projection matrix.
`view : `
The camera view matrix.
"""
@property
def projection(self) -> Matrix44:
"""
The camera projection matrix.
:type: Matrix44
"""
@projection.setter
def projection(self, arg1: handle) -> None:
"""
The camera projection matrix.
"""
@property
def view(self) -> Matrix44:
"""
The camera projection matrix.
:type: Matrix44
"""
@view.setter
def view(self, arg1: handle) -> None:
"""
The camera projection matrix.
"""
pass
class AbstractManipulatorModel():
"""
Bridge to data.
Operates with double and int arrays.
No strings.
No tree, it's a flat list of items.
Manipulator requires the model has specific items.
"""
def __init__(self) -> None: ...
def _item_changed(self, arg0: handle) -> None: ...
def add_item_changed_fn(self, arg0: typing.Callable[[AbstractManipulatorModel, AbstractManipulatorItem], None]) -> int:
"""
Adds the function that will be called every time the value changes.
The id of the callback that is used to remove the callback.
"""
def get_as_bool(self, arg0: handle) -> bool:
"""
Shortcut for `get_as_ints` that returns the first item of the list.
"""
def get_as_float(self, arg0: handle) -> float:
"""
Shortcut for `get_as_floats` that returns the first item of the list.
"""
def get_as_floats(self, arg0: handle) -> typing.List[float]:
"""
Returns the Float values of the item.
"""
def get_as_int(self, arg0: handle) -> int:
"""
Shortcut for `get_as_ints` that returns the first item of the list.
"""
def get_as_ints(self, arg0: handle) -> typing.List[int]:
"""
Returns the int values of the item.
"""
def get_item(self, arg0: str) -> AbstractManipulatorItem:
"""
Returns the items that represents the identifier.
"""
def remove_item_changed_fn(self, arg0: int) -> None:
"""
Remove the callback by its id.
### Arguments:
`id :`
The id that addValueChangedFn returns.
"""
def set_bool(self, arg0: handle, arg1: bool) -> None:
"""
Shortcut for `set_ints` that sets an array with the size of one.
"""
def set_float(self, arg0: handle, arg1: float) -> None:
"""
Shortcut for `set_floats` that sets an array with the size of one.
"""
def set_floats(self, arg0: handle, arg1: typing.List[float]) -> None:
"""
Sets the Float values of the item.
"""
def set_int(self, arg0: handle, arg1: int) -> None:
"""
Shortcut for `set_ints` that sets an array with the size of one.
"""
def set_ints(self, arg0: handle, arg1: typing.List[int]) -> None:
"""
Sets the int values of the item.
"""
def subscribe_item_changed_fn(self, arg0: typing.Callable[[AbstractManipulatorModel, AbstractManipulatorItem], None]) -> carb._carb.Subscription:
"""
Adds the function that will be called every time the value changes.
The id of the callback that is used to remove the callback.
"""
pass
class Arc(AbstractShape, AbstractItem):
"""
"""
def __init__(self, radius: float, **kwargs) -> None:
"""
Constructs Arc.
`kwargs : dict`
See below
### Keyword Arguments:
`begin : `
The start angle of the arc. Angle placement and directions are (0 to 90): Y to Z, Z to X, X to Y
`end : `
The end angle of the arc. Angle placement and directions are (0 to 90): Y to Z, Z to X, X to Y
`thickness : `
The thickness of the line.
`intersection_thickness : `
The thickness of the line for the intersection.
`color : `
The color of the line.
`tesselation : `
Number of points on the curve.
`axis : `
The axis the circle plane is perpendicular to.
`sector : `
Draw two radii of the circle.
`culling : `
Draw two radii of the circle.
`wireframe : `
When true, it's a line. When false it's a mesh.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
@typing.overload
def get_gesture_payload(self) -> ArcGesturePayload:
"""
Contains all the information about the intersection.
Contains all the information about the intersection at the specific state.
"""
@typing.overload
def get_gesture_payload(self, arg0: GestureState) -> ArcGesturePayload: ...
@property
def axis(self) -> int:
"""
The axis the circle plane is perpendicular to.
:type: int
"""
@axis.setter
def axis(self, arg1: int) -> None:
"""
The axis the circle plane is perpendicular to.
"""
@property
def begin(self) -> float:
"""
The start angle of the arc. Angle placement and directions are (0 to 90): Y to Z, Z to X, X to Y
:type: float
"""
@begin.setter
def begin(self, arg1: float) -> None:
"""
The start angle of the arc. Angle placement and directions are (0 to 90): Y to Z, Z to X, X to Y
"""
@property
def color(self) -> object:
"""
The color of the line.
:type: object
"""
@color.setter
def color(self, arg1: handle) -> None:
"""
The color of the line.
"""
@property
def culling(self) -> Culling:
"""
Draw two radii of the circle.
:type: Culling
"""
@culling.setter
def culling(self, arg1: Culling) -> None:
"""
Draw two radii of the circle.
"""
@property
def end(self) -> float:
"""
The end angle of the arc. Angle placement and directions are (0 to 90): Y to Z, Z to X, X to Y
:type: float
"""
@end.setter
def end(self, arg1: float) -> None:
"""
The end angle of the arc. Angle placement and directions are (0 to 90): Y to Z, Z to X, X to Y
"""
@property
def gesture_payload(self) -> ArcGesturePayload:
"""
Contains all the information about the intersection.
:type: ArcGesturePayload
"""
@property
def intersection_thickness(self) -> float:
"""
The thickness of the line for the intersection.
:type: float
"""
@intersection_thickness.setter
def intersection_thickness(self, arg1: float) -> None:
"""
The thickness of the line for the intersection.
"""
@property
def radius(self) -> float:
"""
:type: float
"""
@radius.setter
def radius(self, arg1: float) -> None:
pass
@property
def sector(self) -> bool:
"""
Draw two radii of the circle.
:type: bool
"""
@sector.setter
def sector(self, arg1: bool) -> None:
"""
Draw two radii of the circle.
"""
@property
def tesselation(self) -> int:
"""
Number of points on the curve.
:type: int
"""
@tesselation.setter
def tesselation(self, arg1: int) -> None:
"""
Number of points on the curve.
"""
@property
def thickness(self) -> float:
"""
The thickness of the line.
:type: float
"""
@thickness.setter
def thickness(self, arg1: float) -> None:
"""
The thickness of the line.
"""
@property
def wireframe(self) -> bool:
"""
When true, it's a line. When false it's a mesh.
:type: bool
"""
@wireframe.setter
def wireframe(self, arg1: bool) -> None:
"""
When true, it's a line. When false it's a mesh.
"""
pass
class AbstractShape(AbstractItem):
"""
Base class for all the items that can be drawn and intersected with mouse pointer.
"""
@typing.overload
def get_gesture_payload(self) -> AbstractGesture.GesturePayload:
"""
Contains all the information about the intersection.
Contains all the information about the intersection at the specific state.
"""
@typing.overload
def get_gesture_payload(self, arg0: GestureState) -> AbstractGesture.GesturePayload: ...
@property
def gesture_payload(self) -> AbstractGesture.GesturePayload:
"""
Contains all the information about the intersection.
:type: AbstractGesture.GesturePayload
"""
@property
def gestures(self) -> typing.List[ShapeGesture]:
"""
All the gestures assigned to this shape.
:type: typing.List[ShapeGesture]
"""
@gestures.setter
def gestures(self, arg1: typing.List[ShapeGesture]) -> None:
"""
All the gestures assigned to this shape.
"""
pass
class ArcGesturePayload(AbstractGesture.GesturePayload):
@property
def angle(self) -> float:
"""
:type: float
"""
@property
def culled(self) -> bool:
"""
:type: bool
"""
@property
def distance_to_center(self) -> float:
"""
:type: float
"""
@property
def moved(self) -> object:
"""
:type: object
"""
@property
def moved_angle(self) -> float:
"""
:type: float
"""
@property
def moved_distance_to_center(self) -> float:
"""
:type: float
"""
pass
class AspectRatioPolicy():
"""
Members:
STRETCH
PRESERVE_ASPECT_FIT
PRESERVE_ASPECT_CROP
PRESERVE_ASPECT_VERTICAL
PRESERVE_ASPECT_HORIZONTAL
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
PRESERVE_ASPECT_CROP: omni.ui_scene._scene.AspectRatioPolicy # value = <AspectRatioPolicy.PRESERVE_ASPECT_CROP: 2>
PRESERVE_ASPECT_FIT: omni.ui_scene._scene.AspectRatioPolicy # value = <AspectRatioPolicy.PRESERVE_ASPECT_FIT: 1>
PRESERVE_ASPECT_HORIZONTAL: omni.ui_scene._scene.AspectRatioPolicy # value = <AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL: 4>
PRESERVE_ASPECT_VERTICAL: omni.ui_scene._scene.AspectRatioPolicy # value = <AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: 3>
STRETCH: omni.ui_scene._scene.AspectRatioPolicy # value = <AspectRatioPolicy.STRETCH: 0>
__members__: dict # value = {'STRETCH': <AspectRatioPolicy.STRETCH: 0>, 'PRESERVE_ASPECT_FIT': <AspectRatioPolicy.PRESERVE_ASPECT_FIT: 1>, 'PRESERVE_ASPECT_CROP': <AspectRatioPolicy.PRESERVE_ASPECT_CROP: 2>, 'PRESERVE_ASPECT_VERTICAL': <AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: 3>, 'PRESERVE_ASPECT_HORIZONTAL': <AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL: 4>}
pass
class ClickGesture(ShapeGesture, AbstractGesture):
"""
The gesture that provides a way to capture click mouse event.
"""
@staticmethod
def __init__(*args, **kwargs) -> typing.Any:
"""
Constructs an gesture to track when the user clicked the mouse.
### Arguments:
`onEnded :`
Function that is called when the user clicked the mouse button.
`kwargs : dict`
See below
### Keyword Arguments:
`mouse_button : `
The mouse button this gesture is watching.
`modifiers : `
The modifier that should be pressed to trigger this gesture.
`on_ended_fn : `
Called when the user releases the button.
`name : `
The name of the object. It's used for debugging.
`manager : `
The Manager that controld this gesture.
"""
def __repr__(self) -> str: ...
@staticmethod
def call_on_ended_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user releases the button.
"""
def has_on_ended_fn(self) -> bool:
"""
Called when the user releases the button.
"""
@staticmethod
def set_on_ended_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user releases the button.
"""
@property
def modifiers(self) -> int:
"""
The modifier that should be pressed to trigger this gesture.
:type: int
"""
@modifiers.setter
def modifiers(self, arg1: int) -> None:
"""
The modifier that should be pressed to trigger this gesture.
"""
@property
def mouse_button(self) -> int:
"""
The mouse button this gesture is watching.
:type: int
"""
@mouse_button.setter
def mouse_button(self, arg1: int) -> None:
"""
The mouse button this gesture is watching.
"""
pass
class Color4():
def __add__(self, arg0: Vector4) -> Vector4: ...
def __eq__(self, arg0: Vector4) -> bool: ...
def __getitem__(self, arg0: int) -> float: ...
@typing.overload
def __init__(self, c: Vector4) -> None: ...
@typing.overload
def __init__(self, r: float = 0.0) -> None: ...
@typing.overload
def __init__(self, r: float, g: float, b: float, a: float) -> None: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: float) -> None: ...
@property
def a(self) -> float:
"""
:type: float
"""
@a.setter
def a(self, arg0: float) -> None:
pass
@property
def b(self) -> float:
"""
:type: float
"""
@b.setter
def b(self, arg0: float) -> None:
pass
@property
def g(self) -> float:
"""
:type: float
"""
@g.setter
def g(self, arg0: float) -> None:
pass
@property
def r(self) -> float:
"""
:type: float
"""
@r.setter
def r(self, arg0: float) -> None:
pass
__hash__ = None
pass
class Culling():
"""
Members:
NONE
BACK
FRONT
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
BACK: omni.ui_scene._scene.Culling # value = <Culling.BACK: 1>
FRONT: omni.ui_scene._scene.Culling # value = <Culling.FRONT: 2>
NONE: omni.ui_scene._scene.Culling # value = <Culling.NONE: 0>
__members__: dict # value = {'NONE': <Culling.NONE: 0>, 'BACK': <Culling.BACK: 1>, 'FRONT': <Culling.FRONT: 2>}
pass
class Curve(AbstractShape, AbstractItem):
"""
Represents the curve.
"""
class CurveType():
"""
Members:
LINEAR
CUBIC
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
CUBIC: omni.ui_scene._scene.Curve.CurveType # value = <CurveType.CUBIC: 1>
LINEAR: omni.ui_scene._scene.Curve.CurveType # value = <CurveType.LINEAR: 0>
__members__: dict # value = {'LINEAR': <CurveType.LINEAR: 0>, 'CUBIC': <CurveType.CUBIC: 1>}
pass
def __init__(self, arg0: object, **kwargs) -> None:
"""
Constructs Curve.
### Arguments:
`positions :`
List of positions
`kwargs : dict`
See below
### Keyword Arguments:
`positions : `
The list of positions which defines the curve. It has at least two positions. The curve has len(positions)-1
`colors : `
The list of colors which defines color per vertex. It has the same length as positions.
`thicknesses : `
The list of thicknesses which defines thickness per vertex. It has the same length as positions.
`intersection_thickness : `
The thickness of the line for the intersection.
`curve_type : `
The curve interpolation type.
`tessellation : `
The number of points per curve segment. It can't be less than 2.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
@typing.overload
def get_gesture_payload(self) -> CurveGesturePayload:
"""
Contains all the information about the intersection.
Contains all the information about the intersection at the specific state.
"""
@typing.overload
def get_gesture_payload(self, arg0: GestureState) -> CurveGesturePayload: ...
@property
def colors(self) -> object:
"""
The list of colors which defines color per vertex. It has the same length as positions.
:type: object
"""
@colors.setter
def colors(self, arg1: handle) -> None:
"""
The list of colors which defines color per vertex. It has the same length as positions.
"""
@property
def curve_type(self) -> Curve.CurveType:
"""
The curve interpolation type.
:type: Curve.CurveType
"""
@curve_type.setter
def curve_type(self, arg1: Curve.CurveType) -> None:
"""
The curve interpolation type.
"""
@property
def gesture_payload(self) -> CurveGesturePayload:
"""
Contains all the information about the intersection.
:type: CurveGesturePayload
"""
@property
def intersection_thicknesses(self) -> float:
"""
The thickness of the line for the intersection.
:type: float
"""
@intersection_thicknesses.setter
def intersection_thicknesses(self, arg1: float) -> None:
"""
The thickness of the line for the intersection.
"""
@property
def positions(self) -> object:
"""
The list of positions which defines the curve. It has at least two positions. The curve has len(positions)-1
:type: object
"""
@positions.setter
def positions(self, arg1: handle) -> None:
"""
The list of positions which defines the curve. It has at least two positions. The curve has len(positions)-1
"""
@property
def tesselation(self) -> int:
"""
The number of points per curve segment. It can't be less than 2.
:type: int
"""
@tesselation.setter
def tesselation(self, arg1: int) -> None:
"""
The number of points per curve segment. It can't be less than 2.
"""
@property
def tessellation(self) -> int:
"""
The number of points per curve segment. It can't be less than 2.
:type: int
"""
@tessellation.setter
def tessellation(self, arg1: int) -> None:
"""
The number of points per curve segment. It can't be less than 2.
"""
@property
def thicknesses(self) -> typing.List[float]:
"""
The list of thicknesses which defines thickness per vertex. It has the same length as positions.
:type: typing.List[float]
"""
@thicknesses.setter
def thicknesses(self, arg1: typing.List[float]) -> None:
"""
The list of thicknesses which defines thickness per vertex. It has the same length as positions.
"""
pass
class CurveGesturePayload(AbstractGesture.GesturePayload):
@property
def curve_distance(self) -> float:
"""
:type: float
"""
@property
def moved(self) -> object:
"""
:type: object
"""
@property
def moved_distance(self) -> float:
"""
:type: float
"""
pass
class DoubleClickGesture(ClickGesture, ShapeGesture, AbstractGesture):
"""
The gesture that provides a way to capture double clicks.
"""
@staticmethod
def __init__(*args, **kwargs) -> typing.Any:
"""
Construct the gesture to track double clicks.
### Arguments:
`onEnded :`
Called when the user double clicked
`kwargs : dict`
See below
### Keyword Arguments:
`mouse_button : `
The mouse button this gesture is watching.
`modifiers : `
The modifier that should be pressed to trigger this gesture.
`on_ended_fn : `
Called when the user releases the button.
`name : `
The name of the object. It's used for debugging.
`manager : `
The Manager that controld this gesture.
"""
def __repr__(self) -> str: ...
@staticmethod
def call_on_ended_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user releases the button.
"""
def has_on_ended_fn(self) -> bool:
"""
Called when the user releases the button.
"""
@staticmethod
def set_on_ended_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user releases the button.
"""
pass
class DragGesture(ShapeGesture, AbstractGesture):
"""
The gesture that provides a way to capture click-and-drag mouse event.
"""
def __init__(self, **kwargs) -> None:
"""
Construct the gesture to track mouse drags.
`kwargs : dict`
See below
### Keyword Arguments:
`mouse_button : `
Mouse button that should be active to start the gesture.
`modifiers : `
The keyboard modifier that should be active ti start the gesture.
`check_mouse_moved : `
The check_mouse_moved property is a boolean flag that determines whether the DragGesture should verify if the 2D screen position of the mouse has changed before invoking the on_changed method. This property is essential in a 3D environment, as changes in the camera position can result in the mouse pointing to different locations in the 3D world even when the 2D screen position remains unchanged.
Usage
When check_mouse_moved is set to True, the DragGesture will only call the on_changed method if the actual 2D screen position of the mouse has changed. This can be useful when you want to ensure that the on_changed method is only triggered when there is a genuine change in the mouse's 2D screen position.
If check_mouse_moved is set to False, the DragGesture will not check for changes in the mouse's 2D screen position before calling the on_changed method. This can be useful when you want the on_changed method to be invoked even if the mouse's 2D screen position hasn't changed, such as when the camera position is altered, and the mouse now points to a different location in the 3D world.
`on_began_fn : `
Called if the callback is not set when the user clicks the mouse button.
`on_changed_fn : `
Called if the callback is not set when the user moves the clicked button.
`on_ended_fn : `
Called if the callback is not set when the user releases the mouse button.
`name : `
The name of the object. It's used for debugging.
`manager : `
The Manager that controld this gesture.
"""
def __repr__(self) -> str: ...
@staticmethod
def call_on_began_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user starts drag.
"""
@staticmethod
def call_on_changed_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user is dragging.
"""
@staticmethod
def call_on_ended_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user releases the mouse and finishes the drag.
"""
def has_on_began_fn(self) -> bool:
"""
Called when the user starts drag.
"""
def has_on_changed_fn(self) -> bool:
"""
Called when the user is dragging.
"""
def has_on_ended_fn(self) -> bool:
"""
Called when the user releases the mouse and finishes the drag.
"""
@staticmethod
def set_on_began_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user starts drag.
"""
@staticmethod
def set_on_changed_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user is dragging.
"""
@staticmethod
def set_on_ended_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user releases the mouse and finishes the drag.
"""
@property
def check_mouse_moved(self) -> bool:
"""
The check_mouse_moved property is a boolean flag that determines whether the DragGesture should verify if the 2D screen position of the mouse has changed before invoking the on_changed method. This property is essential in a 3D environment, as changes in the camera position can result in the mouse pointing to different locations in the 3D world even when the 2D screen position remains unchanged.
Usage
When check_mouse_moved is set to True, the DragGesture will only call the on_changed method if the actual 2D screen position of the mouse has changed. This can be useful when you want to ensure that the on_changed method is only triggered when there is a genuine change in the mouse's 2D screen position.
If check_mouse_moved is set to False, the DragGesture will not check for changes in the mouse's 2D screen position before calling the on_changed method. This can be useful when you want the on_changed method to be invoked even if the mouse's 2D screen position hasn't changed, such as when the camera position is altered, and the mouse now points to a different location in the 3D world.
:type: bool
"""
@check_mouse_moved.setter
def check_mouse_moved(self, arg1: bool) -> None:
"""
The check_mouse_moved property is a boolean flag that determines whether the DragGesture should verify if the 2D screen position of the mouse has changed before invoking the on_changed method. This property is essential in a 3D environment, as changes in the camera position can result in the mouse pointing to different locations in the 3D world even when the 2D screen position remains unchanged.
Usage
When check_mouse_moved is set to True, the DragGesture will only call the on_changed method if the actual 2D screen position of the mouse has changed. This can be useful when you want to ensure that the on_changed method is only triggered when there is a genuine change in the mouse's 2D screen position.
If check_mouse_moved is set to False, the DragGesture will not check for changes in the mouse's 2D screen position before calling the on_changed method. This can be useful when you want the on_changed method to be invoked even if the mouse's 2D screen position hasn't changed, such as when the camera position is altered, and the mouse now points to a different location in the 3D world.
"""
@property
def modifiers(self) -> int:
"""
The keyboard modifier that should be active ti start the gesture.
:type: int
"""
@modifiers.setter
def modifiers(self, arg1: int) -> None:
"""
The keyboard modifier that should be active ti start the gesture.
"""
@property
def mouse_button(self) -> int:
"""
Mouse button that should be active to start the gesture.
:type: int
"""
@mouse_button.setter
def mouse_button(self, arg1: int) -> None:
"""
Mouse button that should be active to start the gesture.
"""
pass
class GestureManager():
"""
The object that controls batch processing and preventing of gestures. Typically each scene has a default manager and if the user wants to have own prevention logic, he can reimplement it.
"""
def __init__(self, **kwargs) -> None:
"""
Constructor.
`kwargs : dict`
See below
### Keyword Arguments:
"""
@staticmethod
def amend_input(*args, **kwargs) -> typing.Any:
"""
Called once a frame. Should be overriden to inject own input to the gestures.
"""
def can_be_prevented(self, arg0: AbstractGesture) -> bool:
"""
Called per gesture. Determines if the gesture can be prevented.
"""
def should_prevent(self, arg0: AbstractGesture, arg1: AbstractGesture) -> bool:
"""
Called per gesture. Determines if the gesture should be prevented with another gesture. Useful to resolve intersections.
"""
pass
class GestureState():
"""
Members:
NONE
POSSIBLE
BEGAN
CHANGED
ENDED
CANCELED
PREVENTED
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
BEGAN: omni.ui_scene._scene.GestureState # value = <GestureState.BEGAN: 2>
CANCELED: omni.ui_scene._scene.GestureState # value = <GestureState.CANCELED: 5>
CHANGED: omni.ui_scene._scene.GestureState # value = <GestureState.CHANGED: 3>
ENDED: omni.ui_scene._scene.GestureState # value = <GestureState.ENDED: 4>
NONE: omni.ui_scene._scene.GestureState # value = <GestureState.NONE: 0>
POSSIBLE: omni.ui_scene._scene.GestureState # value = <GestureState.POSSIBLE: 1>
PREVENTED: omni.ui_scene._scene.GestureState # value = <GestureState.PREVENTED: 6>
__members__: dict # value = {'NONE': <GestureState.NONE: 0>, 'POSSIBLE': <GestureState.POSSIBLE: 1>, 'BEGAN': <GestureState.BEGAN: 2>, 'CHANGED': <GestureState.CHANGED: 3>, 'ENDED': <GestureState.ENDED: 4>, 'CANCELED': <GestureState.CANCELED: 5>, 'PREVENTED': <GestureState.PREVENTED: 6>}
pass
class HoverGesture(ShapeGesture, AbstractGesture):
"""
The gesture that provides a way to capture event when mouse enters/leaves the item.
"""
def __init__(self, **kwargs) -> None:
"""
Constructs an gesture to track when the user clicked the mouse.
### Arguments:
`onEnded :`
Function that is called when the user clicked the mouse button.
`kwargs : dict`
See below
### Keyword Arguments:
`mouse_button : `
The mouse button this gesture is watching.
`modifiers : `
The modifier that should be pressed to trigger this gesture.
`trigger_on_view_hover : `
Determines whether the gesture is triggered only when the SceneView is being hovered by the mouse.
`on_began_fn : `
Called if the callback is not set and the mouse enters the item.
`on_changed_fn : `
Called if the callback is not set and the mouse is hovering the item.
`on_ended_fn : `
Called if the callback is not set and the mouse leaves the item.
`name : `
The name of the object. It's used for debugging.
`manager : `
The Manager that controld this gesture.
"""
def __repr__(self) -> str: ...
@staticmethod
def call_on_began_fn(*args, **kwargs) -> typing.Any:
"""
Called when the mouse enters the item.
"""
@staticmethod
def call_on_changed_fn(*args, **kwargs) -> typing.Any:
"""
Called when the mouse is hovering the item.
"""
@staticmethod
def call_on_ended_fn(*args, **kwargs) -> typing.Any:
"""
Called when the mouse leaves the item.
"""
def has_on_began_fn(self) -> bool:
"""
Called when the mouse enters the item.
"""
def has_on_changed_fn(self) -> bool:
"""
Called when the mouse is hovering the item.
"""
def has_on_ended_fn(self) -> bool:
"""
Called when the mouse leaves the item.
"""
@staticmethod
def set_on_began_fn(*args, **kwargs) -> typing.Any:
"""
Called when the mouse enters the item.
"""
@staticmethod
def set_on_changed_fn(*args, **kwargs) -> typing.Any:
"""
Called when the mouse is hovering the item.
"""
@staticmethod
def set_on_ended_fn(*args, **kwargs) -> typing.Any:
"""
Called when the mouse leaves the item.
"""
@property
def modifiers(self) -> int:
"""
The modifier that should be pressed to trigger this gesture.
:type: int
"""
@modifiers.setter
def modifiers(self, arg1: int) -> None:
"""
The modifier that should be pressed to trigger this gesture.
"""
@property
def mouse_button(self) -> int:
"""
The mouse button this gesture is watching.
:type: int
"""
@mouse_button.setter
def mouse_button(self, arg1: int) -> None:
"""
The mouse button this gesture is watching.
"""
@property
def trigger_on_view_hover(self) -> bool:
"""
Determines whether the gesture is triggered only when the SceneView is being hovered by the mouse.
:type: bool
"""
@trigger_on_view_hover.setter
def trigger_on_view_hover(self, arg1: bool) -> None:
"""
Determines whether the gesture is triggered only when the SceneView is being hovered by the mouse.
"""
pass
class Image(Rectangle, AbstractShape, AbstractItem):
"""
"""
class FillPolicy():
"""
Members:
STRETCH
PRESERVE_ASPECT_FIT
PRESERVE_ASPECT_CROP
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
PRESERVE_ASPECT_CROP: omni.ui_scene._scene.Image.FillPolicy # value = <FillPolicy.PRESERVE_ASPECT_CROP: 2>
PRESERVE_ASPECT_FIT: omni.ui_scene._scene.Image.FillPolicy # value = <FillPolicy.PRESERVE_ASPECT_FIT: 1>
STRETCH: omni.ui_scene._scene.Image.FillPolicy # value = <FillPolicy.STRETCH: 0>
__members__: dict # value = {'STRETCH': <FillPolicy.STRETCH: 0>, 'PRESERVE_ASPECT_FIT': <FillPolicy.PRESERVE_ASPECT_FIT: 1>, 'PRESERVE_ASPECT_CROP': <FillPolicy.PRESERVE_ASPECT_CROP: 2>}
pass
@typing.overload
def __init__(self, source_url: str, width: float = 1.0, height: float = 1.0, **kwargs) -> None:
"""
Created an image with the given URL.
`kwargs : dict`
See below
### Keyword Arguments:
`source_url : `
This property holds the image URL. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
`image_provider : `
This property holds the image provider. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
`fill_policy : `
Define what happens when the source image has a different size than the item.
`image_width : `
The resolution for rasterization of svg and for ImageProvider.
`image_height : `
The resolution of rasterization of svg and for ImageProvider.
`width : `
The size of the rectangle.
`height : `
The size of the rectangle.
`thickness : `
The thickness of the line.
`intersection_thickness : `
The thickness of the line for the intersection.
`color : `
The color of the line.
`axis : `
The axis the rectangle is perpendicular to.
`wireframe : `
When true, it's a line. When false it's a mesh.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
Created an image with the given provider.
`kwargs : dict`
See below
### Keyword Arguments:
`source_url : `
This property holds the image URL. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
`image_provider : `
This property holds the image provider. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
`fill_policy : `
Define what happens when the source image has a different size than the item.
`image_width : `
The resolution for rasterization of svg and for ImageProvider.
`image_height : `
The resolution of rasterization of svg and for ImageProvider.
`width : `
The size of the rectangle.
`height : `
The size of the rectangle.
`thickness : `
The thickness of the line.
`intersection_thickness : `
The thickness of the line for the intersection.
`color : `
The color of the line.
`axis : `
The axis the rectangle is perpendicular to.
`wireframe : `
When true, it's a line. When false it's a mesh.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
Created an empty image.
`kwargs : dict`
See below
### Keyword Arguments:
`source_url : `
This property holds the image URL. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
`image_provider : `
This property holds the image provider. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
`fill_policy : `
Define what happens when the source image has a different size than the item.
`image_width : `
The resolution for rasterization of svg and for ImageProvider.
`image_height : `
The resolution of rasterization of svg and for ImageProvider.
`width : `
The size of the rectangle.
`height : `
The size of the rectangle.
`thickness : `
The thickness of the line.
`intersection_thickness : `
The thickness of the line for the intersection.
`color : `
The color of the line.
`axis : `
The axis the rectangle is perpendicular to.
`wireframe : `
When true, it's a line. When false it's a mesh.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
@typing.overload
def __init__(self, image_provider: ImageProvider, width: float = 1.0, height: float = 1.0, **kwargs) -> None: ...
@typing.overload
def __init__(self, width: float = 1.0, height: float = 1.0, **kwargs) -> None: ...
@property
def fill_policy(self) -> Image.FillPolicy:
"""
Define what happens when the source image has a different size than the item.
:type: Image.FillPolicy
"""
@fill_policy.setter
def fill_policy(self, arg1: Image.FillPolicy) -> None:
"""
Define what happens when the source image has a different size than the item.
"""
@property
def image_height(self) -> int:
"""
The resolution of rasterization of svg and for ImageProvider.
:type: int
"""
@image_height.setter
def image_height(self, arg1: int) -> None:
"""
The resolution of rasterization of svg and for ImageProvider.
"""
@property
def image_provider(self) -> ImageProvider:
"""
This property holds the image provider. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
:type: ImageProvider
"""
@image_provider.setter
def image_provider(self, arg1: ImageProvider) -> None:
"""
This property holds the image provider. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
"""
@property
def image_width(self) -> int:
"""
The resolution for rasterization of svg and for ImageProvider.
:type: int
"""
@image_width.setter
def image_width(self, arg1: int) -> None:
"""
The resolution for rasterization of svg and for ImageProvider.
"""
@property
def source_url(self) -> str:
"""
This property holds the image URL. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
:type: str
"""
@source_url.setter
def source_url(self, arg1: str) -> None:
"""
This property holds the image URL. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
"""
pass
class Label(AbstractShape, AbstractItem):
"""
Defines a standard label for user interface items
"""
def __init__(self, arg0: str, **kwargs) -> None:
"""
A standard label for user interface items.
### Arguments:
`text :`
The string with the text to display
`kwargs : dict`
See below
### Keyword Arguments:
`color : `
The color of the text.
`size : `
The font size.
`alignment : `
This property holds the alignment of the label's contents. By default, the contents of the label are left-aligned and vertically-centered.
`text : `
This property holds the label's text.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
@property
def alignment(self) -> omni.ui._ui.Alignment:
"""
This property holds the alignment of the label's contents. By default, the contents of the label are left-aligned and vertically-centered.
:type: omni.ui._ui.Alignment
"""
@alignment.setter
def alignment(self, arg1: omni.ui._ui.Alignment) -> None:
"""
This property holds the alignment of the label's contents. By default, the contents of the label are left-aligned and vertically-centered.
"""
@property
def color(self) -> object:
"""
The color of the text.
:type: object
"""
@color.setter
def color(self, arg1: handle) -> None:
"""
The color of the text.
"""
@property
def size(self) -> float:
"""
The font size.
:type: float
"""
@size.setter
def size(self, arg1: float) -> None:
"""
The font size.
"""
@property
def text(self) -> str:
"""
This property holds the label's text.
:type: str
"""
@text.setter
def text(self, arg1: str) -> None:
"""
This property holds the label's text.
"""
pass
class Line(AbstractShape, AbstractItem):
"""
"""
@typing.overload
def __init__(self, **kwargs) -> None:
"""
A simple line.
### Arguments:
`start :`
The start point of the line
`end :`
The end point of the line
`kwargs : dict`
See below
### Keyword Arguments:
`start : `
The start point of the line.
`end : `
The end point of the line.
`color : `
The line color.
`thickness : `
The line thickness.
`intersection_thickness : `
The thickness of the line for the intersection.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
A simple line.
### Arguments:
`start :`
The start point of the line
`end :`
The end point of the line
`kwargs : dict`
See below
### Keyword Arguments:
`start : `
The start point of the line.
`end : `
The end point of the line.
`color : `
The line color.
`thickness : `
The line thickness.
`intersection_thickness : `
The thickness of the line for the intersection.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
@typing.overload
def __init__(self, arg0: object, arg1: object, **kwargs) -> None: ...
@typing.overload
def get_gesture_payload(self) -> LineGesturePayload:
"""
Contains all the information about the intersection.
Contains all the information about the intersection at the specific state.
"""
@typing.overload
def get_gesture_payload(self, arg0: GestureState) -> LineGesturePayload: ...
@property
def color(self) -> object:
"""
The line color.
:type: object
"""
@color.setter
def color(self, arg1: handle) -> None:
"""
The line color.
"""
@property
def end(self) -> object:
"""
The end point of the line.
:type: object
"""
@end.setter
def end(self, arg1: handle) -> None:
"""
The end point of the line.
"""
@property
def gesture_payload(self) -> LineGesturePayload:
"""
Contains all the information about the intersection.
:type: LineGesturePayload
"""
@property
def intersection_thickness(self) -> float:
"""
The thickness of the line for the intersection.
:type: float
"""
@intersection_thickness.setter
def intersection_thickness(self, arg1: float) -> None:
"""
The thickness of the line for the intersection.
"""
@property
def start(self) -> object:
"""
The start point of the line.
:type: object
"""
@start.setter
def start(self, arg1: handle) -> None:
"""
The start point of the line.
"""
@property
def thickness(self) -> float:
"""
The line thickness.
:type: float
"""
@thickness.setter
def thickness(self, arg1: float) -> None:
"""
The line thickness.
"""
pass
class LineGesturePayload(AbstractGesture.GesturePayload):
@property
def line_closest_point(self) -> object:
"""
:type: object
"""
@property
def line_distance(self) -> float:
"""
:type: float
"""
@property
def moved(self) -> object:
"""
:type: object
"""
pass
class Manipulator(AbstractContainer, AbstractItem):
"""
The base object for the custom manipulators.
"""
def __init__(self, **kwargs) -> None: ...
def _process_gesture(self, arg0: object, arg1: GestureState, arg2: AbstractGesture.GesturePayload) -> None:
"""
Process the ManipulatorGestures that can be casted to the given type
"""
def call_on_build_fn(self, arg0: Manipulator) -> None:
"""
Called when Manipulator is dirty to build the content. It's another way to build the manipulator's content on the case the user doesn't want to reimplement the class.
"""
def has_on_build_fn(self) -> bool:
"""
Called when Manipulator is dirty to build the content. It's another way to build the manipulator's content on the case the user doesn't want to reimplement the class.
"""
def invalidate(self) -> None:
"""
Make Manipulator dirty so onBuild will be executed in _preDrawContent.
"""
def on_build(self) -> None:
"""
Called when Manipulator is dirty to build the content. It's another way to build the manipulator's content on the case the user doesn't want to reimplement the class.
"""
@staticmethod
def on_model_updated(*args, **kwargs) -> typing.Any:
"""
Called by the model when the model value is changed. The class should react to the changes.
### Arguments:
`item :`
The item in the model that is changed. If it's NULL, the root is changed.
"""
def set_on_build_fn(self, fn: typing.Callable[[Manipulator], None]) -> None:
"""
Called when Manipulator is dirty to build the content. It's another way to build the manipulator's content on the case the user doesn't want to reimplement the class.
"""
@property
def gestures(self) -> typing.List[ManipulatorGesture]:
"""
All the gestures assigned to this manipulator.
:type: typing.List[ManipulatorGesture]
"""
@gestures.setter
def gestures(self, arg1: typing.List[ManipulatorGesture]) -> None:
"""
All the gestures assigned to this manipulator.
"""
@property
def model(self) -> AbstractManipulatorModel:
"""
Returns the current model.
:type: AbstractManipulatorModel
"""
@model.setter
def model(self, arg1: AbstractManipulatorModel) -> None:
"""
Returns the current model.
"""
pass
class ManipulatorGesture(AbstractGesture):
"""
The base class for the gestures to provides a way to capture events of the manipulator objects.
"""
def __init__(self, **kwargs) -> None: ...
def __repr__(self) -> str: ...
@property
def sender(self) -> omni::ui::scene::Manipulator:
"""
Returns the relevant shape driving the gesture.
:type: omni::ui::scene::Manipulator
"""
pass
class Matrix44():
"""
Stores a 4x4 matrix of float elements. A basic type.
Matrices are defined to be in row-major order.
The matrix mode is required to define the matrix that resets the transformation to fit the geometry into NDC, Screen space, or rotate it to the camera direction.
"""
def __eq__(self, arg0: Matrix44) -> bool: ...
def __getitem__(self, arg0: int) -> float: ...
@typing.overload
def __init__(self, m: Matrix44) -> None: ...
@typing.overload
def __init__(self, x: float = 1.0) -> None: ...
@typing.overload
def __init__(self, a1: float, a2: float, a3: float, a4: float, a5: float, a6: float, a7: float, a8: float, a9: float, a10: float, a11: float, a12: float, a13: float, a14: float, a15: float, a16: float) -> None: ...
@typing.overload
def __mul__(self, arg0: Matrix44) -> Matrix44: ...
@staticmethod
@typing.overload
def __mul__(*args, **kwargs) -> typing.Any: ...
def __ne__(self, arg0: Matrix44) -> bool: ...
def __repr__(self) -> str: ...
def __rmul__(self, arg0: Matrix44) -> Matrix44: ...
def __setitem__(self, arg0: int, arg1: float) -> None: ...
def get_inverse(self) -> Matrix44: ...
@staticmethod
def get_rotation_matrix(x: float, y: float, z: float, degrees: bool = False) -> Matrix44:
"""
Creates a matrix to specify a rotation around each axis.
### Arguments:
`degrees :`
true if the angles are specified in degrees
"""
@staticmethod
def get_scale_matrix(x: float, y: float, z: float) -> Matrix44:
"""
Creates a matrix to specify a scaling with the given scale factor per axis.
"""
@staticmethod
def get_translation_matrix(x: float, y: float, z: float) -> Matrix44:
"""
Creates a matrix to specify a translation at the given coordinates.
"""
def set_look_at_view(self, arg0: Matrix44) -> Matrix44: ...
@property
def inversed(self) -> Matrix44:
"""
:type: Matrix44
"""
__hash__ = None
pass
class MouseInput():
def __init__(self) -> None: ...
@property
def clicked(self) -> int:
"""
:type: int
"""
@clicked.setter
def clicked(self, arg0: int) -> None:
pass
@property
def double_clicked(self) -> int:
"""
:type: int
"""
@double_clicked.setter
def double_clicked(self, arg0: int) -> None:
pass
@property
def down(self) -> int:
"""
:type: int
"""
@down.setter
def down(self, arg0: int) -> None:
pass
@property
def modifiers(self) -> int:
"""
:type: int
"""
@modifiers.setter
def modifiers(self, arg0: int) -> None:
pass
@property
def mouse(self) -> Vector2:
"""
:type: Vector2
"""
@mouse.setter
def mouse(self, arg0: Vector2) -> None:
pass
@property
def mouse_direction(self) -> Vector3:
"""
:type: Vector3
"""
@mouse_direction.setter
def mouse_direction(self, arg0: Vector3) -> None:
pass
@property
def mouse_origin(self) -> Vector3:
"""
:type: Vector3
"""
@mouse_origin.setter
def mouse_origin(self, arg0: Vector3) -> None:
pass
@property
def mouse_wheel(self) -> Vector2:
"""
:type: Vector2
"""
@mouse_wheel.setter
def mouse_wheel(self, arg0: Vector2) -> None:
pass
@property
def released(self) -> int:
"""
:type: int
"""
@released.setter
def released(self, arg0: int) -> None:
pass
pass
class Points(AbstractShape, AbstractItem):
"""
Represents the point cloud.
"""
def __init__(self, arg0: object, **kwargs) -> None:
"""
Constructs the point cloud object.
### Arguments:
`positions :`
List of positions
`kwargs : dict`
See below
### Keyword Arguments:
`positions : `
List with positions of the points.
`colors : `
List of colors of the points.
`sizes : `
List of point sizes.
`intersection_sizes : `
The size of the points for the intersection.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
@typing.overload
def get_gesture_payload(self) -> PointsGesturePayload:
"""
Contains all the information about the intersection.
Contains all the information about the intersection at the specific state.
"""
@typing.overload
def get_gesture_payload(self, arg0: GestureState) -> PointsGesturePayload: ...
@property
def colors(self) -> object:
"""
List of colors of the points.
:type: object
"""
@colors.setter
def colors(self, arg1: handle) -> None:
"""
List of colors of the points.
"""
@property
def gesture_payload(self) -> PointsGesturePayload:
"""
Contains all the information about the intersection.
:type: PointsGesturePayload
"""
@property
def intersection_sizes(self) -> float:
"""
The size of the points for the intersection.
:type: float
"""
@intersection_sizes.setter
def intersection_sizes(self, arg1: float) -> None:
"""
The size of the points for the intersection.
"""
@property
def positions(self) -> object:
"""
List with positions of the points.
:type: object
"""
@positions.setter
def positions(self, arg1: handle) -> None:
"""
List with positions of the points.
"""
@property
def sizes(self) -> typing.List[float]:
"""
List of point sizes.
:type: typing.List[float]
"""
@sizes.setter
def sizes(self, arg1: typing.List[float]) -> None:
"""
List of point sizes.
"""
pass
class PointsGesturePayload(AbstractGesture.GesturePayload):
@property
def closest_point(self) -> int:
"""
:type: int
"""
@property
def distance_to_point(self) -> float:
"""
:type: float
"""
@property
def moved(self) -> object:
"""
:type: object
"""
pass
class PolygonMesh(AbstractShape, AbstractItem):
"""
Encodes a mesh.
"""
def __init__(self, positions: object, colors: object, vertex_counts: typing.List[int], vertex_indices: typing.List[int], **kwargs) -> None:
"""
Construct a mesh with predefined properties.
### Arguments:
`positions :`
Describes points in local space.
`colors :`
Describes colors per vertex.
`vertexCounts :`
The number of vertices in each face.
`vertexIndices :`
The list of the index of each vertex of each face in the mesh.
`kwargs : dict`
See below
### Keyword Arguments:
`positions : `
The primary geometry attribute, describes points in local space.
`colors : `
Describes colors per vertex.
`vertex_counts : `
Provides the number of vertices in each face of the mesh, which is also the number of consecutive indices in vertex_indices that define the face. The length of this attribute is the number of faces in the mesh.
`vertex_indices : `
Flat list of the index (into the points attribute) of each vertex of each face in the mesh.
`thicknesses : `
When wireframe is true, it defines the thicknesses of lines.
`intersection_thickness : `
The thickness of the line for the intersection.
`wireframe: `
When true, the mesh is drawn as lines.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
@typing.overload
def get_gesture_payload(self) -> PolygonMeshGesturePayload:
"""
Contains all the information about the intersection.
Contains all the information about the intersection at the specific state.
"""
@typing.overload
def get_gesture_payload(self, arg0: GestureState) -> PolygonMeshGesturePayload: ...
@property
def colors(self) -> object:
"""
Describes colors per vertex.
:type: object
"""
@colors.setter
def colors(self, arg1: handle) -> None:
"""
Describes colors per vertex.
"""
@property
def gesture_payload(self) -> PolygonMeshGesturePayload:
"""
Contains all the information about the intersection.
:type: PolygonMeshGesturePayload
"""
@property
def intersection_thicknesses(self) -> float:
"""
The thickness of the line for the intersection.
:type: float
"""
@intersection_thicknesses.setter
def intersection_thicknesses(self, arg1: float) -> None:
"""
The thickness of the line for the intersection.
"""
@property
def positions(self) -> object:
"""
The primary geometry attribute, describes points in local space.
:type: object
"""
@positions.setter
def positions(self, arg1: handle) -> None:
"""
The primary geometry attribute, describes points in local space.
"""
@property
def thicknesses(self) -> typing.List[float]:
"""
When wireframe is true, it defines the thicknesses of lines.
:type: typing.List[float]
"""
@thicknesses.setter
def thicknesses(self, arg1: typing.List[float]) -> None:
"""
When wireframe is true, it defines the thicknesses of lines.
"""
@property
def vertex_counts(self) -> typing.List[int]:
"""
Provides the number of vertices in each face of the mesh, which is also the number of consecutive indices in vertex_indices that define the face. The length of this attribute is the number of faces in the mesh.
:type: typing.List[int]
"""
@vertex_counts.setter
def vertex_counts(self, arg1: typing.List[int]) -> None:
"""
Provides the number of vertices in each face of the mesh, which is also the number of consecutive indices in vertex_indices that define the face. The length of this attribute is the number of faces in the mesh.
"""
@property
def vertex_indices(self) -> typing.List[int]:
"""
Flat list of the index (into the points attribute) of each vertex of each face in the mesh.
:type: typing.List[int]
"""
@vertex_indices.setter
def vertex_indices(self, arg1: typing.List[int]) -> None:
"""
Flat list of the index (into the points attribute) of each vertex of each face in the mesh.
"""
@property
def wireframe(self) -> bool:
"""
When true, the mesh is drawn as lines.
:type: bool
"""
@wireframe.setter
def wireframe(self, arg1: bool) -> None:
"""
When true, the mesh is drawn as lines.
"""
pass
class PolygonMeshGesturePayload(AbstractGesture.GesturePayload):
@property
def face_id(self) -> int:
"""
:type: int
"""
@property
def s(self) -> float:
"""
:type: float
"""
@property
def t(self) -> float:
"""
:type: float
"""
pass
class Rectangle(AbstractShape, AbstractItem):
"""
"""
def __init__(self, width: float = 1.0, height: float = 1.0, **kwargs) -> None:
"""
Construct a rectangle with predefined size.
### Arguments:
`width :`
The size of the rectangle
`height :`
The size of the rectangle
`kwargs : dict`
See below
### Keyword Arguments:
`width : `
The size of the rectangle.
`height : `
The size of the rectangle.
`thickness : `
The thickness of the line.
`intersection_thickness : `
The thickness of the line for the intersection.
`color : `
The color of the line.
`axis : `
The axis the rectangle is perpendicular to.
`wireframe : `
When true, it's a line. When false it's a mesh.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
@typing.overload
def get_gesture_payload(self) -> RectangleGesturePayload:
"""
Contains all the information about the intersection.
Contains all the information about the intersection at the specific state.
"""
@typing.overload
def get_gesture_payload(self, arg0: GestureState) -> RectangleGesturePayload: ...
@property
def axis(self) -> int:
"""
The axis the rectangle is perpendicular to.
:type: int
"""
@axis.setter
def axis(self, arg1: int) -> None:
"""
The axis the rectangle is perpendicular to.
"""
@property
def color(self) -> object:
"""
The color of the line.
:type: object
"""
@color.setter
def color(self, arg1: handle) -> None:
"""
The color of the line.
"""
@property
def gesture_payload(self) -> RectangleGesturePayload:
"""
Contains all the information about the intersection.
:type: RectangleGesturePayload
"""
@property
def height(self) -> float:
"""
The size of the rectangle.
:type: float
"""
@height.setter
def height(self, arg1: float) -> None:
"""
The size of the rectangle.
"""
@property
def intersection_thickness(self) -> float:
"""
The thickness of the line for the intersection.
:type: float
"""
@intersection_thickness.setter
def intersection_thickness(self, arg1: float) -> None:
"""
The thickness of the line for the intersection.
"""
@property
def thickness(self) -> float:
"""
The thickness of the line.
:type: float
"""
@thickness.setter
def thickness(self, arg1: float) -> None:
"""
The thickness of the line.
"""
@property
def width(self) -> float:
"""
The size of the rectangle.
:type: float
"""
@width.setter
def width(self, arg1: float) -> None:
"""
The size of the rectangle.
"""
@property
def wireframe(self) -> bool:
"""
When true, it's a line. When false it's a mesh.
:type: bool
"""
@wireframe.setter
def wireframe(self, arg1: bool) -> None:
"""
When true, it's a line. When false it's a mesh.
"""
pass
class RectangleGesturePayload(AbstractGesture.GesturePayload):
@property
def moved(self) -> object:
"""
:type: object
"""
@property
def moved_s(self) -> float:
"""
:type: float
"""
@property
def moved_t(self) -> float:
"""
:type: float
"""
@property
def s(self) -> float:
"""
:type: float
"""
@property
def t(self) -> float:
"""
:type: float
"""
pass
class Scene(AbstractContainer, AbstractItem):
"""
Top level module string
Represents the root of the scene and holds the shapes, gestures and managers.
"""
def __init__(self, **kwargs) -> None:
"""
Constructor
`kwargs : dict`
See below
### Keyword Arguments:
`visible : `
This property holds whether the item is visible.
"""
@property
def draw_list_buffer_count(self) -> int:
"""
Return the number of buffers used. Using for unit testing.
:type: int
"""
pass
class SceneView(omni.ui._ui.Widget):
"""
The widget to render omni.ui.scene.
"""
def __init__(self, model: AbstractManipulatorModel = None, **kwargs) -> None:
"""
Constructor.
`kwargs : dict`
See below
### Keyword Arguments:
`aspect_ratio_policy : `
Define what happens when the aspect ratio of the camera is different from the aspect ratio of the widget.
`model : `
The camera view matrix. It's a shortcut for Matrix44(SceneView.model.get_as_floats("view"))
`screen_aspect_ratio : `
Aspect ratio of the rendering screen. This screen will be fit to the widget. SceneView simulates the behavior of the Kit viewport where the rendered image (screen) fits into the viewport (widget), and the camera has multiple policies that modify the camera projection matrix's aspect ratio to match it to the screen aspect ratio. When screen_aspect_ratio is 0, Screen size matches the Widget bounds.
`child_windows_input : `
When it's false, the mouse events from other widgets inside the bounds are ignored. We need it to filter out mouse events from mouse events of widgets in `ui.VStack(content_clipping=1)`.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
def get_ray_from_ndc(self, ndc: Vector2) -> typing.Tuple[Vector3, Vector3]:
"""
Convert NDC 2D [-1..1] coordinates to 3D ray.
"""
@property
def aspect_ratio_policy(self) -> AspectRatioPolicy:
"""
Define what happens when the aspect ratio of the camera is different from the aspect ratio of the widget.
:type: AspectRatioPolicy
"""
@aspect_ratio_policy.setter
def aspect_ratio_policy(self, arg1: AspectRatioPolicy) -> None:
"""
Define what happens when the aspect ratio of the camera is different from the aspect ratio of the widget.
"""
@property
def child_windows_input(self) -> bool:
"""
When it's false, the mouse events from other widgets inside the bounds are ignored. We need it to filter out mouse events from mouse events of widgets in `ui.VStack(content_clipping=1)`.
:type: bool
"""
@child_windows_input.setter
def child_windows_input(self, arg1: bool) -> None:
"""
When it's false, the mouse events from other widgets inside the bounds are ignored. We need it to filter out mouse events from mouse events of widgets in `ui.VStack(content_clipping=1)`.
"""
@property
def model(self) -> AbstractManipulatorModel:
"""
Returns the current model.
:type: AbstractManipulatorModel
"""
@model.setter
def model(self, arg1: AbstractManipulatorModel) -> None:
"""
Returns the current model.
"""
@property
def projection(self) -> Matrix44:
"""
The camera projection matrix. It's a shortcut for Matrix44(SceneView.model.get_as_floats("projection"))
:type: Matrix44
"""
@projection.setter
def projection(self, arg1: handle) -> None:
"""
The camera projection matrix. It's a shortcut for Matrix44(SceneView.model.get_as_floats("projection"))
"""
@property
def scene(self) -> Scene:
"""
The container that holds the shapes, gestures and managers.
:type: Scene
"""
@scene.setter
def scene(self, arg1: Scene) -> None:
"""
The container that holds the shapes, gestures and managers.
"""
@property
def screen_aspect_ratio(self) -> float:
"""
Aspect ratio of the rendering screen. This screen will be fit to the widget. SceneView simulates the behavior of the Kit viewport where the rendered image (screen) fits into the viewport (widget), and the camera has multiple policies that modify the camera projection matrix's aspect ratio to match it to the screen aspect ratio. When screen_aspect_ratio is 0, Screen size matches the Widget bounds.
:type: float
"""
@screen_aspect_ratio.setter
def screen_aspect_ratio(self, arg1: float) -> None:
"""
Aspect ratio of the rendering screen. This screen will be fit to the widget. SceneView simulates the behavior of the Kit viewport where the rendered image (screen) fits into the viewport (widget), and the camera has multiple policies that modify the camera projection matrix's aspect ratio to match it to the screen aspect ratio. When screen_aspect_ratio is 0, Screen size matches the Widget bounds.
"""
@property
def view(self) -> Matrix44:
"""
The camera view matrix. It's a shortcut for Matrix44(SceneView.model.get_as_floats("view"))
:type: Matrix44
"""
@view.setter
def view(self, arg1: handle) -> None:
"""
The camera view matrix. It's a shortcut for Matrix44(SceneView.model.get_as_floats("view"))
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Screen(AbstractShape, AbstractItem):
"""
The empty shape that triggers all the gestures at any place. Is used to track gestures when the user clicked the empty space. For example for cameras.
"""
def __init__(self, **kwargs) -> None:
"""
Constructor.
`kwargs : dict`
See below
### Keyword Arguments:
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
@typing.overload
def get_gesture_payload(self) -> ScreenGesturePayload:
"""
Contains all the information about the intersection.
Contains all the information about the intersection at the specific state.
"""
@typing.overload
def get_gesture_payload(self, arg0: GestureState) -> ScreenGesturePayload: ...
@property
def gesture_payload(self) -> ScreenGesturePayload:
"""
Contains all the information about the intersection.
:type: ScreenGesturePayload
"""
pass
class ScreenGesturePayload(AbstractGesture.GesturePayload):
@property
def direction(self) -> object:
"""
:type: object
"""
@property
def mouse(self) -> object:
"""
:type: object
"""
@property
def mouse_moved(self) -> object:
"""
:type: object
"""
@property
def moved(self) -> object:
"""
:type: object
"""
pass
class ScrollGesture(ShapeGesture, AbstractGesture):
"""
The gesture that provides a way to capture mouse scroll event.
"""
@staticmethod
def __init__(*args, **kwargs) -> typing.Any:
"""
Constructs an gesture to track when the user clicked the mouse.
### Arguments:
`onEnded :`
Function that is called when the user clicked the mouse button.
`kwargs : dict`
See below
### Keyword Arguments:
`mouse_button : `
The mouse button this gesture is watching.
`modifiers : `
The modifier that should be pressed to trigger this gesture.
`on_ended_fn : `
Called when the user scrolls.
`name : `
The name of the object. It's used for debugging.
`manager : `
The Manager that controld this gesture.
"""
def __repr__(self) -> str: ...
@staticmethod
def call_on_ended_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user scrolls.
"""
def has_on_ended_fn(self) -> bool:
"""
Called when the user scrolls.
"""
@staticmethod
def set_on_ended_fn(*args, **kwargs) -> typing.Any:
"""
Called when the user scrolls.
"""
@property
def modifiers(self) -> int:
"""
The modifier that should be pressed to trigger this gesture.
:type: int
"""
@modifiers.setter
def modifiers(self, arg1: int) -> None:
"""
The modifier that should be pressed to trigger this gesture.
"""
@property
def mouse_button(self) -> int:
"""
The mouse button this gesture is watching.
:type: int
"""
@mouse_button.setter
def mouse_button(self, arg1: int) -> None:
"""
The mouse button this gesture is watching.
"""
@property
def scroll(self) -> object:
"""
Returns the current scroll state.
:type: object
"""
pass
class ShapeGesture(AbstractGesture):
"""
The base class for the gestures to provides a way to capture mouse events in 3d scene.
"""
def __repr__(self) -> str: ...
@property
def raw_input(self) -> omni::ui::scene::MouseInput:
"""
:type: omni::ui::scene::MouseInput
"""
@property
def sender(self) -> omni::ui::scene::AbstractShape:
"""
:type: omni::ui::scene::AbstractShape
"""
pass
class Space():
"""
Members:
CURRENT
WORLD
OBJECT
NDC
SCREEN
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
CURRENT: omni.ui_scene._scene.Space # value = <Space.CURRENT: 0>
NDC: omni.ui_scene._scene.Space # value = <Space.NDC: 3>
OBJECT: omni.ui_scene._scene.Space # value = <Space.OBJECT: 2>
SCREEN: omni.ui_scene._scene.Space # value = <Space.SCREEN: 4>
WORLD: omni.ui_scene._scene.Space # value = <Space.WORLD: 1>
__members__: dict # value = {'CURRENT': <Space.CURRENT: 0>, 'WORLD': <Space.WORLD: 1>, 'OBJECT': <Space.OBJECT: 2>, 'NDC': <Space.NDC: 3>, 'SCREEN': <Space.SCREEN: 4>}
pass
class TexturedMesh(PolygonMesh, AbstractShape, AbstractItem):
"""
Encodes a polygonal mesh with free-form textures.
"""
@typing.overload
def __init__(self, source_url: str, uvs: object, positions: object, colors: object, vertex_counts: typing.List[int], vertex_indices: typing.List[int], legacy_flipped_v: bool = True, **kwargs) -> None:
"""
Construct a mesh with predefined properties.
### Arguments:
`sourceUrl :`
Describes the texture image url.
`uvs :`
Describes uvs for the image texture.
`positions :`
Describes points in local space.
`colors :`
Describes colors per vertex.
`vertexCounts :`
The number of vertices in each face.
`vertexIndices :`
The list of the index of each vertex of each face in the mesh.
`kwargs : dict`
See below
### Keyword Arguments:
`uvs : `
This property holds the texture coordinates of the mesh.
`source_url : `
This property holds the image URL. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
`image_provider : `
This property holds the image provider. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
`image_width : `
The resolution for rasterization of svg and for ImageProvider.
`image_height : `
The resolution of rasterization of svg and for ImageProvider.
`positions : `
The primary geometry attribute, describes points in local space.
`colors : `
Describes colors per vertex.
`vertex_counts : `
Provides the number of vertices in each face of the mesh, which is also the number of consecutive indices in vertex_indices that define the face. The length of this attribute is the number of faces in the mesh.
`vertex_indices : `
Flat list of the index (into the points attribute) of each vertex of each face in the mesh.
`thicknesses : `
When wireframe is true, it defines the thicknesses of lines.
`intersection_thickness : `
The thickness of the line for the intersection.
`wireframe: `
When true, the mesh is drawn as lines.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
Construct a mesh with predefined properties.
### Arguments:
`imageProvider :`
Describes the texture image provider.
`uvs :`
Describes uvs for the image texture.
`positions :`
Describes points in local space.
`colors :`
Describes colors per vertex.
`vertexCounts :`
The number of vertices in each face.
`vertexIndices :`
The list of the index of each vertex of each face in the mesh.
`kwargs : dict`
See below
### Keyword Arguments:
`uvs : `
This property holds the texture coordinates of the mesh.
`source_url : `
This property holds the image URL. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
`image_provider : `
This property holds the image provider. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
`image_width : `
The resolution for rasterization of svg and for ImageProvider.
`image_height : `
The resolution of rasterization of svg and for ImageProvider.
`positions : `
The primary geometry attribute, describes points in local space.
`colors : `
Describes colors per vertex.
`vertex_counts : `
Provides the number of vertices in each face of the mesh, which is also the number of consecutive indices in vertex_indices that define the face. The length of this attribute is the number of faces in the mesh.
`vertex_indices : `
Flat list of the index (into the points attribute) of each vertex of each face in the mesh.
`thicknesses : `
When wireframe is true, it defines the thicknesses of lines.
`intersection_thickness : `
The thickness of the line for the intersection.
`wireframe: `
When true, the mesh is drawn as lines.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
@typing.overload
def __init__(self, image_provider: omni.ui._ui.ImageProvider, uvs: object, positions: object, colors: object, vertex_counts: typing.List[int], vertex_indices: typing.List[int], legacy_flipped_v: bool = True, **kwargs) -> None: ...
@typing.overload
def get_gesture_payload(self) -> TexturedMeshGesturePayload:
"""
Contains all the information about the intersection.
Contains all the information about the intersection at the specific state.
"""
@typing.overload
def get_gesture_payload(self, arg0: GestureState) -> TexturedMeshGesturePayload: ...
@property
def gesture_payload(self) -> TexturedMeshGesturePayload:
"""
Contains all the information about the intersection.
:type: TexturedMeshGesturePayload
"""
@property
def image_height(self) -> int:
"""
The resolution of rasterization of svg and for ImageProvider.
:type: int
"""
@image_height.setter
def image_height(self, arg1: int) -> None:
"""
The resolution of rasterization of svg and for ImageProvider.
"""
@property
def image_provider(self) -> omni.ui._ui.ImageProvider:
"""
This property holds the image provider. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
:type: omni.ui._ui.ImageProvider
"""
@image_provider.setter
def image_provider(self, arg1: omni.ui._ui.ImageProvider) -> None:
"""
This property holds the image provider. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
"""
@property
def image_width(self) -> int:
"""
The resolution for rasterization of svg and for ImageProvider.
:type: int
"""
@image_width.setter
def image_width(self, arg1: int) -> None:
"""
The resolution for rasterization of svg and for ImageProvider.
"""
@property
def source_url(self) -> str:
"""
This property holds the image URL. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
:type: str
"""
@source_url.setter
def source_url(self, arg1: str) -> None:
"""
This property holds the image URL. It can be an "omni:" path, a "file:" path, a direct path or the path relative to the application root directory.
"""
@property
def uvs(self) -> object:
"""
This property holds the texture coordinates of the mesh.
:type: object
"""
@uvs.setter
def uvs(self, arg1: handle) -> None:
"""
This property holds the texture coordinates of the mesh.
"""
pass
class TexturedMeshGesturePayload(PolygonMeshGesturePayload, AbstractGesture.GesturePayload):
@property
def u(self) -> float:
"""
:type: float
"""
@property
def v(self) -> float:
"""
:type: float
"""
pass
class Transform(AbstractContainer, AbstractItem):
"""
Transforms children with component affine transformations.
"""
class LookAt():
"""
Members:
NONE
CAMERA
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
CAMERA: omni.ui_scene._scene.Transform.LookAt # value = <LookAt.CAMERA: 1>
NONE: omni.ui_scene._scene.Transform.LookAt # value = <LookAt.NONE: 0>
__members__: dict # value = {'NONE': <LookAt.NONE: 0>, 'CAMERA': <LookAt.CAMERA: 1>}
pass
@typing.overload
def __init__(self, **kwargs) -> None:
"""
Constructor.
`kwargs : dict`
See below
### Keyword Arguments:
`transform : `
Single transformation matrix.
`scale_to : `
Which space the current transform will be rescaled before applying the matrix. It's useful to make the object the same size regardless the distance to the camera.
`look_at : `
Rotates this transform to align the direction with the camera.
`basis : `
A custom basis for representing this transform's coordinate system.
`visible : `
This property holds whether the item is visible.
Constructor.
`kwargs : dict`
See below
### Keyword Arguments:
`transform : `
Single transformation matrix.
`scale_to : `
Which space the current transform will be rescaled before applying the matrix. It's useful to make the object the same size regardless the distance to the camera.
`look_at : `
Rotates this transform to align the direction with the camera.
`basis : `
A custom basis for representing this transform's coordinate system.
`visible : `
This property holds whether the item is visible.
"""
@typing.overload
def __init__(self, arg0: object, **kwargs) -> None: ...
@property
def basis(self) -> TransformBasis:
"""
A custom basis for representing this transform's coordinate system.
:type: TransformBasis
"""
@basis.setter
def basis(self, arg1: TransformBasis) -> None:
"""
A custom basis for representing this transform's coordinate system.
"""
@property
def look_at(self) -> Transform.LookAt:
"""
Rotates this transform to align the direction with the camera.
:type: Transform.LookAt
"""
@look_at.setter
def look_at(self, arg1: Transform.LookAt) -> None:
"""
Rotates this transform to align the direction with the camera.
"""
@property
def scale_to(self) -> Space:
"""
Which space the current transform will be rescaled before applying the matrix. It's useful to make the object the same size regardless the distance to the camera.
:type: Space
"""
@scale_to.setter
def scale_to(self, arg1: Space) -> None:
"""
Which space the current transform will be rescaled before applying the matrix. It's useful to make the object the same size regardless the distance to the camera.
"""
@property
def transform(self) -> Matrix44:
"""
Single transformation matrix.
:type: Matrix44
"""
@transform.setter
def transform(self, arg1: handle) -> None:
"""
Single transformation matrix.
"""
pass
class TransformBasis():
def __init__(self, **kwargs) -> None: ...
def get_matrix(self) -> Matrix44: ...
pass
class Vector2():
def __add__(self, arg0: Vector2) -> Vector2: ...
def __eq__(self, arg0: Vector2) -> bool: ...
def __getitem__(self, arg0: int) -> float: ...
@typing.overload
def __init__(self, v: Vector2) -> None: ...
@typing.overload
def __init__(self, x: float = 0.0) -> None: ...
@typing.overload
def __init__(self, x: float, y: float) -> None: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: float) -> None: ...
def get_length(self) -> float: ...
def get_normalized(self) -> Vector2: ...
@property
def x(self) -> float:
"""
:type: float
"""
@x.setter
def x(self, arg0: float) -> None:
pass
@property
def y(self) -> float:
"""
:type: float
"""
@y.setter
def y(self, arg0: float) -> None:
pass
__hash__ = None
pass
class Vector3():
def __add__(self, arg0: Vector3) -> Vector3: ...
def __eq__(self, arg0: Vector3) -> bool: ...
def __getitem__(self, arg0: int) -> float: ...
@typing.overload
def __init__(self, v: Vector3) -> None: ...
@typing.overload
def __init__(self, x: float = 0.0) -> None: ...
@typing.overload
def __init__(self, x: float, y: float, z: float) -> None: ...
def __matmul__(self, arg0: Vector3) -> float: ...
def __mul__(self, arg0: Vector3) -> Vector3: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: float) -> None: ...
def get_length(self) -> float: ...
def get_normalized(self) -> Vector3: ...
@property
def x(self) -> float:
"""
:type: float
"""
@x.setter
def x(self, arg0: float) -> None:
pass
@property
def y(self) -> float:
"""
:type: float
"""
@y.setter
def y(self, arg0: float) -> None:
pass
@property
def z(self) -> float:
"""
:type: float
"""
@z.setter
def z(self, arg0: float) -> None:
pass
__hash__ = None
pass
class Vector4():
def __add__(self, arg0: Vector4) -> Vector4: ...
def __eq__(self, arg0: Vector4) -> bool: ...
def __getitem__(self, arg0: int) -> float: ...
@typing.overload
def __init__(self, v: Vector4) -> None: ...
@typing.overload
def __init__(self, x: float = 0.0) -> None: ...
@typing.overload
def __init__(self, x: float, y: float, z: float, w: float) -> None: ...
@typing.overload
def __init__(self, v: Vector3, w: float) -> None: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: float) -> None: ...
def get_length(self) -> float: ...
def get_normalized(self) -> Vector4: ...
@property
def w(self) -> float:
"""
:type: float
"""
@w.setter
def w(self, arg0: float) -> None:
pass
@property
def x(self) -> float:
"""
:type: float
"""
@x.setter
def x(self, arg0: float) -> None:
pass
@property
def y(self) -> float:
"""
:type: float
"""
@y.setter
def y(self, arg0: float) -> None:
pass
@property
def z(self) -> float:
"""
:type: float
"""
@z.setter
def z(self, arg0: float) -> None:
pass
__hash__ = None
pass
class Widget(Rectangle, AbstractShape, AbstractItem):
"""
The shape that contains the omni.ui widgets. It automatically creates IAppWindow and transfers its content to the texture of the rectangle. It interacts with the mouse and sends the mouse events to the underlying window, so interacting with the UI on this rectangle is smooth for the user.
"""
class FillPolicy():
"""
Members:
STRETCH
PRESERVE_ASPECT_FIT
PRESERVE_ASPECT_CROP
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
PRESERVE_ASPECT_CROP: omni.ui_scene._scene.Widget.FillPolicy # value = <FillPolicy.PRESERVE_ASPECT_CROP: 2>
PRESERVE_ASPECT_FIT: omni.ui_scene._scene.Widget.FillPolicy # value = <FillPolicy.PRESERVE_ASPECT_FIT: 1>
STRETCH: omni.ui_scene._scene.Widget.FillPolicy # value = <FillPolicy.STRETCH: 0>
__members__: dict # value = {'STRETCH': <FillPolicy.STRETCH: 0>, 'PRESERVE_ASPECT_FIT': <FillPolicy.PRESERVE_ASPECT_FIT: 1>, 'PRESERVE_ASPECT_CROP': <FillPolicy.PRESERVE_ASPECT_CROP: 2>}
pass
class UpdatePolicy():
"""
Members:
ON_DEMAND
ALWAYS
ON_MOUSE_HOVERED
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
ALWAYS: omni.ui_scene._scene.Widget.UpdatePolicy # value = <UpdatePolicy.ALWAYS: 1>
ON_DEMAND: omni.ui_scene._scene.Widget.UpdatePolicy # value = <UpdatePolicy.ON_DEMAND: 0>
ON_MOUSE_HOVERED: omni.ui_scene._scene.Widget.UpdatePolicy # value = <UpdatePolicy.ON_MOUSE_HOVERED: 2>
__members__: dict # value = {'ON_DEMAND': <UpdatePolicy.ON_DEMAND: 0>, 'ALWAYS': <UpdatePolicy.ALWAYS: 1>, 'ON_MOUSE_HOVERED': <UpdatePolicy.ON_MOUSE_HOVERED: 2>}
pass
def __init__(self, width: float, height: float, **kwargs) -> None:
"""
Created an empty image.
`kwargs : dict`
See below
### Keyword Arguments:
`fill_policy : `
Define what happens when the source image has a different size than the item.
`update_policy : `
Define when to redraw the widget.
`resolution_scale : `
The resolution scale of the widget.
`resolution_width : `
The resolution of the widget framebuffer.
`resolution_height : `
The resolution of the widget framebuffer.
`width : `
The size of the rectangle.
`height : `
The size of the rectangle.
`thickness : `
The thickness of the line.
`intersection_thickness : `
The thickness of the line for the intersection.
`color : `
The color of the line.
`axis : `
The axis the rectangle is perpendicular to.
`wireframe : `
When true, it's a line. When false it's a mesh.
`gesture : `
All the gestures assigned to this shape.
`gestures : `
All the gestures assigned to this shape.
`visible : `
This property holds whether the item is visible.
"""
def invalidate(self) -> None:
"""
Rebuild and recapture the widgets at the next frame. If
frame
build_fn
"""
@property
def fill_policy(self) -> Widget.FillPolicy:
"""
Define what happens when the source image has a different size than the item.
:type: Widget.FillPolicy
"""
@fill_policy.setter
def fill_policy(self, arg1: Widget.FillPolicy) -> None:
"""
Define what happens when the source image has a different size than the item.
"""
@property
def frame(self) -> omni.ui._ui.Frame:
"""
Return the main frame of the widget.
:type: omni.ui._ui.Frame
"""
@property
def resolution_height(self) -> int:
"""
The resolution of the widget framebuffer.
:type: int
"""
@resolution_height.setter
def resolution_height(self, arg1: int) -> None:
"""
The resolution of the widget framebuffer.
"""
@property
def resolution_scale(self) -> float:
"""
The resolution scale of the widget.
:type: float
"""
@resolution_scale.setter
def resolution_scale(self, arg1: float) -> None:
"""
The resolution scale of the widget.
"""
@property
def resolution_width(self) -> int:
"""
The resolution of the widget framebuffer.
:type: int
"""
@resolution_width.setter
def resolution_width(self, arg1: int) -> None:
"""
The resolution of the widget framebuffer.
"""
@property
def update_policy(self) -> Widget.UpdatePolicy:
"""
Define when to redraw the widget.
:type: Widget.UpdatePolicy
"""
@update_policy.setter
def update_policy(self, arg1: Widget.UpdatePolicy) -> None:
"""
Define when to redraw the widget.
"""
pass
def Cross(arg0: handle, arg1: handle) -> object:
pass
def Dot(arg0: handle, arg1: handle) -> float:
pass
| 115,939 | unknown | 30.411542 | 415 | 0.562313 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/scene_extension.py | ## Copyright (c) 2018-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.
##
from . import scene
import omni.ext
import omni.ui as ui
from .compatibility import add_intersection_attributes
class SceneExtension(omni.ext.IExt):
"""The entry point for MDL Material Graph"""
def on_startup(self):
self.subscription = ui.add_to_namespace(scene)
# Compatibility with old intersections
add_intersection_attributes()
def on_shutdown(self):
self.subscription = None
| 870 | Python | 32.499999 | 77 | 0.749425 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/compatibility.py | ## Copyright (c) 2018-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.
##
__all__ = ["add_intersection_attributes"]
from . import scene as sc
import carb
def _deprecate_warning(func, old, new):
"""Returns decorated function that prints a warning when it's executed"""
def inner(*args, **kwargs):
carb.log_warn(f"[omni.ui.scene] Method {old} is deprecated. Please use {new} instead.")
return func(*args, **kwargs)
return inner
def _add_compatibility(obj, old, new, deprecate_warning=True):
"""Add the attribute old that equals to new"""
new_obj = getattr(obj, new)
if deprecate_warning:
if isinstance(new_obj, property):
setattr(
obj,
old,
property(
fget=_deprecate_warning(new_obj.fget, obj.__name__ + "." + old, obj.__name__ + "." + new),
fset=_deprecate_warning(new_obj.fset, obj.__name__ + "." + old, obj.__name__ + "." + new),
),
)
else:
setattr(obj, old, _deprecate_warning(new_obj, obj.__name__ + "." + old, obj.__name__ + "." + new))
else:
setattr(obj, old, new_obj)
def add_intersection_attributes():
"""Assigns deprecated methods that print warnings when executing"""
for item in [
sc.AbstractGesture,
sc.AbstractShape,
sc.Arc,
sc.Line,
sc.Points,
sc.PolygonMesh,
sc.Rectangle,
sc.Screen,
]:
_add_compatibility(item, "intersection", "gesture_payload")
_add_compatibility(item, "get_intersection", "get_gesture_payload")
_add_compatibility(sc.AbstractGesture, "Intersection", "GesturePayload", False)
| 2,090 | Python | 33.849999 | 110 | 0.616268 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/gesture_manager_utils.py | ## 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.
##
"""The utilities for ui.scene test"""
from omni.ui_scene import scene as sc
class Manager(sc.GestureManager):
def __init__(self, mouse_action_sequence, mouse_position_sequence, scene_view):
"""
The gesture manager takes inputs to mimic the mouse operations for tests
Args:
mouse_action_sequence: a List which contains a sequence of (input.clicked, input.down, input.released)
mouse_position_sequence: a List which contains a sequence of (input.mouse[0], input.mouse[1])
"""
super().__init__()
# The sequence of actions. In the future we need a way to record it.
# mimic the mouse click, hold and move
self.mouse_action_sequence = mouse_action_sequence
self.mouse_position_sequence = mouse_position_sequence
if len(self.mouse_action_sequence) != len(self.mouse_position_sequence):
raise Exception(f"the mouse action sequence length doesn't match the mouse position sequence")
self.scene_view = scene_view
self.counter = 0
def amend_input(self, input):
if self.counter >= len(self.mouse_action_sequence):
# Don't amentd anything.
return input
# Move mouse
input.mouse[0], input.mouse[1] = self.mouse_position_sequence[self.counter]
# Get 3D cords of the mouse
origin, direction = self.scene_view.get_ray_from_ndc(input.mouse)
input.mouse_origin = origin
input.mouse_direction = direction
# Click, move and release
input.clicked, input.down, input.released = self.mouse_action_sequence[self.counter]
self.counter += 1
return input
| 2,124 | Python | 41.499999 | 114 | 0.678908 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_manipulator.py | ## 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.
##
from omni.ui.tests.test_base import OmniUiTest
from functools import partial
from pathlib import Path
from omni.ui_scene import scene as sc
from omni.ui import color as cl
import asyncio
import carb
import math
import omni.kit
import omni.kit.app
import omni.ui as ui
from .gesture_manager_utils import Manager
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
CURRENT_PATH = Path(__file__).parent.joinpath("../../../data")
class TestManipulator(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_manipulator_update(self):
class RotatingCube(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._angle = 0
def on_build(self):
transform = sc.Matrix44.get_rotation_matrix(
0, self._angle, 0, True)
with sc.Transform(transform=transform):
sc.Line([-1, -1, -1], [1, -1, -1])
sc.Line([-1, 1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [1, -1, 1])
sc.Line([-1, 1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, 1, -1])
sc.Line([1, -1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [-1, 1, 1])
sc.Line([1, -1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, -1, 1])
sc.Line([-1, 1, -1], [-1, 1, 1])
sc.Line([1, -1, -1], [1, -1, 1])
sc.Line([1, 1, -1], [1, 1, 1])
# Increase the angle
self._angle += 5
def get_angle(self):
return self._angle
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0]
# Move camera
rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True)
transl = sc.Matrix44.get_translation_matrix(0, 0, -6)
view = transl * rotation
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=200
)
with scene_view.scene:
rcube = RotatingCube()
rcube.invalidate()
await self.wait_n_updates(1)
self.assertEqual(rcube.get_angle(), 5)
rcube.invalidate()
await self.wait_n_updates(1)
self.assertEqual(rcube.get_angle(), 10)
rcube.invalidate()
await self.wait_n_updates(1)
self.assertEqual(rcube.get_angle(), 15)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_manipulator_model(self):
class MovingRectangle(sc.Manipulator):
"""Manipulator that redraws when the model is changed"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0),(0, 1, 0), (0, 0, 1), (0, 0, 0)]
mouse_position_sequence = [(0, 0), (0, 0), (0.15, 0), (0.3, 0), (0.3, 0), (0.3, 0)]
mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
self._gesture = sc.DragGesture(on_changed_fn=self._move, manager=mgr)
def on_build(self):
position = self.model.get_as_floats(self.model.get_item("position"))
transform = sc.Matrix44.get_translation_matrix(*position)
with sc.Transform(transform=transform):
sc.Rectangle(color=cl.blue, gesture=self._gesture)
def on_model_updated(self, item):
self.invalidate()
def _move(self, shape: sc.AbstractShape):
position = shape.gesture_payload.ray_closest_point
item = self.model.get_item("position")
self.model.set_floats(item, position)
class Model(sc.AbstractManipulatorModel):
"""User part. Simple value holder."""
class PositionItem(sc.AbstractManipulatorItem):
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self):
super().__init__()
self.position = Model.PositionItem()
def get_item(self, identifier):
return self.position
def get_as_floats(self, item):
return item.value
def set_floats(self, item, value):
item.value = value
self._item_changed(item)
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0]
# Move camera
rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True)
transl = sc.Matrix44.get_translation_matrix(0, 0, -6)
view = transl * rotation
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=200
)
with scene_view.scene:
MovingRectangle(model=Model())
await self.wait_n_updates(30)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_manipulator_image(self):
"""Check the image in manipulator doesn't crash when invalidation"""
class ImageManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.image = None
def on_build(self):
filename = f"{CURRENT_PATH}/main_ov_logo_square.png"
self.image = sc.Image(filename)
window = await self.create_test_window()
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150)
with scene_view.scene:
manipulator = ImageManipulator()
# removing this wait leads to an error of png unload wait time exceeded limit of 20000 ms!
for _ in range(50):
image_ready = manipulator.image and manipulator.image.image_provider.is_reference_valid
if image_ready:
break
await asyncio.sleep(0.1)
await self.wait_n_updates(1)
# Check it doesn't crash
manipulator.invalidate()
await self.wait_n_updates(1)
# Wait for Image
for _ in range(50):
image_ready = manipulator.image and manipulator.image.image_provider.is_reference_valid
if image_ready:
break
await asyncio.sleep(0.1)
await self.wait_n_updates(1)
await self.finalize_test_no_image()
async def test_manipulator_textured_mesh(self):
"""Check the TexturedMesh in manipulator doesn't crash when invalidation"""
class TexturedMeshManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.mesh = None
def on_build(self):
point_count = 4
# Form the mesh data
points = [[1, -1, 0], [1, 1, 0], [0, 1, 0], [-1, -1, 0]]
vertex_indices = [0, 1, 2, 3]
colors = [[0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1]]
uvs = [[1, 1], [1, 0], [0.5, 0], [0, 1]]
# Draw the mesh
filename = f"{CURRENT_PATH}/main_ov_logo_square.png"
self.mesh = sc.TexturedMesh(filename, uvs, points, colors, [point_count], vertex_indices)
window = await self.create_test_window()
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150)
with scene_view.scene:
manipulator = TexturedMeshManipulator()
# removing this wait leads to an error of png unload wait time exceeded limit of 20000 ms!
for _ in range(50):
image_ready = manipulator.mesh and manipulator.mesh.image_provider.is_reference_valid
if image_ready:
break
await asyncio.sleep(0.1)
await self.wait_n_updates(1)
# Check it doesn't crash
manipulator.invalidate()
await self.wait_n_updates(1)
# Wait for Image
for _ in range(50):
image_ready = manipulator.mesh and manipulator.mesh.image_provider.is_reference_valid
if image_ready:
break
await asyncio.sleep(0.1)
await self.wait_n_updates(1)
await self.finalize_test_no_image()
| 9,718 | Python | 36.670542 | 111 | 0.542498 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_scroll.py | ## 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.
##
__all__ = ["TestScroll"]
import omni.kit.test
from omni.ui import scene as sc
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
class TestScroll(OmniUiTest):
async def test_scroll(self):
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
scrolled = [0, 0]
class Scroll(sc.ScrollGesture):
def on_ended(self):
scrolled[0] += self.scroll[0]
scrolled[1] += self.scroll[1]
with window.frame:
# Camera matrices
projection = [1e-2, 0, 0, 0]
projection += [0, 1e-2, 0, 0]
projection += [0, 0, 2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -5)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
sc.Screen(gesture=Scroll())
await self.wait_n_updates(1)
ref = ui_test.WidgetRef(scene_view, "")
await ui_test.emulate_mouse_move(ref.center)
await ui_test.emulate_mouse_scroll(ui_test.Vec2(1, 0))
await self.wait_n_updates(1)
self.assertTrue(scrolled[0] == 0)
self.assertTrue(scrolled[1] > 0)
await self.finalize_test_no_image()
async def test_scroll_another_window(self):
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
scrolled = [0, 0]
class Scroll(sc.ScrollGesture):
def on_ended(self):
scrolled[0] += self.scroll[0]
scrolled[1] += self.scroll[1]
with window.frame:
# Camera matrices
projection = [1e-2, 0, 0, 0]
projection += [0, 1e-2, 0, 0]
projection += [0, 0, 2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -5)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
sc.Screen(gesture=Scroll())
another_window = ui.Window("cover it", width=128, height=128, position_x=64, position_y=64)
await self.wait_n_updates(1)
ref = ui_test.WidgetRef(scene_view, "")
await ui_test.emulate_mouse_move(ref.center)
await ui_test.emulate_mouse_scroll(ui_test.Vec2(1, 1))
await self.wait_n_updates(1)
# Window covers SceneView. Scroll is not expected.
self.assertTrue(scrolled[0] == 0)
self.assertTrue(scrolled[1] == 0)
await self.finalize_test_no_image()
| 3,104 | Python | 31.010309 | 99 | 0.601482 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_container.py | ## 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.
##
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from omni.ui_scene import scene as sc
from omni.ui import color as cl
import carb
import math
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
class TestContainer(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_transform(self):
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0]
# Move camera
rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True)
transl = sc.Matrix44.get_translation_matrix(0, 0, -6)
view = transl * rotation
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=200
)
with scene_view.scene:
line_count = 36
for i in range(line_count):
weight = i / line_count
angle = 2.0 * math.pi * weight
# translation matrix
move = sc.Matrix44.get_translation_matrix(
8 * (weight - 0.5), 0.5 * math.sin(angle), 0)
# rotation matrix
rotate = sc.Matrix44.get_rotation_matrix(0, 0, angle)
# the final transformation
transform = move * rotate
color = cl(weight, 1.0 - weight, 1.0)
# create transform and put line to it
with sc.Transform(transform=transform):
sc.Line([0, 0, 0], [0.5, 0, 0], color=color)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 2,610 | Python | 34.283783 | 90 | 0.592337 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_arc.py | ## 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.
##
import omni.kit.test
from .gesture_manager_utils import Manager
from omni.ui import color as cl
from omni.ui_scene import scene as sc
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import carb
import math
import omni.appwindow
import omni.kit.app
import omni.ui as ui
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
CURRENT_PATH = Path(__file__).parent.joinpath("../../../data")
class TestArc(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_angle(self):
"""Test the angle"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
class MyDragGesture(sc.DragGesture):
def __init__(self):
super().__init__()
self.began_called = False
self.changed_called = False
self.ended_called = False
self.began_angle = 0.0
self.end_angle = 0.0
def can_be_prevented(self, gesture):
return True
def on_began(self):
self.sender.begin = self.sender.gesture_payload.angle
self.began_angle = self.sender.gesture_payload.angle
self.began_called = True
def on_changed(self):
self.sender.end = self.sender.gesture_payload.angle
self.changed_called = True
def on_ended(self):
self.sender.color = cl.blue
self.end_angle = self.sender.gesture_payload.angle
self.ended_called = True
with window.frame:
# Camera matrices
projection = [1e-2, 0, 0, 0]
projection += [0, 1e-2, 0, 0]
projection += [0, 0, 2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -5)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
transform = sc.Matrix44.get_translation_matrix(0, 0, 0)
transform *= sc.Matrix44.get_scale_matrix(0.2, 0.2, 0.2)
with sc.Transform(transform=transform):
nsteps = 20
# Click, drag 360 deg, release
drag = MyDragGesture()
# Clicked, down, released
mouse_action_sequence = [(0, 0, 0), (1, 1, 0)] + [(0, 1, 0)] * (nsteps + 1) + [(0, 0, 1), (0, 0, 0)]
mouse_position_sequence = (
[(0, 1), (0, 1)]
+ [
(-math.sin(i * math.pi * 2.0 / nsteps), math.cos(i * math.pi * 2.0 / nsteps))
for i in range(nsteps + 1)
]
+ [(0, 1), (0, 1)]
)
drag.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
sc.Arc(500, wireframe=True, color=cl.white, gesture=drag)
await self.wait_n_updates(nsteps + 5)
self.assertTrue(drag.began_called)
self.assertTrue(drag.changed_called)
self.assertTrue(drag.ended_called)
self.assertEqual(drag.began_angle, math.pi * 0.5)
self.assertEqual(drag.end_angle, math.pi * 2.5)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 4,129 | Python | 35.875 | 120 | 0.564301 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_scene.py | ## 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.
##
__all__ = ["TestScene"]
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from omni.ui_scene import scene as sc
from pathlib import Path
import carb
import omni.kit.app
import omni.ui as ui
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
CURRENT_PATH = Path(__file__).parent.joinpath("../../../data")
class CameraModel(sc.AbstractManipulatorModel):
def __init__(self):
super().__init__()
self._angle = 0
def append_angle(self, delta: float):
self._angle += delta * 100
# Inform SceneView that view matrix is changed
self._item_changed("view")
def get_as_floats(self, item):
"""Called by SceneView to get projection and view matrices"""
if item == self.get_item("projection"):
# Projection matrix
return [5, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, -1, 0, 0, -1, 0]
if item == self.get_item("view"):
# Move camera
rotation = sc.Matrix44.get_rotation_matrix(30, self._angle, 0, True)
transl = sc.Matrix44.get_translation_matrix(0, 0, -8)
view = transl * rotation
return [view[i] for i in range(16)]
class StereoModel(sc.AbstractManipulatorModel):
def __init__(self, parent, offset):
super().__init__()
self._parent = parent
self._offset = offset
self._sub = self._parent.subscribe_item_changed_fn(lambda m, i: self.changed(m, i))
def changed(self, model, item):
self._item_changed("view")
def get_as_floats(self, item):
"""Called by SceneView to get projection and view matrices"""
if item == self.get_item("projection"):
return self._parent.get_as_floats(self._parent.get_item("projection"))
if item == self.get_item("view"):
parent = self._parent.get_as_floats(self._parent.get_item("view"))
parent = sc.Matrix44(*parent)
transl = sc.Matrix44.get_translation_matrix(0, 0, 8)
rotation = sc.Matrix44.get_rotation_matrix(0, self._offset, 0, True)
transl_inv = sc.Matrix44.get_translation_matrix(0, 0, -8)
view = transl_inv * rotation * transl * parent
return [view[i] for i in range(16)]
class TestScene(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_stereo(self):
"""Test the stereo setup"""
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
camera = CameraModel()
scene = sc.Scene()
sc.SceneView(StereoModel(camera, 3), scene=scene)
sc.SceneView(StereoModel(camera, -3), scene=scene)
with scene:
# Edges of cube
sc.Line([-1, -1, -1], [1, -1, -1])
sc.Line([-1, 1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [1, -1, 1])
sc.Line([-1, 1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, 1, -1])
sc.Line([1, -1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [-1, 1, 1])
sc.Line([1, -1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, -1, 1])
sc.Line([-1, 1, -1], [-1, 1, 1])
sc.Line([1, -1, -1], [1, -1, 1])
sc.Line([1, 1, -1], [1, 1, 1])
with sc.Transform(transform=sc.Matrix44.get_scale_matrix(0.002, 0.002, 0.002)):
widget = sc.Widget(1000, 500)
with widget.frame:
ui.Label(f"Hello test", style={"font_size": 250})
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_draw_list_buffer_count(self):
class RotatingCube(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._angle = 0
def on_build(self):
transform = sc.Matrix44.get_rotation_matrix(
0, self._angle, 0, True)
with sc.Transform(transform=transform):
sc.Line([-1, -1, -1], [1, -1, -1])
sc.Line([-1, 1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [1, -1, 1])
sc.Line([-1, 1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, 1, -1])
sc.Line([1, -1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [-1, 1, 1])
sc.Line([1, -1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, -1, 1])
sc.Line([-1, 1, -1], [-1, 1, 1])
sc.Line([1, -1, -1], [1, -1, 1])
sc.Line([1, 1, -1], [1, 1, 1])
# Increase the angle
self._angle += 5
def get_angle(self):
return self._angle
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0]
# Move camera
rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True)
transl = sc.Matrix44.get_translation_matrix(0, 0, -6)
view = transl * rotation
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=200
)
with scene_view.scene:
rcube = RotatingCube()
for _ in range(2):
rcube.invalidate()
await self.wait_n_updates(1)
draw_list_buffer_count = scene_view.scene.draw_list_buffer_count
for _ in range(2):
rcube.invalidate()
await self.wait_n_updates(1)
# Testing that the buffer count didn't change
self.assertEqual(scene_view.scene.draw_list_buffer_count, draw_list_buffer_count)
await self.finalize_test_no_image() | 6,836 | Python | 36.77348 | 99 | 0.518432 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_shapes.py | ## 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.
##
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from omni.ui_scene import scene as sc
from omni.ui import color as cl
import omni.ui as ui
import math
import carb
import omni.kit
from omni.kit import ui_test
from .gesture_manager_utils import Manager
from functools import partial
from numpy import pi, cos, sin, arccos
import random
import asyncio
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
CURRENT_PATH = Path(__file__).parent.joinpath("../../../data")
class TestShapes(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
random.seed(10)
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_general(self):
window = await self.create_test_window(width=512, height=256)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150)
with scene_view.scene:
# line
sc.Line([-2.5, -1.0, 0], [-1.5, -1.0, 0], color=cl.red, thickness=5)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(1, 0.2, 0)):
# Rectangle
sc.Rectangle(color=cl.blue)
# wireframe rectangle
sc.Rectangle(2, 1.3, thickness=5, wireframe=True)
# arc
sc.Arc(3, begin=math.pi, end=4, thickness=5, wireframe=True, color=cl.yellow)
# label
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(1, -2, 0)):
sc.Label("NVIDIA Omniverse", alignment=ui.Alignment.CENTER, color=cl.green, size=50)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_image(self):
window = await self.create_test_window(width=512, height=256)
sc_image = None
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150)
with scene_view.scene:
# image
filename = f"{CURRENT_PATH}/main_ov_logo_square.png"
sc_image = sc.Image(filename)
# removing this wait leads to an error of png unload wait time exceeded limit of 20000 ms!
for _ in range(50):
image_ready = sc_image.image_provider.is_reference_valid
if image_ready:
break
await asyncio.sleep(0.1)
await self.wait_n_updates(1)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_distant_shape(self):
window = await self.create_test_window(width=256, height=256)
# Projection matrix
proj = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
# Move camera
transl = sc.Matrix44.get_translation_matrix(100000000000, 100000000000, 119999998)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, transl), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
with sc.Transform(
transform=sc.Matrix44.get_translation_matrix(-100000000000, -100000000000, -119999995)
):
sc.Line([-1, -1, -1], [1, -1, -1])
sc.Line([-1, 1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [1, -1, 1])
sc.Line([-1, 1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, 1, -1])
sc.Line([1, -1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [-1, 1, 1])
sc.Line([1, -1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, -1, 1])
sc.Line([-1, 1, -1], [-1, 1, 1])
sc.Line([1, -1, -1], [1, -1, 1])
sc.Line([1, 1, -1], [1, 1, 1])
await self.wait_n_updates(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_points(self):
window = await self.create_test_window(width=512, height=200)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150)
with scene_view.scene:
point_count = 36
points = []
sizes = []
colors = []
for i in range(point_count):
weight = i / point_count
angle = 2.0 * math.pi * weight
points.append([math.cos(angle), math.sin(angle), 0])
colors.append([weight, 1 - weight, 1, 1])
sizes.append(6 * (weight + 1.0 / point_count))
sc.Points(points, colors=colors, sizes=sizes)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_polygon_mesh(self):
window = await self.create_test_window(width=512, height=200)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150)
with scene_view.scene:
point_count = 36
# Form the mesh data
points = []
vertex_indices = []
sizes = []
colors = []
for i in range(point_count):
weight = i / point_count
angle = 2.0 * math.pi * weight
vertex_indices.append(i)
points.append([math.cos(angle) * weight, -math.sin(angle) * weight, 0])
colors.append([weight, 1 - weight, 1, 1])
sizes.append(6 * (weight + 1.0 / point_count))
# Draw the mesh
sc.PolygonMesh(points, colors, [point_count], vertex_indices)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_polygon_mesh_intersection(self):
"""Click on the different polygon mesh to get the s and t"""
await self.create_test_area(width=1440, height=900, block_devices=False)
self.intersection = False
self.face_id = -1
self.s = -1.0
self.t = -1.0
def _on_shape_clicked(shape):
"""Called when the user clicks the point"""
self.intersection = True
self.face_id = shape.gesture_payload.face_id
self.s = shape.gesture_payload.s
self.t = shape.gesture_payload.t
window = ui.Window("test_polygon_mesh_intersection", width=700, height=500)
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
select = sc.ClickGesture(_on_shape_clicked)
# two triangles
point_count = 3
points = [[-1, -1, 0], [2, -1, 0], [3, 1, 0], [2, -1, 0], [4, 0, -1], [3, 1, 0]]
vertex_indices = [0, 1, 2, 3, 4, 5]
colors = [[1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]]
sc.PolygonMesh(points, colors, [point_count, point_count], vertex_indices, gesture=select)
await ui_test.wait_n_updates(10)
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(850, 300))
await ui_test.wait_n_updates(10)
self.assertEqual(self.intersection, True)
self.assertEqual(self.face_id, 0)
self.assertAlmostEqual(self.s, 0.18666667622178545)
self.assertAlmostEqual(self.t, 0.7600000000000001)
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(870, 300))
await ui_test.wait_n_updates(10)
self.assertEqual(self.intersection, True)
self.assertEqual(self.face_id, 1)
self.assertAlmostEqual(self.s, 0.16000002187854384)
self.assertAlmostEqual(self.t, 0.6799999891122469)
async def test_polygon_mesh_not_intersection(self):
"""Click on a polygon mesh to see shape is not clicked"""
await self.create_test_area(width=1440, height=900, block_devices=False)
self.intersection = False
def _on_shape_clicked(shape):
"""Called when the user clicks the point"""
self.intersection = True
window = ui.Window("test_polygon_mesh_not_intersection", width=700, height=500)
proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0]
view = sc.Matrix44.get_translation_matrix(0, 0, -6)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
select = sc.ClickGesture(_on_shape_clicked)
# a concave quadrangle
point_count = 4
points = [[-1, -1, 0], [1, -1, 0], [0, -0.5, 0], [1, 1, 0]]
vertex_indices = [0, 1, 2, 3]
colors = [[1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]]
sc.PolygonMesh(points, colors, [point_count], vertex_indices, gesture=select)
await ui_test.wait_n_updates(10)
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(740, 350))
await ui_test.wait_n_updates(10)
self.assertEqual(self.intersection, False)
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(700, 350))
await ui_test.wait_n_updates(10)
self.assertEqual(self.intersection, True)
async def __test_textured_mesh(self, golden_img_name: str, **kwargs):
"""Test polygon mesh with texture"""
window = await self.create_test_window(width=512, height=200)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150)
with scene_view.scene:
point_count = 4
# Form the mesh data
vertex_indices = [0, 2, 3, 1]
points = [(-1, -1, 0), (1, -1, 0), (-1, 1, 0), (1, 1, 0)]
colors = [[0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1]]
# UVs specified in USD coordinate system
uvs = [(0, 0), (0, 1), (1, 1), (1, 0)]
# Flip V coordinate is requested
if kwargs.get("legacy_flipped_v") is None:
uvs = [(uv[0], 1.0 - uv[1]) for uv in uvs]
# Draw the mesh
filename = f"{CURRENT_PATH}/main_ov_logo_square.png"
tm = sc.TexturedMesh(filename, uvs, points, colors, [point_count], vertex_indices, **kwargs)
# Test that get of uv property is equal to input in both cases
self.assertTrue(tm.uvs, uvs)
# removing this wait leads to an error of png unload wait time exceeded limit of 20000 ms!
for _ in range(50):
await asyncio.sleep(0.1)
await self.wait_n_updates(1)
await self.finalize_test(golden_img_name=golden_img_name, golden_img_dir=self._golden_img_dir)
async def test_textured_mesh_legacy(self):
"""Test legacy polygon mesh with texture (flipped V)"""
await self.__test_textured_mesh(golden_img_name="test_textured_mesh_legacy.png")
async def test_textured_mesh(self):
"""Test polygon mesh with texture (USD coordinates)"""
await self.__test_textured_mesh(golden_img_name="test_textured_mesh.png", legacy_flipped_v=False)
async def test_textured_mesh_intersection(self):
"""Click on the different polygon mesh to get the s and t"""
await self.create_test_area(width=1440, height=900, block_devices=False)
self.intersection = False
self.face_id = -1
self.u = -1.0
self.v = -1.0
self.s = -1.0
self.t = -1.0
def _on_shape_clicked(shape):
"""Called when the user clicks the point"""
self.intersection = True
self.face_id = shape.gesture_payload.face_id
self.u = shape.gesture_payload.u
self.v = shape.gesture_payload.v
self.s = shape.gesture_payload.s
self.t = shape.gesture_payload.t
window = ui.Window("test_textured_mesh_intersection", width=700, height=700)
proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0]
view = sc.Matrix44.get_translation_matrix(0, 0, -6)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
select = sc.ClickGesture(_on_shape_clicked)
# Form the mesh data
point_count = 4
points = [
[-3, -3, 0],
[3, -3, 0],
[3, 3, 0],
[-3, 3, 0],
[-3, -6, 0],
[3, -6, 0],
[3, -3, 0],
[-3, -3, 0],
]
vertex_indices = [0, 1, 2, 3, 4, 5, 6, 7]
colors = [
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
]
filename = f"{CURRENT_PATH}/main_ov_logo_square.png"
uvs = [[0, 1], [1, 1], [1, 0], [0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]
sc.TexturedMesh(
filename, uvs, points, colors, [point_count, point_count], vertex_indices, gesture=select
)
await ui_test.wait_n_updates(10)
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(580, 130))
await ui_test.wait_n_updates(10)
self.assertEqual(self.face_id, 0)
self.assertAlmostEqual(self.u, 0.03333332762122154)
self.assertAlmostEqual(self.v, 0.18000000715255737)
self.assertAlmostEqual(self.s, 0.03333332818826966)
self.assertAlmostEqual(self.t, 0.8200000000000001)
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(850, 500))
await ui_test.wait_n_updates(10)
self.assertEqual(self.face_id, 1)
self.assertAlmostEqual(self.u, 0.9333333373069763)
self.assertAlmostEqual(self.v, 0.8266666680574417)
self.assertAlmostEqual(self.s, 0.9333333381108925)
self.assertAlmostEqual(self.t, 0.17333333333333378)
async def test_linear_curve(self):
window = await self.create_test_window(width=512, height=512)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150)
with scene_view.scene:
sc.Curve(
[[-2.5, -1.0, 0], [-1.5, -1.0, 0], [-1.5, -2.0, 0], [1.0, 0.5, 0]],
curve_type=sc.Curve.CurveType.LINEAR,
colors=[cl.yellow, cl.blue, cl.yellow, cl.green],
thicknesses=[3.0, 1.5, 3.0, 3],
)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_curve_properties(self):
"""test with different colors and thicknesses"""
window = await self.create_test_window(width=600, height=800)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150)
with scene_view.scene:
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-4, 0, 0)):
sc.Curve(
[[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]],
thicknesses=[1.0, 2.0, 3.0, 4.0],
curve_type=sc.Curve.CurveType.LINEAR,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-4, -2, 0)):
sc.Curve(
[[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]],
colors=[cl.red],
thicknesses=[1.0, 2.0, 3.0],
curve_type=sc.Curve.CurveType.LINEAR,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-4, -4, 0)):
sc.Curve(
[[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]],
colors=[cl.red, cl.blue],
thicknesses=[1.0, 2.0],
curve_type=sc.Curve.CurveType.LINEAR,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-4, -6, 0)):
sc.Curve(
[[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]],
colors=[cl.red, [0, 1, 0, 1], cl.blue],
thicknesses=[1.5],
tessellation=7,
curve_type=sc.Curve.CurveType.LINEAR,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-4, -8, 0)):
sc.Curve(
[[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]],
colors=[cl.red, [0, 1, 0, 1], cl.blue, cl.yellow],
tessellation=7,
curve_type=sc.Curve.CurveType.LINEAR,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 0, 0)):
sc.Curve(
[[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]],
thicknesses=[1.0, 2.0, 3.0, 4.0],
tessellation=4,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, -2, 0)):
sc.Curve(
[[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]],
colors=[cl.red],
thicknesses=[1.0, 2.0, 3.0],
tessellation=4,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, -4, 0)):
sc.Curve(
[[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]],
colors=[cl.red, cl.blue],
thicknesses=[1.0, 2.0],
tessellation=4,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, -6, 0)):
sc.Curve(
[[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]],
colors=[cl.red, [0, 1, 0, 1], cl.blue],
thicknesses=[1.5],
tessellation=4,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, -8, 0)):
sc.Curve(
[[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]],
colors=[cl.red, [0, 1, 0, 1], cl.blue, cl.yellow],
tessellation=4,
)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_curve_intersection_linear(self):
"""Click different segments of the curve sets the curve to different colors"""
def _on_shape_clicked(shape):
"""Called when the user clicks the point"""
shape.colors = [cl.yellow]
window = await self.create_test_window(width=512, height=256)
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
select = sc.ClickGesture(_on_shape_clicked)
mouse_action_sequence = [(0, 0, 0), (1, 1, 0)] + [(0, 1, 0)] * 10 + [(0, 0, 1), (0, 0, 0)]
mouse_position_sequence = [(-0.023809523809523836, -0.19333333333333336)] * 14
select.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
sc.Curve(
[[-2.5, -1.0, 0], [-1.5, -1.0, 0], [-0.5, 0, 0], [0.5, -1, 0], [1.5, -1, 0]],
curve_type=sc.Curve.CurveType.LINEAR,
gesture=select,
)
await self.wait_n_updates(30)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_curve_intersection_distance(self):
"""Click different segments of the curve sets the curve to different colors"""
self.curve_distance = 0.0
def _on_shape_clicked(shape):
"""Called when the user clicks the point"""
shape.colors = [cl.red]
self.curve_distance = shape.gesture_payload.curve_distance
window = await self.create_test_window(width=512, height=256)
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
select = sc.ClickGesture(_on_shape_clicked)
mouse_action_sequence = [(0, 0, 0), (1, 1, 0)] + [(0, 1, 0)] * 5 + [(0, 0, 1)] + [(0, 0, 0)] * 100
mouse_position_sequence = [(0.0978835978835979, 0.04)] * 108
select.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
sc.Curve(
[[-1, 1.0, 0], [1, 0.2, 0], [1, -0.2, 0], [-1, -1, 0]],
thicknesses=[5.0],
colors=[cl.blue],
gesture=select,
)
await self.wait_n_updates(30)
self.assertAlmostEqual(self.curve_distance, 0.4788618615426895)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_bezier_curve(self):
window = await self.create_test_window(width=600, height=450)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150)
with scene_view.scene:
sc.Curve(
[
[-2.5, -1.0, 0],
[-1.5, 0, 0],
[-0.5, -1, 0],
[0.5, -1, 0],
[0.1, 0.6, 0],
[2.0, 0.6, 0],
[3.5, -1, 0],
],
colors=[cl.red],
thicknesses=[3.0],
curve_type=sc.Curve.CurveType.LINEAR,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, -2, 0)):
sc.Curve(
[
[-2.5, -1.0, 0],
[-1.5, 0, 0],
[-0.5, -1, 0],
[0.5, -1, 0],
[0.1, 0.6, 0],
[2.0, 0.6, 0],
[3.5, -1, 0],
],
colors=[cl.red],
thicknesses=[3.0],
tessellation=9,
)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_bezier_curve_move(self):
def move(transform: sc.Transform, shape: sc.AbstractShape):
"""Called by the gesture"""
translate = shape.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
transform.transform *= current
window = await self.create_test_window(width=600, height=256)
# Projection matrix
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
transform = sc.Transform()
with transform:
mouse_action_sequence = [
(0, 0, 0),
(1, 1, 0),
(0, 1, 0),
(0, 1, 0),
(0, 1, 0),
(0, 1, 0),
(0, 0, 1),
(0, 0, 0),
]
mouse_position_sequence = [
(0.009, 0.22667),
(0.009, 0.22667),
(0.009, 0.22667),
(0.01126, 0.22667),
(0.2207, 0.2),
(0.5157, 0.186667),
(0.5157, 0.186667),
(0.5157, 0.186667),
]
mrg = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
drag = sc.DragGesture(manager=mrg, on_changed_fn=partial(move, transform))
sc.Curve(
[[-1.5, -1.0, 0], [-0.5, 1, 0], [0.5, 0.8, 0], [1.5, -1, 0]],
colors=[cl.yellow],
thicknesses=[5.0, 1.5],
gesture=drag,
)
await self.wait_n_updates(30)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
def _curves_on_sphere(self, num_curves, num_segs):
"""generate curves points on a sphere"""
curves = []
for i in range(0, num_curves):
phi = arccos(1 - 2 * i / num_curves)
theta = pi * (1 + 5**0.5) * i
x, y, z = cos(theta) * sin(phi) + 0.5, sin(theta) * sin(phi) + 0.5, cos(phi) + 0.5
curve = []
curve.append([x, y, z])
for j in range(0, num_segs):
rx = (random.random() - 0.5) * 0.2
ry = (random.random() - 0.5) * 0.2
rz = (random.random() - 0.5) * 0.2
curve.append([x + rx, y + ry, z + rz])
curves.append(curve)
return curves
async def test_linear_curve_scalability(self):
"""we can have maximum 21 segments per curve with 10000 linear
10000 curves
21 segments per curve
which has 22 vertices per curve
"""
num_curves = 10000
num_segs = 21
curves = self._curves_on_sphere(num_curves, num_segs)
window = await self.create_test_window(width=600, height=600)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=300)
with scene_view.scene:
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-0.5, -1, 0)):
for curve in curves:
sc.Curve(
curve,
colors=[[curve[0][0], curve[0][1], curve[0][2], 1.0]],
curve_type=sc.Curve.CurveType.LINEAR,
)
await self.wait_n_updates(30)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_bezier_curve_scalability(self):
"""we can have maximum 8920 curves with 3 segments per bezier curve and default 9 tessellation
8920 curves
3 segments per curve
9 tessellation per curve
which has 25 vertices per curve
"""
num_curves = 8920
num_segs = 3
curves = self._curves_on_sphere(num_curves, num_segs)
window = await self.create_test_window(width=600, height=600)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=300)
with scene_view.scene:
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-0.5, -1, 0)):
for curve in curves:
sc.Curve(
curve,
colors=[[curve[0][0], curve[0][1], curve[0][2], 1.0]],
thicknesses=[1.0],
)
await self.wait_n_updates(30)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_bezier_segment_scalability(self):
"""we can have maximum 27 curves per bezier curve with 999 segments and default 9 tessellation
27 curves
999 segments per curve
9 tessellation per curve
which has 7993 vertices per curve
"""
num_curves = 27
num_segs = 999 # the number has to be dividable by 3
curves = []
for i in range(0, num_curves):
x = i % 6
y = int(i / 6)
z = random.random()
curve = []
curve.append([x, y, z])
for j in range(0, num_segs):
curve.append([x + random.random(), y + random.random(), z + random.random()])
curves.append(curve)
window = await self.create_test_window(width=1000, height=800)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=300)
with scene_view.scene:
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-3, -4, 0)):
for curve in curves:
sc.Curve(
curve,
colors=[[1, 1, 0, 1.0]],
thicknesses=[1.0],
)
await self.wait_n_updates(30)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_intersection_scalability(self):
"""for intersection workable, we can have maximum 3000 curves with 9 segments and 9 tessellation per curve
3000 curves
9 segments per curve
9 tessellation per curve
which has 73 vertices per curve
"""
def move(transform: sc.Transform, shape: sc.AbstractShape):
"""Called by the gesture"""
translate = shape.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
transform.transform *= current
num_curves = 3000
num_segs = 9
curves = self._curves_on_sphere(num_curves, num_segs)
mouse_action_sequence = [(0, 0, 0), (1, 1, 0)] + [(0, 1, 0)] * 40 + [(0, 0, 1)] * 20 + [(0, 0, 0)] * 10
mouse_position_sequence = (
[(0.06981981981981988, -0.7333333333333334)] * 22
+ [(0.12387387387387383, -0.8844444444444444)] * 10
+ [(0.2635135135135136, -1.511111111111111)] * 10
+ [(0.6265765765765767, -1.98844444444444444)] * 10
+ [(1.84009009009009006, -2.9977777777777776)] * 20
)
window = await self.create_test_window(width=600, height=600)
with window.frame:
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=300)
mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
with scene_view.scene:
for curve in curves:
transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(-0.5, -1, 0))
with transform:
drag = sc.DragGesture(on_changed_fn=partial(move, transform), manager=mgr)
sc.Curve(curve, colors=[[random.random(), random.random(), random.random(), 1.0]], gesture=drag)
await self.wait_n_updates(100)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_transparency(self):
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
# Background
ui.Rectangle(style={"background_color": ui.color(0.5, 0.5, 0.5)})
scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with scene_view.scene:
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0.25, 0.25, -0.1)):
sc.Rectangle(1, 1, color=ui.color(1.0, 1.0, 0.0, 0.5))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 0, 0)):
sc.Rectangle(1, 1, color=ui.color(1.0, 1.0, 1.0, 0.5))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-0.25, -0.25, 0.1)):
sc.Rectangle(1, 1, color=ui.color(1.0, 0.0, 1.0, 0.5))
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_vertexindices(self):
window = await self.create_test_window(500, 250)
with window.frame:
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
# two triangles, the first one is red and second one is blue
point_count = 3
points = [[-1, -1, 0], [2, -1, 0], [3, 1, 0], [4, 0, -1], [3, 1, 0]]
vertex_indices = [0, 1, 2, 1, 3, 2]
colors = [[1, 0, 0, 1]] * 3 + [[0, 0, 1, 1]] * 3
sc.PolygonMesh(points, colors, [point_count, point_count], vertex_indices)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_polygon_mesh_wireframe(self):
window = await self.create_test_window(500, 250)
with window.frame:
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
# two triangles, the first one is red and second one is blue
point_count = 3
points = [[-1, -1, 0], [2, -1, 0], [3, 1, 0], [4, 0, -1], [3, 1, 0]]
vertex_indices = [0, 1, 2, 1, 3, 2]
colors = [[1, 0, 0, 1]] * 3 + [[0, 0, 1, 1]] * 3
thicknesses = [3] * 6
sc.PolygonMesh(
points, colors, [point_count, point_count], vertex_indices, thicknesses=thicknesses, wireframe=True
)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 36,449 | Python | 44.223325 | 120 | 0.515213 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_widget.py | ## 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.
##
import omni.kit.test
from omni.ui_scene import scene as sc
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import carb
import omni.appwindow
import omni.kit.app
import omni.ui as ui
from omni.ui import color as cl
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
CURRENT_PATH = Path(__file__).parent.joinpath("../../../data")
class TestWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_general(self):
"""General ability to use widgets"""
window = await self.create_test_window()
with window.frame:
# Camera matrices
projection = [1e-2, 0, 0, 0]
projection += [0, 1e-2, 0, 0]
projection += [0, 0, 2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -5)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
transform = sc.Matrix44.get_translation_matrix(0, 0, 0)
transform *= sc.Matrix44.get_scale_matrix(0.4, 0.4, 0.4)
with sc.Transform(transform=transform):
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
widget = sc.Widget(500, 500, update_policy=sc.Widget.UpdatePolicy.ON_DEMAND)
with widget.frame:
ui.Label("Hello world", style={"font_size": 100})
await self.wait_n_updates(2)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_resolution(self):
"""General ability to use widgets"""
window = await self.create_test_window()
with window.frame:
# Camera matrices
projection = [1e-2, 0, 0, 0]
projection += [0, 1e-2, 0, 0]
projection += [0, 0, 2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -5)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
transform = sc.Matrix44.get_translation_matrix(0, 0, 0)
transform *= sc.Matrix44.get_scale_matrix(0.4, 0.4, 0.4)
with sc.Transform(transform=transform):
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
widget = sc.Widget(500, 500, update_policy=sc.Widget.UpdatePolicy.ON_DEMAND)
with widget.frame:
ui.Label("Hello world", style={"font_size": 100}, word_wrap=True)
await self.wait_n_updates(2)
widget.resolution_width = 250
widget.resolution_height = 250
await self.wait_n_updates(2)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_transparency(self):
"""General ability to use widgets"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
# Background
ui.Rectangle(style={"background_color": ui.color(0.5, 0.5, 0.5)})
# Camera matrices
projection = [1e-2, 0, 0, 0]
projection += [0, 1e-2, 0, 0]
projection += [0, 0, 2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -5)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
transform = sc.Matrix44.get_translation_matrix(0, 0, 0)
transform *= sc.Matrix44.get_scale_matrix(0.3, 0.3, 0.3)
with sc.Transform(transform=transform):
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
widget = sc.Widget(500, 500, update_policy=sc.Widget.UpdatePolicy.ON_DEMAND)
with widget.frame:
with ui.VStack():
ui.Label("NVIDIA", style={"font_size": 100, "color": ui.color(1.0, 1.0, 1.0, 0.5)})
ui.Label("NVIDIA", style={"font_size": 100, "color": ui.color(0.0, 0.0, 0.0, 0.5)})
ui.Label("NVIDIA", style={"font_size": 100, "color": ui.color(1.0, 1.0, 1.0, 1.0)})
await self.wait_n_updates(2)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_click(self):
"""General ability to use mouse with widgets"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
was_clicked = [False]
was_pressed = [False, False, False]
was_released = [False, False, False]
def click():
was_clicked[0] = True
def press(x, y, b, m):
was_pressed[b] = True
def release(x, y, b, m):
was_released[b] = True
with window.frame:
# Camera matrices
projection = [1e-2, 0, 0, 0]
projection += [0, 1e-2, 0, 0]
projection += [0, 0, 2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -5)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
transform = sc.Matrix44.get_translation_matrix(0, 0, 0)
transform *= sc.Matrix44.get_scale_matrix(0.4, 0.4, 0.4)
with sc.Transform(transform=transform):
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
widget = sc.Widget(500, 500)
with widget.frame:
# Put the button to the center
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.Button("Hello world", width=0, clicked_fn=click,
mouse_pressed_fn=press, mouse_released_fn=release)
ui.Spacer()
ui.Spacer()
ref = ui_test.WidgetRef(scene_view, "")
await self.wait_n_updates(2)
# Click in the center
await ui_test.emulate_mouse_move_and_click(ref.center)
await self.wait_n_updates(2)
self.assertTrue(was_clicked[0])
self.assertTrue(was_pressed[0])
self.assertTrue(was_released[0])
self.assertFalse(was_pressed[1])
self.assertFalse(was_released[1])
self.assertFalse(was_pressed[2])
self.assertFalse(was_released[2])
# Right-click
await ui_test.emulate_mouse_move_and_click(ref.center, right_click=True)
await self.wait_n_updates(2)
self.assertTrue(was_pressed[1])
self.assertTrue(was_released[1])
self.assertFalse(was_pressed[2])
self.assertFalse(was_released[2])
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_keyboard(self):
"""General ability to use mouse with widgets"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
# Camera matrices
projection = [1e-2 * 3, 0, 0, 0]
projection += [0, 1e-2 * 3, 0, 0]
projection += [0, 0, 2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -5)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
transform = sc.Matrix44.get_translation_matrix(0, 0, 0)
transform *= sc.Matrix44.get_scale_matrix(0.4, 0.4, 0.4)
with sc.Transform(transform=transform):
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
widget = sc.Widget(500, 500)
with widget.frame:
# Put the button to the center
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.StringField()
ui.Spacer()
ui.Spacer()
ref = ui_test.WidgetRef(scene_view, "")
await self.wait_n_updates(2)
# Click in the center
await ui_test.emulate_mouse_move_and_click(ref.center)
await self.wait_n_updates(2)
await ui_test.emulate_char_press("NVIDIA Omniverse")
await self.wait_n_updates(2)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_widget_color_not_leak(self):
class Manipulator(sc.Manipulator):
def on_build(self):
with sc.Transform(scale_to=sc.Space.SCREEN):
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
widget = sc.Widget(
100, 100, update_policy=sc.Widget.UpdatePolicy.ALWAYS
)
sc.Arc(
radius=20,
wireframe=False,
thickness=2,
tesselation=16,
color=cl.red,
)
window = await self.create_test_window(block_devices=False)
with window.frame:
projection = [1e-2, 0, 0, 0]
projection += [0, 1e-2, 0, 0]
projection += [0, 0, -2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, 5)
with sc.SceneView(sc.CameraModel(projection, view)).scene:
Manipulator()
await self.wait_n_updates(2)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 10,896 | Python | 38.625454 | 119 | 0.530195 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_transform_basis.py | ## 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.
##
__all__ = ["TestTransformBasis"]
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from omni.ui_scene import scene as sc
from omni.ui import color as cl
import carb
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
class TestTransformBasis(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_transform_basis(self):
class ConstantTransformBasis(sc.TransformBasis):
def __init__(self, x: float, y: float, z: float, **kwargs):
super().__init__(**kwargs)
self.__matrix = sc.Matrix44.get_translation_matrix(x, y, z)
def get_matrix(self):
return self.__matrix
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0]
# Move camera
rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True)
transl = sc.Matrix44.get_translation_matrix(0, -1, -6)
view = transl * rotation
with window.frame:
self.scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
positions = [0, 0, 0]
sizes = [20]
white = cl(1.0, 1.0, 1.0, 1.0)
red = cl(1.0, 0.0, 0.0, 1.0)
green = cl(0.0, 1.0, 0.0, 1.0)
blue = cl(0.0, 0.0, 1.0, 1.0)
yellow = cl(1.0, 1.0, 0.0, 1.0)
with self.scene_view.scene:
sc.Points(positions, sizes=sizes, colors=[white])
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(2, 0, 0)):
sc.Points(positions, sizes=sizes, colors=[red])
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 2, 0)):
sc.Points(positions, sizes=sizes, colors=[green])
# Now throw in a transform with a custom basis, overriding the parent transforms
with sc.Transform(basis=ConstantTransformBasis(-2, 0, 0)):
sc.Points(positions, sizes=sizes, colors=[blue])
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 2, 0)):
sc.Points(positions, sizes=sizes, colors=[yellow])
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
self.scene_view.scene.clear()
self.scene_view = None
del window
async def test_transform_basis_python_class_deleted(self):
self.was_deleted = False
def do_delete():
self.was_deleted = True
class LoggingTransformBasis(sc.TransformBasis):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.__matrix = sc.Matrix44.get_translation_matrix(0, 0, 0)
def __del__(self):
do_delete()
def get_matrix(self):
return self.__matrix
xform = sc.Transform(basis=LoggingTransformBasis())
self.assertFalse(self.was_deleted, "Python child class of sc.TransformBasis was deleted too soon")
del xform
self.assertTrue(self.was_deleted, "Python child class of sc.TransformBasis was not deleted")
del self.was_deleted
| 4,181 | Python | 35.365217 | 116 | 0.596508 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/__init__.py | # 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.
#
from .test_arc import TestArc
from .test_camera import TestCamera
from .test_shapes import TestShapes
from .test_container import TestContainer
from .test_gestures import TestGestures
from .test_manipulator import TestManipulator
from .test_widget import TestWidget
from .test_scene import TestScene
from .test_scroll import TestScroll
from .test_transform_basis import TestTransformBasis
| 817 | Python | 42.052629 | 76 | 0.824969 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_camera.py | ## 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.
##
from omni.ui.tests.test_base import OmniUiTest
from omni.ui_scene import scene as sc
from pathlib import Path
import carb
import omni.kit.test
import omni.ui as ui
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
class TestCamera(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_general(self):
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0]
# Move camera
rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True)
transl = sc.Matrix44.get_translation_matrix(0, 0, -6)
view = transl * rotation
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
# Edges of cube
sc.Line([-1, -1, -1], [1, -1, -1])
sc.Line([-1, 1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [1, -1, 1])
sc.Line([-1, 1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, 1, -1])
sc.Line([1, -1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [-1, 1, 1])
sc.Line([1, -1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, -1, 1])
sc.Line([-1, 1, -1], [-1, 1, 1])
sc.Line([1, -1, -1], [1, -1, 1])
sc.Line([1, 1, -1], [1, 1, 1])
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_distant_camera(self):
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0]
# Move camera
rotation = sc.Matrix44.get_rotation_matrix(-25, 55, 0, True)
transl = sc.Matrix44.get_translation_matrix(-10000000000, 10000000000, -20000000000)
view = transl * rotation
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200
)
with scene_view.scene:
sc.Line([-10000000000, -10000000000, -10000000000], [-2000000000, -10000000000, -10000000000])
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_camera_model(self):
class CameraModel(sc.AbstractManipulatorModel):
def __init__(self):
super().__init__()
self._angle = 0
def append_angle(self, delta: float):
self._angle += delta * 100
# Inform SceneView that view matrix is changed
self._item_changed("view")
def get_as_floats(self, item):
"""Called by SceneView to get projection and view matrices"""
if item == self.get_item("projection"):
# Projection matrix
return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0]
if item == self.get_item("view"):
# Move camera
rotation = sc.Matrix44.get_rotation_matrix(30, self._angle, 0, True)
transl = sc.Matrix44.get_translation_matrix(0, 0, -8)
view = transl * rotation
return [view[i] for i in range(16)]
def on_mouse_dragged(sender):
# Change the model's angle according to mouse x offset
mouse_moved = sender.gesture_payload.mouse_moved[0]
sender.scene_view.model.append_angle(mouse_moved)
window = await self.create_test_window(width=512, height=256)
camera_model = CameraModel()
# check initial projection and view matrix
proj = camera_model.get_as_floats(camera_model.get_item("projection"))
view = camera_model.get_as_floats(camera_model.get_item("view"))
self.assertEqual(proj, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0])
self.assertAlmostEqual(view[5], 0.866025, places=5)
self.assertAlmostEqual(view[10], 0.866025, places=5)
self.assertAlmostEqual(view[6], 0.5, places=5)
self.assertAlmostEqual(view[9], -0.5, places=5)
with window.frame:
with sc.SceneView(camera_model, height=200).scene:
# Camera control
sender = sc.Screen(gesture=sc.DragGesture(on_changed_fn=on_mouse_dragged))
# Edges of cube
sc.Line([-1, -1, -1], [1, -1, -1])
sc.Line([-1, 1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [1, -1, 1])
sc.Line([-1, 1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, 1, -1])
sc.Line([1, -1, -1], [1, 1, -1])
sc.Line([-1, -1, 1], [-1, 1, 1])
sc.Line([1, -1, 1], [1, 1, 1])
sc.Line([-1, -1, -1], [-1, -1, 1])
sc.Line([-1, 1, -1], [-1, 1, 1])
sc.Line([1, -1, -1], [1, -1, 1])
sc.Line([1, 1, -1], [1, 1, 1])
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 6,090 | Python | 39.879194 | 116 | 0.534483 |
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_gestures.py | ## 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.
##
from .gesture_manager_utils import Manager
from functools import partial
from omni.ui import color as cl
from omni.ui_scene import scene as sc
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.ui_test as ui_test
from pathlib import Path
import carb
import omni.kit
import omni.ui as ui
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
class TestGestures(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_gesture_select(self):
def _on_shape_clicked(shape):
"""Called when the user clicks the point"""
shape.color = cl.red
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=200
)
with scene_view.scene:
select = sc.ClickGesture(_on_shape_clicked)
mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)]
mouse_position_sequence = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
select.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
sc.Rectangle(color=cl.blue, gesture=select)
await self.wait_n_updates(30)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_gesture_drag(self):
class MyDragGesture(sc.DragGesture):
def __init__(self):
super().__init__()
self.began_called = False
self.changed_called = False
self.ended_called = False
def can_be_prevented(self, gesture):
return True
def on_began(self):
self.began_called = True
def on_changed(self):
self.changed_called = True
def on_ended(self):
self.ended_called = True
class PriorityManager(Manager):
"""
Manager makes the gesture high priority
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def can_be_prevented(self, gesture):
return False
def should_prevent(self, gesture, preventer):
return gesture.state == sc.GestureState.CHANGED and (
preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED
)
window = await self.create_test_window()
# Projection matrix
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
)
with scene_view.scene:
# Click, move, release in the center
drag = MyDragGesture()
# Clicked, down, released
mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)]
mouse_position_sequence = [(0, 0), (0, 0), (0, 0), (0.1, 0), (0.1, 0), (0.1, 0)]
drag.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
rectangle = sc.Rectangle(color=cl.blue, gesture=drag)
await self.wait_n_updates(30)
self.assertTrue(drag.began_called)
self.assertTrue(drag.changed_called)
self.assertTrue(drag.ended_called)
# Click, move, release on the side
drag = MyDragGesture()
mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)]
mouse_position_sequence = [(0, 0.9), (0, 0.9), (0, 0.9), (0.1, 0.9), (0.1, 0.9), (0.1, 0.9)]
drag.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
rectangle.gestures = [drag]
await self.wait_n_updates(30)
self.assertFalse(drag.began_called)
self.assertFalse(drag.changed_called)
self.assertFalse(drag.ended_called)
# Testing preventing
drag = MyDragGesture()
mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)]
mouse_position_sequence = [(0, 0), (0, 0), (0, 0), (0.1, 0), (0.1, 0), (0.1, 0)]
drag.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
rectangle.gestures = [
sc.DragGesture(manager=PriorityManager(mouse_action_sequence, mouse_position_sequence, scene_view)),
drag,
]
await self.wait_n_updates(30)
self.assertTrue(drag.began_called)
self.assertFalse(drag.changed_called)
self.assertTrue(drag.ended_called)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_gesture_callback(self):
def move(transform: sc.Transform, shape: sc.AbstractShape):
"""Called by the gesture"""
translate = shape.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
transform.transform *= current
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=200
)
mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0),(0, 1, 0), (0, 0, 1), (0, 0, 0)]
mouse_position_sequence = [(0, 0), (0, 0), (0.15, 0), (0.3, 0), (0.3, 0), (0.3, 0)]
mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Line(
[-1, 0, 0],
[1, 0, 0],
color=cl.blue,
thickness=5,
gesture=sc.DragGesture(
manager = mgr,
on_changed_fn=partial(move, transform)
)
)
await self.wait_n_updates(30)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_gesture_override(self):
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform):
super().__init__()
self.__transform = transform
def on_began(self):
self.sender.color = cl.red
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
def on_ended(self):
self.sender.color = cl.blue
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=200
)
with scene_view.scene:
transform=sc.Transform()
with transform:
move = Move(transform)
mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0),(0, 1, 0), (0, 0, 1), (0, 0, 0)]
mouse_position_sequence = [(0, 0), (0, 0), (-0.25, -0.07), (-0.6, -0.15), (-0.6, -0.15), (-0.6, -0.15)]
move.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
sc.Rectangle(color=cl.blue, gesture=move)
await self.wait_n_updates(30)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_gesture_manager(self):
class PrimeManager(Manager):
def __init__(self, mouse_action_sequence, mouse_position_sequence, scene_view):
super().__init__(mouse_action_sequence, mouse_position_sequence, scene_view)
def should_prevent(self, gesture, preventer):
# prime gesture always wins
if preventer.name == "prime":
return True
def move(transform: sc.Transform, shape: sc.AbstractShape):
"""Called by the gesture"""
translate = shape.gesture_payload.moved
current = sc.Matrix44.get_translation_matrix(*translate)
transform.transform *= current
window = await self.create_test_window(width=512, height=256)
# Projection matrix
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=200
)
mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0),(0, 1, 0), (0, 0, 1), (0, 0, 0)]
mouse_position_sequence = [(0, 0), (0, 0), (-0.25, -0.15), (-0.6, -0.3), (-0.6, -0.3), (-0.6, -0.3)]
mgr = PrimeManager(mouse_action_sequence, mouse_position_sequence, scene_view)
# create two cubes overlap with each other
# since the red one has the name of prime, it wins the gesture of move
with scene_view.scene:
transform1 = sc.Transform()
with transform1:
sc.Rectangle(
color=cl.blue,
gesture=sc.DragGesture(
manager=mgr,
on_changed_fn=partial(move, transform1)
)
)
transform2 = sc.Transform()
with transform2:
sc.Rectangle(
color=cl.red,
gesture=sc.DragGesture(
name="prime",
manager=mgr,
on_changed_fn=partial(move, transform2)
)
)
await self.wait_n_updates(30)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_hover_gesture(self):
class HoverGesture(sc.HoverGesture):
def on_began(self):
self.sender.color = cl.red
def on_ended(self):
self.sender.color = cl.blue
window = await self.create_test_window()
# Projection matrix
proj = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -1)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT
)
mouse_action_sequence = [(0, 0, 0)] * 10
# Move mouse close (2px) to the second line and after that on the
# first line. The second line will be blue, the first one is the
# red.
mouse_position_sequence = [(-0, -1)] * 2 + [(0, 0.028)] * 3 + [(0, 0)] * 5
mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
# create two cubes overlap with each other
# since the red one has the name of prime, it wins the gesture of move
with scene_view.scene:
sc.Line([-1, -1, 0], [1, 1, 0], thickness=1, gesture=HoverGesture(manager=mgr))
sc.Line([-1, 1, 0], [1, -0.9, 0], thickness=4, gesture=HoverGesture(manager=mgr))
await self.wait_n_updates(9)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_hover_gesture_trigger_on_view_hover(self):
"""Testing trigger_on_view_hover"""
class HoverGesture(sc.HoverGesture):
def __init__(self, manager):
super().__init__(trigger_on_view_hover=True, manager=manager)
def on_began(self):
self.sender.color = cl.red
def on_ended(self):
self.sender.color = cl.blue
window = await self.create_test_window()
# Projection matrix
proj = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -1)
with window.frame:
# The same setup like in test_hover_gesture, but we have ZStack on top
with ui.ZStack():
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT
)
ui.ZStack(content_clipping=1)
mouse_action_sequence = [(0, 0, 0)] * 10
mouse_position_sequence = [(-0, -1)] * 2 + [(0, 0.028)] * 3 + [(0, 0)] * 5
mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
with scene_view.scene:
sc.Line([-1, -1, 0], [1, 1, 0], thickness=1, gesture=HoverGesture(manager=mgr))
sc.Line([-1, 1, 0], [1, -0.9, 0], thickness=4, gesture=HoverGesture(manager=mgr))
await self.wait_n_updates(9)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_intersection_thickness(self):
class HoverGesture(sc.HoverGesture):
def on_began(self):
self.sender.color = cl.red
def on_ended(self):
self.sender.color = cl.blue
window = await self.create_test_window()
# Projection matrix
proj = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -1)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT
)
mouse_action_sequence = [(0, 0, 0)] * 10
# Move mouse close (about 4px) to the second line and after that on
# the first line. The second line will be blue, the first one is the
# red.
mouse_position_sequence = [(-0, -1)] * 2 + [(0, 0.43)] * 3 + [(0, 0)] * 5
mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
# create two cubes overlap with each other
# since the red one has the name of prime, it wins the gesture of move
with scene_view.scene:
sc.Line([-1, -1, 0], [1, 1, 0], thickness=1, gesture=HoverGesture(manager=mgr))
sc.Line(
[-1, 1, 0], [1, 0, 0], thickness=1, intersection_thickness=8, gesture=HoverGesture(manager=mgr)
)
await self.wait_n_updates(9)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_hover_smallscale(self):
# Flag that it was hovered
hovered = [0, 0]
class HoverGesture(sc.HoverGesture):
def __init__(self, manager: sc.GestureManager):
super().__init__(manager=manager)
def on_began(self):
if isinstance(self.sender, sc.Line):
hovered[0] = 1
elif isinstance(self.sender, sc.Rectangle):
hovered[1] = 1
self.sender.color = [0, 0, 1, 1]
def on_ended(self):
self.sender.color = [1, 1, 1, 1]
class SmallScale(sc.Manipulator):
def __init__(self, manager: sc.GestureManager):
super().__init__()
self.manager = manager
def on_build(self):
transform = sc.Matrix44.get_translation_matrix(-0.01, 0, 0)
with sc.Transform(transform=transform):
sc.Line([0, 0.005, 0], [0, 0.01, 0], gestures=HoverGesture(manager=self.manager))
sc.Rectangle(0.01, 0.01, gestures=HoverGesture(manager=self.manager))
window = await self.create_test_window()
proj = [
4.772131,
0.000000,
0.000000,
0.000000,
0.000000,
7.987040,
0.000000,
0.000000,
0.000000,
0.000000,
-1.002002,
-1.000000,
0.000000,
0.000000,
-0.200200,
0.000000,
]
view = [
0.853374,
-0.124604,
0.506188,
0.000000,
-0.000000,
0.971013,
0.239026,
0.000000,
-0.521299,
-0.203979,
0.828638,
0.000000,
0.008796,
-0.003659,
-0.198528,
1.000000,
]
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT
)
mouse_action_sequence = [(0, 0, 0)] * 10
# Move mouse close (about 4px) to the second line and after that on
# the first line. The second line will be blue, the first one is the
# red.
mouse_position_sequence = [(-0, -1)] * 2 + [(0, 0)] * 3 + [(0, 0.1)] * 5
mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
with scene_view.scene:
SmallScale(mgr)
await self.wait_n_updates(9)
self.assertTrue(hovered[0])
self.assertTrue(hovered[1])
await self.finalize_test_no_image()
async def test_gesture_click(self):
single_click, double_click = False, False
def _on_shape_clicked(shape):
nonlocal single_click
single_click = True
def _on_shape_double_clicked(shape):
nonlocal double_click
double_click = True
window = await self.create_test_window(width=1440, height=900, block_devices=False)
# Projection matrix
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=200
)
with scene_view.scene:
click_1 = sc.ClickGesture(_on_shape_clicked)
click_2 = sc.DoubleClickGesture(_on_shape_double_clicked)
sc.Rectangle(color=cl.blue, gestures=[click_1, click_2])
await self.wait_n_updates(15)
single_click, double_click = False, False
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(720, 100), double=False)
await self.wait_n_updates(15)
self.assertTrue(single_click)
self.assertFalse(double_click)
await self.wait_n_updates(15)
single_click, double_click = False, False
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(720, 100), double=True)
await self.wait_n_updates(15)
self.assertTrue(double_click)
self.assertFalse(single_click)
async def test_raw_input(self):
class MyDragGesture(sc.DragGesture):
def __init__(self):
super().__init__()
self.inputs = []
def on_began(self):
self.inputs.append(self.raw_input)
def on_changed(self):
self.inputs.append(self.raw_input)
def on_ended(self):
self.inputs.append(self.raw_input)
window = await self.create_test_window()
# Projection matrix
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
)
with scene_view.scene:
# Click, move, release in the center
drag = MyDragGesture()
# Clicked, down, released
mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)]
mouse_position_sequence = [(0, 0), (0, 0), (0, 0), (0.1, 0), (0.1, 0), (0.1, 0)]
drag.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view)
sc.Rectangle(color=cl.blue, gesture=drag)
for _ in range(30):
await omni.kit.app.get_app().next_update_async()
self.assertEqual(len(drag.inputs), 3)
self.assertEqual(drag.inputs[0].mouse_origin, drag.inputs[1].mouse_origin)
self.assertEqual(drag.inputs[1].mouse_origin, drag.inputs[2].mouse_origin)
for i in drag.inputs:
self.assertEqual(i.mouse_direction, sc.Vector3(0, 0, 1))
await self.finalize_test_no_image()
async def test_check_mouse_moved_off(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
proj = [0.3, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
with ui.ZStack():
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
)
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform):
super().__init__(check_mouse_moved=False)
self.__transform = transform
def on_began(self):
self.sender.color = cl.red
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
def on_ended(self):
self.sender.color = cl.blue
with scene_view.scene:
transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 0, -1))
with transform:
sc.Rectangle(color=cl.blue, gesture=Move(transform))
with sc.Transform(transform=sc.Matrix44.get_scale_matrix(3, 3, 3)):
sc.Rectangle(color=cl.grey)
scene_view_ref = ui_test.WidgetRef(scene_view, "")
await ui_test.wait_n_updates()
await ui_test.input.emulate_mouse(MouseEventType.MOVE, scene_view_ref.center)
# Press mouse button
await ui_test.wait_n_updates()
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN)
# Move camera
await ui_test.wait_n_updates()
view *= sc.Matrix44.get_translation_matrix(0, 1.0, 0)
scene_view.model = sc.CameraModel(proj, view)
# Release mouse button
await ui_test.wait_n_updates()
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP)
await ui_test.wait_n_updates()
await self.finalize_test()
async def test_check_mouse_moved_on(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
proj = [0.3, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, -10)
with window.frame:
with ui.ZStack():
scene_view = sc.SceneView(
sc.CameraModel(proj, view),
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
)
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform):
super().__init__(check_mouse_moved=True)
self.__transform = transform
def on_began(self):
self.sender.color = cl.red
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
def on_ended(self):
self.sender.color = cl.blue
with scene_view.scene:
transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 0, -1))
with transform:
sc.Rectangle(color=cl.blue, gesture=Move(transform))
with sc.Transform(transform=sc.Matrix44.get_scale_matrix(3, 3, 3)):
sc.Rectangle(color=cl.grey)
scene_view_ref = ui_test.WidgetRef(scene_view, "")
await ui_test.wait_n_updates()
await ui_test.input.emulate_mouse(MouseEventType.MOVE, scene_view_ref.center)
# Press mouse button
await ui_test.wait_n_updates()
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN)
# Move camera
await ui_test.wait_n_updates()
view *= sc.Matrix44.get_translation_matrix(0, 1.0, 0)
scene_view.model = sc.CameraModel(proj, view)
# Release mouse button
await ui_test.wait_n_updates()
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP)
await ui_test.wait_n_updates()
await self.finalize_test()
async def test_check_no_crash(self):
class ClickGesture(sc.ClickGesture):
def __init__(self, *args, **kwargs):
# Passing `self` while using `super().__init__` is legal python, but not correct.
# However, it shouldn't crash.
super().__init__(self, *args, **kwargs)
with self.assertRaises(TypeError) as cm:
self.assertTrue(bool(ClickGesture()))
await self.finalize_test_no_image()
| 27,877 | Python | 38.655761 | 123 | 0.5431 |
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/style.py | from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons")
fl.welcome_extensions_scroll_size = 10
EXTENSIONS_PAGE_STYLE = {
"Extensions.Label": {"color": cl.welcome_label},
"Extensions.Button": {
"padding": 0,
"background_color": cl.welcome_content_background,
"stack_direction": ui.Direction.LEFT_TO_RIGHT,
},
"Extensions.Button.Label": {"color": cl.welcome_label},
"Extensions.Button.Image::refresh": {"image_url": f"{ICON_PATH}/refresh.svg", "color": cl.welcome_label},
"Extensions.Button.Image::update": {"image_url": f"{ICON_PATH}/update_all.svg", "color": cl.welcome_label},
"Extensions.Frame": {
"background_color": cl.transparent,
"secondary_color": 0xFF666666,
"border_radius": 0,
"scrollbar_size": 10,
},
"Card.Background": {"border_radius": 10, "border_width": 1, "border_color": 0xFF707070, "background_color": 0xFF2E2C29},
"Card.Name": {"color": 0xFF38B583, "font_size": 16},
"Card.Icon": {"padding": 0, "margin": 0},
"Card.Version": {"color": cl.welcome_label, "font_size": 10},
"Card.Description": {"color": cl.welcome_label, "font_size": 16},
"Card.Button": {"border_radius": 4, "background_color": 0xFF38B583, "margin": 10},
"Card.Button.Label": {"color": 0xFFD9F1E8},
}
| 1,471 | Python | 38.783783 | 124 | 0.647179 |
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/extension.py | import carb
import omni.ext
import omni.ui as ui
from omni.kit.welcome.window import register_page
from omni.ui import constant as fl
from .extensions_widget import ExtensionsWidget
from .style import EXTENSIONS_PAGE_STYLE, ICON_PATH
_extension_instance = None
class ExtensionsPageExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self.__ext_name = omni.ext.get_extension_name(ext_id)
register_page(self.__ext_name, self.build_ui)
def on_shutdown(self):
global _extension_instance
_extension_instance = None
def build_ui(self) -> None:
with ui.ZStack(style=EXTENSIONS_PAGE_STYLE):
# Background
ui.Rectangle(style_type_name_override="Content")
with ui.VStack():
with ui.VStack(height=fl._find("welcome_page_title_height")):
ui.Spacer()
with ui.HStack():
ui.Spacer()
ui.Button(
text="Open Extension Manager",
image_url=f"{ICON_PATH}/external_link.svg",
width=0,
spacing=10,
clicked_fn=self.__show_extension_manager,
style_type_name_override="Title.Button"
)
ui.Spacer()
ui.Spacer()
ExtensionsWidget()
def __show_extension_manager(self):
try:
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate("omni.kit.window.extensions", True)
from omni.kit.window.extensions import get_instance as get_extensions_instance
inst_ref = get_extensions_instance()
inst_ref().show_window(True)
except Exception as e:
carb.log_warn(f"Failed to show extension manager: {e}")
| 1,979 | Python | 35.666666 | 90 | 0.554826 |
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/extensions_widget.py | from typing import List
import omni.kit.app
import omni.ui as ui
from omni.ui import constant as fl
from .extensions_model import ExtensionItem, ExtensionsModel
class ExtensionCard:
def __init__(self, item: ExtensionItem):
self._item = item
self._build_ui()
def _build_ui(self):
ICON_SIZE = 40
with ui.ZStack(height=80):
ui.Rectangle(style_type_name_override="Card.Background")
with ui.HStack():
with ui.HStack(width=250):
with ui.VStack(width=52):
ui.Spacer()
#with ui.Frame(height=ICON_SIZE, width=ICON_SIZE):
# ui.Image(self._item.icon, style_type_name_override="Card.Icon")
with ui.HStack():
ui.Spacer()
ui.Image(self._item.icon, width=ICON_SIZE, height=ICON_SIZE, style_type_name_override="Card.Icon")
ui.Spacer()
ui.Label(f"v{self._item.version}", alignment=ui.Alignment.CENTER, style_type_name_override="Card.Version")
ui.Spacer()
ui.Label(self._item.name, alignment=ui.Alignment.LEFT_CENTER, style_type_name_override="Card.Name")
with ui.ZStack():
ui.Label(self._item.description, alignment=ui.Alignment.LEFT_CENTER, style_type_name_override="Card.Description")
with ui.VStack(width=130):
ui.Spacer()
ui.Button("UPDATE", height=32, style_type_name_override="Card.Button", mouse_pressed_fn=lambda x, y, b, a: self.__update())
ui.Spacer()
def __update(self):
try:
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate("omni.kit.window.extensions", True)
from omni.kit.window.extensions import ext_controller
# If autoload for that one is enabled, move it to latest:
'''
# TODO:
if ext_controller.is_autoload_enabled(self._item.enabled_id):
ext_controller.toggle_autoload(self._item.enabled_id, False)
if check_can_be_toggled(self._item.latest_id, for_autoload=True):
ext_controller.toggle_autoload(self._item.latest_id, True)
'''
# If extension is enabled, switch off to latest:
if self._item.enabled:
self._toggle_extension(self._item.enabled_id, False)
self._toggle_extension(self._item.latest_id, True)
except Exception as e:
carb.log_warn(f"Faild to update {self._item.enabled_id} to {self._item.latest_id}: {e}")
def _toggle_extension(self, ext_id: str, enable: bool):
'''
# TODO:
if enable and not check_can_be_toggled(ext_id):
return False
'''
omni.kit.commands.execute("ToggleExtension", ext_id=ext_id, enable=enable)
return True
class ExtensionsWidget:
def __init__(self):
self._build_ui()
def _build_ui(self):
with ui.HStack():
ui.Spacer(width=fl._find("welcome_content_padding_x"))
with ui.VStack(spacing=5):
with ui.HStack(height=30):
ui.Spacer(width=fl._find("welcome_extensions_scroll_size"))
ui.Label("New Updates", style_type_name_override="Extensions.Label")
ui.Spacer()
ui.Button(
"CHECK FOR UPDATES",
width=0,
image_width=16,
spacing=4,
name="refresh",
style_type_name_override="Extensions.Button",
clicked_fn=self.__refresh
)
ui.Spacer(width=10)
ui.Button(
"UPDATE ALL",
width=0,
image_width=16,
spacing=4,
name="update",
style_type_name_override="Extensions.Button",
clicked_fn=self.__update_all
)
ui.Spacer(width=fl._find("welcome_extensions_scroll_size"))
with ui.HStack():
ui.Spacer(width=fl._find("welcome_extensions_scroll_size"))
self._model = ExtensionsModel()
self._frame = ui.Frame(build_fn=self._build_ext_cards)
ui.Spacer(width=fl._find("welcome_content_padding_x"))
def _build_exts(self):
self._model = ExtensionsModel()
self._frame = ui.Frame(build_fn=self._build_ext_cards)
def _build_ext_cards(self):
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="Extensions.Frame"
):
with ui.VStack(spacing=5):
for item in self._model.get_item_children(None):
ExtensionCard(item)
def __refresh(self):
self._model.refresh()
with self._frame:
self._frame.call_build_fn()
def __update_all(self):
pass
| 5,453 | Python | 40.633587 | 143 | 0.526683 |
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/extensions_model.py | import os
from functools import lru_cache
from typing import List, Optional
import omni.kit.app
import omni.ui as ui
ext_manager = None
# Sync only once for now
@lru_cache()
def _sync_registry():
ext_manager.refresh_registry()
@lru_cache()
def get_extpath_git_ext():
try:
import omni.kit.extpath.git as git_ext
return git_ext
except ImportError:
return None
class ExtensionItem(ui.AbstractItem):
def __init__(self, ext_info: dict):
super().__init__()
self.name = ext_info.get("fullname")
enabled_version = ext_info.get("enabled_version")
self.enabled_id = enabled_version.get("id")
self.version = self.__get_version(self.enabled_id)
latest_version = ext_info.get("latest_version")
self.latest_id = latest_version.get("id")
self.flags = ext_info.get("flags")
self.enabled = bool(self.flags & omni.ext.EXTENSION_SUMMARY_FLAG_ANY_ENABLED)
ext_info_local = ext_manager.get_extension_dict(self.enabled_id)
self.path = ext_info_local.get("path", "")
package_dict = ext_info_local.get("package", {})
self.icon = self.__get_icon(package_dict)
self.description = package_dict.get("description", "") or "No Description"
def __get_version(self, ext_id: str) -> str:
"""Convert 'omni.foo-tag-1.2.3' to '1.2.3'"""
a, b, *_ = ext_id.split("-") + [""]
if b and b[0:1].isdigit():
return f"{b}"
return ""
def __get_icon(self, package_dict: dict) -> str:
path = package_dict.get("icon", None)
if path:
icon_path = os.path.join(self.path, path)
if os.path.exists(icon_path):
return icon_path
return ""
class ExtensionsModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._items: List[ExtensionItem] = []
global ext_manager
app = omni.kit.app.get_app()
ext_manager = app.get_extension_manager()
self.refresh()
def get_item_children(self, item: Optional[ExtensionItem]) -> List[ExtensionItem]:
return self._items
def refresh(self):
# Refresh exts (comes from omni.kit.window.extensions)
get_extpath_git_ext.cache_clear()
_sync_registry()
ext_summaries = ext_manager.fetch_extension_summaries()
updates_exts = [
ext for ext in ext_summaries if ext["enabled_version"]["id"] and ext["enabled_version"]["id"] != ext["latest_version"]["id"]
]
self._items = [ExtensionItem(ext) for ext in updates_exts]
| 2,619 | Python | 29.823529 | 136 | 0.599847 |
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/tests/test_page.py | from pathlib import Path
import omni.kit.app
from omni.ui.tests.test_base import OmniUiTest
from ..extension import ExtensionsPageExtension
CURRENT_PATH = Path(__file__).parent
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests")
class TestPage(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_page(self):
window = await self.create_test_window(width=800, height=300)
with window.frame:
ext = ExtensionsPageExtension()
ext.on_startup("omni.kit.welcome.extensions-1.1.0")
ext.build_ui()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="page.png")
| 1,012 | Python | 30.656249 | 99 | 0.670949 |
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/tests/__init__.py | from .test_page import * | 24 | Python | 23.999976 | 24 | 0.75 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/tools.py | # 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.
#
from pathlib import Path
from typing import List
import traceback
import carb
import carb.dictionary
import carb.events
import carb.settings
import omni.kit.app
import omni.kit.context_menu
import omni.usd
from omni.kit.manipulator.tool.snap import SnapToolButton
from omni.kit.manipulator.transform.manipulator import TransformManipulator
from omni.kit.manipulator.transform.toolbar_tool import SimpleToolButton
from omni.kit.manipulator.transform.types import Operation
from .settings_constants import Constants as prim_c
from .tool_models import LocalGlobalModeModel
from .toolbar_registry import get_toolbar_registry
ICON_FOLDER_PATH = Path(
f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons"
)
TOOLS_ENABLED_SETTING_PATH = "/exts/omni.kit.manipulator.prim2.core/tools/enabled"
class SelectionPivotTool(SimpleToolButton):
# menu entry only needs to register once
__menu_entries = []
@classmethod
def register_menu(cls):
def build_placement_setting_entry(setting: str):
menu = {
"name": setting,
"checked_fn": lambda _: carb.settings.get_settings().get(prim_c.MANIPULATOR_PLACEMENT_SETTING)
== setting,
"onclick_fn": lambda _: carb.settings.get_settings().set(prim_c.MANIPULATOR_PLACEMENT_SETTING, setting),
}
return menu
menu = [
build_placement_setting_entry(s)
for s in [
prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT,
prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE,
prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER,
prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER,
prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM,
]
]
for item in menu:
cls.__menu_entries.append(omni.kit.context_menu.add_menu(item, "sel_pivot", "omni.kit.manipulator.prim"))
@classmethod
def unregister_menu(cls):
for sub in cls.__menu_entries:
sub.release()
cls.__menu_entries.clear()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# TODO assume the context is "" for VP1
self._usd_context = omni.usd.get_context(self._toolbar_payload.get("usd_context_name", ""))
self._selection = self._usd_context.get_selection()
enabled_img_url = f"{ICON_FOLDER_PATH}/pivot_location.svg"
self._build_widget(
button_name="sel_pivot",
enabled_img_url=enabled_img_url,
model=None,
menu_index="sel_pivot",
menu_extension_id="omni.kit.manipulator.prim",
no_toggle=True,
menu_on_left_click=True,
tooltip="Selection Pivot Placement",
)
# order=1 to register after prim manipulator so _on_selection_changed gets updated len of xformable_prim_paths
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop_by_type(
int(omni.usd.StageEventType.SELECTION_CHANGED),
self._on_stage_selection_event,
name="SelectionPivotTool stage event",
order=1,
)
if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED:
self._on_selection_changed()
def destroy(self):
super().destroy()
self._stage_event_sub = None
if self._model:
self._model.destroy()
self._model = None
@classmethod
def can_build(cls, manipulator: TransformManipulator, operation: Operation) -> bool:
return operation == Operation.TRANSLATE or operation == Operation.ROTATE or operation == Operation.SCALE
def _on_stage_selection_event(self, event: carb.events.IEvent):
self._on_selection_changed()
def _on_selection_changed(self):
selected_xformable_paths_count = (
len(self._manipulator.model.xformable_prim_paths) if self._manipulator.model else 0
)
if self._stack:
visible = selected_xformable_paths_count > 0
if self._stack.visible != visible:
self._stack.visible = visible
self._manipulator.refresh_toolbar()
class LocalGlobalTool(SimpleToolButton):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self._operation == Operation.TRANSLATE:
setting_path = "/app/transform/moveMode"
elif self._operation == Operation.ROTATE:
setting_path = "/app/transform/rotateMode"
else:
raise RuntimeError("Invalid operation")
self._model = LocalGlobalModeModel(setting_path)
enabled_img_url = f"{ICON_FOLDER_PATH}/transformspace_global_dark.svg"
disabled_img_url = f"{ICON_FOLDER_PATH}/transformspace_local_dark.svg"
self._build_widget(
button_name="local_global",
enabled_img_url=enabled_img_url,
disabled_img_url=disabled_img_url,
model=self._model,
tooltip="Current Transform Space: World",
disabled_tooltip="Current Transform Space: Local"
)
def destroy(self):
super().destroy()
if self._model:
self._model.destroy()
self._model = None
@classmethod
def can_build(cls, manipulator: TransformManipulator, operation: Operation) -> bool:
return operation == Operation.TRANSLATE or operation == Operation.ROTATE
class PrimManipTools:
def __init__(self):
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._toolbar_reg = get_toolbar_registry()
SelectionPivotTool.register_menu() # one time startup
self._builtin_tool_classes = {
"prim:1space": LocalGlobalTool,
"prim:2snap": SnapToolButton,
"prim:3sel_pivot": SelectionPivotTool,
}
self._registered_tool_ids: List[str] = []
self._sub = self._settings.subscribe_to_node_change_events(TOOLS_ENABLED_SETTING_PATH, self._on_setting_changed)
if self._settings.get(TOOLS_ENABLED_SETTING_PATH) is True:
self._register_tools()
self._pivot_button_group = None
# register pivot placement to "factory explorer" toolbar
app_name = omni.kit.app.get_app().get_app_filename()
if "omni.factory_explorer" in app_name:
# add manu entry to factory explorer toolbar
manager = omni.kit.app.get_app().get_extension_manager()
self._hooks = manager.subscribe_to_extension_enable(
lambda _: self._register_main_toolbar_button(),
lambda _: self._unregister_main_toolbar_button(),
ext_name="omni.explore.toolbar",
hook_name="omni.kit.manipulator.prim.pivot_placement listener",
)
def __del__(self):
self.destroy()
def destroy(self):
self._hooks = None
if self._pivot_button_group is not None:
self._unregister_main_toolbar_button()
self._unregister_tools()
if self._sub is not None:
self._settings.unsubscribe_to_change_events(self._sub)
self._sub = None
SelectionPivotTool.unregister_menu() # one time shutdown
def _register_tools(self):
for id, tool_class in self._builtin_tool_classes.items():
self._toolbar_reg.register_tool(tool_class, id)
self._registered_tool_ids.append(id)
def _unregister_tools(self):
for id in self._registered_tool_ids:
self._toolbar_reg.unregister_tool(id)
self._registered_tool_ids.clear()
def _on_setting_changed(self, item, event_type):
enabled = self._dict.get(item)
if enabled and not self._registered_tool_ids:
self._register_tools()
elif not enabled:
self._unregister_tools()
def _register_main_toolbar_button(self):
try:
if not self._pivot_button_group:
import omni.explore.toolbar
from .pivot_button_group import PivotButtonGroup
self._pivot_button_group = PivotButtonGroup()
explorer_toolbar_ext = omni.explore.toolbar.get_toolbar_instance()
explorer_toolbar_ext.toolbar.add_widget_group(self._pivot_button_group, 1)
# also add to MODIFY_TOOLS list, when menu Modify is selected
# all items in toolbar will be cleared and re-added from MODIFY_TOOLS list
explorer_tools = omni.explore.toolbar.groups.MODIFY_TOOLS
explorer_tools.append(self._pivot_button_group)
except Exception:
carb.log_warn(traceback.format_exc())
def _unregister_main_toolbar_button(self):
try:
if self._pivot_button_group:
import omni.explore.toolbar
explorer_toolbar_ext = omni.explore.toolbar.get_toolbar_instance()
explorer_toolbar_ext.toolbar.remove_widget_group(self._pivot_button_group)
# remove from MODIFY_TOOLS list as well
explorer_tools = omni.explore.toolbar.groups.MODIFY_TOOLS
if self._pivot_button_group in explorer_tools:
explorer_tools.remove(self._pivot_button_group)
self._pivot_button_group.clean()
self._pivot_button_group = None
except Exception:
carb.log_warn(traceback.format_exc())
| 10,032 | Python | 36.576779 | 120 | 0.627691 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/extension.py | # 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.
#
import omni.ext
from omni.kit.manipulator.viewport import ManipulatorFactory
from .prim_transform_manipulator import PrimTransformManipulator
from .prim_transform_manipulator_registry import TransformManipulatorRegistry
from .reference_prim_marker import ReferencePrimMarker
from .tools import PrimManipTools
class ManipulatorPrim(omni.ext.IExt):
def on_startup(self, ext_id):
self._tools = PrimManipTools()
# For VP1
self._legacy_manipulator = PrimTransformManipulator()
self._legacy_marker = ManipulatorFactory.create_manipulator(
ReferencePrimMarker, usd_context_name="", manipulator_model=self._legacy_manipulator.model, legacy=True
)
# For VP2
self._manipulator_registry = TransformManipulatorRegistry()
def on_shutdown(self):
if self._legacy_manipulator is not None:
self._legacy_manipulator.destroy()
self._legacy_manipulator = None
if self._legacy_marker is not None:
ManipulatorFactory.destroy_manipulator(self._legacy_marker)
self._legacy_marker = None
if self._manipulator_registry is not None:
self._manipulator_registry.destroy()
self._manipulator_registry = None
if self._tools is not None:
self._tools.destroy()
self._tools = None
| 1,788 | Python | 36.270833 | 115 | 0.714765 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/__init__.py | from .extension import *
from .model import *
from .toolbar_registry import *
| 78 | Python | 18.749995 | 31 | 0.75641 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/prim_transform_manipulator.py | # 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.
#
import copy
from typing import List, Union
import carb.dictionary
import carb.events
import carb.settings
import omni.ext
import omni.usd
from omni.kit.manipulator.selector import ManipulatorBase
from omni.kit.manipulator.tool.snap import SnapProviderManager
from omni.kit.manipulator.tool.snap import settings_constants as snap_c
from omni.kit.manipulator.transform import get_default_style
from omni.kit.manipulator.transform.manipulator import TransformManipulator
from omni.kit.manipulator.transform.settings_constants import c
from omni.kit.manipulator.transform.settings_listener import OpSettingsListener, SnapSettingsListener
from omni.kit.manipulator.viewport import ManipulatorFactory
from pxr import Sdf, Usd, UsdGeom
from .model import PrimRotateChangedGesture, PrimScaleChangedGesture, PrimTransformModel, PrimTranslateChangedGesture
from .toolbar_registry import get_toolbar_registry
TRANSFORM_GIZMO_HIDDEN_OVERRIDE = "/app/transform/gizmoHiddenOverride"
class PrimTransformManipulator(ManipulatorBase):
def __init__(
self,
usd_context_name: str = "",
viewport_api=None,
name="omni.kit.manipulator.prim2.core",
model: PrimTransformModel = None,
size: float = 1.0,
):
super().__init__(name=name, usd_context_name=usd_context_name)
self._dict = carb.dictionary.get_dictionary()
self._settings = carb.settings.get_settings()
self._usd_context = omni.usd.get_context(usd_context_name)
self._selection = self._usd_context.get_selection()
self._model_is_external = model is not None
self._model = model if self._model_is_external else PrimTransformModel(usd_context_name, viewport_api)
self._legacy_mode = viewport_api is None # if no viewport_api is supplied, it is from VP1
self._snap_manager = SnapProviderManager(viewport_api=viewport_api)
if self._legacy_mode:
self._manipulator = ManipulatorFactory.create_manipulator(
TransformManipulator,
size=size,
model=self._model,
enabled=False,
gestures=[
PrimTranslateChangedGesture(
self._snap_manager, usd_context_name=usd_context_name, viewport_api=viewport_api
),
PrimRotateChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api),
PrimScaleChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api),
],
tool_registry=get_toolbar_registry(),
)
else:
self._manipulator = TransformManipulator(
size=size,
model=self._model,
enabled=False,
gestures=[
PrimTranslateChangedGesture(
self._snap_manager, usd_context_name=usd_context_name, viewport_api=viewport_api
),
PrimRotateChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api),
PrimScaleChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api),
],
tool_registry=get_toolbar_registry(),
tool_button_additional_payload={"viewport_api": viewport_api, "usd_context_name": usd_context_name},
)
# Hide the old C++ imguizmo when omni.ui.scene manipulator is enabled
self._prev_transform_hidden_override = self._settings.get(TRANSFORM_GIZMO_HIDDEN_OVERRIDE)
self._settings.set(TRANSFORM_GIZMO_HIDDEN_OVERRIDE, True)
self._set_default_settings()
self._create_local_global_styles()
self._op_settings_listener = OpSettingsListener()
self._op_settings_listener_sub = self._op_settings_listener.subscribe_listener(self._on_op_listener_changed)
self._snap_settings_listener = SnapSettingsListener(
enabled_setting_path=None,
move_x_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH,
move_y_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH,
move_z_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH,
rotate_setting_path=snap_c.SNAP_ROTATE_SETTING_PATH,
scale_setting_path=snap_c.SNAP_SCALE_SETTING_PATH,
provider_setting_path=snap_c.SNAP_PROVIDER_NAME_SETTING_PATH,
)
self._snap_settings_listener_sub = self._snap_settings_listener.subscribe_listener(
self._on_snap_listener_changed
)
self._enabled: bool = self._manipulator.enabled
self._prim_style_applied: bool = False
self._set_style()
def __del__(self):
self.destroy()
def destroy(self):
super().destroy()
self._op_settings_listener_sub = None
self._snap_settings_listener_sub = None
if self._op_settings_listener:
self._op_settings_listener.destroy()
self._op_settings_listener = None
if self._manipulator:
if self._legacy_mode:
ManipulatorFactory.destroy_manipulator(self._manipulator)
else:
self._manipulator.destroy()
self._manipulator = None
if self._model and not self._model_is_external:
self._model.destroy()
self._model = None
if self._snap_manager:
self._snap_manager.destroy()
self._snap_manager = None
# restore imguizmo visibility
self._settings.set(TRANSFORM_GIZMO_HIDDEN_OVERRIDE, self._prev_transform_hidden_override)
@property
def model(self) -> PrimTransformModel:
return self._model
@property
def snap_manager(self) -> SnapProviderManager:
return self._snap_manager
@property
def enabled(self):
return self._manipulator.enabled
@enabled.setter
def enabled(self, value: bool):
if value != self._enabled:
self._enabled = value
self._update_manipulator_enable()
def _set_default_settings(self):
self._settings.set_default_string(c.TRANSFORM_OP_SETTING, c.TRANSFORM_OP_MOVE)
self._settings.set_default_string(c.TRANSFORM_MOVE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL)
self._settings.set_default_string(c.TRANSFORM_ROTATE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL)
def _create_local_global_styles(self):
COLOR_LOCAL = 0x8A248AE3
local_style = get_default_style()
local_style["Translate.Point"]["color"] = COLOR_LOCAL
local_style["Rotate.Arc::screen"]["color"] = COLOR_LOCAL
local_style["Scale.Point"]["color"] = COLOR_LOCAL
self._styles = {c.TRANSFORM_MODE_GLOBAL: get_default_style(), c.TRANSFORM_MODE_LOCAL: local_style}
self._snap_styles = copy.deepcopy(self._styles)
self._snap_styles[c.TRANSFORM_MODE_GLOBAL]["Translate.Focal"]["visible"] = True
self._snap_styles[c.TRANSFORM_MODE_LOCAL]["Translate.Focal"]["visible"] = True
def on_selection_changed(self, stage: Usd.Stage, selection: Union[List[Sdf.Path], None], *args, **kwargs) -> bool:
if selection is None:
if self.model:
self.model.on_selection_changed([])
return False
if self.model:
self.model.on_selection_changed(selection)
for path in selection:
prim = stage.GetPrimAtPath(path)
if prim.IsA(UsdGeom.Xformable):
return True
return False
def _update_manipulator_enable(self) -> None:
if not self._manipulator:
return
is_enabled: bool = self._prim_style_applied and self._enabled
if not self._manipulator.enabled and is_enabled:
self._manipulator.enabled = True
elif self._manipulator.enabled and not is_enabled:
self._manipulator.enabled = False
def _set_style(self) -> None:
def set_manipulator_style(styles, mode: str):
# An unknown style will return false here.
if mode in styles:
self._manipulator.style = styles[mode]
return True
else:
return False
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE:
styles = (
self._snap_styles
if self._snap_settings_listener.snap_enabled and self._snap_settings_listener.snap_to_surface
else self._styles
)
self._prim_style_applied = set_manipulator_style(styles, self._op_settings_listener.translation_mode)
elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE:
self._prim_style_applied = set_manipulator_style(self._styles, self._op_settings_listener.rotation_mode)
elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_SCALE:
self._prim_style_applied = set_manipulator_style(self._styles, c.TRANSFORM_MODE_LOCAL)
else:
# unknown op disables.
self._prim_style_applied = False
self._update_manipulator_enable()
def _on_op_listener_changed(self, type: OpSettingsListener.CallbackType, value: str):
if (
type == OpSettingsListener.CallbackType.OP_CHANGED
or type == OpSettingsListener.CallbackType.TRANSLATION_MODE_CHANGED
or type == OpSettingsListener.CallbackType.ROTATION_MODE_CHANGED
):
self._set_style()
def _on_snap_listener_changed(self, setting_val_name: str, value: str):
if setting_val_name == "snap_enabled" or setting_val_name == "snap_to_surface":
self._set_style()
| 10,126 | Python | 41.372385 | 118 | 0.644381 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/tool_models.py | # 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.
#
import carb
import carb.dictionary
import carb.settings
import omni.ui as ui
class LocalGlobalModeModel(ui.AbstractValueModel):
TRANSFORM_MODE_GLOBAL = "global"
TRANSFORM_MODE_LOCAL = "local"
def __init__(self, op_space_setting_path):
super().__init__()
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._setting_path = op_space_setting_path
self._op_space_sub = self._settings.subscribe_to_node_change_events(
self._setting_path, self._on_op_space_changed
)
self._op_space = self._settings.get(self._setting_path)
def __del__(self):
self.destroy()
def destroy(self):
if self._op_space_sub is not None:
self._settings.unsubscribe_to_change_events(self._op_space_sub)
self._op_space_sub = None
def _on_op_space_changed(self, item, event_type):
self._op_space = self._dict.get(item)
self._value_changed()
def get_value_as_bool(self):
return self._op_space != self.TRANSFORM_MODE_LOCAL
def set_value(self, value):
self._settings.set(
self._setting_path,
self.TRANSFORM_MODE_LOCAL if value == False else self.TRANSFORM_MODE_GLOBAL,
)
| 1,719 | Python | 32.72549 | 88 | 0.669575 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/settings_constants.py | # 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.
#
class Constants:
MANIPULATOR_PLACEMENT_SETTING = "/persistent/exts/omni.kit.manipulator.prim2.core/manipulator/placement"
MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT = "Authored Pivot"
MANIPULATOR_PLACEMENT_SELECTION_CENTER = "Selection Center"
MANIPULATOR_PLACEMENT_BBOX_BASE = "Bounding Box Base"
MANIPULATOR_PLACEMENT_BBOX_CENTER = "Bounding Box Center"
MANIPULATOR_PLACEMENT_PICK_REF_PRIM = "Pick Reference Prim"
| 865 | Python | 47.111108 | 108 | 0.788439 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/utils.py | # 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.
#
import math
from typing import List
import carb
import carb.profiler
import carb.settings
from pxr import Gf, Usd, UsdGeom
@carb.profiler.profile
def flatten(transform):
"""Convert array[4][4] to array[16]"""
# flatten the matrix by hand
# USING LIST COMPREHENSION IS VERY SLOW (e.g. return [item for sublist in transform for item in sublist]), which takes around 10ms.
m0, m1, m2, m3 = transform[0], transform[1], transform[2], transform[3]
return [
m0[0],
m0[1],
m0[2],
m0[3],
m1[0],
m1[1],
m1[2],
m1[3],
m2[0],
m2[1],
m2[2],
m2[3],
m3[0],
m3[1],
m3[2],
m3[3],
]
@carb.profiler.profile
def get_local_transform_pivot_inv(prim: Usd.Prim, time: Usd.TimeCode = Usd.TimeCode):
xform = UsdGeom.Xformable(prim)
xform_ops = xform.GetOrderedXformOps()
if len(xform_ops):
pivot_op_inv = xform_ops[-1]
if (
pivot_op_inv.GetOpType() == UsdGeom.XformOp.TypeTranslate
and pivot_op_inv.IsInverseOp()
and pivot_op_inv.GetName().endswith("pivot")
):
return pivot_op_inv.GetOpTransform(time)
return Gf.Matrix4d(1.0)
def compose_transform_ops_to_matrix(
translation: Gf.Vec3d, rotation: Gf.Vec3d, rotation_order: Gf.Vec3i, scale: Gf.Vec3d
):
axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()]
rot = []
for i in range(3):
axis_idx = rotation_order[i]
rot.append(Gf.Rotation(axes[axis_idx], rotation[axis_idx]))
rotation_mtx = Gf.Matrix4d(1.0)
rotation_mtx.SetRotate(rot[0] * rot[1] * rot[2])
valid_scale = Gf.Vec3d(0.0)
for i in range(3):
if abs(scale[i]) == 0:
valid_scale[i] = 0.001
else:
valid_scale[i] = scale[i]
scale_mtx = Gf.Matrix4d(1.0)
scale_mtx.SetScale(valid_scale)
translate_mtx = Gf.Matrix4d(1.0)
translate_mtx.SetTranslate(translation)
return scale_mtx * rotation_mtx * translate_mtx
def repeat(t: float, length: float) -> float:
return t - (math.floor(t / length) * length)
def generate_compatible_euler_angles(euler: Gf.Vec3d, rotation_order: Gf.Vec3i) -> List[Gf.Vec3d]:
equal_eulers = [euler]
mid_order = rotation_order[1]
equal = Gf.Vec3d()
for i in range(3):
if i == mid_order:
equal[i] = 180 - euler[i]
else:
equal[i] = euler[i] + 180
equal_eulers.append(equal)
for i in range(3):
equal[i] -= 360
equal_eulers.append(equal)
return equal_eulers
def find_best_euler_angles(old_rot_vec: Gf.Vec3d, new_rot_vec: Gf.Vec3d, rotation_order: Gf.Vec3i) -> Gf.Vec3d:
equal_eulers = generate_compatible_euler_angles(new_rot_vec, rotation_order)
nearest_euler = None
for euler in equal_eulers:
for i in range(3):
euler[i] = repeat(euler[i] - old_rot_vec[i] + 180.0, 360.0) + old_rot_vec[i] - 180.0
if nearest_euler is None:
nearest_euler = euler
else:
distance_1 = (nearest_euler - old_rot_vec).GetLength()
distance_2 = (euler - old_rot_vec).GetLength()
if distance_2 < distance_1:
nearest_euler = euler
return nearest_euler
| 3,734 | Python | 26.873134 | 135 | 0.61248 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/reference_prim_marker.py | # 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.
#
from __future__ import annotations
import asyncio
import colorsys
import weakref
from collections import defaultdict
from typing import DefaultDict, Dict, Set, Union
from weakref import ProxyType
import concurrent.futures
import carb
import carb.dictionary
import carb.events
import carb.profiler
import carb.settings
import omni.timeline
import omni.usd
from omni.kit.async_engine import run_coroutine
from omni.kit.manipulator.transform.style import COLOR_X, COLOR_Y, COLOR_Z, abgr_to_color
from omni.kit.manipulator.transform.settings_constants import Constants as TrCon
from omni.ui import color as cl
from omni.ui import scene as sc
from pxr import Sdf, Tf, Usd, UsdGeom
from .model import PrimTransformModel
from omni.kit.viewport.manipulator.transform import Viewport1WindowState
from .settings_constants import Constants
from .utils import flatten, get_local_transform_pivot_inv
LARGE_SELECTION_CAP = 20
class PreventViewportOthers(sc.GestureManager):
def can_be_prevented(self, gesture):
return True
def should_prevent(self, gesture, preventer):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
if issubclass(type(preventer), ClickMarkerGesture):
if issubclass(type(gesture), ClickMarkerGesture):
return gesture.gesture_payload.ray_distance > preventer.gesture_payload.ray_distance
elif isinstance(gesture, ClickMarkerGesture):
return False
else:
return True
else:
return True
return super().should_prevent(gesture, preventer)
class ClickMarkerGesture(sc.DragGesture):
def __init__(
self,
prim_path: Sdf.Path,
marker: ProxyType[ReferencePrimMarker],
):
super().__init__(manager=PreventViewportOthers())
self._prim_path = prim_path
self._marker = marker
self._vp1_window_state = None
def on_began(self):
self._viewport_on_began()
def on_canceled(self):
self._viewport_on_ended()
def on_ended(self):
self._viewport_on_ended()
self._marker.on_pivot_marker_picked(self._prim_path)
def _viewport_on_began(self):
self._viewport_on_ended()
if self._marker.legacy:
self._vp1_window_state = Viewport1WindowState()
def _viewport_on_ended(self):
if self._vp1_window_state:
self._vp1_window_state.destroy()
self._vp1_window_state = None
class MarkerHoverGesture(sc.HoverGesture):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.items = []
self._began_count = 0
self._original_colors = []
self._original_ends = []
def on_began(self):
self._began_count += 1
if self._began_count == 1:
self._original_colors = [None] * len(self.items)
self._original_ends = [None] * len(self.items)
for i, item in enumerate(self.items):
self._original_colors[i] = item.color
item.color = self._make_brighter(item.color)
if isinstance(item, sc.Line):
self._original_ends[i] = item.end
end = [dim * 1.2 for dim in item.end]
item.end = end
if isinstance(item, sc.Arc):
... # TODO change color to white, blocked by OM-56044
def on_ended(self):
self._began_count -= 1
if self._began_count <= 0:
self._began_count = 0
for i, item in enumerate(self.items):
item.color = self._original_colors[i]
if isinstance(item, sc.Line):
item.end = self._original_ends[i]
if isinstance(item, sc.Arc):
... # TODO change color back, blocked by OM-56044
def _make_brighter(self, color):
hsv = colorsys.rgb_to_hsv(color[0], color[1], color[2])
rgb = colorsys.hsv_to_rgb(hsv[0], hsv[1], hsv[2] * 1.2)
return cl(rgb[0], rgb[1], rgb[2], color[3])
class ReferencePrimMarker(sc.Manipulator):
def __init__(
self, usd_context_name: str = "", manipulator_model: ProxyType[PrimTransformModel] = None, legacy: bool = False
):
super().__init__()
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._usd_context_name = usd_context_name
self._usd_context = omni.usd.get_context(self._usd_context_name)
self._manipulator_model = manipulator_model
self._legacy = legacy
self._selection = self._usd_context.get_selection()
self._timeline = omni.timeline.get_timeline_interface()
self._current_time = self._timeline.get_current_time()
# dict from prefixes -> dict of affected markers.
self._markers: DefaultDict[Dict] = defaultdict(dict)
self._stage_listener = None
self._pending_changed_paths: Set[Sdf.Path] = set()
self._process_pending_change_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None
# order=1 to ensure the event handler is called after prim manipulator
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="ReferencePrimMarker stage event", order=1
)
self._placement_sub = self._settings.subscribe_to_node_change_events(
Constants.MANIPULATOR_PLACEMENT_SETTING, self._on_placement_changed
)
self._placement = self._settings.get(Constants.MANIPULATOR_PLACEMENT_SETTING)
self._op_sub = self._settings.subscribe_to_node_change_events(TrCon.TRANSFORM_OP_SETTING, self._on_op_changed)
self._selected_op = self._settings.get(TrCon.TRANSFORM_OP_SETTING)
def destroy(self):
self._stage_event_sub = None
if self._placement_sub:
self._settings.unsubscribe_to_change_events(self._placement_sub)
self._placement_sub = None
if self._op_sub:
self._settings.unsubscribe_to_change_events(self._op_sub)
self._op_sub = None
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
if self._process_pending_change_task_or_future and not self._process_pending_change_task_or_future.done():
self._process_pending_change_task_or_future.cancel()
self._process_pending_change_task_or_future = None
self._timeline_sub = None
@property
def usd_context_name(self) -> str:
return self._usd_context_name
@usd_context_name.setter
def usd_context_name(self, value: str):
if value != self._usd_context_name:
new_usd_context = omni.usd.get_context(value)
if not new_usd_context:
carb.log_error(f"Invalid usd context name {value}")
return
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
self._usd_context_name = value
self._usd_context = new_usd_context
# order=1 to ensure the event handler is called after prim manipulator
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="ReferencePrimMarker stage event", order=1
)
self.invalidate()
@property
def manipulator_model(self) -> ProxyType[PrimTransformModel]:
return self._manipulator_model
@manipulator_model.setter
def manipulator_model(self, value):
if value != self._manipulator_model:
self._manipulator_model = value
self.invalidate()
@property
def legacy(self) -> bool:
return self._legacy
@legacy.setter
def legacy(self, value):
self._legacy = value
def on_pivot_marker_picked(self, path: Sdf.Path):
if self._manipulator_model.set_pivot_prim_path(path):
# Hide marker on the new pivot prim and show marker on old pivot prim
old_pivot_marker = self._markers.get(self._pivot_prim_path, {}).get(self._pivot_prim_path, None)
if old_pivot_marker:
old_pivot_marker.visible = True
self._pivot_prim_path = self._manipulator_model.get_pivot_prim_path()
new_pivot_marker = self._markers.get(self._pivot_prim_path, {}).get(self._pivot_prim_path, None)
if new_pivot_marker:
new_pivot_marker.visible = False
def on_build(self):
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
self._timeline_sub = None
self._markers.clear()
if self._placement != Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM:
return
# don't build marker on "select" mode
if self._selected_op == TrCon.TRANSFORM_OP_SELECT:
return
selected_xformable_paths = self._manipulator_model.xformable_prim_paths
stage = self._usd_context.get_stage()
self._current_time = self._timeline.get_current_time()
selection_count = len(selected_xformable_paths)
# skip if there's only one xformable
if selection_count <= 1:
return
if selection_count > LARGE_SELECTION_CAP:
carb.log_warn(
f"{selection_count} is greater than the maximum selection cap {LARGE_SELECTION_CAP}, "
f"{Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM} mode will be disabled and fallback to "
f"{Constants.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT} due to performance concern."
)
return
timecode = self._get_current_time_code()
self._pivot_prim_path = self._manipulator_model.get_pivot_prim_path()
xform_cache = UsdGeom.XformCache(timecode)
for path in selected_xformable_paths:
prim = stage.GetPrimAtPath(path)
pivot_inv = get_local_transform_pivot_inv(prim, timecode)
transform = pivot_inv.GetInverse() * xform_cache.GetLocalToWorldTransform(prim)
transform.Orthonormalize() # in case of a none uniform scale
marker_transform = sc.Transform(transform=flatten(transform), visible=self._pivot_prim_path != path)
with marker_transform:
with sc.Transform(scale_to=sc.Space.SCREEN):
gesture = ClickMarkerGesture(path, marker=weakref.proxy(self))
hover_gesture = MarkerHoverGesture()
x_line = sc.Line(
(0, 0, 0),
(50, 0, 0),
color=abgr_to_color(COLOR_X),
thickness=2,
intersection_thickness=8,
gestures=[gesture, hover_gesture],
)
y_line = sc.Line(
(0, 0, 0),
(0, 50, 0),
color=abgr_to_color(COLOR_Y),
thickness=2,
intersection_thickness=8,
gestures=[gesture, hover_gesture],
)
z_line = sc.Line(
(0, 0, 0),
(0, 0, 50),
color=abgr_to_color(COLOR_Z),
thickness=2,
intersection_thickness=8,
gestures=[gesture, hover_gesture],
)
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
point = sc.Arc(
radius=6,
wireframe=False,
tesselation=8,
color=cl.white, # TODO default color grey, blocked by OM-56044
)
hover_gesture.items = [x_line, y_line, z_line, point]
prefixes = path.GetPrefixes()
for prefix in prefixes:
self._markers[prefix][path] = marker_transform
if self._markers:
self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_objects_changed, stage)
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_event
)
def _on_stage_event(self, event: carb.events.IEvent):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
if self._placement == Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM:
self.invalidate()
def _on_placement_changed(self, item, event_type):
placement = self._dict.get(item)
if placement != self._placement:
self._placement = placement
self.invalidate()
def _on_op_changed(self, item, event_type):
selected_op = self._dict.get(item)
if selected_op != self._selected_op:
if selected_op == TrCon.TRANSFORM_OP_SELECT or self._selected_op == TrCon.TRANSFORM_OP_SELECT:
self.invalidate()
self._selected_op = selected_op
def _on_timeline_event(self, e: carb.events.IEvent):
if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED):
current_time = e.payload["currentTime"]
if current_time != self._current_time:
self._current_time = current_time
if self._placement != Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM:
# TODO only invalidate transform if this prim or ancestors transforms are time varying?
self.invalidate()
@carb.profiler.profile
async def _process_pending_change(self):
processed_transforms = set()
timecode = self._get_current_time_code()
xform_cache = UsdGeom.XformCache(timecode)
stage = self._usd_context.get_stage()
for path in self._pending_changed_paths:
prim_path = path.GetPrimPath()
affected_transforms = self._markers.get(prim_path, {})
if affected_transforms:
if not UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(path.name):
continue
for path, transform in affected_transforms.items():
if transform in processed_transforms:
continue
prim = stage.GetPrimAtPath(path)
if not prim:
continue
pivot_inv = get_local_transform_pivot_inv(prim, timecode)
xform = pivot_inv.GetInverse() * xform_cache.GetLocalToWorldTransform(prim)
xform.Orthonormalize() # in case of a none uniform scale
transform_value = flatten(xform)
transform.transform = transform_value
processed_transforms.add(transform)
self._pending_changed_paths.clear()
@carb.profiler.profile
def _on_objects_changed(self, notice, sender):
self._pending_changed_paths.update(notice.GetChangedInfoOnlyPaths())
if self._process_pending_change_task_or_future is None or self._process_pending_change_task_or_future.done():
self._process_pending_change_task_or_future = run_coroutine(self._process_pending_change())
def _get_current_time_code(self):
return Usd.TimeCode(
omni.usd.get_frame_time_code(self._current_time, self._usd_context.get_stage().GetTimeCodesPerSecond())
)
| 16,316 | Python | 38.70073 | 119 | 0.59647 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/model.py | # 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.
#
from __future__ import annotations
import asyncio
import math
import traceback
from enum import Enum, Flag, IntEnum, auto
from typing import Dict, List, Sequence, Set, Tuple, Union
import concurrent.futures
import carb
import carb.dictionary
import carb.events
import carb.profiler
import carb.settings
import omni.kit.app
from omni.kit.async_engine import run_coroutine
import omni.kit.commands
import omni.kit.undo
import omni.timeline
from omni.kit.manipulator.tool.snap import SnapProviderManager
from omni.kit.manipulator.tool.snap import settings_constants as snap_c
from omni.kit.manipulator.transform import AbstractTransformManipulatorModel, Operation
from omni.kit.viewport.manipulator.transform import (
ViewportTransformModel,
DataAccessor,
DataAccessorRegistry,
ManipulationMode,
)
from omni.kit.viewport.manipulator.transform.gestures import (
ViewportTranslateChangedGesture,
ViewportRotateChangedGesture,
ViewportScaleChangedGesture,
)
from omni.kit.manipulator.transform.settings_constants import c
from omni.kit.manipulator.transform.settings_listener import OpSettingsListener, SnapSettingsListener
from omni.ui import scene as sc
from pxr import Gf, Sdf, Tf, Usd, UsdGeom, UsdUtils
from .settings_constants import Constants as prim_c
from .utils import *
# Settings needed for zero-gravity
TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED = "/app/transform/gizmoCustomManipulatorEnabled"
TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_PRIMS = "/app/transform/gizmoCustomManipulatorPrims"
TRANSFORM_GIZMO_IS_USING = "/app/transform/gizmoIsUsing"
TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ = "/app/transform/gizmoTranslateDeltaXYZ"
TRANSFORM_GIZMO_PIVOT_WORLD_POSITION = "/app/transform/tempPivotWorldPosition"
TRANSFORM_GIZMO_ROTATE_DELTA_XYZW = "/app/transform/gizmoRotateDeltaXYZW"
TRANSFORM_GIZMO_SCALE_DELTA_XYZ = "/app/transform/gizmoScaleDeltaXYZ"
TRANSLATE_DELAY_FRAME_SETTING = "/exts/omni.kit.manipulator.prim2.core/visual/delayFrame"
class OpFlag(Flag):
TRANSLATE = auto()
ROTATE = auto()
SCALE = auto()
class Placement(Enum):
LAST_PRIM_PIVOT = auto()
SELECTION_CENTER = auto()
BBOX_CENTER = auto()
REF_PRIM = auto()
BBOX_BASE = auto()
class PrimTranslateChangedGesture(ViewportTranslateChangedGesture):
def _get_model(self, payload_type) -> PrimTransformModel:
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type):
return None
return self.sender.model
class PrimRotateChangedGesture(ViewportRotateChangedGesture):
...
class PrimScaleChangedGesture(ViewportScaleChangedGesture):
...
class PrimTransformModel(ViewportTransformModel):
def __init__(self, usd_context_name: str = "", viewport_api=None):
ViewportTransformModel.__init__(self, usd_context_name=usd_context_name, viewport_api=viewport_api)
self._dataAccessor = None
self._transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] # visual transform of manipulator
self._no_scale_transform_manipulator = Gf.Matrix4d(1.0) # transform of manipulator without scale
self._scale_manipulator = Gf.Vec3d(1.0) # scale of manipulator
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._timeline = omni.timeline.get_timeline_interface()
self._app = omni.kit.app.get_app()
self._usd_context_name = usd_context_name
self._usd_context = omni.usd.get_context(usd_context_name)
self.dataAccessorRegistry = PrimDataAccessorRegistry(dataType = "USD")
self._dataAccessor = self.dataAccessorRegistry.getDataAccessor(model = self)
self._enabled_hosting_widget_count: int = 0
self._stage_listener = None
self._xformable_prim_paths: List[Sdf.Path] = []
self._xformable_prim_paths_sorted: List[Sdf.Path] = []
self._xformable_prim_paths_set: Set[Sdf.Path] = set()
self._xformable_prim_paths_prefix_set: Set[Sdf.Path] = set()
self._consolidated_xformable_prim_paths: List[Sdf.Path] = []
self._pending_changed_paths_for_xform_data: Set[Sdf.Path] = set()
self._pivot_prim: Usd.Prim = None
self._update_prim_xform_from_prim_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None
self._current_editing_op: Operation = None
self._ignore_xform_data_change = False
self._timeline_sub = None
self._pending_changed_paths: Dict[Sdf.Path, bool] = {}
self._mode = ManipulationMode.PIVOT
self._viewport_fps: float = 0.0 # needed this as heuristic for delaying the visual update of manipulator to match rendering
self._viewport_api = viewport_api
self._delay_dirty_tasks_or_futures: Dict[int, Union[asyncio.Task, concurrent.futures.Future]] = {}
self._no_scale_transform_manipulator_item = sc.AbstractManipulatorItem()
self._items["no_scale_transform_manipulator"] = self._no_scale_transform_manipulator_item
self._scale_manipulator_item = sc.AbstractManipulatorItem()
self._items["scale_manipulator"] = self._scale_manipulator_item
self._transform_manipulator_item = sc.AbstractManipulatorItem()
self._items["transform_manipulator"] = self._transform_manipulator_item
self._manipulator_mode_item = sc.AbstractManipulatorItem()
self._items["manipulator_mode"] = self._manipulator_mode_item
self._viewport_fps_item = sc.AbstractManipulatorItem()
self._items["viewport_fps"] = self._viewport_fps_item
self._set_default_settings()
# subscribe to snap events
self._snap_settings_listener = SnapSettingsListener(
enabled_setting_path=None,
move_x_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH,
move_y_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH,
move_z_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH,
rotate_setting_path=snap_c.SNAP_ROTATE_SETTING_PATH,
scale_setting_path=snap_c.SNAP_SCALE_SETTING_PATH,
provider_setting_path=snap_c.SNAP_PROVIDER_NAME_SETTING_PATH,
)
# subscribe to operation/mode events
self._op_settings_listener = OpSettingsListener()
self._op_settings_listener_sub = self._op_settings_listener.subscribe_listener(self._on_op_listener_changed)
self._placement_sub = self._settings.subscribe_to_node_change_events(
prim_c.MANIPULATOR_PLACEMENT_SETTING, self._on_placement_setting_changed
)
self._placement = Placement.LAST_PRIM_PIVOT
placement = self._settings.get(prim_c.MANIPULATOR_PLACEMENT_SETTING)
self._update_placement(placement)
# cache unique setting path for selection pivot position
# vp1 default
self._selection_pivot_position_path = TRANSFORM_GIZMO_PIVOT_WORLD_POSITION + "/Viewport"
# vp2
if self._viewport_api:
self._selection_pivot_position_path = (
TRANSFORM_GIZMO_PIVOT_WORLD_POSITION + "/" + self._viewport_api.id.split("/")[0]
)
# update setting with pivot placement position on init
self._update_temp_pivot_world_position()
def subscribe_to_value_and_get_current(setting_val_name: str, setting_path: str):
sub = self._settings.subscribe_to_node_change_events(
setting_path, lambda item, type: setattr(self, setting_val_name, self._dict.get(item))
)
setattr(self, setting_val_name, self._settings.get(setting_path))
return sub
# subscribe to zero-gravity settings
self._custom_manipulator_enabled_sub = subscribe_to_value_and_get_current(
"_custom_manipulator_enabled", TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED
)
self._warning_notification = None
self._selected_instance_proxy_paths = set()
# subscribe to USD related events
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="PrimTransformModel stage event"
)
if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED:
self._on_stage_opened()
def _on_timeline_event(self, e: carb.events.IEvent):
if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED):
current_time = e.payload["currentTime"]
if current_time != self._current_time:
self._current_time = current_time
self._dataAccessor.xform_set_time()
# TODO only update transform if this prim or ancestors transforms are time varying?
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
def _on_stage_event(self, event: carb.events.IEvent):
if event.type == int(omni.usd.StageEventType.OPENED):
self._on_stage_opened()
elif event.type == int(omni.usd.StageEventType.CLOSING):
self._on_stage_closing()
def _on_stage_opened(self):
self._dataAccessor._stage = self._usd_context.get_stage()
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_event
)
self._current_time = self._timeline.get_current_time()
self._dataAccessor.update_xform_cache()
#commands
def _on_ended_transform(
self,
paths: List[str],
new_translations: List[float],
new_rotation_eulers: List[float],
new_rotation_orders: List[int],
new_scales: List[float],
old_translations: List[float],
old_rotation_eulers: List[float],
old_rotation_orders: List[int],
old_scales: List[float],
):
self._alert_if_selection_has_instance_proxies()
self._dataAccessor._on_ended_transform(
paths,
new_translations,
new_rotation_eulers,
new_rotation_orders,
new_scales,
old_translations,
old_rotation_eulers,
old_rotation_orders,
old_scales,
)
def _do_transform_selected_prims(
self,
paths: List[str],
new_translations: List[float],
new_rotation_eulers: List[float],
new_rotation_orders: List[int],
new_scales: List[float],
):
"""Function ran by _transform_selected_prims(). Can be overridden to change the behavior
Do not remove this function: can be used outside of this code"""
self._alert_if_selection_has_instance_proxies()
self._dataAccessor._do_transform_selected_prims(
paths,
new_translations,
new_rotation_eulers,
new_rotation_orders,
new_scales
)
def _do_transform_all_selected_prims_to_manipulator_pivot(
self,
paths: List[str],
new_translations: List[float],
new_rotation_eulers: List[float],
new_rotation_orders: List[int],
new_scales: List[float],
):
"""Function ran by _transform_all_selected_prims_to_manipulator_pivot().
Can be overridden to change the behavior. Do not remove this function: can be used outside of this code"""
self._alert_if_selection_has_instance_proxies()
self._dataAccessor._do_transform_all_selected_prims_to_manipulator_pivot(
paths,
new_translations,
new_rotation_eulers,
new_rotation_orders,
new_scales
)
def __del__(self):
self.destroy()
def destroy(self):
if self._warning_notification:
self._warning_notification.dismiss()
self._warning_notification= None
self._op_settings_listener_sub = None
if self._op_settings_listener:
self._op_settings_listener.destroy()
self._op_settings_listener = None
self._stage_event_sub = None
if self._stage_listener:
self._stage_listener = self._dataAccessor.remove_update_callback(self._stage_listener)
# if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED:
self._on_stage_closing()
self._timeline_sub = None
if self._snap_settings_listener:
self._snap_settings_listener.destroy()
self._snap_settings_listener = None
if self._custom_manipulator_enabled_sub:
self._settings.unsubscribe_to_change_events(self._custom_manipulator_enabled_sub)
self._custom_manipulator_enabled_sub = None
if self._placement_sub:
self._settings.unsubscribe_to_change_events(self._placement_sub)
self._placement_sub = None
for task_or_future in self._delay_dirty_tasks_or_futures.values():
task_or_future.cancel()
self._delay_dirty_tasks_or_futures.clear()
def set_pivot_prim_path(self, path: Sdf.Path) -> bool:
if path not in self._xformable_prim_paths_set:
carb.log_warn(f"Cannot set pivot prim path to {path}")
return False
if not self._pivot_prim or self._pivot_prim.GetPath() != path:
self._pivot_prim = self._dataAccessor.get_prim_at_path(path)
else:
return False
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
return True
def get_pivot_prim_path(self) -> Sdf.Path:
if self._pivot_prim:
return self._pivot_prim.GetPath()
return None
def _update_xform_data_from_dirty_paths(self):
for p in self._pending_changed_paths_for_xform_data:
prim_path = p.GetPrimPath()
if prim_path in self.all_xformable_prim_data_curr and self._path_may_affect_transform(p):
prim = self._dataAccessor.get_prim_at_path(prim_path)
xform_tuple = self._dataAccessor.get_local_transform_SRT(prim, self._dataAccessor.get_current_time_code(self._current_time))
pivot = get_local_transform_pivot_inv(prim, self._dataAccessor.get_current_time_code(self._current_time)).GetInverse()
self.all_xformable_prim_data_curr[prim_path] = xform_tuple + (pivot,)
if prim_path in self._consolidated_xformable_prim_paths:
self.consolidated_xformable_prim_data_curr[prim_path] = xform_tuple + (pivot,)
self._pending_changed_paths_for_xform_data.clear()
def on_began(self, payload):
item = payload.changing_item
self._current_editing_op = item.operation
# All selected xformable prims' transforms. Store this for when `Keep Spacing` option is off during snapping,
# because it can modify parent's and child're transform differently.
self._all_xformable_prim_data_prev: Dict[Sdf.Path, Tuple[Gf.Vec3d, Gf.Vec3d, Gf.Vec3i, Gf.Vec3d, Gf.Vec3d]] = {}
# consolidated xformable prims' transforms. If parent is in the dict, child will be excluded.
self._consolidated_xformable_prim_data_prev: Dict[Sdf.Path, Tuple[Gf.Vec3d, Gf.Vec3d, Gf.Vec3i, Gf.Vec3d]] = {}
for path in self._xformable_prim_paths:
prim = self._dataAccessor.get_prim_at_path(path)
xform_tuple = self._dataAccessor.get_local_transform_SRT(prim, self._dataAccessor.get_current_time_code(self._current_time))
pivot = get_local_transform_pivot_inv(prim, self._dataAccessor.get_current_time_code(self._current_time)).GetInverse()
self._all_xformable_prim_data_prev[path] = xform_tuple + (pivot,)
if path in self._consolidated_xformable_prim_paths:
self._consolidated_xformable_prim_data_prev[path] = xform_tuple + (pivot,)
self.all_xformable_prim_data_curr = self._all_xformable_prim_data_prev.copy()
self.consolidated_xformable_prim_data_curr = self._consolidated_xformable_prim_data_prev.copy()
self._pending_changed_paths_for_xform_data.clear()
if self.custom_manipulator_enabled:
self._settings.set(TRANSFORM_GIZMO_IS_USING, True)
def on_changed(self, payload):
# Always re-fetch the changed transform on_changed. Although it might not be manipulated by manipulator,
# prim's transform can be modified by other runtime (e.g. omnigraph), and we always want the latest.
self._update_xform_data_from_dirty_paths()
def on_ended(self, payload):
# Always re-fetch the changed transform on_changed. Although it might not be manipulated by manipulator,
# prim's transform can be modified by other runtime (e.g. omnigraph), and we always want the latest.
self._update_xform_data_from_dirty_paths()
carb.profiler.begin(1, "PrimTransformChangedGestureBase.TransformPrimSRT.all")
paths = []
new_translations = []
new_rotation_eulers = []
new_rotation_orders = []
new_scales = []
old_translations = []
old_rotation_eulers = []
old_rotation_orders = []
old_scales = []
for path, (s, r, ro, t, pivot) in self.all_xformable_prim_data_curr.items():
# Data didn't change
if self._all_xformable_prim_data_prev[path] == self.all_xformable_prim_data_curr[path]:
# carb.log_info(f"Skip {path}")
continue
(old_s, old_r, old_ro, old_t, old_pivot) = self._all_xformable_prim_data_prev[path]
paths.append(path.pathString)
new_translations += [t[0], t[1], t[2]]
new_rotation_eulers += [r[0], r[1], r[2]]
new_rotation_orders += [ro[0], ro[1], ro[2]]
new_scales += [s[0], s[1], s[2]]
old_translations += [old_t[0], old_t[1], old_t[2]]
old_rotation_eulers += [old_r[0], old_r[1], old_r[2]]
old_rotation_orders += [old_ro[0], old_ro[1], old_ro[2]]
old_scales += [old_s[0], old_s[1], old_s[2]]
self._ignore_xform_data_change = True
self._on_ended_transform(
paths,
new_translations,
new_rotation_eulers,
new_rotation_orders,
new_scales,
old_translations,
old_rotation_eulers,
old_rotation_orders,
old_scales,
)
self._ignore_xform_data_change = False
carb.profiler.end(1)
if self.custom_manipulator_enabled:
self._settings.set(TRANSFORM_GIZMO_IS_USING, False)
# if the manipulator was locked to orientation or translation,
# refresh it on_ended so the transform is up to date
mode = self._get_transform_mode_for_current_op()
if self._should_keep_manipulator_orientation_unchanged(
mode
) or self._should_keep_manipulator_translation_unchanged(mode):
# set editing op to None AFTER _should_keep_manipulator_*_unchanged but
# BEFORE self._update_transform_from_prims
self._current_editing_op = None
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
self._current_editing_op = None
def on_canceled(self, payload):
if self.custom_manipulator_enabled:
self._settings.set(TRANSFORM_GIZMO_IS_USING, False)
self._current_editing_op = None
def widget_enabled(self):
self._enabled_hosting_widget_count += 1
# just changed from no active widget to 1 active widget
if self._enabled_hosting_widget_count == 1:
# listener only needs to be activated if manipulator is visible
if self._consolidated_xformable_prim_paths:
assert self._stage_listener is None
self._stage_listener = self._dataAccessor.setup_update_callback(self._on_objects_changed)
def _clear_temp_pivot_position_setting(self):
if self._settings.get(self._selection_pivot_position_path):
self._settings.destroy_item(self._selection_pivot_position_path)
def widget_disabled(self):
self._enabled_hosting_widget_count -= 1
self._clear_temp_pivot_position_setting()
assert self._enabled_hosting_widget_count >= 0
if self._enabled_hosting_widget_count < 0:
carb.log_error(f"manipulator enabled widget tracker out of sync: {self._enabled_hosting_widget_count}")
self._enabled_hosting_widget_count = 0
# If no hosting manipulator is active, revoke the listener since there's no need to sync Transform
if self._enabled_hosting_widget_count == 0:
if self._stage_listener:
self._stage_listener = self._dataAccessor.remove_update_callback(self._stage_listener)
for task_or_future in self._delay_dirty_tasks_or_futures.values():
task_or_future.cancel()
self._delay_dirty_tasks_or_futures.clear()
def set_floats(self, item: sc.AbstractManipulatorItem, value: Sequence[float]):
if item == self._viewport_fps_item:
self._viewport_fps = value[0]
return
flag = None
if issubclass(type(item), AbstractTransformManipulatorModel.OperationItem):
if (
item.operation == Operation.TRANSLATE_DELTA
or item.operation == Operation.ROTATE_DELTA
or item.operation == Operation.SCALE_DELTA
):
return
if item.operation == Operation.TRANSLATE:
flag = OpFlag.TRANSLATE
elif item.operation == Operation.ROTATE:
flag = OpFlag.ROTATE
elif item.operation == Operation.SCALE:
flag = OpFlag.SCALE
transform = Gf.Matrix4d(*value)
elif item == self._transform_manipulator_item:
flag = OpFlag.TRANSLATE | OpFlag.ROTATE | OpFlag.SCALE
transform = Gf.Matrix4d(*value)
elif item == self._no_scale_transform_manipulator_item:
flag = OpFlag.TRANSLATE | OpFlag.ROTATE
old_manipulator_scale_mtx = Gf.Matrix4d(1.0)
old_manipulator_scale_mtx.SetScale(self._scale_manipulator)
transform = old_manipulator_scale_mtx * Gf.Matrix4d(*value)
if flag is not None:
if self._mode == ManipulationMode.PIVOT:
self._transform_selected_prims(
transform, self._no_scale_transform_manipulator, self._scale_manipulator, flag
)
elif self._mode == ManipulationMode.UNIFORM:
self._transform_all_selected_prims_to_manipulator_pivot(transform, flag)
else:
carb.log_warn(f"Unsupported item {item}")
def set_ints(self, item: sc.AbstractManipulatorItem, value: Sequence[int]):
if item == self._manipulator_mode_item:
try:
self._mode = ManipulationMode(value[0])
except:
carb.log_error(traceback.format_exc())
else:
carb.log_warn(f"unsupported item {item}")
return None
def get_as_floats(self, item: sc.AbstractManipulatorItem):
if item == self._transform_item:
return self._transform
elif item == self._no_scale_transform_manipulator_item:
return flatten(self._no_scale_transform_manipulator)
elif item == self._scale_manipulator_item:
return [self._scale_manipulator[0], self._scale_manipulator[1], self._scale_manipulator[2]]
elif item == self._transform_manipulator_item:
scale_mtx = Gf.Matrix4d(1)
scale_mtx.SetScale(self._scale_manipulator)
return flatten(scale_mtx * self._no_scale_transform_manipulator)
else:
carb.log_warn(f"unsupported item {item}")
return None
def get_as_ints(self, item: sc.AbstractManipulatorItem):
if item == self._manipulator_mode_item:
return [int(self._mode)]
else:
carb.log_warn(f"unsupported item {item}")
return None
def get_operation(self) -> Operation:
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE:
return Operation.TRANSLATE
elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE:
return Operation.ROTATE
elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_SCALE:
return Operation.SCALE
return Operation.NONE
def get_snap(self, item: AbstractTransformManipulatorModel.OperationItem):
if not self._snap_settings_listener.snap_enabled:
return None
if item.operation == Operation.TRANSLATE:
if self._snap_settings_listener.snap_provider:
return None
return (
self._snap_settings_listener.snap_move_x,
self._snap_settings_listener.snap_move_y,
self._snap_settings_listener.snap_move_z,
)
elif item.operation == Operation.ROTATE:
return self._snap_settings_listener.snap_rotate
elif item.operation == Operation.SCALE:
return self._snap_settings_listener.snap_scale
return None
@carb.profiler.profile
def _transform_selected_prims(
self,
new_manipulator_transform: Gf.Matrix4d,
old_manipulator_transform_no_scale: Gf.Matrix4d,
old_manipulator_scale: Gf.Vec3d,
dirty_ops: OpFlag,
):
carb.profiler.begin(1, "omni.kit.manipulator.prim2.core.model._transform_selected_prims.prepare_data")
paths = []
new_translations = []
new_rotation_eulers = []
new_rotation_orders = []
new_scales = []
self._dataAccessor.clear_xform_cache()
# any op may trigger a translation change if multi-manipulating
should_update_translate = dirty_ops & OpFlag.TRANSLATE or len(self._xformable_prim_paths) > 1 or self._placement != Placement.LAST_PRIM_PIVOT
should_update_rotate = dirty_ops & OpFlag.ROTATE
should_update_scale = dirty_ops & OpFlag.SCALE
old_manipulator_scale_mtx = Gf.Matrix4d(1.0)
old_manipulator_scale_mtx.SetScale(old_manipulator_scale)
old_manipulator_transform_inv = (old_manipulator_scale_mtx * old_manipulator_transform_no_scale).GetInverse()
for path in self._consolidated_xformable_prim_paths:
if self._custom_manipulator_enabled and self._should_skip_custom_manipulator_path(path.pathString):
continue
selected_prim = self._dataAccessor.get_prim_at_path(path)
# We check whether path is in consolidated_xformable_prim_data_curr because it may have not made it the dictionary if an error occured
if not selected_prim or path not in self.consolidated_xformable_prim_data_curr:
continue
(s, r, ro, t, selected_pivot) = self.consolidated_xformable_prim_data_curr[path]
selected_pivot_inv = selected_pivot.GetInverse()
selected_local_to_world_mtx = self._dataAccessor.get_local_to_world_transform(selected_prim)
selected_parent_to_world_mtx = self._dataAccessor.get_parent_to_world_transform(selected_prim)
# Transform the prim from world space to pivot's space
# Then apply the new pivotPrim-to-world-space transform matrix
selected_local_to_world_pivot_mtx = (
selected_pivot * selected_local_to_world_mtx * old_manipulator_transform_inv * new_manipulator_transform
)
world_to_parent_mtx = selected_parent_to_world_mtx.GetInverse()
selected_local_mtx_new = selected_local_to_world_pivot_mtx * world_to_parent_mtx * selected_pivot_inv
if should_update_translate:
translation = selected_local_mtx_new.ExtractTranslation()
if should_update_rotate:
# Construct the new rotation from old scale and translation.
# Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation
old_s_mtx = Gf.Matrix4d(1.0)
old_s_mtx.SetScale(Gf.Vec3d(s))
old_t_mtx = Gf.Matrix4d(1.0)
old_t_mtx.SetTranslate(Gf.Vec3d(t))
rot_new = (old_s_mtx.GetInverse() * selected_local_mtx_new * old_t_mtx.GetInverse()).ExtractRotation()
axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()]
decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]])
index_order = Gf.Vec3i()
for i in range(3):
index_order[ro[i]] = 2 - i
rotation = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]])
rotation = find_best_euler_angles(Gf.Vec3d(r), rotation, ro)
if should_update_scale:
# Construct the new scale from old rotation and translation.
# Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation
old_rt_mtx = compose_transform_ops_to_matrix(t, r, ro, Gf.Vec3d(1))
new_s_mtx = selected_local_mtx_new * old_rt_mtx.GetInverse()
scale = Gf.Vec3d(new_s_mtx[0][0], new_s_mtx[1][1], new_s_mtx[2][2])
translation = translation if should_update_translate else t
rotation = rotation if should_update_rotate else r
scale = scale if should_update_scale else s
paths.append(path.pathString)
new_translations += [translation[0], translation[1], translation[2]]
new_rotation_eulers += [rotation[0], rotation[1], rotation[2]]
new_rotation_orders += [ro[0], ro[1], ro[2]]
new_scales += [scale[0], scale[1], scale[2]]
xform_tuple = (scale, rotation, ro, translation, selected_pivot)
self.consolidated_xformable_prim_data_curr[path] = xform_tuple
self.all_xformable_prim_data_curr[path] = xform_tuple
carb.profiler.end(1)
self._ignore_xform_data_change = True
self._do_transform_selected_prims(paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales)
self._ignore_xform_data_change = False
@carb.profiler.profile
def _transform_all_selected_prims_to_manipulator_pivot(
self,
new_manipulator_transform: Gf.Matrix4d,
dirty_ops: OpFlag,
):
paths = []
new_translations = []
new_rotation_eulers = []
new_rotation_orders = []
new_scales = []
old_translations = []
old_rotation_eulers = []
old_rotation_orders = []
old_scales = []
self._dataAccessor.clear_xform_cache()
# any op may trigger a translation change if multi-manipulating
should_update_translate = dirty_ops & OpFlag.TRANSLATE or len(self._xformable_prim_paths) > 1
should_update_rotate = dirty_ops & OpFlag.ROTATE
should_update_scale = dirty_ops & OpFlag.SCALE
for path in self._xformable_prim_paths_sorted:
if self._custom_manipulator_enabled and self._should_skip_custom_manipulator_path(path.pathString):
continue
selected_prim = self._dataAccessor.get_prim_at_path(path)
# We check whether path is in all_xformable_prim_data_curr because it may have not made it the dictionary if an error occured
if not selected_prim or path not in self.all_xformable_prim_data_curr:
continue
(s, r, ro, t, selected_pivot) = self.all_xformable_prim_data_curr[path]
selected_parent_to_world_mtx = self._dataAccessor.get_parent_to_world_transform(selected_prim)
world_to_parent_mtx = selected_parent_to_world_mtx.GetInverse()
selected_local_mtx_new = new_manipulator_transform * world_to_parent_mtx * selected_pivot.GetInverse()
if should_update_translate:
translation = selected_local_mtx_new.ExtractTranslation()
if should_update_rotate:
# Construct the new rotation from old scale and translation.
# Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation
old_s_mtx = Gf.Matrix4d(1.0)
old_s_mtx.SetScale(Gf.Vec3d(s))
old_t_mtx = Gf.Matrix4d(1.0)
old_t_mtx.SetTranslate(Gf.Vec3d(t))
rot_new = (old_s_mtx.GetInverse() * selected_local_mtx_new * old_t_mtx.GetInverse()).ExtractRotation()
axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()]
decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]])
index_order = Gf.Vec3i()
for i in range(3):
index_order[ro[i]] = 2 - i
rotation = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]])
rotation = find_best_euler_angles(Gf.Vec3d(r), rotation, ro)
if should_update_scale:
# Construct the new scale from old rotation and translation.
# Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation
old_rt_mtx = compose_transform_ops_to_matrix(t, r, ro, Gf.Vec3d(1))
new_s_mtx = selected_local_mtx_new * old_rt_mtx.GetInverse()
scale = Gf.Vec3d(new_s_mtx[0][0], new_s_mtx[1][1], new_s_mtx[2][2])
# any op may trigger a translation change if multi-manipulating
translation = translation if should_update_translate else t
rotation = rotation if should_update_rotate else r
scale = scale if should_update_scale else s
paths.append(path.pathString)
new_translations += [translation[0], translation[1], translation[2]]
new_rotation_eulers += [rotation[0], rotation[1], rotation[2]]
new_rotation_orders += [ro[0], ro[1], ro[2]]
new_scales += [scale[0], scale[1], scale[2]]
old_translations += [t[0], t[1], t[2]]
old_rotation_eulers += [r[0], r[1], r[2]]
old_rotation_orders += [ro[0], ro[1], ro[2]]
old_scales += [s[0], s[1], s[2]]
xform_tuple = (scale, rotation, ro, translation, selected_pivot)
self.all_xformable_prim_data_curr[path] = xform_tuple
if path in self.consolidated_xformable_prim_data_curr:
self.consolidated_xformable_prim_data_curr[path] = xform_tuple
self._ignore_xform_data_change = True
self._do_transform_all_selected_prims_to_manipulator_pivot(
paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales
)
self._ignore_xform_data_change = False
def _alert_if_selection_has_instance_proxies(self):
if self._selected_instance_proxy_paths and (not self._warning_notification or self._warning_notification.dismissed):
try:
import omni.kit.notification_manager as nm
self._warning_notification = nm.post_notification(
"Children of an instanced prim cannot be modified, uncheck Instanceable on the instanced prim to modify child prims.",
status=nm.NotificationStatus.WARNING
)
except ImportError:
pass
def _on_stage_closing(self):
self._dataAccessor.free_stage()
self._dataAccessor.free_xform_cache()
self._xformable_prim_paths.clear()
self._xformable_prim_paths_sorted.clear()
self._xformable_prim_paths_set.clear()
self._xformable_prim_paths_prefix_set.clear()
self._consolidated_xformable_prim_paths.clear()
self._pivot_prim = None
self._timeline_sub = None
if self._stage_listener:
self._stage_listener = self._dataAccessor.remove_update_callback(self._stage_listener)
self._pending_changed_paths.clear()
if self._update_prim_xform_from_prim_task_or_future is not None:
self._update_prim_xform_from_prim_task_or_future.cancel()
self._update_prim_xform_from_prim_task_or_future = None
def on_selection_changed(self, selection: List[Sdf.Path]):
if self._update_prim_xform_from_prim_task_or_future is not None:
self._update_prim_xform_from_prim_task_or_future.cancel()
self._update_prim_xform_from_prim_task_or_future = None
self._selected_instance_proxy_paths.clear()
self._xformable_prim_paths.clear()
self._xformable_prim_paths_set.clear()
self._xformable_prim_paths_prefix_set.clear()
self._consolidated_xformable_prim_paths.clear()
self._pivot_prim = None
for sdf_path in selection:
prim = self._dataAccessor.get_prim_at_path(sdf_path)
if prim and prim.IsA(UsdGeom.Xformable) and prim.IsActive():
self._xformable_prim_paths.append(sdf_path)
if self._xformable_prim_paths:
# Make a sorted list so parents always appears before child
self._xformable_prim_paths_sorted = self._xformable_prim_paths.copy()
self._xformable_prim_paths_sorted.sort()
# Find the most recently selected valid xformable prim as the pivot prim where the transform gizmo is located at.
self._pivot_prim = self._dataAccessor.get_prim_at_path(self._xformable_prim_paths[-1])
# Get least common prims ancestors.
# We do this so that if one selected prim is a descendant of other selected prim, the descendant prim won't be
# transformed twice.
self._consolidated_xformable_prim_paths = Sdf.Path.RemoveDescendentPaths(self._xformable_prim_paths)
# Filter all instance proxy paths.
for path in self._consolidated_xformable_prim_paths:
prim = self._dataAccessor.get_prim_at_path(path)
if prim.IsInstanceProxy():
self._selected_instance_proxy_paths.add(sdf_path)
self._xformable_prim_paths_set.update(self._xformable_prim_paths)
for path in self._xformable_prim_paths_set:
self._xformable_prim_paths_prefix_set.update(path.GetPrefixes())
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
# Happens when host widget is already enabled and first selection in a new stage
if self._enabled_hosting_widget_count > 0 and self._stage_listener is None:
self._stage_listener = self._dataAccessor.setup_update_callback(self._on_objects_changed)
def _should_keep_manipulator_orientation_unchanged(self, mode: str) -> bool:
# Exclude snap_to_face. During snap_to_face operation, it may modify the orientation of object to confrom to surface
# normal and the `new_manipulator_transform` param for `_transform_selected_prims` is set to the final transform
# of the manipulated prim. However, if we use old rotation in the condition below, _no_scale_transform_manipulator
# will not confrom to the new orientation, and _transform_selected_prims would double rotate the prims because it
# sees the rotation diff between the old prim orientation (captured at on_began) vs new normal orient, instead of
# current prim orientation vs new normal orientation.
# Plus, it is nice to see the normal of the object changing while snapping.
snap_provider_enabled = self.snap_settings_listener.snap_enabled and self.snap_settings_listener.snap_provider
# When the manipulator is being manipulated as local translate or scale, we do not want to change the rotation of
# the manipulator even if it's rotated, otherwise the direction of moving or scaling will change and can be very hard to control.
# It can happen when you move a prim that has a constraint on it (e.g. lookAt)
# In this case keep the rotation the same as on_began
return (
mode == c.TRANSFORM_MODE_LOCAL
and (self._current_editing_op == Operation.TRANSLATE or self._current_editing_op == Operation.SCALE)
and not snap_provider_enabled
)
def _should_keep_manipulator_translation_unchanged(self, mode: str) -> bool:
# When the pivot placement is BBOX_CENTER and multiple prims being rotated, the bbox center may shifts, and the
# rotation center will shift with them. This causes weird user experience. So we pin the rotation center until
# mouse is released.
return (
self._current_editing_op == Operation.ROTATE
and (self._placement == Placement.BBOX_CENTER or self._placement == Placement.BBOX_BASE)
)
def _get_transform_mode_for_current_op(self) -> str:
mode = c.TRANSFORM_MODE_LOCAL
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE:
mode = self._op_settings_listener.rotation_mode
elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE:
mode = self._op_settings_listener.translation_mode
return mode
# Adds a delay to the visual update during translate (only) manipulation
# It's due to the renderer having a delay of rendering the mesh and the manipulator appears to drift apart.
# It's only an estimation and may varying from scene/renderer setup.
async def _delay_dirty(self, transform, id):
if self._viewport_fps:
render_frame_time = 1.0 / self._viewport_fps * self._settings.get(TRANSLATE_DELAY_FRAME_SETTING)
while True:
dt = await self._app.next_update_async()
render_frame_time -= dt
# break a frame early
if render_frame_time < dt:
break
# cancel earlier job if a later one catches up (fps suddenly changed?)
earlier_tasks_or_futures = []
for key, task_or_future in self._delay_dirty_tasks_or_futures.items():
if key < id:
earlier_tasks_or_futures.append(key)
task_or_future.cancel()
else:
break
for key in earlier_tasks_or_futures:
self._delay_dirty_tasks_or_futures.pop(key)
self._transform = transform
self._item_changed(self._transform_item)
self._delay_dirty_tasks_or_futures.pop(id)
def _update_temp_pivot_world_position(self):
if type(self._transform) is not list:
return
new_world_position = self._transform[12:15]
self._settings.set_float_array(
self._selection_pivot_position_path,
new_world_position
)
@carb.profiler.profile
def _update_transform_from_prims(self):
xform_flattened = self._calculate_transform_from_prim()
if self._transform != xform_flattened:
self._transform = xform_flattened
# update setting with new pivot placement position
self._update_temp_pivot_world_position()
return True
return False
#def _calculate_transform_from_obj(self):
def _calculate_transform_from_prim(self):
if not self._dataAccessor.get_stage():
return False
if not self._pivot_prim:
return False
self._dataAccessor.clear_xform_cache()
cur_time = self._dataAccessor.get_current_time_code(self._current_time)
mode = self._get_transform_mode_for_current_op()
pivot_inv = get_local_transform_pivot_inv(self._pivot_prim, cur_time)
if self._should_keep_manipulator_orientation_unchanged(mode):
pivot_prim_path = self._pivot_prim.GetPath()
(s, r, ro, t) = self._dataAccessor.get_local_transform_SRT(self._pivot_prim, cur_time)
pivot = get_local_transform_pivot_inv(self._pivot_prim, self._dataAccessor.get_current_time_code(self._current_time)).GetInverse()
self.all_xformable_prim_data_curr[pivot_prim_path] = (s, r, ro, t) + (pivot,)
# This method may be called from _on_op_listener_changed, before any gesture has started
# in which case _all_xformable_prim_data_prev would be empty
piv_xf_tuple = self._all_xformable_prim_data_prev.get(pivot_prim_path, False)
if not piv_xf_tuple:
piv_xf_tuple = self._dataAccessor.get_local_transform_SRT(self._pivot_prim, cur_time)
pv_xf_pivot = get_local_transform_pivot_inv(
self._pivot_prim, self._dataAccessor.get_current_time_code(self._current_time)
).GetInverse()
self._all_xformable_prim_data_prev[self._pivot_prim.GetPath()] = piv_xf_tuple + (pv_xf_pivot,)
(s_p, r_p, ro_p, t_p, t_piv) = piv_xf_tuple
xform = self._construct_transform_matrix_from_SRT(t, r_p, ro_p, s, pivot_inv)
parent = self._dataAccessor.get_local_to_world_transform(self._pivot_prim.GetParent())
xform *= parent
else:
xform = self._dataAccessor.get_local_to_world_transform(self._pivot_prim)
xform = pivot_inv.GetInverse() * xform
if self._should_keep_manipulator_translation_unchanged(mode):
xform.SetTranslateOnly((self._transform[12], self._transform[13], self._transform[14]))
else:
# if there's only one selection, we always use LAST_PRIM_PIVOT though
if (
self._placement != Placement.LAST_PRIM_PIVOT
and self._placement != Placement.REF_PRIM
):
average_translation = Gf.Vec3d(0.0)
if self._placement == Placement.BBOX_CENTER or self._placement == Placement.BBOX_BASE:
world_bound = Gf.Range3d()
def get_prim_translation(xformable):
xformable_world_mtx = self._dataAccessor.get_local_to_world_transform(xformable)
xformable_pivot_inv = get_local_transform_pivot_inv(xformable, cur_time)
xformable_world_mtx = xformable_pivot_inv.GetInverse() * xformable_world_mtx
return xformable_world_mtx.ExtractTranslation()
for path in self._xformable_prim_paths:
xformable = self._dataAccessor.get_prim_at_path(path)
if self._placement == Placement.SELECTION_CENTER:
average_translation += get_prim_translation(xformable)
elif self._placement == Placement.BBOX_CENTER or Placement.BBOX_BASE:
bound_range = self._usd_context.compute_path_world_bounding_box(path.pathString)
bound_range = Gf.Range3d(Gf.Vec3d(*bound_range[0]), Gf.Vec3d(*bound_range[1]))
if not bound_range.IsEmpty():
world_bound = Gf.Range3d.GetUnion(world_bound, bound_range)
else:
# extend world bound with tranlation for prims with zero bbox, e.g. Xform, Camera
prim_translation = get_prim_translation(xformable)
world_bound.UnionWith(prim_translation)
if self._placement == Placement.SELECTION_CENTER:
average_translation /= len(self._xformable_prim_paths)
elif self._placement == Placement.BBOX_CENTER:
average_translation = world_bound.GetMidpoint()
elif self._placement == Placement.BBOX_BASE:
# xform may not have bbox but its descendants may have, exclude cases that only xform are selected
if not world_bound.IsEmpty():
bbox_center = world_bound.GetMidpoint()
bbox_size = world_bound.GetSize()
if UsdGeom.GetStageUpAxis(self._dataAccessor.get_stage()) == UsdGeom.Tokens.y:
# Y-up world
average_translation = bbox_center - Gf.Vec3d(0.0, bbox_size[1]/2.0, 0.0)
else:
# Z-up world
average_translation = bbox_center - Gf.Vec3d(0.0, 0.0, bbox_size[2]/2.0)
else:
# fallback to SELECTION_CENTER
average_translation /= len(self._xformable_prim_paths)
# Only take the translate from selected prim average.
# The rotation and scale still comes from pivot prim
xform.SetTranslateOnly(average_translation)
# instead of using RemoveScaleShear, additional steps made to handle negative scale properly
scale, _, _, _ = self._dataAccessor.get_local_transform_SRT(self._pivot_prim, cur_time)
scale_epsilon = 1e-6
for i in range(3):
if Gf.IsClose(scale[i], 0.0, scale_epsilon):
scale[i] = -scale_epsilon if scale[i] < 0 else scale_epsilon
inverse_scale = Gf.Matrix4d().SetScale(Gf.Vec3d(1.0 / scale[0], 1.0 / scale[1], 1.0 / scale[2]))
xform = inverse_scale * xform
# this is the average xform without scale
self._no_scale_transform_manipulator = Gf.Matrix4d(xform)
# store the scale separately
self._scale_manipulator = Gf.Vec3d(scale)
# Visual transform of the manipulator
xform = xform.RemoveScaleShear()
if mode == c.TRANSFORM_MODE_GLOBAL:
xform = xform.SetTranslate(xform.ExtractTranslation())
return flatten(xform)
def _construct_transform_matrix_from_SRT(
self,
translation: Gf.Vec3d,
rotation_euler: Gf.Vec3d,
rotation_order: Gf.Vec3i,
scale: Gf.Vec3d,
pivot_inv: Gf.Matrix4d,
):
trans_mtx = Gf.Matrix4d()
rot_mtx = Gf.Matrix4d()
scale_mtx = Gf.Matrix4d()
trans_mtx.SetTranslate(Gf.Vec3d(translation))
axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()]
rotation = (
Gf.Rotation(axes[rotation_order[0]], rotation_euler[rotation_order[0]])
* Gf.Rotation(axes[rotation_order[1]], rotation_euler[rotation_order[1]])
* Gf.Rotation(axes[rotation_order[2]], rotation_euler[rotation_order[2]])
)
rot_mtx.SetRotate(rotation)
scale_mtx.SetScale(Gf.Vec3d(scale))
return pivot_inv * scale_mtx * rot_mtx * pivot_inv.GetInverse() * trans_mtx
def _on_op_listener_changed(self, type: OpSettingsListener.CallbackType, value: str):
if type == OpSettingsListener.CallbackType.OP_CHANGED:
# cancel all delayed tasks
for task_or_future in self._delay_dirty_tasks_or_futures.values():
task_or_future.cancel()
self._delay_dirty_tasks_or_futures.clear()
self._update_transform_from_prims()
self._item_changed(self._transform_item)
elif type == OpSettingsListener.CallbackType.TRANSLATION_MODE_CHANGED:
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE:
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
elif type == OpSettingsListener.CallbackType.ROTATION_MODE_CHANGED:
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE:
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
def _update_placement(self, placement_str: str):
if placement_str == prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER:
placement = Placement.SELECTION_CENTER
elif placement_str == prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER:
placement = Placement.BBOX_CENTER
elif placement_str == prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM:
placement = Placement.REF_PRIM
elif placement_str == prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE:
placement = Placement.BBOX_BASE
else: # placement == prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT or bad values
placement = Placement.LAST_PRIM_PIVOT
if placement != self._placement:
if placement == Placement.LAST_PRIM_PIVOT and self._placement == Placement.REF_PRIM:
# reset the pivot prim in case it was changed by MANIPULATOR_PLACEMENT_PICK_REF_PRIM
if self._xformable_prim_paths:
self._pivot_prim = self._dataAccessor.get_prim_at_path(self._xformable_prim_paths[-1])
self._placement = placement
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
def _on_placement_setting_changed(self, item, event_type):
placement_str = self._dict.get(item)
self._update_placement(placement_str)
def _check_update_selected_instance_proxy_list(self, path: Sdf.Path, resynced):
def track_or_remove_from_instance_proxy_list(prim):
valid_proxy = prim and prim.IsActive() and prim.IsInstanceProxy()
if valid_proxy:
self._selected_instance_proxy_paths.add(prim.GetPath())
else:
self._selected_instance_proxy_paths.discard(prim.GetPath())
prim_path = path.GetPrimPath()
changed_prim = self._dataAccessor.get_prim_at_path(prim_path)
# Update list of instance proxy paths.
if resynced and path.IsPrimPath():
if prim_path in self._consolidated_xformable_prim_paths:
# Quick path if it's selected already.
track_or_remove_from_instance_proxy_list(changed_prim)
else:
# Slow path to verify if any of its ancestors are changed.
for path in self._consolidated_xformable_prim_paths:
if not path.HasPrefix(prim_path):
continue
prim = self._dataAccessor.get_prim_at_path(path)
track_or_remove_from_instance_proxy_list(prim)
@carb.profiler.profile
async def _update_transform_from_prims_async(self):
try:
check_all_prims = (
self._placement != Placement.LAST_PRIM_PIVOT
and self._placement != Placement.REF_PRIM
and len(self._xformable_prim_paths) > 1
)
pivot_prim_path = self._pivot_prim.GetPath()
for p, resynced in self._pending_changed_paths.items():
self._check_update_selected_instance_proxy_list(p, resynced)
prim_path = p.GetPrimPath()
# Update either check_all_prims
# or prim_path is a prefix of pivot_prim_path (pivot prim's parent affect pivot prim transform)
# Note: If you move the manipulator and the prim flies away while manipulator stays in place, check this
# condition!
if (
# check _xformable_prim_paths_prefix_set so that if the parent path of selected prim(s) changed, it
# can still update manipulator transform
prim_path in self._xformable_prim_paths_prefix_set
if check_all_prims
else pivot_prim_path.HasPrefix(prim_path)
):
if self._path_may_affect_transform(p):
# only delay the visual update in translate mode.
should_delay_frame = self._settings.get(TRANSLATE_DELAY_FRAME_SETTING) > 0
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE and should_delay_frame:
xform = self._calculate_transform_from_prim()
id = self._app.get_update_number()
self._delay_dirty_tasks_or_futures[id] = run_coroutine(self._delay_dirty(xform, id))
else:
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
break
except Exception as e:
carb.log_error(traceback.format_exc())
finally:
self._pending_changed_paths.clear()
self._update_prim_xform_from_prim_task_or_future = None
@carb.profiler.profile
def _on_objects_changed(self, notice, sender):
if not self._pivot_prim:
return
# collect resynced paths so that removed/added xformOps triggers refresh
for path in notice.GetResyncedPaths():
self._pending_changed_paths[path] = True
# collect changed only paths
for path in notice.GetChangedInfoOnlyPaths():
self._pending_changed_paths[path] = False
# if an operation is in progess, record all dirty xform path
if self._current_editing_op is not None and not self._ignore_xform_data_change:
self._pending_changed_paths_for_xform_data.update(notice.GetChangedInfoOnlyPaths())
if self._update_prim_xform_from_prim_task_or_future is None or self._update_prim_xform_from_prim_task_or_future.done():
self._update_prim_xform_from_prim_task_or_future = run_coroutine(self._update_transform_from_prims_async())
def _set_default_settings(self):
self._settings.set_default(TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED, False)
self._settings.set_default(TRANSFORM_GIZMO_IS_USING, False)
self._settings.set_default(TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ, [0, 0, 0])
self._settings.set_default(TRANSFORM_GIZMO_ROTATE_DELTA_XYZW, [0, 0, 0, 1])
self._settings.set_default(TRANSFORM_GIZMO_SCALE_DELTA_XYZ, [0, 0, 0])
def _should_skip_custom_manipulator_path(self, path: str) -> bool:
custom_manipulator_path_prims_settings_path = TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_PRIMS + path
return self._settings.get(custom_manipulator_path_prims_settings_path)
def _path_may_affect_transform(self, path: Sdf.Path) -> bool:
# Batched changes sent in a SdfChangeBlock may not have property name but only the prim path
return not path.ContainsPropertyElements() or UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(path.name)
@property
def stage(self):
return self._dataAccessor.get_stage()
@property
def custom_manipulator_enabled(self):
return self._custom_manipulator_enabled
@property
def snap_settings_listener(self):
return self._snap_settings_listener
@property
def op_settings_listener(self):
return self._op_settings_listener
@property
def usd_context(self) -> omni.usd.UsdContext:
return self._usd_context
@property
def xformable_prim_paths(self) -> List[Sdf.Path]:
return self._xformable_prim_paths
class PrimDataAccessorRegistry(DataAccessorRegistry):
def __init__(self, dataType = "USD"):
self._dataType = dataType
def getDataAccessor(self, model):
if self._dataType == "USD":
self.dataAccessor = UsdDataAccessor(model = model)
elif self._dataType == "Fabric":
self.dataAccessor = FabricDataAccessor(model = model)
else:
self.dataAccessor = None
#self.dataAccessor = FabricDataAccessor()
return self.dataAccessor
#to be moved to omni.kit.manipulator.prim2.usd
class UsdDataAccessor(DataAccessor):
def __init__(self, usd_context_name: str = "", model = None):
super().__init__()
self._model = model
self._xform_cache = None
self._stage: Usd.Stage = None
def _update_transform_from_prims(self):
...
def _update_xform_data_from_dirty_paths(self):
...
def get_prim_at_path(self, path):
return self._stage.GetPrimAtPath(path)
def get_current_time_code(self, currentTime):
return Usd.TimeCode(omni.usd.get_frame_time_code(currentTime, self._stage.GetTimeCodesPerSecond()))
def get_local_transform_SRT(self, prim, time):
return omni.usd.get_local_transform_SRT(prim, time)
#xform cache
def get_local_to_world_transform(self, obj):
return self._xform_cache.GetLocalToWorldTransform(obj)
def get_parent_to_world_transform(self, obj):
return self._xform_cache.GetParentToWorldTransform(obj)
def clear_xform_cache(self):
self._xform_cache.Clear()
def free_xform_cache(self):
self._xform_cache = None
def xform_set_time(self):
self._xform_cache.SetTime(self.get_current_time_code(self._model._current_time))
def update_xform_cache(self):
self._xform_cache = UsdGeom.XformCache(self.get_current_time_code(self._model._current_time))
#stage
def free_stage(self):
self._stage = None
def get_stage(self):
return self._stage
#callbacks
def setup_update_callback(self, function):
res = Tf.Notice.Register(Usd.Notice.ObjectsChanged, function, self._stage)
carb.log_info("Tf.Notice.Register in PrimTransformModel")
return res
def remove_update_callback(self, listener): #removeUpdateCallback
listener.Revoke()
carb.log_info("Tf.Notice.Revoke in PrimTransformModel")
return None
#USD specific commands
def _do_transform_all_selected_prims_to_manipulator_pivot(
self,
paths: List[str],
new_translations: List[float],
new_rotation_eulers: List[float],
new_rotation_orders: List[int],
new_scales: List[float],
):
omni.kit.commands.create(
"TransformMultiPrimsSRTCpp",
count=len(paths),
no_undo=True,
paths=paths,
new_translations=new_translations,
new_rotation_eulers=new_rotation_eulers,
new_rotation_orders=new_rotation_orders,
new_scales=new_scales,
usd_context_name=self._model._usd_context_name,
time_code=self.get_current_time_code(self._model._current_time).GetValue(),
).do()
def _do_transform_selected_prims(
self,
paths: List[str],
new_translations: List[float],
new_rotation_eulers: List[float],
new_rotation_orders: List[int],
new_scales: List[float],
):
omni.kit.commands.create(
"TransformMultiPrimsSRTCpp",
count=len(paths),
no_undo=True,
paths=paths,
new_translations=new_translations,
new_rotation_eulers=new_rotation_eulers,
new_rotation_orders=new_rotation_orders,
new_scales=new_scales,
usd_context_name=self._model._usd_context_name,
time_code=self.get_current_time_code(self._model._current_time).GetValue(),
).do()
def _on_ended_transform(
self,
paths: List[str],
new_translations: List[float],
new_rotation_eulers: List[float],
new_rotation_orders: List[int],
new_scales: List[float],
old_translations: List[float],
old_rotation_eulers: List[float],
old_rotation_orders: List[int],
old_scales: List[float],
):
omni.kit.commands.execute(
"TransformMultiPrimsSRTCpp",
count=len(paths),
paths=paths,
new_translations=new_translations,
new_rotation_eulers=new_rotation_eulers,
new_rotation_orders=new_rotation_orders,
new_scales=new_scales,
old_translations=old_translations,
old_rotation_eulers=old_rotation_eulers,
old_rotation_orders=old_rotation_orders,
old_scales=old_scales,
usd_context_name=self._model._usd_context_name,
time_code=self.get_current_time_code(self._model._current_time).GetValue(),
)
#to be moved to omni.kit.manipulator.prim2.fabric
class FabricDataAccessor(DataAccessor):
#TODO
def __init__(self, usd_context_name: str = "", model = None):
...
| 64,918 | Python | 45.140014 | 149 | 0.627191 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/pivot_button_group.py | # 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.
#
from pathlib import Path
import carb.input
import carb.settings
import omni.kit.context_menu
import omni.ui as ui
from omni.kit.widget.toolbar.widget_group import WidgetGroup
ICON_FOLDER_PATH = Path(
f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons"
)
class PivotButtonGroup(WidgetGroup):
"""
Toolbar entry for pivot placement
"""
def __init__(self):
super().__init__()
self._input = carb.input.acquire_input_interface()
self._settings = carb.settings.get_settings()
def clean(self):
super().clean()
def __del__(self):
self.clean()
def get_style(self):
style = {
"Button.Image::pivot_placement": {"image_url": f"{ICON_FOLDER_PATH}/pivot_location.svg"}
}
return style
def get_button(self) -> ui.ToolButton:
return self._button
def create(self, default_size):
self._button = ui.Button(
name="pivot_placement",
width=default_size,
height=default_size,
tooltip="Pivot Placement",
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "multi_sel_pivot", min_menu_entries=1),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b)
)
return {"pivot": self._button}
def _on_mouse_pressed(self, button, button_id: str, min_menu_entries: int = 2):
# override default behavior, left or right click will show menu without delay
self._acquire_toolbar_context()
if button == 0 or button == 1:
self._invoke_context_menu(button_id, min_menu_entries)
def _invoke_context_menu(self, button_id: str, min_menu_entries: int = 1):
"""
Function to invoke context menu.
Args:
button_id: button_id of the context menu to be invoked.
min_menu_entries: minimal number of menu entries required for menu to be visible (default 1).
"""
button_id = "multi_sel_pivot"
context_menu = omni.kit.context_menu.get_instance()
objects = {"widget_name": button_id, "main_toolbar": True}
menu_list = omni.kit.context_menu.get_menu_dict(button_id, "omni.kit.manipulator.prim2.core")
context_menu.show_context_menu(
button_id,
objects,
menu_list,
min_menu_entries,
delegate=ui.MenuDelegate()
)
| 2,892 | Python | 32.639535 | 113 | 0.633126 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/prim_transform_manipulator_registry.py | # 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.
#
__all__ = ["TransformManipulatorRegistry"]
import weakref
from omni.kit.viewport.registry import RegisterScene
from .prim_transform_manipulator import PrimTransformManipulator
from .reference_prim_marker import ReferencePrimMarker
class PrimTransformManipulatorScene:
def __init__(self, desc: dict):
usd_context_name = desc.get("usd_context_name")
self.__transform_manip = PrimTransformManipulator(
usd_context_name=usd_context_name, viewport_api=desc.get("viewport_api")
)
self.__reference_prim_marker = ReferencePrimMarker(
usd_context_name=usd_context_name, manipulator_model=weakref.proxy(self.__transform_manip.model)
)
def destroy(self):
if self.__transform_manip:
self.__transform_manip.destroy()
self.__transform_manip = None
if self.__reference_prim_marker:
self.__reference_prim_marker.destroy()
self.__reference_prim_marker = None
# PrimTransformManipulator & TransformManipulator don't have their own visibility
@property
def visible(self):
return True
@visible.setter
def visible(self, value):
pass
@property
def categories(self):
return ("manipulator",)
@property
def name(self):
return "Prim Transform"
class TransformManipulatorRegistry:
def __init__(self):
self._scene = RegisterScene(PrimTransformManipulatorScene, "omni.kit.manipulator.prim2.core")
def __del__(self):
self.destroy()
def destroy(self):
self._scene = None
| 2,024 | Python | 29.681818 | 108 | 0.692194 |
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/tests/test_manipulator_prim.py | # 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.
#
import omni.kit.test
import inspect
import logging
import math
import os
from pathlib import Path
from typing import Awaitable, Callable, List
import carb
import carb.input
import carb.settings
import omni.kit.commands
import omni.kit.ui_test as ui_test
import omni.kit.undo
import omni.usd
from carb.input import MouseEventType
from omni.kit.manipulator.prim2.core.settings_constants import Constants as prim_c
from omni.kit.manipulator.tool.snap import settings_constants as snap_c
from omni.kit.manipulator.tool.snap.builtin_snap_tools import SURFACE_SNAP_NAME
from omni.kit.manipulator.transform.settings_constants import c
from omni.kit.ui_test import Vec2
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.test_helpers_gfx.compare_utils import capture_and_compare, ComparisonMetric
from pxr import UsdGeom, Gf
CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.manipulator.prim2.core}/data"))
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()).resolve().absolute()
logger = logging.getLogger(__name__)
class TestTransform(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._context = omni.usd.get_context()
self._selection = self._context.get_selection()
self._settings = carb.settings.get_settings()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests").joinpath("golden")
self._usd_scene_dir = CURRENT_PATH.absolute().resolve().joinpath("tests").joinpath("usd")
self._window_width = self._settings.get("/app/window/width")
self._window_height = self._settings.get("/app/window/height")
# Load renderer before USD is loaded
await self._context.new_stage_async()
# After running each test
async def tearDown(self):
# Move and close the stage so selections are reset to avoid triggering ghost gestures.
await ui_test.emulate_mouse_move(Vec2(0, 0))
await ui_test.human_delay()
await self._context.close_stage_async()
self._golden_img_dir = None
await super().tearDown()
async def _snapshot(self, golden_img_name: str = "", threshold: float = 2e-4):
await ui_test.human_delay()
test_fn_name = ""
for frame_info in inspect.stack():
if os.path.samefile(frame_info[1], __file__):
test_fn_name = frame_info[3]
golden_img_name = f"{test_fn_name}.{golden_img_name}.png"
# Because we're testing RTX renderered pixels, use a better threshold filter for differences
diff = await capture_and_compare(
golden_img_name,
threshold=threshold,
output_img_dir=OUTPUTS_DIR,
golden_img_dir=self._golden_img_dir,
metric=ComparisonMetric.MEAN_ERROR_SQUARED,
)
self.assertLessEqual(
diff,
threshold,
f"The generated image {golden_img_name} has a difference of {diff}, but max difference is {threshold}",
)
async def _setup_global(
self,
op: str,
enable_toolbar: bool = False,
file_name: str = "test_scene.usda",
prims_to_select=["/World/Cube", "/World/Xform", "/World/Xform/Cube_01"],
placement=prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT,
):
await self._setup(file_name, c.TRANSFORM_MODE_GLOBAL, op, enable_toolbar, prims_to_select, placement)
async def _setup_local(
self,
op: str,
enable_toolbar: bool = False,
file_name: str = "test_scene.usda",
prims_to_select=["/World/Cube", "/World/Xform", "/World/Xform/Cube_01"],
placement=prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT,
):
await self._setup(file_name, c.TRANSFORM_MODE_LOCAL, op, enable_toolbar, prims_to_select, placement)
async def _setup(
self,
scene_file: str,
mode: str,
op: str,
enable_toolbar: bool = False,
prims_to_select=["/World/Cube", "/World/Xform", "/World/Xform/Cube_01"],
placement=prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT,
):
usd_path = self._usd_scene_dir.joinpath(scene_file)
success, error = await self._context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
# move the mouse out of the way
await ui_test.emulate_mouse_move(Vec2(0, 0))
await ui_test.human_delay()
self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, placement)
self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, mode)
self._settings.set(c.TRANSFORM_ROTATE_MODE_SETTING, mode)
self._settings.set(c.TRANSFORM_OP_SETTING, op)
self._settings.set("/app/viewport/snapEnabled", False)
self._settings.set("/persistent/app/viewport/snapToSurface", False)
self._settings.set("/exts/omni.kit.manipulator.prim2.core/tools/enabled", enable_toolbar)
self._selection.set_selected_prim_paths([], True)
await ui_test.human_delay(human_delay_speed=10)
self._selection.set_selected_prim_paths(prims_to_select, True)
await ui_test.human_delay(human_delay_speed=10)
# Save prims initial state to restore to.
stage = self._context.get_stage()
self._restore_transform = {}
for prim_path in prims_to_select:
xform_ops = []
for xform_op in UsdGeom.Xformable(stage.GetPrimAtPath(prim_path)).GetOrderedXformOps():
if not xform_op.IsInverseOp():
xform_ops.append((xform_op, xform_op.Get()))
self._restore_transform[prim_path] = xform_ops
async def _restore_initial_state(self):
for xform_op_list in self._restore_transform.values():
for xform_op_tuple in xform_op_list:
xform_op, start_value = xform_op_tuple[0], xform_op_tuple[1]
xform_op.Set(start_value)
async def _emulate_mouse_drag_and_drop_multiple_waypoints(
self,
waypoints: List[Vec2],
right_click=False,
human_delay_speed: int = 4,
num_steps: int = 8,
on_before_drop: Callable[[int], Awaitable[None]] = None,
):
"""Emulate Mouse Drag & Drop. Click at start position and slowly move to end position."""
logger.info(f"emulate_mouse_drag_and_drop poses: {waypoints} (right_click: {right_click})")
count = len(waypoints)
if count < 2:
return
await ui_test.input.emulate_mouse(MouseEventType.MOVE, waypoints[0])
await ui_test.human_delay(human_delay_speed)
await ui_test.input.emulate_mouse(
MouseEventType.RIGHT_BUTTON_DOWN if right_click else MouseEventType.LEFT_BUTTON_DOWN
)
await ui_test.human_delay(human_delay_speed)
for i in range(1, count):
await ui_test.input.emulate_mouse_slow_move(
waypoints[i - 1], waypoints[i], num_steps=num_steps, human_delay_speed=human_delay_speed
)
if on_before_drop:
await ui_test.human_delay(human_delay_speed)
await on_before_drop()
await ui_test.input.emulate_mouse(
MouseEventType.RIGHT_BUTTON_UP if right_click else MouseEventType.LEFT_BUTTON_UP
)
await ui_test.human_delay(human_delay_speed)
################################################################
################## test manipulator placement ##################
################################################################
async def test_placement(self):
await self._setup_global(c.TRANSFORM_OP_MOVE)
PLACEMENTS = {
"placement_selection_center": prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER,
"placement_bbox_center": prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER,
"placement_authored_pivot": prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT,
"placement_bbox_base": prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE
}
for test_name, val in PLACEMENTS.items():
self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, val)
await ui_test.human_delay()
await self._snapshot(test_name)
async def test_tmp_placement(self):
await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Xform/Cube_01", "/World/Cube"])
self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM)
await ui_test.human_delay()
await self._snapshot("pick_default")
center = Vec2(self._window_width, self._window_height) / 2
# pick the other prim as tmp pivot prim
await ui_test.emulate_mouse_move_and_click(center)
await ui_test.human_delay()
await self._snapshot("pick")
# reset placement to last prim, the manipulator should go to last prim and marker disappears
self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT)
await ui_test.human_delay()
await self._snapshot("last_selected")
async def test_bbox_placement_for_xform(self):
await self._setup_global(c.TRANSFORM_OP_MOVE, file_name="test_pivot_with_invalid_bbox.usda", prims_to_select=["/World/Xform"])
self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER)
await ui_test.human_delay()
await self._snapshot("placement_bbox_center")
self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE)
await ui_test.human_delay()
await self._snapshot("placement_bbox_base")
################################################################
####################### test translation #######################
################################################################
################## test manipulator move axis ##################
async def test_move_global_axis(self):
await self._setup_global(c.TRANSFORM_OP_MOVE)
await self._test_move_axis()
async def test_move_local_axis(self):
await self._setup_local(c.TRANSFORM_OP_MOVE)
await self._test_move_axis(180)
async def _test_move_axis(self, angle_offset: float = 0, distance: float = 50):
OFFSET = 50
MOVEMENT = ["x", "y", "z"]
center = Vec2(self._window_width, self._window_height) / 2
for i, test_name in enumerate(MOVEMENT):
await ui_test.human_delay()
dir = Vec2(
math.cos(math.radians(-i * 120 + 30 + angle_offset)),
math.sin(math.radians(-i * 120 + 30 + angle_offset)),
)
try:
await ui_test.emulate_mouse_drag_and_drop(center + dir * OFFSET, center + dir * (OFFSET + distance))
await self._snapshot(f"{test_name}.{angle_offset}.{distance}")
finally:
await self._restore_initial_state()
################## test manipulator move plane ##################
async def test_move_global_plane(self):
await self._setup_global(c.TRANSFORM_OP_MOVE)
await self._test_move_plane()
async def test_move_local_plane(self):
await self._setup_local(c.TRANSFORM_OP_MOVE)
await self._test_move_plane(180)
async def _test_move_plane(self, angle_offset: float = 0, distance=75):
OFFSET = 50
MOVEMENT = ["xz", "zy", "yx"]
center = Vec2(self._window_width, self._window_height) / 2
for i, test_name in enumerate(MOVEMENT):
await ui_test.human_delay()
dir = Vec2(
math.cos(math.radians(-i * 120 + 90 + angle_offset)),
math.sin(math.radians(-i * 120 + 90 + angle_offset)),
)
try:
await ui_test.emulate_mouse_drag_and_drop(center + dir * OFFSET, center + dir * (OFFSET + distance))
await self._snapshot(f"{test_name}.{angle_offset}.{distance}")
finally:
await self._restore_initial_state()
################## test manipulator move center ##################
async def test_move_global_center(self):
await self._setup_global(c.TRANSFORM_OP_MOVE)
await self._test_move_center()
await self._test_move_center(
modifier=carb.input.KeyboardInput.LEFT_ALT
) # with alt down, transform is not changed
async def test_move_local_center(self):
await self._setup_local(c.TRANSFORM_OP_MOVE)
await self._test_move_center()
async def _test_move_center(self, dirs=[Vec2(50, 0)], modifier: carb.input.KeyboardInput = None):
try:
center = Vec2(self._window_width, self._window_height) / 2
waypoints = [center]
for dir in dirs:
waypoints.append(center + dir)
if modifier:
await ui_test.input.emulate_keyboard(carb.input.KeyboardEventType.KEY_PRESS, modifier)
await ui_test.human_delay()
await self._emulate_mouse_drag_and_drop_multiple_waypoints(waypoints)
if modifier:
await ui_test.input.emulate_keyboard(carb.input.KeyboardEventType.KEY_RELEASE, modifier)
await ui_test.human_delay()
test_name = f"xyz.{len(dirs)}"
if modifier:
test_name += str(modifier).split(".")[-1]
await self._snapshot(test_name) # todo better hash name?
finally:
await self._restore_initial_state()
# Test manipulator is placed correctly if the selected prim's parent is moved
async def test_move_selected_parent(self):
await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Xform/Cube_01"])
stage = self._context.get_stage()
parent_translate_attr = stage.GetAttributeAtPath("/World/Xform.xformOp:translate")
try:
parent_translate_attr.Set((0, 100, -100))
await ui_test.human_delay(4)
await self._snapshot()
finally:
await self._restore_initial_state()
################################################################
######################## test rotation #########################
################################################################
################## test manipulator rotate arc ##################
async def test_rotate_global_arc(self):
await self._setup_global(c.TRANSFORM_OP_ROTATE)
await self._test_rotate_arc()
# add a test to only select prims in the same hierarchy and pivot prim being the child
# to cover the bug when consolidated prim path has one entry and is not the pivot prim
async def test_rotate_global_arc_single_hierarchy(self):
await self._setup_global(c.TRANSFORM_OP_ROTATE, prims_to_select=["/World/Xform", "/World/Xform/Cube_01"])
await self._test_rotate_arc()
async def test_rotate_local_arc(self):
await self._setup_local(c.TRANSFORM_OP_ROTATE)
await self._test_rotate_arc(180)
async def test_free_rotation_clamped(self):
await self._setup_global(c.TRANSFORM_OP_ROTATE)
self._settings.set(c.FREE_ROTATION_TYPE_SETTING, c.FREE_ROTATION_TYPE_CLAMPED)
await self._test_move_center(dirs=[Vec2(100, 100)])
async def test_free_rotation_continuous(self):
await self._setup_global(c.TRANSFORM_OP_ROTATE)
self._settings.set(c.FREE_ROTATION_TYPE_SETTING, c.FREE_ROTATION_TYPE_CONTINUOUS)
await self._test_move_center(dirs=[Vec2(100, 100)])
async def test_bbox_center_multi_prim_rotate_global(self):
await self._test_bbox_center_multi_prim_rotate(self._setup_global)
async def test_bbox_center_multi_prim_rotate_local(self):
await self._test_bbox_center_multi_prim_rotate(self._setup_local)
async def _test_bbox_center_multi_prim_rotate(self, test_fn):
await test_fn(
c.TRANSFORM_OP_ROTATE,
file_name="test_bbox_rotation.usda",
prims_to_select=["/World/Cube", "/World/Cube_01", "/World/Cube_02"],
placement=prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER,
)
await self._test_rotate_arc(post_snap=True)
async def _test_rotate_arc(self, offset: float = 0, post_snap=False):
OFFSET = 45
MOVEMENT = ["x", "y", "z", "screen"]
SEGMENT_COUNT = 12
center = Vec2(self._window_width, self._window_height) / 2
for i, test_name in enumerate(MOVEMENT):
await ui_test.human_delay()
waypoints = []
step = 360 / SEGMENT_COUNT
for wi in range(int(SEGMENT_COUNT * 1.5)):
dir = Vec2(
math.cos(math.radians(-i * 120 - 30 + wi * step + offset)),
math.sin(math.radians(-i * 120 - 30 + wi * step + offset)),
)
waypoints.append(center + dir * (OFFSET if i < 3 else 80))
try:
async def before_drop():
await self._snapshot(test_name)
await self._emulate_mouse_drag_and_drop_multiple_waypoints(waypoints, on_before_drop=before_drop)
if post_snap:
await ui_test.human_delay(human_delay_speed=4)
await self._snapshot(f"{test_name}.post")
finally:
await self._restore_initial_state()
################################################################
########################## test scale ##########################
################################################################
# Given the complexity of multi-manipulating with non-uniform scale and potential shear from parents,
# we reduce the test complexity using a simpler manipulating case.
# Revisit when there's more complicated scaling needs.
################## test manipulator scale axis ##################
async def test_scale_local_axis(self):
await self._setup_local(c.TRANSFORM_OP_SCALE)
self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True)
await ui_test.human_delay()
# test scale up
await self._test_move_axis(180)
# test scale down
await self._test_move_axis(180, distance=-100)
################## test manipulator move plane ##################
async def test_scale_local_plane(self):
await self._setup_local(c.TRANSFORM_OP_SCALE)
self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True)
await ui_test.human_delay()
# test scale up
await self._test_move_plane(180)
# test scale down
await self._test_move_plane(180, distance=-100)
################## test manipulator move center ##################
async def test_scale_local_center(self):
await self._setup_local(c.TRANSFORM_OP_SCALE)
self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True)
await ui_test.human_delay()
await self._test_move_center()
await ui_test.human_delay()
await self._test_move_center(dirs=[Vec2(50, 0), Vec2(-100, 0)])
################################################################
################### test manipulator toolbar ###################
################################################################
async def test_toolbar(self):
await self._setup_global(c.TRANSFORM_OP_MOVE, True)
await ui_test.human_delay(30)
await ui_test.emulate_mouse_move_and_click(Vec2(210, 340), human_delay_speed=20)
# expand the toolbar and take a snapshot to make sure the render/layout is correct.
# if you changed the look of toolbar button or toolbar layout, update the golden image for this test.
# added since OM-65012 for a broken button image
await self._snapshot("visual")
# Test the local/global button
await ui_test.human_delay(30)
await ui_test.emulate_mouse_move_and_click(Vec2(215, 365), human_delay_speed=20)
self.assertEqual(self._settings.get(c.TRANSFORM_MOVE_MODE_SETTING), c.TRANSFORM_MODE_LOCAL)
await ui_test.human_delay(30)
await ui_test.emulate_mouse_move_and_click(Vec2(215, 365), human_delay_speed=20)
self.assertEqual(self._settings.get(c.TRANSFORM_MOVE_MODE_SETTING), c.TRANSFORM_MODE_GLOBAL)
################################################################
#################### test manipulator snap #####################
################################################################
async def _run_snap_test(self, keep_spacing: bool):
await self._setup_global(c.TRANSFORM_OP_MOVE, True, "test_snap.usda", ["/World/Cube", "/World/Cube_01"])
stage = self._context.get_stage()
cube_prim = stage.GetPrimAtPath("/World/Cube")
cube01_prim = stage.GetPrimAtPath("/World/Cube_01")
_, _, _, translate_cube_original = omni.usd.get_local_transform_SRT(cube_prim)
_, _, _, translate_cube01_original = omni.usd.get_local_transform_SRT(cube01_prim)
self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER)
self._settings.set(snap_c.SNAP_PROVIDER_NAME_SETTING_PATH, [SURFACE_SNAP_NAME])
self._settings.set(snap_c.CONFORM_TO_TARGET_SETTING_PATH, True)
self._settings.set(snap_c.KEEP_SPACING_SETTING_PATH, keep_spacing)
self._settings.set("/app/viewport/snapEnabled", True)
center = Vec2(self._window_width, self._window_height) / 2
await ui_test.human_delay()
await ui_test.emulate_mouse_move(center, 10)
await self._emulate_mouse_drag_and_drop_multiple_waypoints(
[center, center / 1.5], human_delay_speed=1, num_steps=50
)
_, _, _, translate_cube = omni.usd.get_local_transform_SRT(cube_prim)
_, _, _, translate_cube01 = omni.usd.get_local_transform_SRT(cube01_prim)
self._settings.set("/app/viewport/snapEnabled", False)
return translate_cube, translate_cube_original, translate_cube01, translate_cube01_original
async def test_snap_keep_spacing(self):
(
translate_cube,
translate_cube_original,
translate_cube01,
translate_cube01_original,
) = await self._run_snap_test(True)
# Make sure start conditions aren't already on Plane
self.assertFalse(Gf.IsClose(translate_cube_original[1], -100, 0.02))
self.assertFalse(Gf.IsClose(translate_cube01_original[1], -100, 0.02))
# Y position should be snapped to surface at -100 Y (within a tolerance for Storm)
self.assertTrue(Gf.IsClose(translate_cube[1], -100, 0.02))
self.assertTrue(Gf.IsClose(translate_cube01[1], -100, 0.02))
# X and Z should be greater than original
self.assertTrue(translate_cube[0] > translate_cube_original[0])
self.assertTrue(translate_cube[2] > translate_cube_original[2])
# X and Z should be greater than original
self.assertTrue(translate_cube01[2] > translate_cube01_original[2])
self.assertTrue(translate_cube01[0] > translate_cube01_original[0])
# Workaround for testing on new Viewport, needs delay before running test_snap_no_keep_spacing test.
self._selection.set_selected_prim_paths([], True)
await ui_test.human_delay(10)
async def test_snap_no_keep_spacing(self):
(
translate_cube,
translate_cube_original,
translate_cube01,
translate_cube01_original,
) = await self._run_snap_test(False)
self.assertFalse(Gf.IsClose(translate_cube_original[1], -100, 0.02))
self.assertFalse(Gf.IsClose(translate_cube01_original[1], -100, 0.02))
# cube and cube01 should be at same location since keep spacing is off
self.assertTrue(Gf.IsClose(translate_cube, translate_cube01, 1e-6))
# Y position should be snapped to surface at -100 Y
self.assertTrue(Gf.IsClose(translate_cube[1], -100, 0.02))
# X and Z should be greater than original
self.assertTrue(translate_cube[0] > translate_cube_original[0])
self.assertTrue(translate_cube[2] > translate_cube_original[2])
# Workaround for testing on new Viewport, needs delay before running test_snap_no_keep_spacing test.
self._selection.set_selected_prim_paths([], True)
await ui_test.human_delay(10)
################################################################
##################### test prim with pivot #####################
################################################################
async def _test_move_axis_one_dir(self, dir: Vec2 = Vec2(0, 1), distance: float = 50):
OFFSET = 50
center = Vec2(self._window_width, self._window_height) / 2
try:
await ui_test.emulate_mouse_drag_and_drop(center + dir * OFFSET, center + dir * (OFFSET + distance))
await self._snapshot(f"{distance}")
finally:
await self._restore_initial_state()
async def test_move_local_axis_with_pivot(self):
# tests for when _should_keep_manipulator_orientation_unchanged is true
await self._setup_local(c.TRANSFORM_OP_MOVE, file_name="test_pivot.usda", prims_to_select=["/World/Cube"])
await self._test_move_axis_one_dir()
async def test_scale_local_axis_with_pivot(self):
# tests for when _should_keep_manipulator_orientation_unchanged is true
await self._setup_local(c.TRANSFORM_OP_SCALE, file_name="test_pivot.usda", prims_to_select=["/World/Cube"])
await self._test_move_axis_one_dir()
################################################################
##################### test remove xformOps #####################
################################################################
async def test_remove_xform_ops_pivot(self):
# remove the xformOps attributes, the manipulator position should update
await self._setup_local(
c.TRANSFORM_OP_MOVE, file_name="test_remove_xformOps.usda", prims_to_select=["/World/Cube"]
)
stage = self._context.get_stage()
cube_prim = stage.GetPrimAtPath("/World/Cube")
attrs_to_remove = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
for attr in attrs_to_remove:
cube_prim.RemoveProperty(attr)
await ui_test.human_delay(10)
await self._snapshot()
async def test_remove_xform_op_order_pivot(self):
# remove the xformOpOrder attribute, the manipulator position should update
await self._setup_local(
c.TRANSFORM_OP_MOVE, file_name="test_remove_xformOps.usda", prims_to_select=["/World/Cube"]
)
stage = self._context.get_stage()
cube_prim = stage.GetPrimAtPath("/World/Cube")
cube_prim.RemoveProperty("xformOpOrder")
await ui_test.human_delay(10)
await self._snapshot()
################################################################
################### test unknown op & modes ####################
################################################################
async def test_unknown_move_mode(self):
await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Xform/Cube_01"])
await self._snapshot("pre-unknown-mode")
self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, "UNKNOWN")
await self._snapshot("post-unknown-mode")
self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, c.TRANSFORM_MODE_LOCAL)
await self._snapshot("reset-known-mode")
async def test_unknown_rotate_mode(self):
await self._setup_global(c.TRANSFORM_OP_ROTATE, prims_to_select=["/World/Xform/Cube_01"])
await self._snapshot("pre-unknown-mode")
self._settings.set(c.TRANSFORM_ROTATE_MODE_SETTING, "UNKNOWN")
await self._snapshot("post-unknown-mode")
self._settings.set(c.TRANSFORM_ROTATE_MODE_SETTING, c.TRANSFORM_MODE_LOCAL)
await self._snapshot("reset-known-mode")
async def test_unknown_mode_enabled(self):
await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=[])
await self._snapshot("known-mode-unselected")
self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, "UNKNOWN")
await self._snapshot("unknown-mode-unselected")
self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True)
await self._snapshot("unknown-mode-selected")
self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL)
await self._snapshot("known-mode-selected")
async def test_unknown_op_enabled(self):
await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=[])
await self._snapshot("move-op-unselected")
self._settings.set(c.TRANSFORM_OP_SETTING, "UNKNOWN")
await self._snapshot("unknown-op-selected")
self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True)
await self._snapshot("unknown-op-selected")
self._settings.set(c.TRANSFORM_OP_SETTING, c.TRANSFORM_OP_ROTATE)
await self._snapshot("rotate-op-selected")
| 29,723 | Python | 42.711765 | 134 | 0.600949 |
omniverse-code/kit/exts/omni.hydra.pxr/omni/hydra/pxr/engine/tests/__init__.py | from .render_test import *
| 27 | Python | 12.999994 | 26 | 0.740741 |
omniverse-code/kit/exts/omni.hydra.pxr/omni/hydra/pxr/engine/tests/render_test.py |
import omni.kit.test
import omni.usd
import carb
from omni.kit.viewport.utility.tests import capture_viewport_and_compare
from omni.kit.test.teamcity import is_running_in_teamcity
import sys
import unittest
from pathlib import Path
EXTENSION_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${omni.hydra.pxr}")).resolve().absolute()
TESTS_ROOT = EXTENSION_ROOT.joinpath("data", "tests")
USD_SCENES = TESTS_ROOT.joinpath("usd")
GOLDEN_IMAGES = TESTS_ROOT.joinpath("images")
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path())
class HydraTextureTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self.usd_context = omni.usd.get_context()
await self.usd_context.new_stage_async()
async def tearDown(self):
await self.usd_context.new_stage_async()
async def run_imge_test(self, usd_file: str, image_name: str, fn = None, wait_iterations: int = 5, threshold: int = 10):
await self.usd_context.open_stage_async(str(USD_SCENES.joinpath(usd_file)))
app = omni.kit.app.get_app()
for i in range(wait_iterations):
await app.next_update_async()
if fn:
fn()
for i in range(wait_iterations):
await app.next_update_async()
passed, fail_msg = await capture_viewport_and_compare(image_name, threshold=threshold, output_img_dir=OUTPUTS_DIR, golden_img_dir=GOLDEN_IMAGES)
self.assertTrue(passed, msg=fail_msg)
@unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020")
async def test_render_cube(self):
"""Test rendering produces an image"""
await self.run_imge_test('cube.usda', 'render_cube.png')
@unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020")
async def test_render_cubes(self):
"""Test rendering produces an image after re-open"""
await self.run_imge_test('cubes.usda', 'render_cubes.png')
@unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020")
async def test_select_cube_x(self):
"""Test selection on cube_x hilights correct prim"""
await self.run_imge_test('cubes.usda', 'select_cube_x.png',
lambda: self.usd_context.get_selection().set_selected_prim_paths(['/World/cube_x'], True)
)
@unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020")
async def test_select_cube_y(self):
"""Test selection on cube_y hilights correct prim"""
await self.run_imge_test('cubes.usda', 'select_cube_y.png',
lambda: self.usd_context.get_selection().set_selected_prim_paths(['/World/cube_y'], True)
)
@unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020")
async def test_select_cube_z(self):
"""Test selection on cube_z hilights correct prim"""
await self.run_imge_test('cubes.usda', 'select_cube_z.png',
lambda: self.usd_context.get_selection().set_selected_prim_paths(['/World/cube_z'], True)
)
@unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020")
async def test_display_purpose(self):
"""Test the carb display purpose settings"""
def set_puposes(guide: bool, proxy: bool, render: bool):
settings = carb.settings.get_settings()
settings.set('/persistent/app/hydra/displayPurpose/guide', guide)
settings.set('/persistent/app/hydra/displayPurpose/proxy', proxy)
settings.set('/persistent/app/hydra/displayPurpose/render', render)
try:
# Test, guide, proxy, and render purposes render by default
await self.run_imge_test('purpose.usda', 'all_purposes.png')
# Test with proxy purpose disabled
set_puposes(False, True, True)
await self.run_imge_test('purpose.usda', 'proxy_purposes.png')
# Test with guide purpose disabled
set_puposes(True, False, True)
await self.run_imge_test('purpose.usda', 'guide_purposes.png')
# Test with render purpose disabled
set_puposes(True, True, False)
await self.run_imge_test('purpose.usda', 'render_purposes.png')
finally:
set_puposes(True, True, True)
# Run the all purpose test once more now that all have been re-enabled
await self.run_imge_test('purpose.usda', 'all_purposes.png')
@unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020")
async def test_rtx_render_modes(self):
"""Test some RTX render settings are honored"""
settings = carb.settings.get_settings()
settings.set("/rtx/debugMaterialType", -1)
settings.set("/rtx/wireframe/mode", 0)
try:
# Test, guide, proxy, and render purposes render by default
await self.run_imge_test('render_modes.usda', 'render_modes_default.png')
settings.set("/rtx/debugMaterialType", 0)
await self.run_imge_test('render_modes.usda', 'render_modes_no_material.png')
# Tests below create images that are outside a meaningful range/image test on Windows with Vulkan
# Since they are highly specific test of wireframe rendering, just skip them in that case
import sys
if sys.platform.startswith('win') and ("--vulkan" in sys.argv):
return
settings.set("/rtx/wireframe/mode", 2)
await self.run_imge_test('render_modes.usda', 'render_modes_no_material_wire.png')
settings.set("/rtx/debugMaterialType", -1)
await self.run_imge_test('render_modes.usda', 'render_modes_wire_material.png')
finally:
settings.set("/rtx/debugMaterialType", -1)
settings.set("/rtx/wireframe/mode", 0)
| 5,984 | Python | 43.333333 | 152 | 0.642714 |
omniverse-code/kit/exts/omni.kit.window.reshade_editor/config/extension.toml | [package]
title = "ReShade preset editor window"
version = "0.1.1"
repository = ""
keywords = ["kit", "reshade"]
[dependencies]
"omni.ui" = {}
"omni.kit.viewport.utility" = {}
"omni.hydra.rtx" = {}
[[python.module]]
name = "omni.kit.window.reshade_editor"
[[test]]
viewport_legacy_only = true
args = [
"--/rtx/reshade/enable=true"
]
dependencies = [
"omni.kit.mainwindow",
"omni.hydra.rtx",
"omni.kit.window.viewport"
]
timeout = 600 # OM-51983
stdoutFailPatterns.exclude = [
"*Tried to call pure virtual function \"AbstractItemModel::get_item_children\"*",
]
| 584 | TOML | 18.499999 | 85 | 0.659247 |
omniverse-code/kit/exts/omni.kit.window.reshade_editor/omni/kit/window/reshade_editor/reshade_window.py | # 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.
import omni.ui as ui
import rtx.reshade
from typing import Callable
reshade = rtx.reshade.acquire_reshade_interface()
class ComboListItem(ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = ui.SimpleStringModel(text)
class ComboListModel(ui.AbstractItemModel):
def __init__(self, parent_model, items):
super().__init__()
self._current_index = parent_model
self._current_index.add_value_changed_fn(lambda a: self._item_changed(None))
self._items = [ComboListItem(item) for item in items]
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
class ReshadeUniformValue(ui.AbstractItem, ui.AbstractValueModel):
def __init__(self, handle, component: int, reshade_ctx):
ui.AbstractItem.__init__(self)
ui.AbstractValueModel.__init__(self)
self._handle = handle
self._component = component
self._reshade_ctx = reshade_ctx
def get_value_as_int(self) -> int:
return reshade.get_uniform_value_as_int(self._reshade_ctx, self._handle, self._component)
def get_value_as_bool(self) -> bool:
return reshade.get_uniform_value_as_bool(self._reshade_ctx, self._handle, self._component)
def get_value_as_float(self) -> float:
return reshade.get_uniform_value_as_float(self._reshade_ctx, self._handle, self._component)
def set_value(self, value):
if isinstance(value, int):
reshade.set_uniform_value_as_int(self._reshade_ctx, self._handle, self._component, value)
else:
reshade.set_uniform_value_as_float(self._reshade_ctx, self._handle, self._component, float(value))
self._value_changed()
class ReshadeUniformVectorValue(ui.AbstractItemModel):
def __init__(self, handle, component_count: int, reshade_ctx):
super().__init__()
self._items = [ ReshadeUniformValue(handle, component, reshade_ctx) for component in range(component_count) ]
for item in self._items:
item.add_value_changed_fn(lambda a, item=item: self._item_changed(item))
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
return item
def begin_edit(self, item):
pass # Crashes without this
def end_edit(self, item):
pass # Crashes without this
class ReshadeUniformItem(ui.AbstractItem):
def __init__(self, handle, reshade_ctx):
super().__init__()
type_info = reshade.get_uniform_type(handle)
self._name = reshade.get_uniform_name(handle)
self._base_type = type_info[0]
self._components = type_info[1]
self._ui_type = reshade.get_uniform_annotation_as_string(handle, "ui_type")
self._ui_label = reshade.get_uniform_annotation_as_string(handle, "ui_label")
self._ui_tooltip = reshade.get_uniform_annotation_as_string(handle, "ui_tooltip")
ui_min = reshade.get_uniform_annotation_as_float(handle, "ui_min")
ui_max = reshade.get_uniform_annotation_as_float(handle, "ui_max")
if (ui_min == ui_max):
self._ui_min = 0
self._ui_max = 1
else:
self._ui_min = ui_min
self._ui_max = ui_max
self._ui_step = reshade.get_uniform_annotation_as_float(handle, "ui_step")
ui_items = reshade.get_uniform_annotation_as_string(handle, "ui_items")
self._ui_items = ui_items.split(';') if ui_items else []
if self._ui_items and not self._ui_items[-1]: # Delete last item if empty
del self._ui_items[-1]
self.model = ReshadeUniformValue(handle, 0, reshade_ctx) if self._components == 1 else ReshadeUniformVectorValue(handle, self._components, reshade_ctx)
class ReshadeEffectListItem(ui.AbstractItem):
def __init__(self, effect, reshade_ctx):
super().__init__()
self._name = reshade.get_effect_name(effect)
self._uniforms = []
for handle in reshade.get_uniform_list(reshade_ctx, effect):
if reshade.get_uniform_annotation_as_string(handle, "source"):
continue # Skip uniforms that have a custom source
self._uniforms.append(ReshadeUniformItem(handle, reshade_ctx))
class ReshadeVariableEditorModel(ui.AbstractItemModel):
def __init__(self, reshade_ctx):
super().__init__()
self._effects = []
for handle in reshade.get_effect_list(reshade_ctx):
effect = ReshadeEffectListItem(handle, reshade_ctx)
if not effect._uniforms:
continue # Skip effects that have not configurable uniforms
self._effects.append(effect)
def get_item_children(self, item):
if item is None:
return self._effects
elif isinstance(item, ReshadeEffectListItem):
return item._uniforms
def get_item_value_model(self, item, column_id):
if item is None:
return None
else:
return item.model
def get_item_value_model_count(self, item):
return 1
class ReshadeVariableEditorDelegate(ui.AbstractItemDelegate):
def build_branch(self, model, item, column_id, level, expanded):
with ui.HStack(width=20*level, height=0):
if level == 0:
triangle_alignment = ui.Alignment.RIGHT_CENTER
if expanded:
triangle_alignment = ui.Alignment.CENTER_BOTTOM
ui.Spacer(width=3)
ui.Triangle(alignment=triangle_alignment, width=10, height=10, style={"background_color": 0xFFFFFFFF})
ui.Spacer(width=7)
else:
ui.Spacer()
def build_widget(self, model, item, column_id, level, expanded):
with ui.VStack():
ui.Spacer(height=2.5)
if level == 1: # Effect list level
ui.Label(item._name)
else: # Uniform list level
with ui.HStack(width=500, spacing=5):
if item._base_type == 1:
self.create_bool_widget(item)
elif item._base_type >= 2 and item._base_type <= 5:
self.create_int_widget(item)
elif item._base_type >= 6 and item._base_type <= 7:
self.create_float_widget(item)
else:
return
label = ui.Label(item._ui_label if item._ui_label else item._name)
if item._ui_tooltip:
label.set_tooltip(item._ui_tooltip)
ui.Spacer(height=2.5)
def create_bool_widget(self, uniform):
if uniform._components != 1:
return
if uniform._ui_type == "combo":
return ui.ComboBox(ComboListModel(uniform.model, ["False", "True"]))
else:
return ui.CheckBox(uniform.model)
def create_int_widget(self, uniform):
if uniform._components == 1:
return self.create_int_widget_scalar(uniform)
else:
return self.create_int_widget_vector(uniform)
def create_int_widget_scalar(self, uniform):
if uniform._ui_type == "combo" or uniform._ui_type == "list" or uniform._ui_type == "radio":
return ui.ComboBox(ComboListModel(uniform.model, uniform._ui_items))
if uniform._ui_type == "slider":
return ui.IntSlider(uniform.model, min=int(uniform._ui_min), max=int(uniform._ui_max), step=int(uniform._ui_step))
elif uniform._ui_type == "drag":
return ui.IntDrag(uniform.model, min=int(uniform._ui_min), max=int(uniform._ui_max))
else:
return ui.IntField(uniform.model)
def create_int_widget_vector(self, uniform):
if uniform._ui_type == "drag":
return ui.MultiIntDragField(uniform.model, min=int(uniform._ui_min), max=int(uniform._ui_max), h_spacing=2)
else:
return ui.MultiIntField(uniform.model, h_spacing=2)
def create_float_widget(self, uniform):
if uniform._components == 1:
return self.create_float_widget_scalar(uniform)
else:
return self.create_float_widget_vector(uniform)
def create_float_widget_scalar(self, uniform):
if uniform._ui_type == "slider":
return ui.FloatSlider(uniform.model, min=float(uniform._ui_min), max=float(uniform._ui_max), step=float(uniform._ui_step))
elif uniform._ui_type == "drag":
return ui.FloatDrag(uniform.model, min=float(uniform._ui_min), max=float(uniform._ui_max))
else:
return ui.FloatField(uniform.model)
def create_float_widget_vector(self, uniform):
if uniform._ui_type == "drag":
return ui.MultiFloatDragField(uniform.model, min=float(uniform._ui_min), max=float(uniform._ui_max), h_spacing=2)
elif uniform._ui_type == "color":
with ui.HStack(spacing=2):
widget = ui.MultiFloatDragField(uniform.model, min=float(uniform._ui_min), max=float(uniform._ui_max), h_spacing=2)
ui.ColorWidget(uniform.model, width=0, height=0)
return widget
else:
return ui.MultiFloatField(uniform.model, h_spacing=2)
class ReshadeTechniqueModel(ui.AbstractValueModel):
def __init__(self, handle, reshade_ctx):
super().__init__()
self._handle = handle
self._reshade_ctx = reshade_ctx
def get_value_as_bool(self) -> bool:
return reshade.get_technique_enabled(self._reshade_ctx, self._handle)
def set_value(self, value: bool):
reshade.set_technique_enabled(self._reshade_ctx, self._handle, value)
self._value_changed()
class ReshadeTechniqueListItem(ui.AbstractItem):
def __init__(self, handle, reshade_ctx):
super().__init__()
self._name = reshade.get_technique_name(handle)
self._ui_label = reshade.get_technique_annotation_as_string(handle, "ui_label")
self._ui_tooltip = reshade.get_technique_annotation_as_string(handle, "ui_tooltip")
self.model = ReshadeTechniqueModel(handle, reshade_ctx)
class ReshadeTechniqueEditorModel(ui.AbstractItemModel):
def __init__(self, reshade_ctx):
super().__init__()
self._techniques = [ ReshadeTechniqueListItem(handle, reshade_ctx) for handle in reshade.get_technique_list(reshade_ctx) ]
def get_item_children(self, item):
if item is not None:
return []
return self._techniques
def get_item_value_model(self, item, column_id):
if item is None:
return None
return item.model
def get_item_value_model_count(self, item):
return 1
class ReshadeTechniqueEditorDelegate(ui.AbstractItemDelegate):
def build_branch(self, model, item, column_id, level, expanded):
pass
def build_widget(self, model, item, column_id, level, expanded):
with ui.VStack():
ui.Spacer(height=2.5)
with ui.HStack(width=0, height=0, spacing=5):
ui.CheckBox(item.model)
label = ui.Label(item._ui_label if item._ui_label else item._name)
if item._ui_tooltip:
label.set_tooltip(item._ui_tooltip)
ui.Spacer(height=2.5)
class ReshadeWindow:
def __init__(self, on_visibility_changed_fn: Callable):
self._window = ui.Window("ReShade", width=500, height=500)
self._window.set_visibility_changed_fn(on_visibility_changed_fn)
self._reshade_ctx = None
try:
from omni.kit.viewport.utility import get_active_viewport
viewport = get_active_viewport()
self._reshade_ctx = reshade.get_context(viewport.usd_context_name)
except (ImportError, AttributeError):
pass
if self._reshade_ctx is None:
with self._window.frame:
with ui.VStack():
ui.Spacer()
ui.Label("ReShade context not available", alignment=ui.Alignment.CENTER, style={"font_size": 48})
ui.Spacer()
import carb
carb.log_error(f"ReShade context not available for Viewport {viewport}")
return
self._update_sub = reshade.subscribe_to_update_events(self._reshade_ctx, self._on_update)
self._build_ui()
def destroy(self):
self._window = None
self._update_sub = None
def _build_ui(self):
reshade_ctx = self._reshade_ctx
self._tmodel = ReshadeTechniqueEditorModel(reshade_ctx)
self._tdelegate = ReshadeTechniqueEditorDelegate()
self._vmodel = ReshadeVariableEditorModel(reshade_ctx)
self._vdelegate = ReshadeVariableEditorDelegate()
with self._window.frame:
with ui.VStack(height=0, spacing=5):
self._tview = ui.TreeView(
self._tmodel,
delegate=self._tdelegate,
root_visible=False,
header_visible=False)
ui.Line()
self._vview = ui.TreeView(
self._vmodel,
delegate=self._vdelegate,
root_visible=False,
header_visible=False,
expand_on_branch_click=True)
def _on_update(self):
self._build_ui()
| 13,948 | Python | 38.854286 | 159 | 0.610984 |
omniverse-code/kit/exts/omni.kit.window.reshade_editor/omni/kit/window/reshade_editor/extension.py | # 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.
import omni.ext
import omni.kit.ui
from .reshade_window import ReshadeWindow
MENU_PATH = "Window/ReShade Editor"
class ReshadeWindowExtension(omni.ext.IExt):
def on_startup(self):
self._window = None
try:
self._menu = omni.kit.ui.get_editor_menu().add_item(
MENU_PATH, lambda m, v: self.show_window(v), toggle=True, value=False
)
except:
pass
def on_shutdown(self):
self._menu = None
def show_window(self, value):
if value:
def on_visibility_changed(visible):
omni.kit.ui.get_editor_menu().set_value(MENU_PATH, visible)
self._window = ReshadeWindow(on_visibility_changed if self._menu else None)
else:
if self._window:
self._window.destroy()
self._window = None
| 1,291 | Python | 32.128204 | 87 | 0.654531 |
omniverse-code/kit/exts/omni.kit.window.reshade_editor/omni/kit/window/reshade_editor/__init__.py | from .extension import ReshadeWindowExtension
| 46 | Python | 22.499989 | 45 | 0.891304 |
omniverse-code/kit/exts/omni.kit.window.reshade_editor/omni/kit/window/reshade_editor/tests/__init__.py | from .test_extension import *
| 30 | Python | 14.499993 | 29 | 0.766667 |
omniverse-code/kit/exts/omni.kit.window.reshade_editor/omni/kit/window/reshade_editor/tests/test_extension.py | # 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.
import omni.kit.test
import pathlib
import carb
import omni.usd
import omni.kit.app
from omni.kit.test import AsyncTestCase
from omni.kit.window.reshade_editor.reshade_window import ReshadeWindow
EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
TESTS_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests")
class TestReshadeEditor(AsyncTestCase):
async def setUp(self):
super().setUp()
await omni.usd.get_context().new_stage_async()
settings = carb.settings.get_settings()
settings.set("/rtx/reshade/enable", "true")
settings.set("/rtx/reshade/presetFilePath", f"{TESTS_PATH}/preset.ini")
settings.set("/rtx/reshade/effectSearchDirPath", f"{TESTS_PATH}")
# Update app a few times for effects to load and compile
for i in range(20):
await omni.kit.app.get_app().next_update_async()
async def test_variable_list(self):
w = ReshadeWindow(None)
self.assertIsNotNone(w._window)
effects = w._vmodel.get_item_children(None)
self.assertIsNotNone(effects)
self.assertTrue(len(effects) == 1) # data/tests/simple.fx
variables = w._vmodel.get_item_children(effects[0])
self.assertIsNotNone(effects)
self.assertTrue(len(variables) == 1) # "fill_color" in data/tests/simple.fx
async def test_technique_list(self):
w = ReshadeWindow(None)
self.assertIsNotNone(w._window)
techniques = w._tmodel.get_item_children(None)
self.assertIsNotNone(techniques)
self.assertTrue(len(techniques) == 1) # technique "simple" in data/tests/simple.fx
| 2,119 | Python | 40.568627 | 123 | 0.706937 |
omniverse-code/kit/exts/omni.kit.window.reshade_editor/docs/CHANGELOG.md | # Changelog
## [0.1.1] - 2022-05-23
### Changed
- Support new Viewport API
- Add dependency on omni.kit.viewport.utility
| 122 | Markdown | 16.571426 | 45 | 0.696721 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.