file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.volume_nodes/ogn/docs/LoadVDB.rst | .. _omni_volume_LoadVDB_1:
.. _omni_volume_LoadVDB:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Load VDB
:keywords: lang-en omnigraph node Omni Volume ReadOnly volume load-v-d-b
Load VDB
========
.. <description>
Loads a VDB from file and puts it in a memory buffer.
.. </description>
Installation
------------
To use this node enable :ref:`omni.volume_nodes<ext_omni_volume_nodes>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:assetPath", "``token``", "Path to VDB file to load.", ""
"inputs:execIn", "``execution``", "Input execution", "None"
"inputs:gridName", "``token``", "Optional name of the grid to extract. All grids are extracted if this is left empty.", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:data", "``uint[]``", "Data loaded from VDB file in NanoVDB memory format.", "None"
"outputs:execOut", "``execution``", "Output execution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.volume.LoadVDB"
"Version", "1"
"Extension", "omni.volume_nodes"
"Has State?", "True"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"tags", "VDB"
"uiName", "Load VDB"
"__tokens", "{}"
"Categories", "Omni Volume"
"Generated Class Name", "LoadVDBDatabase"
"Python Module", "omni.volume_nodes"
| 1,789 | reStructuredText | 23.520548 | 131 | 0.553382 |
omniverse-code/kit/exts/omni.volume_nodes/omni/volume_nodes/ogn/LoadVDBDatabase.py | """Support for simplified access to data on nodes of type omni.volume.LoadVDB
Loads a VDB from file and puts it in a memory buffer.
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class LoadVDBDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.volume.LoadVDB
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.assetPath
inputs.execIn
inputs.gridName
Outputs:
outputs.data
outputs.execOut
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:assetPath', 'token', 0, None, 'Path to VDB file to load.', {}, True, "", False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('inputs:gridName', 'token', 0, None, 'Optional name of the grid to extract. All grids are extracted if this is left empty.', {}, False, None, False, ''),
('outputs:data', 'uint[]', 0, None, 'Data loaded from VDB file in NanoVDB memory format.', {}, True, None, False, ''),
('outputs:execOut', 'execution', 0, None, 'Output execution', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def assetPath(self):
data_view = og.AttributeValueHelper(self._attributes.assetPath)
return data_view.get()
@assetPath.setter
def assetPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.assetPath)
data_view = og.AttributeValueHelper(self._attributes.assetPath)
data_view.set(value)
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
@property
def gridName(self):
data_view = og.AttributeValueHelper(self._attributes.gridName)
return data_view.get()
@gridName.setter
def gridName(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gridName)
data_view = og.AttributeValueHelper(self._attributes.gridName)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.data_size = None
self._batchedWriteValues = { }
@property
def data(self):
data_view = og.AttributeValueHelper(self._attributes.data)
return data_view.get(reserved_element_count=self.data_size)
@data.setter
def data(self, value):
data_view = og.AttributeValueHelper(self._attributes.data)
data_view.set(value)
self.data_size = data_view.get_array_size()
@property
def execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = LoadVDBDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = LoadVDBDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = LoadVDBDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,054 | Python | 43.09375 | 163 | 0.647009 |
omniverse-code/kit/exts/omni.volume_nodes/omni/volume_nodes/ogn/SaveVDBDatabase.py | """Support for simplified access to data on nodes of type omni.volume.SaveVDB
Saves a VDB from file and puts it in a memory buffer.
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class SaveVDBDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.volume.SaveVDB
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.assetPath
inputs.compressionMode
inputs.data
inputs.execIn
Outputs:
outputs.execOut
Predefined Tokens:
tokens.none
tokens.blosc
tokens.zip
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:assetPath', 'token', 0, None, 'Path to VDB file to save.', {}, True, "", False, ''),
('inputs:compressionMode', 'token', 0, None, 'The compression mode to use when encoding', {ogn.MetadataKeys.ALLOWED_TOKENS: 'None,Blosc,Zip', 'default': 'None', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"none": "None", "blosc": "Blosc", "zip": "Zip"}'}, False, None, False, ''),
('inputs:data', 'uint[]', 0, None, 'Data to save to file in NanoVDB or OpenVDB memory format.', {}, True, [], False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('outputs:execOut', 'execution', 0, None, 'Output execution', {}, True, None, False, ''),
])
class tokens:
none = "None"
blosc = "Blosc"
zip = "Zip"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def assetPath(self):
data_view = og.AttributeValueHelper(self._attributes.assetPath)
return data_view.get()
@assetPath.setter
def assetPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.assetPath)
data_view = og.AttributeValueHelper(self._attributes.assetPath)
data_view.set(value)
@property
def compressionMode(self):
data_view = og.AttributeValueHelper(self._attributes.compressionMode)
return data_view.get()
@compressionMode.setter
def compressionMode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.compressionMode)
data_view = og.AttributeValueHelper(self._attributes.compressionMode)
data_view.set(value)
@property
def data(self):
data_view = og.AttributeValueHelper(self._attributes.data)
return data_view.get()
@data.setter
def data(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.data)
data_view = og.AttributeValueHelper(self._attributes.data)
data_view.set(value)
self.data_size = data_view.get_array_size()
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = SaveVDBDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = SaveVDBDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = SaveVDBDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,422 | Python | 42.409356 | 283 | 0.644301 |
omniverse-code/kit/exts/usdrt.gf.tests/PACKAGE-LICENSES/usdrt.gf.tests-LICENSE.md | 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. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfRect.py | #!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Note: This is just pulled directly from USD and modified.
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfRect2i.py
from __future__ import division
import math
import sys
import unittest
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
from usdrt import Gf
class TestGfRect2i(TestClass):
def test_Constructor(self):
self.assertIsInstance(Gf.Rect2i(), Gf.Rect2i)
self.assertIsInstance(Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i()), Gf.Rect2i)
self.assertIsInstance(Gf.Rect2i(Gf.Vec2i(), 1, 1), Gf.Rect2i)
self.assertTrue(Gf.Rect2i().IsNull())
self.assertTrue(Gf.Rect2i().IsEmpty())
self.assertFalse(Gf.Rect2i().IsValid())
# further test of above.
r = Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i(-1, 0))
self.assertTrue(not r.IsNull() and r.IsEmpty())
self.assertEqual(
Gf.Rect2i(Gf.Vec2i(-1, 1), Gf.Vec2i(1, -1)).GetNormalized(), Gf.Rect2i(Gf.Vec2i(-1, -1), Gf.Vec2i(1, 1))
)
def test_Properties(self):
r = Gf.Rect2i()
r.max = Gf.Vec2i()
r.min = Gf.Vec2i(1, 1)
r.GetNormalized()
r.max = Gf.Vec2i(1, 1)
r.min = Gf.Vec2i()
r.GetNormalized()
r.min = Gf.Vec2i(3, 1)
self.assertEqual(r.min, Gf.Vec2i(3, 1))
r.max = Gf.Vec2i(4, 5)
self.assertEqual(r.max, Gf.Vec2i(4, 5))
r.minX = 10
self.assertEqual(r.minX, 10)
r.maxX = 20
self.assertEqual(r.maxX, 20)
r.minY = 30
self.assertEqual(r.minY, 30)
r.maxY = 40
self.assertEqual(r.maxY, 40)
r = Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i(10, 10))
self.assertEqual(r.GetCenter(), Gf.Vec2i(5, 5))
self.assertEqual(r.GetArea(), 121)
self.assertEqual(r.GetHeight(), 11)
self.assertEqual(r.GetWidth(), 11)
self.assertEqual(r.GetSize(), Gf.Vec2i(11, 11))
r.Translate(Gf.Vec2i(10, 10))
self.assertEqual(r, Gf.Rect2i(Gf.Vec2i(10, 10), Gf.Vec2i(20, 20)))
r1 = Gf.Rect2i()
r2 = Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i(1, 1))
r1.GetIntersection(r2)
r2.GetIntersection(r1)
r1.GetIntersection(r1)
r1.GetUnion(r2)
r2.GetUnion(r1)
r1.GetUnion(r1)
r1 = Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(10, 10))
r2 = Gf.Rect2i(Gf.Vec2i(5, 5), Gf.Vec2i(15, 15))
self.assertEqual(r1.GetIntersection(r2), Gf.Rect2i(Gf.Vec2i(5, 5), Gf.Vec2i(10, 10)))
self.assertEqual(r1.GetUnion(r2), Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(15, 15)))
tmp = Gf.Rect2i(r1)
tmp += r2
self.assertEqual(tmp, Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(15, 15)))
self.assertTrue(r1.Contains(Gf.Vec2i(3, 3)) and not r1.Contains(Gf.Vec2i(11, 11)))
self.assertEqual(r1, Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(10, 10)))
self.assertTrue(r1 != r2)
self.assertEqual(r1, eval(repr(r1)))
self.assertTrue(len(str(Gf.Rect2i())))
if __name__ == "__main__":
unittest.main()
| 4,475 | Python | 29.657534 | 116 | 0.631732 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/test_gf_quat_extras.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications 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
import math
import os
import platform
import sys
import time
import unittest
from . import TestRtScenegraph, tc_logger, update_path_and_load_usd
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
update_path_and_load_usd()
def get_quat_info():
"""Return list of tuples of class, scalar size, and format string"""
from usdrt import Gf
quat_info = [
(Gf.Quatd, 8, "d"),
(Gf.Quatf, 4, "f"),
(Gf.Quath, 2, "e"),
]
return quat_info
def get_quat_numpy_types():
import numpy
import usdrt
equivalent_types = {
usdrt.Gf.Quatd: numpy.double,
usdrt.Gf.Quatf: numpy.single,
usdrt.Gf.Quath: numpy.half,
}
return equivalent_types
class TestGfQuatBuffer(TestRtScenegraph):
"""Test buffer protocol for usdrt.Gf.Quat* classes"""
@tc_logger
def test_buffer_inspect(self):
"""Use memoryview to validate that buffer protocol is implemented"""
quat_info = get_quat_info()
test_values = [9, 8, 7, 1]
for Quat, size, fmt in quat_info:
q = Quat(test_values[3], test_values[0], test_values[1], test_values[2])
view = memoryview(q)
self.assertEquals(view.itemsize, size)
self.assertEquals(view.ndim, 1)
self.assertEquals(view.shape, (4,))
self.assertEquals(view.format, fmt)
self.assertEquals(view.obj, Quat(test_values[3], test_values[0], test_values[1], test_values[2]))
@tc_logger
def test_buffer_init(self):
"""Validate initialization from an array using buffer protocol"""
import array
quat_info = get_quat_info()
test_values = [9, 8, 7, 1]
for Quat, size, fmt in quat_info:
if fmt == "e":
# GfHalf not supported with array.array
continue
test_array = array.array(fmt, test_values)
test_quat = Quat(test_array)
self.assertEquals(test_quat, Quat(test_values[3], test_values[0], test_values[1], test_values[2]))
@tc_logger
def test_buffer_init_from_numpy_type(self):
"""Test initialization from numpy types"""
import numpy
quat_info = get_quat_info()
equivalent_types = get_quat_numpy_types()
test_values = [9, 8, 7, 1]
for Quat, size, fmt in quat_info:
test_numpy_type = numpy.array(test_values, dtype=equivalent_types[Quat])
test_quat = Quat(test_numpy_type)
self.assertEquals(test_quat, Quat(test_values[3], test_values[0], test_values[1], test_values[2]))
@tc_logger
def test_buffer_init_wrong_type(self):
"""Verify that an exception is raised with initializing via buffer with different data type"""
import array
quat_info = get_quat_info()
test_values = [9, 8, 7, 1]
for Quat, size, fmt in quat_info:
test_array = array.array("h", test_values)
with self.assertRaises(ValueError):
test_quat = Quat(test_array)
@tc_logger
def test_buffer_init_wrong_size(self):
"""Verify that an exception is raised with initializing via buffer with different data array length"""
import array
quat_info = get_quat_info()
test_values = [9, 8, 7, 6, 1]
for Quat, size, fmt in quat_info:
if fmt == "e":
# GfHalf not supported with array.array
continue
test_array = array.array(fmt, test_values)
with self.assertRaises(ValueError):
test_vec = Quat(test_array)
@tc_logger
def test_buffer_init_wrong_dimension(self):
"""Verify that an exception is raised with initializing via buffer with different data dimensions"""
import numpy
quat_info = get_quat_info()
equivalent_types = get_quat_numpy_types()
test_values = [9, 8, 7, 1]
for Quat, size, fmt in quat_info:
test_array = numpy.array([test_values, test_values], dtype=equivalent_types[Quat])
with self.assertRaises(ValueError):
test_quat = Quat(test_array)
class TestGfQuatGetSetItem(TestRtScenegraph):
"""Test item accessors for usdrt.Gf.Quat* classes"""
@tc_logger
def test_get_item(self):
"""Validate __getitem__ on GfQuat"""
from usdrt import Gf
for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]:
q = Quat(0.5, 1, 2, 3)
# Note that these are in memory layout order,
# which is different from constructor order
self.assertEqual(q[0], 1)
self.assertEqual(q[1], 2)
self.assertEqual(q[2], 3)
self.assertEqual(q[3], 0.5)
self.assertEqual(q[-4], 1)
self.assertEqual(q[-3], 2)
self.assertEqual(q[-2], 3)
self.assertEqual(q[-1], 0.5)
@tc_logger
def test_set_item(self):
"""Validate __setitem__ on GfQuat"""
from usdrt import Gf
for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]:
q = Quat()
self.assertEqual(q.imaginary[0], 0)
self.assertEqual(q.imaginary[1], 0)
self.assertEqual(q.imaginary[2], 0)
self.assertEqual(q.real, 0)
q[0] = 1
q[1] = 2
q[2] = 3
q[3] = 0.5
self.assertEqual(q.imaginary[0], 1)
self.assertEqual(q.imaginary[1], 2)
self.assertEqual(q.imaginary[2], 3)
self.assertEqual(q.real, 0.5)
@tc_logger
def test_get_item_slice(self):
"""Validate __getitem__ with a slice on GfQuat"""
from usdrt import Gf
for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]:
q = Quat(0.5, 1, 2, 3)
self.assertEqual(q[1:], [2, 3, 0.5])
@tc_logger
def test_set_item_slice(self):
"""Validate __setitem__ with a slice on GfQuat"""
from usdrt import Gf
for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]:
q = Quat(0.5, 1, 2, 3)
self.assertEqual(q.imaginary[0], 1)
self.assertEqual(q.imaginary[1], 2)
self.assertEqual(q.imaginary[2], 3)
self.assertEqual(q.real, 0.5)
q[1:] = [5, 6, 7]
self.assertEqual(q.imaginary[0], 1)
self.assertEqual(q.imaginary[1], 5)
self.assertEqual(q.imaginary[2], 6)
self.assertEqual(q.real, 7)
class TestGfQuatCopy(TestRtScenegraph):
"""Test copy and deepcopy support for Gf.Quat* classes"""
@tc_logger
def test_copy(self):
"""Test __copy__"""
quat_info = get_quat_info()
for Quat, size, fmt in quat_info:
x = Quat()
y = x
self.assertTrue(y is x)
y[0] = 10
self.assertEqual(x[0], 10)
z = copy.copy(y)
self.assertFalse(z is y)
y[0] = 100
self.assertEqual(z[0], 10)
@tc_logger
def test_deepcopy(self):
"""Test __deepcopy__"""
quat_info = get_quat_info()
for Quat, size, fmt in quat_info:
x = Quat()
y = x
self.assertTrue(y is x)
y[0] = 10
self.assertEqual(x[0], 10)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y[0] = 100
self.assertEqual(z[0], 10)
| 7,951 | Python | 27.916364 | 110 | 0.569991 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfVec.py | # Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Note: This is just pulled directly from USD and lightly modified
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfVec.py
from __future__ import division
__copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications 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 os
import platform
import sys
import time
import unittest
##### Uncomment for better assert messages
# if 'unittest.util' in __import__('sys').modules:
# # Show full diff in self.assertEqual.
# __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
import math
import sys
import unittest
def floatTypeRank(vec):
from usdrt import Gf
vecIntTypes = [Gf.Vec2i, Gf.Vec3i, Gf.Vec4i]
vecDoubleTypes = [Gf.Vec2d, Gf.Vec3d, Gf.Vec4d]
vecFloatTypes = [Gf.Vec2f, Gf.Vec3f, Gf.Vec4f]
vecHalfTypes = [Gf.Vec2h, Gf.Vec3h, Gf.Vec4h]
if vec in vecDoubleTypes:
return 3
elif vec in vecFloatTypes:
return 2
elif vec in vecHalfTypes:
return 1
def isFloatingPoint(vec):
from usdrt import Gf
vecIntTypes = [Gf.Vec2i, Gf.Vec3i, Gf.Vec4i]
vecDoubleTypes = [Gf.Vec2d, Gf.Vec3d, Gf.Vec4d]
vecFloatTypes = [Gf.Vec2f, Gf.Vec3f, Gf.Vec4f]
vecHalfTypes = [Gf.Vec2h, Gf.Vec3h, Gf.Vec4h]
return (vec in vecDoubleTypes) or (vec in vecFloatTypes) or (vec in vecHalfTypes)
def getEps(vec):
rank = floatTypeRank(vec)
if rank == 1:
return 1e-2
elif rank == 2:
return 1e-3
elif rank == 3:
return 1e-4
def vecWithType(vecType, type):
from usdrt import Gf
if vecType.dimension == 2:
if type == "d":
return Gf.Vec2d
elif type == "f":
return Gf.Vec2f
elif type == "h":
return Gf.Vec2h
elif type == "i":
return Gf.Vec2i
elif vecType.dimension == 3:
if type == "d":
return Gf.Vec3d
elif type == "f":
return Gf.Vec3f
elif type == "h":
return Gf.Vec3h
elif type == "i":
return Gf.Vec3i
elif vecType.dimension == 4:
if type == "d":
return Gf.Vec4d
elif type == "f":
return Gf.Vec4f
elif type == "h":
return Gf.Vec4h
elif type == "i":
return Gf.Vec4i
assert False, "No valid conversion for " + vecType + " to type " + type
return None
def checkVec(vec, values):
for i in range(len(vec)):
if vec[i] != values[i]:
return False
return True
def checkVecDot(v1, v2, dp):
if len(v1) != len(v2):
return False
checkdp = 0
for i in range(len(v1)):
checkdp += v1[i] * v2[i]
return checkdp == dp
def SetVec(vec, values):
for i in range(len(vec)):
vec[i] = values[i]
class TestGfVec(TestClass):
def ConstructorsTest(self, Vec):
# no arg constructor
self.assertIsInstance(Vec(), Vec)
# default constructor
v = Vec()
for x in v:
self.assertEqual(0, x)
# copy constructor
v = Vec()
for i in range(len(v)):
v[i] = i
v2 = Vec(v)
for i in range(len(v2)):
self.assertEqual(v[i], v2[i])
# explicit constructor
values = [3, 1, 4, 1]
if Vec.dimension == 2:
v = Vec(3, 1)
self.assertTrue(checkVec(v, values))
elif Vec.dimension == 3:
v = Vec(3, 1, 4)
self.assertTrue(checkVec(v, values))
elif Vec.dimension == 4:
v = Vec(3, 1, 4, 1)
self.assertTrue(checkVec(v, values))
else:
self.assertTrue(False, "No explicit constructor check for " + Vec)
# constructor taking single scalar value.
v = Vec(0)
self.assertTrue(all([x == 0 for x in v]))
v = Vec(1)
self.assertTrue(all([x == 1 for x in v]))
v = Vec(2)
self.assertTrue(all([x == 2 for x in v]))
# conversion from other types to this float type.
if isFloatingPoint(Vec):
for t in "dfih":
V = vecWithType(Vec, t)
self.assertTrue(Vec(V()))
# comparison to int type
Veci = vecWithType(Vec, "i")
vi = Veci()
SetVec(vi, (3, 1, 4, 1))
self.assertEqual(Vec(vi), vi)
if isFloatingPoint(Vec):
# Comparison to float type
for t in "dfh":
V = vecWithType(Vec, t)
v = V()
SetVec(v, (0.3, 0.1, 0.4, 0.1))
if floatTypeRank(Vec) >= floatTypeRank(V):
self.assertEqual(Vec(v), v)
else:
self.assertNotEqual(Vec(v), v)
def OperatorsTest(self, Vec):
from usdrt import Gf
v1 = Vec()
v2 = Vec()
# equality
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [3, 1, 4, 1])
self.assertEqual(v1, v2)
# inequality
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
self.assertNotEqual(v1, v2)
# component-wise addition
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
v3 = v1 + v2
v1 += v2
self.assertTrue(checkVec(v1, [8, 10, 6, 7]))
self.assertTrue(checkVec(v3, [8, 10, 6, 7]))
# component-wise subtraction
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
v3 = v1 - v2
v1 -= v2
self.assertTrue(checkVec(v1, [-2, -8, 2, -5]))
self.assertTrue(checkVec(v3, [-2, -8, 2, -5]))
# component-wise multiplication
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
v4 = v1 * 10
v5 = 10 * v1
v1 *= 10
self.assertTrue(checkVec(v1, [30, 10, 40, 10]))
self.assertTrue(checkVec(v4, [30, 10, 40, 10]))
self.assertTrue(checkVec(v5, [30, 10, 40, 10]))
# component-wise division
SetVec(v1, [3, 6, 9, 12])
v3 = v1 / 3
v1 /= 3
self.assertTrue(checkVec(v1, [1, 2, 3, 4]))
self.assertTrue(checkVec(v3, [1, 2, 3, 4]))
# dot product
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
dp = v1 * v2
dp2 = Gf.Dot(v1, v2)
dp3 = v1.GetDot(v2) # 2x compatibility
self.assertTrue(checkVecDot(v1, v2, dp))
self.assertTrue(checkVecDot(v1, v2, dp2))
self.assertTrue(checkVecDot(v1, v2, dp3))
# unary minus (negation)
SetVec(v1, [3, 1, 4, 1])
self.assertTrue(checkVec(-v1, [-3, -1, -4, -1]))
# repr
self.assertEqual(v1, eval(repr(v1)))
# string
self.assertTrue(len(str(Vec())) > 0)
# indexing
v = Vec()
for i in range(Vec.dimension):
v[i] = i + 1
self.assertEqual(v[-1], v[v.dimension - 1])
self.assertEqual(v[0], 1)
self.assertIn(v.dimension, v)
self.assertNotIn(v.dimension + 1, v)
with self.assertRaises(IndexError):
v[v.dimension + 1] = v.dimension + 1
# slicing
v = Vec()
value = [3, 1, 4, 1]
SetVec(v, value)
value = v[0 : v.dimension]
self.assertEqual(v[:], value)
self.assertEqual(v[:2], value[:2])
self.assertEqual(v[0:2], value[0:2])
self.assertEqual(v[-2:], value[-2:])
self.assertEqual(v[1:1], [])
if v.dimension > 2:
self.assertEqual(v[0:3:2], [3, 4])
v[:2] = (8, 9)
checkVec(v, [8, 9, 4, 1])
if v.dimension > 2:
v[:3:2] = [0, 1]
checkVec(v, [0, 9, 1, 1])
with self.assertRaises(ValueError):
# This should fail. Wrong length sequence
#
v[:2] = [1, 2, 3]
with self.assertRaises(TypeError):
# This should fail. Cannot use floats for indices
v[0.0:2.0] = [7, 7]
with self.assertRaises(TypeError):
# This should fail. Cannot convert None to vector data
#
v[:2] = [None, None]
def MethodsTest(self, Vec):
from usdrt import Gf
v1 = Vec()
v2 = Vec()
if isFloatingPoint(Vec):
eps = getEps(Vec)
# length
SetVec(v1, [3, 1, 4, 1])
l = Gf.GetLength(v1)
l2 = v1.GetLength()
self.assertTrue(Gf.IsClose(l, l2, eps), repr(l) + " " + repr(l2))
self.assertTrue(
Gf.IsClose(l, math.sqrt(Gf.Dot(v1, v1)), eps),
" ".join([repr(x) for x in [l, v1, math.sqrt(Gf.Dot(v1, v1))]]),
)
# Normalize...
SetVec(v1, [3, 1, 4, 1])
v2 = Vec(v1)
v2.Normalize()
nv = Gf.GetNormalized(v1)
nv2 = v1.GetNormalized()
nvcheck = v1 / Gf.GetLength(v1)
self.assertTrue(Gf.IsClose(nv, nvcheck, eps))
self.assertTrue(Gf.IsClose(nv2, nvcheck, eps))
self.assertTrue(Gf.IsClose(v2, nvcheck, eps))
SetVec(v1, [3, 1, 4, 1])
nv = v1.GetNormalized()
nvcheck = v1 / Gf.GetLength(v1)
self.assertTrue(Gf.IsClose(nv, nvcheck, eps)) # nv edit - linalg implementation not exactly equal
SetVec(v1, [0, 0, 0, 0])
v1.Normalize()
self.assertTrue(checkVec(v1, [0, 0, 0, 0]))
SetVec(v1, [2, 0, 0, 0])
Gf.Normalize(v1)
self.assertTrue(checkVec(v1, [1, 0, 0, 0]))
# projection
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
p1 = Gf.GetProjection(v1, v2)
p2 = v1.GetProjection(v2)
check = (v1 * v2) * v2
self.assertEqual(p1, check)
self.assertEqual(p2, check)
# complement
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
p1 = Gf.GetComplement(v1, v2)
p2 = v1.GetComplement(v2)
check = v1 - (v1 * v2) * v2
self.assertTrue((p1 == check) and (p2 == check))
# component-wise multiplication
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
v3 = Gf.CompMult(v1, v2)
self.assertTrue(checkVec(v3, [15, 9, 8, 6]))
# component-wise division
SetVec(v1, [3, 9, 18, 21])
SetVec(v2, [3, 3, 9, 7])
v3 = Gf.CompDiv(v1, v2)
self.assertTrue(checkVec(v3, [1, 3, 2, 3]))
# is close
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
self.assertTrue(Gf.IsClose(v1, v1, 0.1))
self.assertFalse(Gf.IsClose(v1, v2, 0.1))
# static Axis methods
for i in range(Vec.dimension):
v1 = Vec.Axis(i)
v2 = Vec()
v2[i] = 1
self.assertEqual(v1, v2)
v1 = Vec.XAxis()
self.assertTrue(checkVec(v1, [1, 0, 0, 0]))
v1 = Vec.YAxis()
self.assertTrue(checkVec(v1, [0, 1, 0, 0]))
if Vec.dimension != 2:
v1 = Vec.ZAxis()
self.assertTrue(checkVec(v1, [0, 0, 1, 0]))
if Vec.dimension == 3:
# cross product
SetVec(v1, [3, 1, 4, 0])
SetVec(v2, [5, 9, 2, 0])
v3 = Vec(Gf.Cross(v1, v2))
v4 = v1 ^ v2
v5 = v1.GetCross(v2) # 2x compatibility
check = Vec()
SetVec(check, [1 * 2 - 4 * 9, 4 * 5 - 3 * 2, 3 * 9 - 1 * 5, 0])
self.assertTrue(v3 == check and v4 == check and v5 == check)
# orthogonalize basis
# case 1: close to orthogonal, don't normalize
SetVec(v1, [1, 0, 0.1])
SetVec(v2, [0.1, 1, 0])
SetVec(v3, [0, 0.1, 1])
self.assertTrue(Vec.OrthogonalizeBasis(v1, v2, v3, False))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
# case 2: far from orthogonal, normalize
SetVec(v1, [1, 2, 3])
SetVec(v2, [-1, 2, 3])
SetVec(v3, [-1, -2, 3])
self.assertTrue(Vec.OrthogonalizeBasis(v1, v2, v3, True))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
self.assertTrue(Gf.IsClose(v1.GetLength(), 1, eps))
self.assertTrue(Gf.IsClose(v2.GetLength(), 1, eps))
self.assertTrue(Gf.IsClose(v3.GetLength(), 1, eps))
# case 3: already orthogonal - shouldn't change, even with large
# tolerance
SetVec(v1, [1, 0, 0])
SetVec(v2, [0, 1, 0])
SetVec(v3, [0, 0, 1])
vt1 = v1
vt2 = v2
vt3 = v3
self.assertTrue(Vec.OrthogonalizeBasis(v1, v2, v3, False)) # nv edit - no epsilon parameter
self.assertTrue(v1 == vt1)
self.assertTrue(v2 == vt2)
self.assertTrue(v3 == vt3)
# case 4: co-linear input vectors - should do nothing
SetVec(v1, [1, 0, 0])
SetVec(v2, [1, 0, 0])
SetVec(v3, [0, 0, 1])
vt1 = v1
vt2 = v2
vt3 = v3
self.assertFalse(Vec.OrthogonalizeBasis(v1, v2, v3, False)) # nv edit - no epsilon parameter
self.assertEqual(v1, vt1)
self.assertEqual(v2, vt2)
self.assertEqual(v3, vt3)
# build orthonormal frame
SetVec(v1, [1, 1, 1, 1])
(v2, v3) = v1.BuildOrthonormalFrame()
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
SetVec(v1, [0, 0, 0, 0])
(v2, v3) = v1.BuildOrthonormalFrame()
self.assertTrue(Gf.IsClose(v2, Vec(), eps))
self.assertTrue(Gf.IsClose(v3, Vec(), eps))
SetVec(v1, [1, 0, 0, 0])
(v2, v3) = v1.BuildOrthonormalFrame()
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
SetVec(v1, [1, 0, 0, 0])
(v2, v3) = v1.BuildOrthonormalFrame()
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
SetVec(v1, [1, 0, 0, 0])
(v2, v3) = v1.BuildOrthonormalFrame(2)
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
# test Slerp w/ orthogonal vectors
SetVec(v1, [1, 0, 0])
SetVec(v2, [0, 1, 0])
v3 = Gf.Slerp(0, v1, v2)
self.assertTrue(Gf.IsClose(v3, v1, eps))
v3 = Gf.Slerp(1, v1, v2)
self.assertTrue(Gf.IsClose(v3, v3, eps))
v3 = Gf.Slerp(0.5, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0.7071, 0.7071, 0), eps))
# test Slerp w/ nearly parallel vectors
SetVec(v1, [1, 0, 0])
SetVec(v2, [1.001, 0.0001, 0])
v2.Normalize()
v3 = Gf.Slerp(0, v1, v2)
self.assertTrue(Gf.IsClose(v3, v1, eps))
v3 = Gf.Slerp(1, v1, v2)
self.assertTrue(Gf.IsClose(v3, v3, eps))
v3 = Gf.Slerp(0.5, v1, v2)
self.assertTrue(Gf.IsClose(v3, v1, eps), [v3, v1, eps])
self.assertTrue(Gf.IsClose(v3, v2, eps))
# test Slerp w/ opposing vectors
SetVec(v1, [1, 0, 0])
SetVec(v2, [-1, 0, 0])
v3 = Gf.Slerp(0, v1, v2)
self.assertTrue(Gf.IsClose(v3, v1, eps))
v3 = Gf.Slerp(0.25, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0.70711, 0, -0.70711), eps))
v3 = Gf.Slerp(0.5, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0, 0, -1), eps))
v3 = Gf.Slerp(0.75, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(-0.70711, 0, -0.70711), eps))
v3 = Gf.Slerp(1, v1, v2)
self.assertTrue(Gf.IsClose(v3, v3, eps))
# test Slerp w/ opposing vectors
SetVec(v1, [0, 1, 0])
SetVec(v2, [0, -1, 0])
v3 = Gf.Slerp(0, v1, v2)
self.assertTrue(Gf.IsClose(v3, v1, eps))
v3 = Gf.Slerp(0.25, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0, 0.70711, 0.70711), eps))
v3 = Gf.Slerp(0.5, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0, 0, 1), eps))
v3 = Gf.Slerp(0.75, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0, -0.70711, 0.70711), eps))
v3 = Gf.Slerp(1, v1, v2)
self.assertTrue(Gf.IsClose(v3, v3, eps))
def test_Types(self):
from usdrt import Gf
vecTypes = [
Gf.Vec2d,
Gf.Vec2f,
Gf.Vec2h,
Gf.Vec2i,
Gf.Vec3d,
Gf.Vec3f,
Gf.Vec3h,
Gf.Vec3i,
Gf.Vec4d,
Gf.Vec4f,
Gf.Vec4h,
Gf.Vec4i,
]
for Vec in vecTypes:
self.ConstructorsTest(Vec)
self.OperatorsTest(Vec)
self.MethodsTest(Vec)
def test_TupleToVec(self):
from usdrt import Gf
""" nv edits - no implicit construction w/ pybind yet (TODO maybe?)
# Test passing tuples for vecs.
self.assertEqual(Gf.Dot((1,1), (1,1)), 2)
self.assertEqual(Gf.Dot((1,1,1), (1,1,1)), 3)
self.assertEqual(Gf.Dot((1,1,1,1), (1,1,1,1)), 4)
self.assertEqual(Gf.Dot((1.0,1.0), (1.0,1.0)), 2.0)
self.assertEqual(Gf.Dot((1.0,1.0,1.0), (1.0,1.0,1.0)), 3.0)
self.assertEqual(Gf.Dot((1.0,1.0,1.0,1.0), (1.0,1.0,1.0,1.0)), 4.0)
"""
self.assertEqual(Gf.Vec2f((1, 1)), Gf.Vec2f(1, 1))
self.assertEqual(Gf.Vec3f((1, 1, 1)), Gf.Vec3f(1, 1, 1))
self.assertEqual(Gf.Vec4f((1, 1, 1, 1)), Gf.Vec4f(1, 1, 1, 1))
# Test passing lists for vecs.
""" nv edits - no construction w/ lists yet (TODO maybe?)
#self.assertEqual(Gf.Dot([1,1], [1,1]), 2)
#self.assertEqual(Gf.Dot([1,1,1], [1,1,1]), 3)
#self.assertEqual(Gf.Dot([1,1,1,1], [1,1,1,1]), 4)
#self.assertEqual(Gf.Dot([1.0,1.0], [1.0,1.0]), 2.0)
#self.assertEqual(Gf.Dot([1.0,1.0,1.0], [1.0,1.0,1.0]), 3.0)
#self.assertEqual(Gf.Dot([1.0,1.0,1.0,1.0], [1.0,1.0,1.0,1.0]), 4.0)
#self.assertEqual(Gf.Vec2f([1,1]), Gf.Vec2f(1,1))
#self.assertEqual(Gf.Vec3f([1,1,1]), Gf.Vec3f(1,1,1))
#self.assertEqual(Gf.Vec4f([1,1,1,1]), Gf.Vec4f(1,1,1,1))
# Test passing both for vecs.
self.assertEqual(Gf.Dot((1,1), [1,1]), 2)
self.assertEqual(Gf.Dot((1,1,1), [1,1,1]), 3)
self.assertEqual(Gf.Dot((1,1,1,1), [1,1,1,1]), 4)
self.assertEqual(Gf.Dot((1.0,1.0), [1.0,1.0]), 2.0)
self.assertEqual(Gf.Dot((1.0,1.0,1.0), [1.0,1.0,1.0]), 3.0)
self.assertEqual(Gf.Dot((1.0,1.0,1.0,1.0), [1.0,1.0,1.0,1.0]), 4.0)
self.assertEqual(Gf.Vec2f([1,1]), Gf.Vec2f(1,1))
self.assertEqual(Gf.Vec3f([1,1,1]), Gf.Vec3f(1,1,1))
self.assertEqual(Gf.Vec4f([1,1,1,1]), Gf.Vec4f(1,1,1,1))
"""
""" nv edit - no implict construction
def test_Exceptions(self):
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1, 1))
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1, 1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1.0, 1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1.0, 1.0, 1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot((1, 1, 1, 1, 1, 1), (1, 1))
with self.assertRaises(TypeError):
Gf.Dot((1, 1, 1, 1, 1, 1), (1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot((1, 1, 1, 1, 1, 1), (1, 1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot((1.0, 1.0, 1.0, 1.0, 1.0, 1.0), (1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot((1.0, 1.0, 1.0, 1.0, 1.0, 1.0), (1.0, 1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot((1.0, 1.0, 1.0, 1.0, 1.0, 1.0), (1.0, 1.0, 1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b'), (1, 1))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b', 'c'), (1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b', 'c', 'd'), (1, 1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b'), (1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b', 'c'), (1.0, 1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b', 'c', 'd'), (1.0, 1.0, 1.0, 1.0))
"""
| 23,800 | Python | 33.001429 | 110 | 0.504916 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/test_gf_vec_extras.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications 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
import math
import os
import platform
import sys
import time
import unittest
from . import TestRtScenegraph, tc_logger, update_path_and_load_usd
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
update_path_and_load_usd()
def get_vec_info():
"""Return list of tuples of class, scalar size, item count, and format string"""
from usdrt import Gf
vec_info = [
(Gf.Vec2d, 8, 2, "d"),
(Gf.Vec2f, 4, 2, "f"),
(Gf.Vec2h, 2, 2, "e"),
(Gf.Vec2i, 4, 2, "i"),
(Gf.Vec3d, 8, 3, "d"),
(Gf.Vec3f, 4, 3, "f"),
(Gf.Vec3h, 2, 3, "e"),
(Gf.Vec3i, 4, 3, "i"),
(Gf.Vec4d, 8, 4, "d"),
(Gf.Vec4f, 4, 4, "f"),
(Gf.Vec4h, 2, 4, "e"),
(Gf.Vec4i, 4, 4, "i"),
]
return vec_info
def get_vec_numpy_types():
import numpy
import usdrt
equivalent_types = {
usdrt.Gf.Vec2d: numpy.double,
usdrt.Gf.Vec2f: numpy.single,
usdrt.Gf.Vec2h: numpy.half,
usdrt.Gf.Vec2i: numpy.int,
usdrt.Gf.Vec3d: numpy.double,
usdrt.Gf.Vec3f: numpy.single,
usdrt.Gf.Vec3h: numpy.half,
usdrt.Gf.Vec3i: numpy.int,
usdrt.Gf.Vec4d: numpy.double,
usdrt.Gf.Vec4f: numpy.single,
usdrt.Gf.Vec4h: numpy.half,
usdrt.Gf.Vec4i: numpy.int,
}
return equivalent_types
class TestGfVecBuffer(TestRtScenegraph):
"""Test buffer protocol for usdrt.Gf.Vec* classes"""
@tc_logger
def test_buffer_inspect(self):
"""Use memoryview to validate that buffer protocol is implemented"""
vec_info = get_vec_info()
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
v = Vec(*test_values[:count])
view = memoryview(v)
self.assertEquals(view.itemsize, size)
self.assertEquals(view.ndim, 1)
self.assertEquals(view.shape, (count,))
self.assertEquals(view.format, fmt)
self.assertEquals(view.obj, Vec(*test_values[:count]))
@tc_logger
def test_buffer_init(self):
"""Validate initialization from an array using buffer protocol"""
import array
vec_info = get_vec_info()
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
if fmt == "e":
# GfHalf not supported with array.array
continue
test_array = array.array(fmt, test_values[:count])
test_vec = Vec(test_array)
self.assertEquals(test_vec, Vec(*test_values[:count]))
@tc_logger
def test_buffer_init_from_pxr_type(self):
"""Validate initialization from equivalent Pixar types"""
import pxr
import usdrt
vec_info = get_vec_info()
equivalent_types = {
usdrt.Gf.Vec2d: pxr.Gf.Vec2d,
usdrt.Gf.Vec2f: pxr.Gf.Vec2f,
usdrt.Gf.Vec2h: pxr.Gf.Vec2h,
usdrt.Gf.Vec2i: pxr.Gf.Vec2i,
usdrt.Gf.Vec3d: pxr.Gf.Vec3d,
usdrt.Gf.Vec3f: pxr.Gf.Vec3f,
usdrt.Gf.Vec3h: pxr.Gf.Vec3h,
usdrt.Gf.Vec3i: pxr.Gf.Vec3i,
usdrt.Gf.Vec4d: pxr.Gf.Vec4d,
usdrt.Gf.Vec4f: pxr.Gf.Vec4f,
usdrt.Gf.Vec4h: pxr.Gf.Vec4h,
usdrt.Gf.Vec4i: pxr.Gf.Vec4i,
}
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
test_pxr_type = equivalent_types[Vec](test_values[:count])
# Note that in all cases pybind choses the tuple initializer and
# not the buffer initializer. Oh well.
test_vec = Vec(test_pxr_type)
self.assertEquals(test_vec, Vec(*test_values[:count]))
@tc_logger
def test_buffer_init_from_numpy_type(self):
"""Test initialization from numpy types"""
import numpy
vec_info = get_vec_info()
equivalent_types = get_vec_numpy_types()
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
test_numpy_type = numpy.array(test_values[:count], dtype=equivalent_types[Vec])
# Note that in all cases except half pybind choses the tuple initializer and
# not the buffer initializer. Oh well.
test_vec = Vec(test_numpy_type)
self.assertEquals(test_vec, Vec(*test_values[:count]))
@tc_logger
def test_buffer_init_wrong_type(self):
"""Verify that an exception is raised with initializing via buffer with different data type"""
import array
vec_info = get_vec_info()
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
if fmt in ["e"]:
# GfHalf is tricky because it will cast from any
# numeric type, which pybind too-helpfully interprets
# into a tuple of GfHalf
continue
# Here, pybind will convert arrays of similar types to tuples
# which is fine I guess but makes testing harder to validate
# type correctness with buffer support
test_array = array.array("d" if fmt == "i" else "h", test_values[:count])
with self.assertRaises(ValueError):
test_vec = Vec(test_array)
@tc_logger
def test_buffer_init_wrong_size(self):
"""Verify that an exception is raised with initializing via buffer with different data array length"""
import array
vec_info = get_vec_info()
test_values = [9, 8, 7, 6, 5]
for Vec, size, count, fmt in vec_info:
if fmt in ["e"]:
# GfHalf not supported with array.array
continue
# Here, pybind will convert arrays of similar types to tuples
# which is fine I guess but makes testing harder to validate
# type correctness with buffer support
test_array = array.array(fmt, test_values)
with self.assertRaises(ValueError):
test_vec = Vec(test_array)
@tc_logger
def test_buffer_init_wrong_dimension(self):
"""Verify that an exception is raised with initializing via buffer with different data dimensions"""
import numpy
vec_info = get_vec_info()
equivalent_types = get_vec_numpy_types()
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
test_array = numpy.array([test_values[:count], test_values[:count]], dtype=equivalent_types[Vec])
with self.assertRaises(ValueError):
test_vec = Vec(test_array)
class TestGfVecCopy(TestRtScenegraph):
"""Test copy and deepcopy support for Gf.Vec* classes"""
@tc_logger
def test_copy(self):
"""Test __copy__"""
vec_info = get_vec_info()
for Vec, size, count, fmt in vec_info:
x = Vec()
y = x
self.assertTrue(y is x)
y[0] = 10
self.assertEqual(x[0], 10)
z = copy.copy(y)
self.assertFalse(z is y)
y[0] = 100
self.assertEqual(z[0], 10)
@tc_logger
def test_deepcopy(self):
"""Test __deepcopy__"""
vec_info = get_vec_info()
for Vec, size, count, fmt in vec_info:
x = Vec()
y = x
self.assertTrue(y is x)
y[0] = 10
self.assertEqual(x[0], 10)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y[0] = 100
self.assertEqual(z[0], 10)
| 8,089 | Python | 29.186567 | 110 | 0.572877 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/__init__.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications 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
# I wasted an hour finding this
scan_for_test_modules = True
TestRtScenegraph = omni.kit.test.AsyncTestCase
def tc_logger(func):
"""
Print TC macros about the test when running on TC
(unneeded in kit)
"""
return func
def update_path_and_load_usd():
"""
Stub to help load USD before USDRT
(unneeded in kit)
"""
pass
| 835 | Python | 23.588235 | 78 | 0.731737 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfMath.py | #!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import division
# Note: This is just pulled directly from USD and lightly modified
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfMath.py
__copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications 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
import sys
import unittest
# In python 3 there is no type called "long", but a regular int is backed by
# a long. Fake it here so we can keep test coverage working for the types
# available in python 2, where there are separate int and long types
if sys.version_info.major >= 3:
long = int
def err(msg):
return "ERROR: " + msg + " failed"
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
class TestGfMath(TestClass):
def _AssertListIsClose(self, first, second, delta=1e-6):
self.assertTrue(len(first) == len(second))
for (f, s) in zip(first, second):
self.assertAlmostEqual(f, s, delta=delta)
""" nv edit - no _HalfRoundTrip
def test_HalfRoundTrip(self):
from pxr.Gf import _HalfRoundTrip
self.assertEqual(1.0, _HalfRoundTrip(1.0))
self.assertEqual(1.0, _HalfRoundTrip(1))
self.assertEqual(2.0, _HalfRoundTrip(2))
self.assertEqual(3.0, _HalfRoundTrip(long(3)))
with self.assertRaises(TypeError):
_HalfRoundTrip([])
"""
def test_RadiansDegrees(self):
from usdrt.Gf import DegreesToRadians, RadiansToDegrees
self.assertEqual(0, RadiansToDegrees(0))
self.assertEqual(180, RadiansToDegrees(math.pi))
self.assertEqual(720, RadiansToDegrees(4 * math.pi))
self.assertEqual(0, DegreesToRadians(0))
self.assertEqual(math.pi, DegreesToRadians(180))
self.assertEqual(8 * math.pi, DegreesToRadians(4 * 360))
""" nv edit - not supporting some basic math stuff for now
def test_Sqr(self):
self.assertEqual(9, Sqr(3))
self.assertAlmostEqual(Sqr(math.sqrt(2)), 2, delta=1e-7)
self.assertEqual(5, Sqr(Vec2i(1,2)))
self.assertEqual(14, Sqr(Vec3i(1,2,3)))
self.assertEqual(5, Sqr(Vec2d(1,2)))
self.assertEqual(14, Sqr(Vec3d(1,2,3)))
self.assertEqual(30, Sqr(Vec4d(1,2,3,4)))
self.assertEqual(5, Sqr(Vec2f(1,2)))
self.assertEqual(14, Sqr(Vec3f(1,2,3)))
self.assertEqual(30, Sqr(Vec4f(1,2,3,4)))
def test_Sgn(self):
self.assertEqual(-1, Sgn(-3))
self.assertEqual(1, Sgn(3))
self.assertEqual(0, Sgn(0))
self.assertEqual(-1, Sgn(-3.3))
self.assertEqual(1, Sgn(3.3))
self.assertEqual(0, Sgn(0.0))
def test_Sqrt(self):
self.assertAlmostEqual( Sqrt(2), math.sqrt(2), delta=1e-5 )
self.assertAlmostEqual( Sqrtf(2), math.sqrt(2), delta=1e-5 )
def test_Exp(self):
self.assertAlmostEqual( Sqr(math.e), Exp(2), delta=1e-5 )
self.assertAlmostEqual( Sqr(math.e), Expf(2), delta=1e-5 )
def test_Log(self):
self.assertEqual(1, Log(math.e))
self.assertAlmostEqual(Log(Exp(math.e)), math.e, delta=1e-5)
self.assertAlmostEqual(Logf(math.e), 1, delta=1e-5)
self.assertAlmostEqual(Logf(Expf(math.e)), math.e, delta=1e-5)
def test_Floor(self):
self.assertEqual(3, Floor(3.141))
self.assertEqual(-4, Floor(-3.141))
self.assertEqual(3, Floorf(3.141))
self.assertEqual(-4, Floorf(-3.141))
def test_Ceil(self):
self.assertEqual(4, Ceil(3.141))
self.assertEqual(-3, Ceil(-3.141))
self.assertEqual(4, Ceilf(3.141))
self.assertEqual(-3, Ceilf(-3.141))
def test_Abs(self):
self.assertAlmostEqual(Abs(-3.141), 3.141, delta=1e-6)
self.assertAlmostEqual(Abs(3.141), 3.141, delta=1e-6)
self.assertAlmostEqual(Absf(-3.141), 3.141, delta=1e-6)
self.assertAlmostEqual(Absf(3.141), 3.141, delta=1e-6)
def test_Round(self):
self.assertEqual(3, Round(3.1))
self.assertEqual(4, Round(3.5))
self.assertEqual(-3, Round(-3.1))
self.assertEqual(-4, Round(-3.6))
self.assertEqual(3, Roundf(3.1))
self.assertEqual(4, Roundf(3.5))
self.assertEqual(-3, Roundf(-3.1))
self.assertEqual(-4, Roundf(-3.6))
def test_Pow(self):
self.assertEqual(16, Pow(2, 4))
self.assertEqual(16, Powf(2, 4))
def test_Clamp(self):
self.assertAlmostEqual(Clamp(3.141, 3.1, 3.2), 3.141, delta=1e-5)
self.assertAlmostEqual(Clamp(2.141, 3.1, 3.2), 3.1, delta=1e-5)
self.assertAlmostEqual(Clamp(4.141, 3.1, 3.2), 3.2, delta=1e-5)
self.assertAlmostEqual(Clampf(3.141, 3.1, 3.2), 3.141, delta=1e-5)
self.assertAlmostEqual(Clampf(2.141, 3.1, 3.2), 3.1, delta=1e-5)
self.assertAlmostEqual(Clampf(4.141, 3.1, 3.2), 3.2, delta=1e-5)
def test_Mod(self):
self.assertEqual(2, Mod(5, 3))
self.assertEqual(1, Mod(-5, 3))
self.assertEqual(2, Modf(5, 3))
self.assertEqual(1, Modf(-5, 3))
"""
""" nv edit - not supporting these for scalars
def test_Dot(self):
from usdrt.Gf import Dot
self.assertEqual(Dot(2.0, 3.0), 6.0)
self.assertEqual(Dot(-2.0, 3.0), -6.0)
def test_CompMult(self):
from usdrt.Gf import CompMult
self.assertEqual(CompMult(2.0, 3.0), 6.0)
self.assertEqual(CompMult(-2.0, 3.0), -6.0)
def test_CompDiv(self):
from usdrt.Gf import CompDiv
self.assertEqual(CompDiv(6.0, 3.0), 2.0)
self.assertEqual(CompDiv(-6.0, 3.0), -2.0)
"""
if __name__ == "__main__":
unittest.main()
| 7,394 | Python | 34.898058 | 93 | 0.649175 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/test_gf_matrix_extras.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications 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
import math
import os
import platform
import sys
import time
import unittest
from . import TestRtScenegraph, tc_logger, update_path_and_load_usd
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
update_path_and_load_usd()
def get_mat_info():
"""Return list of tuples of class, scalar size, item count, and format string"""
from usdrt import Gf
mat_info = [
(Gf.Matrix3d, 8, 9, "d"),
(Gf.Matrix3f, 4, 9, "f"),
(Gf.Matrix4d, 8, 16, "d"),
(Gf.Matrix4f, 4, 16, "f"),
]
return mat_info
def get_mat_numpy_types():
import numpy
import usdrt
equivalent_types = {
usdrt.Gf.Matrix3d: numpy.double,
usdrt.Gf.Matrix3f: numpy.single,
usdrt.Gf.Matrix4d: numpy.double,
usdrt.Gf.Matrix4f: numpy.single,
}
return equivalent_types
class TestGfMatBuffer(TestRtScenegraph):
"""Test buffer protocol for usdrt.Gf.Matrix* classes"""
@tc_logger
def test_buffer_inspect(self):
"""Use memoryview to validate that buffer protocol is implemented"""
mat_info = get_mat_info()
test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for Mat, size, count, fmt in mat_info:
v = Mat(*test_values[:count])
view = memoryview(v)
self.assertEquals(view.itemsize, size)
self.assertEquals(view.ndim, 2)
self.assertEquals(view.shape, (math.sqrt(count), math.sqrt(count)))
self.assertEquals(view.format, fmt)
self.assertEquals(view.obj, Mat(*test_values[:count]))
@tc_logger
def test_buffer_init_from_pxr_type(self):
"""Validate initialization from equivalent Pixar types"""
import pxr
import usdrt
mat_info = get_mat_info()
equivalent_types = {
usdrt.Gf.Matrix3d: pxr.Gf.Matrix3d,
usdrt.Gf.Matrix3f: pxr.Gf.Matrix3f,
usdrt.Gf.Matrix4d: pxr.Gf.Matrix4d,
usdrt.Gf.Matrix4f: pxr.Gf.Matrix4f,
}
test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for Mat, size, count, fmt in mat_info:
test_pxr_type = equivalent_types[Mat](*test_values[:count])
test_mat = Mat(test_pxr_type)
self.assertEquals(test_mat, Mat(*test_values[:count]))
@tc_logger
def test_buffer_init_from_numpy_type(self):
"""Test initialization from numpy types"""
import numpy
mat_info = get_mat_info()
equivalent_types = get_mat_numpy_types()
test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for Mat, size, count, fmt in mat_info:
py_mat = []
stride = int(math.sqrt(count))
for i in range(stride):
py_mat.append(test_values[i * stride : i * stride + stride])
test_numpy_type = numpy.array(py_mat, dtype=equivalent_types[Mat])
test_mat = Mat(test_numpy_type)
self.assertEquals(test_mat, Mat(*test_values[:count]))
@tc_logger
def test_buffer_init_wrong_type(self):
"""Verify that an exception is raised with initializing via buffer with different data type"""
import numpy
mat_info = get_mat_info()
equivalent_types = get_mat_numpy_types()
test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for Mat, size, count, fmt in mat_info:
py_mat = []
stride = int(math.sqrt(count))
for i in range(stride):
py_mat.append(test_values[i * stride : i * stride + stride])
test_numpy_type = numpy.array(py_mat, dtype=numpy.int_)
with self.assertRaises(ValueError):
test_mat = Mat(test_numpy_type)
@tc_logger
def test_buffer_init_wrong_size(self):
"""Verify that an exception is raised with initializing via buffer with different data array length"""
import numpy
mat_info = get_mat_info()
equivalent_types = get_mat_numpy_types()
test_values = [[0, 1], [2, 3]]
for Mat, size, count, fmt in mat_info:
test_numpy_type = numpy.array(test_values, dtype=equivalent_types[Mat])
with self.assertRaises(ValueError):
test_mat = Mat(test_numpy_type)
@tc_logger
def test_buffer_init_wrong_dimension(self):
"""Verify that an exception is raised with initializing via buffer with different data dimensions"""
import numpy
mat_info = get_mat_info()
equivalent_types = get_mat_numpy_types()
test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for Mat, size, count, fmt in mat_info:
test_array = numpy.array(test_values[:count], dtype=equivalent_types[Mat])
with self.assertRaises(ValueError):
test_mat = Mat(test_array)
class TestGfMatrixGetSetItem(TestRtScenegraph):
"""Test single-item accessors for usdrt.Gf.Matrix* classes"""
@tc_logger
def test_get_item(self):
"""Validate GetArrayItem on GfMatrix"""
from usdrt import Gf
for Mat in [Gf.Matrix3d, Gf.Matrix3f, Gf.Matrix4d, Gf.Matrix4f]:
items = Mat.dimension[0] * Mat.dimension[1]
m = Mat(*[i for i in range(items)])
for i in range(items):
self.assertTrue(m.GetArrayItem(i) == i)
@tc_logger
def test_set_item(self):
"""Validate SetArrayItem on GfMatrix"""
from usdrt import Gf
for Mat in [Gf.Matrix3d, Gf.Matrix3f, Gf.Matrix4d, Gf.Matrix4f]:
m = Mat()
self.assertEqual(m, Mat(1))
items = Mat.dimension[0] * Mat.dimension[1]
expected = Mat(*[i for i in range(items)])
for i in range(items):
m.SetArrayItem(i, i)
self.assertNotEqual(m, Mat(1))
self.assertEqual(m, expected)
class TestGfMatCopy(TestRtScenegraph):
"""Test copy and deepcopy support for Gf.Mat* classes"""
@tc_logger
def test_copy(self):
"""Test __copy__"""
mat_info = get_mat_info()
for Mat, size, count, fmt in mat_info:
x = Mat()
y = x
self.assertTrue(y is x)
y[0, 0] = 10
self.assertEqual(x[0, 0], 10)
z = copy.copy(y)
self.assertFalse(z is y)
y[0, 0] = 100
self.assertEqual(z[0, 0], 10)
@tc_logger
def test_deepcopy(self):
"""Test __deepcopy__"""
mat_info = get_mat_info()
for Mat, size, count, fmt in mat_info:
x = Mat()
y = x
self.assertTrue(y is x)
y[0, 0] = 10
self.assertEqual(x[0, 0], 10)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y[0, 0] = 100
self.assertEqual(z[0, 0], 10)
| 7,470 | Python | 28.529644 | 110 | 0.577778 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfMatrix.py | # Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Note: This is just pulled directly from USD and lightly modified
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfMatrix.py
from __future__ import division, print_function
__copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications 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
import sys
import unittest
##### Uncomment for better assert messages
# if 'unittest.util' in __import__('sys').modules:
# # Show full diff in self.assertEqual.
# __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
try:
import numpy
hasNumpy = True
except ImportError:
print("numpy not available, skipping buffer protocol tests")
hasNumpy = False
def makeValue(Value, vals):
if Value == float:
return Value(vals[0])
else:
v = Value()
for i in range(v.dimension):
v[i] = vals[i]
return v
class TestGfMatrix(TestClass):
def test_Basic(self):
from usdrt import Gf
Matrices = [ # (Gf.Matrix2d, Gf.Vec2d),
# (Gf.Matrix2f, Gf.Vec2f),
(Gf.Matrix3d, Gf.Vec3d),
(Gf.Matrix3f, Gf.Vec3f),
(Gf.Matrix4d, Gf.Vec4d),
(Gf.Matrix4f, Gf.Vec4f),
]
for (Matrix, Vec) in Matrices:
# constructors
self.assertIsInstance(Matrix(), Matrix)
self.assertIsInstance(Matrix(1), Matrix)
self.assertIsInstance(Matrix(Vec()), Matrix)
# python default constructor produces identity.
self.assertEqual(Matrix(), Matrix(1))
if hasNumpy:
# Verify population of numpy arrays.
emptyNumpyArray = numpy.empty((1, Matrix.dimension[0], Matrix.dimension[1]), dtype="float32")
emptyNumpyArray[0] = Matrix(1)
if Matrix.dimension == (2, 2):
self.assertIsInstance(Matrix(1, 2, 3, 4), Matrix)
self.assertEqual(Matrix().Set(1, 2, 3, 4), Matrix(1, 2, 3, 4))
array = numpy.array(Matrix(1, 2, 3, 4))
self.assertEqual(array.shape, (2, 2))
# XXX: Currently cannot round-trip Gf.Matrix*f through
# numpy.array
if Matrix != Gf.Matrix2f:
self.assertEqual(Matrix(array), Matrix(1, 2, 3, 4))
elif Matrix.dimension == (3, 3):
self.assertIsInstance(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9), Matrix)
self.assertEqual(Matrix().Set(1, 2, 3, 4, 5, 6, 7, 8, 9), Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9))
array = numpy.array(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9))
self.assertEqual(array.shape, (3, 3))
# XXX: Currently cannot round-trip Gf.Matrix*f through
# numpy.array
if Matrix != Gf.Matrix3f:
self.assertEqual(Matrix(array), Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9))
elif Matrix.dimension == (4, 4):
self.assertIsInstance(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), Matrix)
self.assertEqual(
Matrix().Set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16),
Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16),
)
array = numpy.array(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
self.assertEqual(array.shape, (4, 4))
# XXX: Currently cannot round-trip Gf.Matrix*f through
# numpy.array
if Matrix != Gf.Matrix4f:
self.assertEqual(Matrix(array), Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
else:
self.fail()
self.assertEqual(Matrix().SetIdentity(), Matrix(1))
self.assertEqual(Matrix().SetZero(), Matrix(0))
self.assertEqual(Matrix().SetDiagonal(0), Matrix().SetZero())
self.assertEqual(Matrix().SetDiagonal(1), Matrix().SetIdentity())
def test_Comparisons(self):
from usdrt import Gf
Matrices = [(Gf.Matrix3d, Gf.Matrix3f), (Gf.Matrix4d, Gf.Matrix4f)] # (Gf.Matrix2d, Gf.Matrix2f),
for (Matrix, Matrixf) in Matrices:
# Test comparison of Matrix and Matrixf
#
size = Matrix.dimension[0] * Matrix.dimension[1]
contents = list(range(1, size + 1))
md = Matrix(*contents)
mf = Matrixf(*contents)
self.assertEqual(md, mf)
contents.reverse()
md.Set(*contents)
mf.Set(*contents)
self.assertEqual(md, mf)
# Convert to double precision floating point values
contents = [1.0 / x for x in contents]
mf.Set(*contents)
md.Set(*contents)
# These should *NOT* be equal due to roundoff errors in the floats.
self.assertNotEqual(md, mf)
def test_Other(self):
from usdrt import Gf
Matrices = [ # (Gf.Matrix2d, Gf.Vec2d),
# (Gf.Matrix2f, Gf.Vec2f),
(Gf.Matrix3d, Gf.Vec3d),
(Gf.Matrix3f, Gf.Vec3f),
(Gf.Matrix4d, Gf.Vec4d),
(Gf.Matrix4f, Gf.Vec4f),
]
for (Matrix, Vec) in Matrices:
v = Vec()
for i in range(v.dimension):
v[i] = i
m1 = Matrix().SetDiagonal(v)
m2 = Matrix(0)
for i in range(m2.dimension[0]):
m2[i, i] = i
self.assertEqual(m1, m2)
v = Vec()
for i in range(v.dimension):
v[i] = 10
self.assertEqual(Matrix().SetDiagonal(v), Matrix().SetDiagonal(10))
self.assertEqual(type(Matrix()[0]), Vec)
m = Matrix()
m[0] = makeValue(Vec, (3, 1, 4, 1))
self.assertEqual(m[0], makeValue(Vec, (3, 1, 4, 1)))
m = Matrix()
m[-1] = makeValue(Vec, (3, 1, 4, 1))
self.assertEqual(m[-1], makeValue(Vec, (3, 1, 4, 1)))
m = Matrix()
m[0, 0] = 1
m[1, 0] = 2
m[0, 1] = 3
m[1, 1] = 4
self.assertTrue(m[0, 0] == 1 and m[1, 0] == 2 and m[0, 1] == 3 and m[1, 1] == 4)
m = Matrix()
m[-1, -1] = 1
m[-2, -1] = 2
m[-1, -2] = 3
m[-2, -2] = 4
self.assertTrue(m[-1, -1] == 1 and m[-2, -1] == 2 and m[-1, -2] == 3 and m[-2, -2] == 4)
m = Matrix()
for i in range(m.dimension[0]):
for j in range(m.dimension[1]):
m[i, j] = i * m.dimension[1] + j
m = m.GetTranspose()
for i in range(m.dimension[0]):
for j in range(m.dimension[1]):
self.assertEqual(m[j, i], i * m.dimension[1] + j)
self.assertEqual(Matrix(1).GetInverse(), Matrix(1))
self.assertEqual(Matrix(4).GetInverse() * Matrix(4), Matrix(1))
# nv edit - intentionally diverge from pixar's implementation
# GetInverse for zero matrix returns zero matrix instead of max float scale matrix
# "so that multiplying by this is less likely to be catastrophic."
self.assertEqual(Matrix(0).GetInverse(), Matrix(0))
self.assertEqual(Matrix(3).GetDeterminant(), 3 ** Matrix.dimension[0])
self.assertEqual(len(Matrix()), Matrix.dimension[0])
# Test GetRow, GetRow3, GetColumn
m = Matrix(1)
for i in range(m.dimension[0]):
for j in range(m.dimension[1]):
m[i, j] = i * m.dimension[1] + j
for i in range(m.dimension[0]):
j0 = i * m.dimension[1]
self.assertEqual(m.GetRow(i), makeValue(Vec, tuple(range(j0, j0 + m.dimension[1]))))
if Matrix == Gf.Matrix4d:
self.assertEqual(m.GetRow3(i), Gf.Vec3d(j0, j0 + 1, j0 + 2))
for j in range(m.dimension[1]):
self.assertEqual(
m.GetColumn(j), makeValue(Vec, tuple(j + x * m.dimension[0] for x in range(m.dimension[0])))
)
# Test SetRow, SetRow3, SetColumn
m = Matrix(1)
for i in range(m.dimension[0]):
j0 = i * m.dimension[1]
v = makeValue(Vec, tuple(range(j0, j0 + m.dimension[1])))
m.SetRow(i, v)
self.assertEqual(v, m.GetRow(i))
m = Matrix(1)
if Matrix == Gf.Matrix4d:
for i in range(m.dimension[0]):
j0 = i * m.dimension[1]
v = Gf.Vec3d(j0, j0 + 1, j0 + 2)
m.SetRow3(i, v)
self.assertEqual(v, m.GetRow3(i))
m = Matrix(1)
for j in range(m.dimension[0]):
v = makeValue(Vec, tuple(j + x * m.dimension[0] for x in range(m.dimension[0])))
m.SetColumn(i, v)
self.assertEqual(v, m.GetColumn(i))
m = Matrix(4)
m *= Matrix(1.0 / 4)
self.assertEqual(m, Matrix(1))
m = Matrix(4)
self.assertEqual(m * Matrix(1.0 / 4), Matrix(1))
self.assertEqual(Matrix(4) * 2, Matrix(8))
self.assertEqual(2 * Matrix(4), Matrix(8))
m = Matrix(4)
m *= 2
self.assertEqual(m, Matrix(8))
m = Matrix(3)
m += Matrix(2)
self.assertEqual(m, Matrix(5))
m = Matrix(3)
m -= Matrix(2)
self.assertEqual(m, Matrix(1))
self.assertEqual(Matrix(2) + Matrix(3), Matrix(5))
self.assertEqual(Matrix(4) - Matrix(4), Matrix(0))
self.assertEqual(-Matrix(-1), Matrix(1))
self.assertEqual(Matrix(3) / Matrix(2), Matrix(3) * Matrix(2).GetInverse())
self.assertEqual(Matrix(2) * makeValue(Vec, (3, 1, 4, 1)), makeValue(Vec, (6, 2, 8, 2)))
self.assertEqual(makeValue(Vec, (3, 1, 4, 1)) * Matrix(2), makeValue(Vec, (6, 2, 8, 2)))
Vecf = {Gf.Vec2d: Gf.Vec2f, Gf.Vec3d: Gf.Vec3f, Gf.Vec4d: Gf.Vec4f}.get(Vec)
if Vecf is not None:
self.assertEqual(Matrix(2) * makeValue(Vecf, (3, 1, 4, 1)), makeValue(Vecf, (6, 2, 8, 2)))
self.assertEqual(makeValue(Vecf, (3, 1, 4, 1)) * Matrix(2), makeValue(Vecf, (6, 2, 8, 2)))
self.assertTrue(2 in Matrix(2) and not 4 in Matrix(2))
m = Matrix(1)
try:
m[m.dimension[0] + 1] = Vec()
except:
pass
else:
self.fail()
m = Matrix(1)
try:
m[m.dimension[0] + 1, m.dimension[1] + 1] = 10
except:
pass
else:
self.fail()
m = Matrix(1)
try:
m[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] = 3
self.fail()
except:
pass
try:
x = m[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
self.fail()
except:
pass
m = Matrix(1)
try:
m["foo"] = 3
except:
pass
else:
self.fail()
self.assertEqual(m, eval(repr(m)))
self.assertTrue(len(str(Matrix())))
def test_Matrix3Transforms(self):
from usdrt import Gf
# TODO - Gf.Rotation not supported,
# so this test is currently a noop
Matrices = [ # (Gf.Matrix3d, Gf.Vec3d, Gf.Quatd),
# (Gf.Matrix3f, Gf.Vec3f, Gf.Quatf)
]
for (Matrix, Vec, Quat) in Matrices:
def _VerifyOrthonormVecs(mat):
v0 = Vec(mat[0][0], mat[0][1], mat[0][2])
v1 = Vec(mat[1][0], mat[1][1], mat[1][2])
v2 = Vec(mat[2][0], mat[2][1], mat[2][2])
self.assertTrue(
Gf.IsClose(Gf.Dot(v0, v1), 0, 0.0001)
and Gf.IsClose(Gf.Dot(v0, v2), 0, 0.0001)
and Gf.IsClose(Gf.Dot(v1, v2), 0, 0.0001)
)
m = Matrix()
m.SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30))
m2 = Matrix(m)
m_o = m.GetOrthonormalized()
self.assertEqual(m_o, m2)
m.Orthonormalize()
self.assertEqual(m, m2)
m = Matrix(3)
m_o = m.GetOrthonormalized()
# GetOrthonormalized() should not mutate m
self.assertNotEqual(m, m_o)
self.assertEqual(m_o, Matrix(1))
m.Orthonormalize()
self.assertEqual(m, Matrix(1))
m = Matrix(1, 0, 0, 1, 0, 0, 1, 0, 0)
# should print a warning
print("expect a warning about failed convergence in OrthogonalizeBasis:")
m.Orthonormalize()
m = Matrix(1, 0, 0, 1, 0, 0.0001, 0, 1, 0)
m_o = m.GetOrthonormalized()
_VerifyOrthonormVecs(m_o)
m.Orthonormalize()
_VerifyOrthonormVecs(m)
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)).ExtractRotation()
r2 = Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 1, 1), 60)).ExtractRotation()
r2 = Gf.Rotation(Gf.Vec3d(1, 1, 1), 60)
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 1, 1), 90)).ExtractRotation()
r2 = Gf.Rotation(Gf.Vec3d(1, 1, 1), 90)
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 1, 1), 120)).ExtractRotation()
r2 = Gf.Rotation(Gf.Vec3d(1, 1, 1), 120)
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
# Setting rotation using a quaternion should give the same results
# as setting a GfRotation.
rot = Gf.Rotation(Gf.Vec3d(1, 1, 1), 120)
quat = Quat(rot.GetQuaternion().GetReal(), Vec(rot.GetQuaternion().GetImaginary()))
r = Matrix().SetRotate(rot).ExtractRotation()
r2 = Matrix().SetRotate(quat).ExtractRotation()
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
self.assertEqual(Matrix().SetScale(10), Matrix(10))
m = Matrix().SetScale(Vec(1, 2, 3))
self.assertTrue(m[0, 0] == 1 and m[1, 1] == 2 and m[2, 2] == 3)
# Initializing with GfRotation should give same results as SetRotate.
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)).ExtractRotation()
r2 = Matrix(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)).ExtractRotation()
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
# Initializing with a quaternion should give same results as SetRotate.
rot = Gf.Rotation(Gf.Vec3d(1, 1, 1), 120)
quat = Quat(rot.GetQuaternion().GetReal(), Vec(rot.GetQuaternion().GetImaginary()))
r = Matrix().SetRotate(quat).ExtractRotation()
r2 = Matrix(quat).ExtractRotation()
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
self.assertEqual(Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1).GetHandedness(), 1.0)
self.assertEqual(Matrix(-1, 0, 0, 0, 1, 0, 0, 0, 1).GetHandedness(), -1.0)
self.assertEqual(Matrix(0, 0, 0, 0, 0, 0, 0, 0, 0).GetHandedness(), 0.0)
self.assertTrue(Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1).IsRightHanded())
self.assertTrue(Matrix(-1, 0, 0, 0, 1, 0, 0, 0, 1).IsLeftHanded())
# Test that this does not generate a nan in the angle (bug #12744)
mx = Gf.Matrix3d(
0.999999999982236,
-5.00662622471027e-06,
2.07636574601397e-06,
5.00666175191934e-06,
1.0000000000332,
-2.19113616402155e-07,
-2.07635686422463e-06,
2.19131379884019e-07,
1,
)
r = mx.ExtractRotation()
# math.isnan won't be available until python 2.6
if sys.version_info[0] >= 2 and sys.version_info[1] >= 6:
self.assertFalse(math.isnan(r.angle))
else:
# If this fails, then r.angle is Nan. Works on linux, may not be portable.
self.assertEqual(r.angle, r.angle)
def test_Matrix4Transforms(self):
from usdrt import Gf
# nv edit - TODO support Quatd and Quatf
Matrices = [
(Gf.Matrix4d, Gf.Vec4d, Gf.Matrix3d, Gf.Vec3d), # , Gf.Quatd),
(Gf.Matrix4f, Gf.Vec4f, Gf.Matrix3f, Gf.Vec3f),
] # , Gf.Quatf)]
# for (Matrix, Vec, Matrix3, Vec3, Quat) in Matrices:
for (Matrix, Vec, Matrix3, Vec3) in Matrices:
def _VerifyOrthonormVecs(mat):
v0 = Vec3(mat[0][0], mat[0][1], mat[0][2])
v1 = Vec3(mat[1][0], mat[1][1], mat[1][2])
v2 = Vec3(mat[2][0], mat[2][1], mat[2][2])
self.assertTrue(
Gf.IsClose(Gf.Dot(v0, v1), 0, 0.0001)
and Gf.IsClose(Gf.Dot(v0, v2), 0, 0.0001)
and Gf.IsClose(Gf.Dot(v1, v2), 0, 0.0001)
)
m = Matrix()
m.SetLookAt(Vec3(1, 0, 0), Vec3(0, 0, 1), Vec3(0, 1, 0))
# nv edit - break this across multiple statements
self.assertTrue(Gf.IsClose(m[0], Vec(-0.707107, 0, 0.707107, 0), 0.0001))
self.assertTrue(Gf.IsClose(m[1], Vec(0, 1, 0, 0), 0.0001))
self.assertTrue(Gf.IsClose(m[2], Vec(-0.707107, 0, -0.707107, 0), 0.0001))
self.assertTrue(Gf.IsClose(m[3], Vec(0.707107, 0, -0.707107, 1), 0.0001))
# Transform
v = Gf.Vec3f(1, 1, 1)
v2 = Matrix(3).Transform(v)
self.assertEqual(v2, Gf.Vec3f(1, 1, 1))
self.assertEqual(type(v2), Gf.Vec3f)
v = Gf.Vec3d(1, 1, 1)
v2 = Matrix(3).Transform(v)
self.assertEqual(v2, Gf.Vec3d(1, 1, 1))
self.assertEqual(type(v2), Gf.Vec3d)
# TransformDir
v = Gf.Vec3f(1, 1, 1)
v2 = Matrix(3).TransformDir(v)
self.assertEqual(v2, Gf.Vec3f(3, 3, 3))
self.assertEqual(type(v2), Gf.Vec3f)
v = Gf.Vec3d(1, 1, 1)
v2 = Matrix(3).TransformDir(v)
self.assertEqual(v2, Gf.Vec3d(3, 3, 3))
self.assertEqual(type(v2), Gf.Vec3d)
# TransformAffine
v = Gf.Vec3f(1, 1, 1)
# nv edit - no implict conversion from tuple yet
v2 = Matrix(3).SetTranslateOnly(Vec3(1, 2, 3)).TransformAffine(v)
self.assertEqual(v2, Gf.Vec3f(4, 5, 6))
self.assertEqual(type(v2), Gf.Vec3f)
v = Gf.Vec3d(1, 1, 1)
# nv edit - no implict conversion from tuple yet
v2 = Matrix(3).SetTranslateOnly(Vec3(1, 2, 3)).TransformAffine(v)
self.assertEqual(v2, Gf.Vec3d(4, 5, 6))
self.assertEqual(type(v2), Gf.Vec3d)
# Constructor, SetRotate, and SetRotateOnly w/GfQuaternion
""" nv edit Gf.Rotation not supported
m = Matrix()
r = Gf.Rotation(Gf.Vec3d(1,0,0), 30)
quat = r.GetQuaternion()
m.SetRotate(Quat(quat.GetReal(), Vec3(quat.GetImaginary())))
m2 = Matrix(r, Vec3(0,0,0))
m_o = m.GetOrthonormalized()
self.assertEqual(m_o, m2)
m.Orthonormalize()
self.assertEqual(m, m2)
m3 = Matrix(1)
m3.SetRotateOnly(Quat(quat.GetReal(), Vec3(quat.GetImaginary())))
self.assertEqual(m2, m3)
# Constructor, SetRotate, and SetRotateOnly w/GfRotation
m = Matrix()
r = Gf.Rotation(Gf.Vec3d(1,0,0), 30)
m.SetRotate(r)
m2 = Matrix(r, Vec3(0,0,0))
m_o = m.GetOrthonormalized()
self.assertEqual(m_o, m2)
m.Orthonormalize()
self.assertEqual(m, m2)
m3 = Matrix(1)
m3.SetRotateOnly(r)
self.assertEqual(m2, m3)
# Constructor, SetRotate, and SetRotateOnly w/mx
m3d = Matrix3()
m3d.SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), 30))
m = Matrix(m3d, Vec3(0,0,0))
m2 = Matrix()
m2 = m2.SetRotate(m3d)
m3 = Matrix()
m3 = m2.SetRotateOnly(m3d)
self.assertEqual(m, m2)
self.assertEqual(m2, m3)
"""
m = Matrix().SetTranslate(Vec3(12, 13, 14)) * Matrix(3)
m.Orthonormalize()
t = Matrix().SetTranslate(m.ExtractTranslation())
mnot = m * t.GetInverse()
self.assertEqual(mnot, Matrix(1))
m = Matrix()
m.SetTranslate(Vec3(1, 2, 3))
m2 = Matrix(m)
m3 = Matrix(1)
m3.SetTranslateOnly(Vec3(1, 2, 3))
m_o = m.GetOrthonormalized()
self.assertEqual(m_o, m2)
self.assertEqual(m_o, m3)
m.Orthonormalize()
self.assertEqual(m, m2)
self.assertEqual(m, m3)
v = Vec3(11, 22, 33)
m = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16).SetTranslateOnly(v)
self.assertEqual(m.ExtractTranslation(), v)
# Initializing with GfRotation should give same results as SetRotate
# and SetTransform
""" nv edit TODO
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0),30)).ExtractRotation()
r2 = Matrix(Gf.Rotation(Gf.Vec3d(1,0,0),30), Vec3(1,2,3)).ExtractRotation()
r3 = Matrix().SetTransform(Gf.Rotation(Gf.Vec3d(1,0,0),30), Vec3(1,2,3)).ExtractRotation()
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and \
Gf.IsClose(r.angle, r2.angle, 0.0001))
self.assertTrue(Gf.IsClose(r3.axis, r2.axis, 0.0001) and \
Gf.IsClose(r3.angle, r2.angle, 0.0001))
# Initializing with GfRotation should give same results as
# SetRotate(quaternion) and SetTransform
rot = Gf.Rotation(Gf.Vec3d(1,0,0),30)
quat = Quat(rot.GetQuaternion().GetReal(),
Vec3(rot.GetQuaternion().GetImaginary()))
r = Matrix().SetRotate(quat).ExtractRotation()
r2 = Matrix(rot, Vec3(1,2,3)).ExtractRotation()
r3 = Matrix().SetTransform(rot, Vec3(1,2,3)).ExtractRotation()
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and \
Gf.IsClose(r.angle, r2.angle, 0.0001))
self.assertTrue(Gf.IsClose(r3.axis, r2.axis, 0.0001) and \
Gf.IsClose(r3.angle, r2.angle, 0.0001))
# Same test w/mx instead of GfRotation
mx3d = Matrix3(Gf.Rotation(Gf.Vec3d(1,0,0),30))
r4 = Matrix().SetTransform(mx3d, Vec3(1,2,3)).ExtractRotation()
r5 = Matrix(mx3d, Vec3(1,2,3)).ExtractRotation()
self.assertTrue(Gf.IsClose(r4.axis, r2.axis, 0.0001) and \
Gf.IsClose(r4.angle, r2.angle, 0.0001))
self.assertTrue(Gf.IsClose(r4.axis, r5.axis, 0.0001) and \
Gf.IsClose(r4.angle, r5.angle, 0.0001))
# ExtractQuat() and ExtractRotation() should yield
# equivalent rotations.
m = Matrix(mx3d, Vec3(1,2,3))
r1 = m.ExtractRotation()
r2 = Gf.Rotation(m.ExtractRotationQuat())
self.assertTrue(Gf.IsClose(r1.axis, r2.axis, 0.0001) and \
Gf.IsClose(r2.angle, r2.angle, 0.0001))
m4 = Matrix(mx3d, Vec3(1,2,3)).ExtractRotationMatrix()
self.assertEqual(m4, mx3d)
"""
# Initializing with GfMatrix3d
# nv edit - dumb, not supported
# m = Matrix(1,2,3,0,4,5,6,0,7,8,9,0,10,11,12,1)
# m2 = Matrix(Matrix3(1,2,3,4,5,6,7,8,9), Vec3(10, 11, 12))
# assert(m == m2)
m = Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1)
# should print a warning - nv edit - our implementation doesn't
# print("expect a warning about failed convergence in OrthogonalizeBasis:")
m.Orthonormalize()
m = Matrix(1, 0, 0, 0, 1, 0, 0.0001, 0, 0, 1, 0, 0, 0, 0, 0, 1)
m_o = m.GetOrthonormalized()
_VerifyOrthonormVecs(m_o)
m.Orthonormalize()
_VerifyOrthonormVecs(m)
m = Matrix()
m[3, 0] = 4
m[3, 1] = 5
m[3, 2] = 6
self.assertEqual(m.ExtractTranslation(), Vec3(4, 5, 6))
self.assertEqual(Matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).GetHandedness(), 1.0)
self.assertEqual(Matrix(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).GetHandedness(), -1.0)
self.assertEqual(Matrix(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).GetHandedness(), 0.0)
self.assertTrue(Matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).IsRightHanded())
self.assertTrue(Matrix(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).IsLeftHanded())
# RemoveScaleShear
""" nv edit Gf.Rotation not supported
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), 45))
m = Matrix().SetScale(Vec3(3,4,2)) * m
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), -30)) * m
r = m.RemoveScaleShear()
ro = r
ro.Orthonormalize()
self.assertEqual(ro, r)
shear = Matrix(1,0,1,0, 0,1,0,0, 0,0,1,0, 0,0,0,1)
r = shear.RemoveScaleShear()
ro = r
ro.Orthonormalize()
self.assertEqual(ro, r)
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), 45))
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), -30)) * m
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,1,0), 59)) * m
r = m.RemoveScaleShear()
maxEltErr = 0
for i in range(4):
for j in range(4):
maxEltErr = max(maxEltErr, abs(r[i][j] - m[i][j]))
self.assertTrue(Gf.IsClose(maxEltErr, 0.0, 1e-5))
# IsClose
self.assertFalse(Gf.IsClose(Matrix(1), Matrix(1.0001), 1e-5))
self.assertTrue(Gf.IsClose(Matrix(1), Matrix(1.000001), 1e-5))
"""
def test_Matrix4Factoring(self):
from usdrt import Gf
""" nv edit Gf.Rotation not supported
Matrices = [(Gf.Matrix4d, Gf.Vec3d),
(Gf.Matrix4f, Gf.Vec3f)]
for (Matrix, Vec3) in Matrices:
def testFactor(m, expectSuccess, eps=None):
factor = lambda m : m.Factor()
if eps is not None:
factor = lambda m : m.Factor(eps)
(success, scaleOrientation, scale, rotation, \
translation, projection) = factor(m)
self.assertEqual(success, expectSuccess)
factorProduct = scaleOrientation * \
Matrix().SetScale(scale) * \
scaleOrientation.GetInverse() * \
rotation * \
Matrix().SetTranslate(translation) * \
projection
maxEltErr = 0
for i in range(4):
for j in range(4):
maxEltErr = max(maxEltErr, abs(factorProduct[i][j] - m[i][j]))
self.assertTrue(Gf.IsClose(maxEltErr, 0.0, 1e-5), maxEltErr)
# A rotate
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), 45))
testFactor(m,True)
# A couple of rotates
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), -45))
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), 45)) * m
testFactor(m,True)
# A scale
m = Matrix().SetScale(Vec3(3,1,4))
testFactor(m,True)
# A scale in a rotated space
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), 45))
m = Matrix().SetScale(Vec3(3,4,2)) * m
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), -45)) * m
testFactor(m,True)
# A nearly degenerate scale
if Matrix == Gf.Matrix4d:
eps = 1e-10
elif Matrix == Gf.Matrix4f:
eps = 1e-5
m = Matrix().SetScale((eps*2, 1, 1))
testFactor(m,True)
# Test with epsilon.
m = Matrix().SetScale((eps*2, 1, 1))
testFactor(m,False,eps*3)
# A singular (1) scale in a rotated space
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,1,1), Gf.Vec3d(1,0,0) ))
m = m * Matrix().SetScale(Vec3(0,1,1))
m = m * Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), Gf.Vec3d(1,1,1) ))
testFactor(m,False)
# A singular (2) scale in a rotated space
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,1,1), Gf.Vec3d(1,0,0) ))
m = m * Matrix().SetScale(Vec3(0,0,1))
m = m * Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), Gf.Vec3d(1,1,1) ))
testFactor(m,False)
# A scale in a sheared space
shear = Matrix(1)
shear.SetRow3(0, Vec3(1, 1, 1).GetNormalized())
m = shear.GetInverse() * Matrix().SetScale(Vec3(2,3,4)) * shear
testFactor(m,True)
# A singular (1) scale in a sheared space
shear = Matrix(1)
shear.SetRow3(0, Vec3(1, 1, 1).GetNormalized())
m = shear.GetInverse() * Matrix().SetScale(Vec3(2,0,4)) * shear
testFactor(m,False)
# A singular (2) scale in a sheared space
shear = Matrix(1)
shear.SetRow3(0, Vec3(1, 1, 1).GetNormalized())
m = shear.GetInverse() * Matrix().SetScale(Vec3(0,3,0)) * shear
testFactor(m,False)
# A scale and a rotate
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) ))
m = Matrix().SetScale(Vec3(1,2,3)) * m
testFactor(m,True)
# A singular (1) scale and a rotate
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) ))
m = Matrix().SetScale(Vec3(0,2,3)) * m
testFactor(m,False)
# A singular (2) scale and a rotate
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) ))
m = Matrix().SetScale(Vec3(0,0,3)) * m
testFactor(m,False)
# A singular scale (1), rotate, translate
m = Matrix().SetTranslate(Vec3(3,1,4))
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) )) * m
m = Matrix().SetScale(Vec3(0,2,3)) * m
testFactor(m,False)
# A translate, rotate, singular scale (1), translate
m = Matrix().SetTranslate(Vec3(3,1,4))
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) )) * m
m = Matrix().SetScale(Vec3(0,2,3)) * m
m = Matrix().SetTranslate(Vec3(-10,-20,-30)) * m
testFactor(m,False)
"""
def test_Matrix4Determinant(self):
from usdrt import Gf
Matrices = [Gf.Matrix4d, Gf.Matrix4f]
for Matrix in Matrices:
# Test GetDeterminant and GetInverse on Matrix4
def AssertDeterminant(m, det):
# Unfortunately, we don't have an override of Gf.IsClose
# for Gf.Matrix4*
for row1, row2 in zip(m * m.GetInverse(), Matrix()):
self.assertTrue(Gf.IsClose(row1, row2, 1e-5))
self.assertTrue(Gf.IsClose(m.GetDeterminant(), det, 1e-5))
m1 = Matrix(0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
det1 = -1.0
m2 = Matrix(0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)
det2 = -1.0
m3 = Matrix(0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0)
det3 = -1.0
m4 = Matrix(1.0, 2.0, -1.0, 3.0, 2.0, 1.0, 4.0, 5.1, 2.0, 3.0, 1.0, 6.0, 3.0, 2.0, 1.0, 1.0)
det4 = 16.8
AssertDeterminant(m1, det1)
AssertDeterminant(m2, det2)
AssertDeterminant(m3, det3)
AssertDeterminant(m4, det4)
AssertDeterminant(m1 * m1, det1 * det1)
AssertDeterminant(m1 * m4, det1 * det4)
AssertDeterminant(m1 * m3 * m4, det1 * det3 * det4)
AssertDeterminant(m1 * m3 * m4 * m2, det1 * det3 * det4 * det2)
AssertDeterminant(m2 * m3 * m4 * m2, det2 * det3 * det4 * det2)
| 35,507 | Python | 40.384615 | 118 | 0.514321 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/test_gf_range_extras.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications 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
import math
import os
import platform
import sys
import time
import unittest
from . import TestRtScenegraph, tc_logger, update_path_and_load_usd
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
update_path_and_load_usd()
class TestGfRangeCopy(TestRtScenegraph):
"""Test copy and deepcopy support for Gf.Range* classes"""
@tc_logger
def test_copy(self):
"""Test __copy__"""
from usdrt import Gf
x = Gf.Range3d()
y = x
self.assertTrue(y is x)
y.min[0] = 10
self.assertEqual(x.min[0], 10)
z = copy.copy(y)
self.assertFalse(z is y)
y.min[0] = 100
self.assertEqual(z.min[0], 10)
x = Gf.Range2d()
y = x
self.assertTrue(y is x)
y.min[0] = 20
self.assertEqual(x.min[0], 20)
z = copy.copy(y)
self.assertFalse(z is y)
y.min[0] = 200
self.assertEqual(z.min[0], 20)
x = Gf.Range1d()
y = x
self.assertTrue(y is x)
y.min = 30
self.assertEqual(x.min, 30)
z = copy.copy(y)
self.assertFalse(z is y)
y.min = 300
self.assertEqual(z.min, 30)
@tc_logger
def test_deepcopy(self):
"""Test __deepcopy__"""
from usdrt import Gf
x = Gf.Range3d()
y = x
self.assertTrue(y is x)
y.min[0] = 10
self.assertEqual(x.min[0], 10)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y.min[0] = 100
self.assertEqual(z.min[0], 10)
x = Gf.Range2d()
y = x
self.assertTrue(y is x)
y.min[0] = 20
self.assertEqual(x.min[0], 20)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y.min[0] = 200
self.assertEqual(z.min[0], 20)
x = Gf.Range1d()
y = x
self.assertTrue(y is x)
y.min = 30
self.assertEqual(x.min, 30)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y.min = 300
self.assertEqual(z.min, 30)
| 2,593 | Python | 22.160714 | 78 | 0.573853 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfRange.py | #!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Note: This is just pulled directly from USD and modified
# (we only support Gf.Range3d classes, but not Gf.Range3f, so
# these tests are updated to reflect that)
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfRange.py
import math
import sys
import unittest
##### Uncomment for better assert messages
# if 'unittest.util' in __import__('sys').modules:
# # Show full diff in self.assertEqual.
# __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
from usdrt import Gf
def makeValue(Value, vals):
if Value == float:
return Value(vals[0])
else:
v = Value()
for i in range(v.dimension):
v[i] = vals[i]
return v
class TestGfRange(TestClass):
Ranges = [
(Gf.Range1d, float),
(Gf.Range2d, Gf.Vec2d),
(Gf.Range3d, Gf.Vec3d),
(Gf.Range1f, float),
(Gf.Range2f, Gf.Vec2f),
(Gf.Range3f, Gf.Vec3f),
]
def runTest(self):
for Range, Value in self.Ranges:
# constructors
self.assertIsInstance(Range(), Range)
self.assertIsInstance(Range(Value(), Value()), Range)
v = makeValue(Value, [1, 2, 3, 4])
r = Range()
r.min = v
self.assertEqual(r.min, v)
r.max = v
self.assertEqual(r.max, v)
r = Range()
self.assertTrue(r.IsEmpty())
r = Range(-1)
self.assertTrue(r.IsEmpty())
v1 = makeValue(Value, [-1, -2, -3, -4])
v2 = makeValue(Value, [1, 2, 3, 4])
r = Range(v2, v1)
self.assertTrue(r.IsEmpty())
r = Range(v1, v2)
self.assertFalse(r.IsEmpty())
r.SetEmpty()
self.assertTrue(r.IsEmpty())
r = Range(v1, v2)
self.assertEqual(r.GetSize(), v2 - v1)
v1 = makeValue(Value, [-1, 1, -11, 2])
v2 = makeValue(Value, [1, 3, -10, 2])
v3 = makeValue(Value, [0, 2, -10.5, 2])
v4 = makeValue(Value, [0, 0, 0, 0])
r1 = Range(v1, v2)
self.assertEqual(r1.GetMidpoint(), v3)
r1.SetEmpty()
r2 = Range()
self.assertEqual(r1.GetMidpoint(), v4)
self.assertEqual(r2.GetMidpoint(), v4)
v1 = makeValue(Value, [-1, -2, -3, -4])
v2 = makeValue(Value, [1, 2, 3, 4])
r = Range(v1, v2)
v1 = makeValue(Value, [0, 0, 0, 0])
v2 = makeValue(Value, [2, 3, 4, 5])
self.assertTrue(r.Contains(v1))
self.assertFalse(r.Contains(v2))
v1 = makeValue(Value, [-2, -4, -6, -8])
v2 = makeValue(Value, [2, 4, 6, 8])
r1 = Range(v1, v2)
v1 = makeValue(Value, [-1, -2, -3, -4])
v2 = makeValue(Value, [1, 2, 3, 4])
r2 = Range(v1, v2)
self.assertTrue(r1.Contains(r2))
self.assertFalse(r2.Contains(r1))
v1 = makeValue(Value, [-1, -2, -3, -4])
v2 = makeValue(Value, [2, 4, 6, 8])
v3 = makeValue(Value, [-2, -4, -6, -8])
v4 = makeValue(Value, [1, 2, 3, 4])
r1 = Range(v1, v2)
r2 = Range(v3, v4)
self.assertEqual(Range.GetUnion(r1, r2), Range(v3, v2))
self.assertEqual(Range.GetIntersection(r1, r2), Range(v1, v4))
r1 = Range(v1, v2)
self.assertEqual(r1.UnionWith(r2), Range(v3, v2))
r1 = Range(v1, v2)
self.assertEqual(r1.UnionWith(v3), Range(v3, v2))
r1 = Range(v1, v2)
self.assertEqual(r1.IntersectWith(r2), Range(v1, v4))
r1 = Range(v1, v2)
v5 = makeValue(Value, [100, 100, 100, 100])
dsqr = r1.GetDistanceSquared(v5)
if Value == float:
self.assertEqual(dsqr, 9604)
elif Value.dimension == 2:
self.assertEqual(dsqr, 18820)
elif Value.dimension == 3:
self.assertEqual(dsqr, 27656)
else:
self.fail()
r1 = Range(v1, v2)
v5 = makeValue(Value, [-100, -100, -100, -100])
dsqr = r1.GetDistanceSquared(v5)
if Value == float:
self.assertEqual(dsqr, 9801)
elif Value.dimension == 2:
self.assertEqual(dsqr, 19405)
elif Value.dimension == 3:
self.assertEqual(dsqr, 28814)
else:
self.fail()
v1 = makeValue(Value, [1, 2, 3, 4])
v2 = makeValue(Value, [2, 3, 4, 5])
v3 = makeValue(Value, [3, 4, 5, 6])
v4 = makeValue(Value, [4, 5, 6, 7])
r1 = Range(v1, v2)
r2 = Range(v2, v3)
r3 = Range(v3, v4)
r4 = Range(v4, v5)
self.assertEqual(r1 + r2, Range(makeValue(Value, [3, 5, 7, 9]), makeValue(Value, [5, 7, 9, 11])))
self.assertEqual(r1 - r2, Range(makeValue(Value, [-2, -2, -2, -2]), makeValue(Value, [0, 0, 0, 0])))
self.assertEqual(r1 * 10, Range(makeValue(Value, [10, 20, 30, 40]), makeValue(Value, [20, 30, 40, 50])))
self.assertEqual(10 * r1, Range(makeValue(Value, [10, 20, 30, 40]), makeValue(Value, [20, 30, 40, 50])))
tmp = r1 / 10
self.assertTrue(
Gf.IsClose(tmp.min, makeValue(Value, [0.1, 0.2, 0.3, 0.4]), 0.00001)
and Gf.IsClose(tmp.max, makeValue(Value, [0.2, 0.3, 0.4, 0.5]), 0.00001)
)
self.assertEqual(r1, Range(makeValue(Value, [1, 2, 3, 4]), makeValue(Value, [2, 3, 4, 5])))
self.assertFalse(r1 != Range(makeValue(Value, [1, 2, 3, 4]), makeValue(Value, [2, 3, 4, 5])))
r1 = Range(v1, v2)
r2 = Range(v2, v3)
r1 += r2
self.assertEqual(r1, Range(makeValue(Value, [3, 5, 7, 9]), makeValue(Value, [5, 7, 9, 11])))
r1 = Range(v1, v2)
r1 -= r2
self.assertEqual(r1, Range(makeValue(Value, [-2, -2, -2, -2]), makeValue(Value, [0, 0, 0, 0])))
r1 = Range(v1, v2)
r1 *= 10
self.assertEqual(r1, Range(makeValue(Value, [10, 20, 30, 40]), makeValue(Value, [20, 30, 40, 50])))
r1 = Range(v1, v2)
r1 *= -10
self.assertEqual(r1, Range(makeValue(Value, [-20, -30, -40, -50]), makeValue(Value, [-10, -20, -30, -40])))
r1 = Range(v1, v2)
r1 /= 10
self.assertTrue(
Gf.IsClose(r1.min, makeValue(Value, [0.1, 0.2, 0.3, 0.4]), 0.00001)
and Gf.IsClose(r1.max, makeValue(Value, [0.2, 0.3, 0.4, 0.5]), 0.00001)
)
self.assertEqual(r1, eval(repr(r1)))
self.assertTrue(len(str(Range())))
# now test GetCorner and GetOctant for Gf.Range2f and Gf.Range2d
Ranges = [(Gf.Range2d, Gf.Vec2d), (Gf.Range2f, Gf.Vec2f)]
for Range, Value in Ranges:
rf = Range.unitSquare()
self.assertTrue(
rf.GetCorner(0) == Value(0, 0)
and rf.GetCorner(1) == Value(1, 0)
and rf.GetCorner(2) == Value(0, 1)
and rf.GetCorner(3) == Value(1, 1)
)
self.assertTrue(
rf.GetQuadrant(0) == Range(Value(0, 0), Value(0.5, 0.5))
and rf.GetQuadrant(1) == Range(Value(0.5, 0), Value(1, 0.5))
and rf.GetQuadrant(2) == Range(Value(0, 0.5), Value(0.5, 1))
and rf.GetQuadrant(3) == Range(Value(0.5, 0.5), Value(1, 1))
)
# now test GetCorner and GetOctant for Gf.Range3f and Gf.Range3d
Ranges = [(Gf.Range3d, Gf.Vec3d), (Gf.Range3f, Gf.Vec3f)]
for Range, Value in Ranges:
rf = Range.unitCube()
self.assertTrue(
rf.GetCorner(0) == Value(0, 0, 0)
and rf.GetCorner(1) == Value(1, 0, 0)
and rf.GetCorner(2) == Value(0, 1, 0)
and rf.GetCorner(3) == Value(1, 1, 0)
and rf.GetCorner(4) == Value(0, 0, 1)
and rf.GetCorner(5) == Value(1, 0, 1)
and rf.GetCorner(6) == Value(0, 1, 1)
and rf.GetCorner(7) == Value(1, 1, 1)
and rf.GetCorner(8) == Value(0, 0, 0)
)
vals = [
[(0.0, 0.0, 0.0), (0.5, 0.5, 0.5)],
[(0.5, 0.0, 0.0), (1.0, 0.5, 0.5)],
[(0.0, 0.5, 0.0), (0.5, 1.0, 0.5)],
[(0.5, 0.5, 0.0), (1.0, 1.0, 0.5)],
[(0.0, 0.0, 0.5), (0.5, 0.5, 1.0)],
[(0.5, 0.0, 0.5), (1.0, 0.5, 1.0)],
[(0.0, 0.5, 0.5), (0.5, 1.0, 1.0)],
[(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)],
]
ranges = [Range(Value(v[0]), Value(v[1])) for v in vals]
for i in range(8):
self.assertEqual(rf.GetOctant(i), ranges[i])
if __name__ == "__main__":
unittest.main()
| 10,526 | Python | 34.564189 | 119 | 0.51197 |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfQuat.py | # Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Note: This is just pulled directly from USD and modified
# (we only support Gf.Quat classes, but not Gf.Quaternion, so
# these tests are updated to reflect that)
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfQuaternion.py
from __future__ import division
__copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications 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
import sys
import unittest
##### Uncomment for better assert messages
# if 'unittest.util' in __import__('sys').modules:
# # Show full diff in self.assertEqual.
# __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
class TestGfQuaternion(TestClass):
def test_Constructors(self):
from usdrt import Gf
# self.assertIsInstance(Gf.Quaternion(), Gf.Quaternion)
# self.assertIsInstance(Gf.Quaternion(0), Gf.Quaternion)
# self.assertIsInstance(Gf.Quaternion(1, Gf.Vec3d(1,1,1)), Gf.Quaternion)
self.assertIsInstance(Gf.Quath(Gf.Quath()), Gf.Quath)
self.assertIsInstance(Gf.Quatf(Gf.Quatf()), Gf.Quatf)
self.assertIsInstance(Gf.Quatd(Gf.Quatd()), Gf.Quatd)
# Testing conversions between Quat[h,f,d]
self.assertIsInstance(Gf.Quath(Gf.Quatf()), Gf.Quath)
self.assertIsInstance(Gf.Quath(Gf.Quatd()), Gf.Quath)
self.assertIsInstance(Gf.Quatf(Gf.Quath()), Gf.Quatf)
self.assertIsInstance(Gf.Quatf(Gf.Quatd()), Gf.Quatf)
self.assertIsInstance(Gf.Quatd(Gf.Quath()), Gf.Quatd)
self.assertIsInstance(Gf.Quatd(Gf.Quatf()), Gf.Quatd)
def test_Properties(self):
from usdrt import Gf
# nv edit - use Quat classses instead of Quaternion
for Quat, Vec in ((Gf.Quatd, Gf.Vec3d), (Gf.Quatf, Gf.Vec3f), (Gf.Quath, Gf.Vec3h)):
q = Quat()
q.real = 10
self.assertEqual(q.real, 10)
q.imaginary = Vec(1, 2, 3)
self.assertEqual(q.imaginary, Vec(1, 2, 3))
def test_Methods(self):
from usdrt import Gf
# nv edit - use Quat classses instead of Quaternion
for Quat, Vec in ((Gf.Quatd, Gf.Vec3d), (Gf.Quatf, Gf.Vec3f), (Gf.Quath, Gf.Vec3h)):
q = Quat()
self.assertEqual(Quat.GetIdentity(), Quat(1, Vec()))
self.assertTrue(
Quat.GetIdentity().GetLength() == 1
and Gf.IsClose(Quat(1, Vec(2, 3, 4)).GetLength(), 5.4772255750516612, 0.00001)
)
q = Quat(1, Vec(2, 3, 4)).GetNormalized()
self.assertTrue(
Gf.IsClose(q.real, 0.182574, 0.0001)
and Gf.IsClose(q.imaginary, Vec(0.365148, 0.547723, 0.730297), 0.00001)
)
# nv edit - linalg does not support arbitrary epsilon here
# q = Quat(1,Vec(2,3,4)).GetNormalized(10)
# self.assertEqual(q, Quat.GetIdentity())
q = Quat(1, Vec(2, 3, 4))
q.Normalize()
self.assertTrue(
Gf.IsClose(q.real, 0.182574, 0.0001)
and Gf.IsClose(q.imaginary, Vec(0.365148, 0.547723, 0.730297), 0.00001)
)
# nv edit - linalg does not support arbitrary epsilon here
# q = Quat(1,Vec(2,3,4)).Normalize(10)
# self.assertEqual(q, Quat.GetIdentity())
if Quat == Gf.Quath:
# FIXME - below test does not pass for Quath:
# AssertionError: Gf.Quath(1.0, Gf.Vec3h(0.0, 0.0, 0.0)) != Gf.Quath(1.0, Gf.Vec3h(-0.0, -0.0, -0.0))
continue
q = Quat.GetIdentity()
self.assertEqual(q, q.GetInverse())
q = Quat(1, Vec(1, 2, 3))
q.Normalize()
(re, im) = (q.real, q.imaginary)
self.assertTrue(
Gf.IsClose(q.GetInverse().real, re, 0.00001) and Gf.IsClose(q.GetInverse().imaginary, -im, 0.00001)
)
def test_Operators(self):
from usdrt import Gf
# nv edit - use Quat classses instead of Quaternion
for Quat, Vec in ((Gf.Quatd, Gf.Vec3d), (Gf.Quatf, Gf.Vec3f), (Gf.Quath, Gf.Vec3h)):
q1 = Quat(1, Vec(2, 3, 4))
q2 = Quat(1, Vec(2, 3, 4))
self.assertEqual(q1, q2)
self.assertFalse(q1 != q2)
q2.real = 2
self.assertTrue(q1 != q2)
q = Quat(1, Vec(2, 3, 4)) * Quat.GetIdentity()
self.assertEqual(q, Quat(1, Vec(2, 3, 4)))
q = Quat(1, Vec(2, 3, 4))
q *= Quat.GetIdentity()
self.assertEqual(q, Quat(1, Vec(2, 3, 4)))
q *= 10
self.assertEqual(q, Quat(10, Vec(20, 30, 40)))
q = q * 10
self.assertEqual(q, Quat(100, Vec(200, 300, 400)))
q = 10 * q
self.assertEqual(q, Quat(1000, Vec(2000, 3000, 4000)))
q /= 100
self.assertEqual(q, Quat(10, Vec(20, 30, 40)))
q = q / 10
self.assertEqual(q, Quat(1, Vec(2, 3, 4)))
q += q
self.assertEqual(q, Quat(2, Vec(4, 6, 8)))
q -= Quat(1, Vec(2, 3, 4))
self.assertEqual(q, Quat(1, Vec(2, 3, 4)))
q = q + q
self.assertEqual(q, Quat(2, Vec(4, 6, 8)))
q = q - Quat(1, Vec(2, 3, 4))
self.assertEqual(q, Quat(1, Vec(2, 3, 4)))
q = q * q
self.assertEqual(q, Quat(-28, Vec(4, 6, 8)))
q1 = Quat(1, Vec(2, 3, 4)).GetNormalized()
q2 = Quat(4, Vec(3, 2, 1)).GetNormalized()
self.assertEqual(Gf.Slerp(0, q1, q2), q1)
# nv edit - these are close but not exact with our implementation
eps = 0.00001 if Quat in [Gf.Quatd, Gf.Quatf] else 0.001
# self.assertEqual(Gf.Slerp(1, q1, q2), q2)
self.assertTrue(Gf.IsClose(Gf.Slerp(1, q1, q2), q2, eps))
# self.assertEqual(Gf.Slerp(0.5, q1, q2), Quat(0.5, Vec(0.5, 0.5, 0.5)))
self.assertTrue(Gf.IsClose(Gf.Slerp(0.5, q1, q2), Quat(0.5, Vec(0.5, 0.5, 0.5)), eps))
# code coverage goodness
q1 = Quat(0, Vec(1, 1, 1))
q2 = Quat(0, Vec(-1, -1, -1))
q = Gf.Slerp(0.5, q1, q2)
self.assertTrue(Gf.IsClose(q.real, 0, 0.00001) and Gf.IsClose(q.imaginary, Vec(1, 1, 1), 0.00001))
q1 = Quat(0, Vec(1, 1, 1))
q2 = Quat(0, Vec(1, 1, 1))
q = Gf.Slerp(0.5, q1, q2)
self.assertTrue(Gf.IsClose(q.real, 0, 0.00001) and Gf.IsClose(q.imaginary, Vec(1, 1, 1), 0.00001))
self.assertEqual(q, eval(repr(q)))
self.assertTrue(len(str(Quat())))
for quatType in (Gf.Quatd, Gf.Quatf, Gf.Quath):
q1 = quatType(1, [2, 3, 4])
q2 = quatType(2, [3, 4, 5])
self.assertTrue(Gf.IsClose(Gf.Dot(q1, q2), 40, 0.00001))
if __name__ == "__main__":
unittest.main()
| 8,699 | Python | 37.157895 | 117 | 0.583975 |
omniverse-code/kit/exts/usdrt.gf.tests/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# 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 = "usdrt.Gf tests"
description="Tests for usdrt.Gf library"
# 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 = "Runtime"
# Keywords for the extension
keywords = ["usdrt", "runtime", "tests"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
# changelog="docs/CHANGELOG.md"
[dependencies]
"omni.usd.libs" = {}
# Main python module this extension provides, it will be publicly available as "import omni.example.hello".
[[python.module]]
name = "usdrt.gf.tests"
[[test]]
name="pxrGf"
dependencies = [
"omni.kit.test"
]
| 1,116 | TOML | 26.924999 | 117 | 0.729391 |
omniverse-code/kit/exts/omni.kit.property.audio/PACKAGE-LICENSES/omni.kit.property.audio-LICENSE.md | 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. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.property.audio/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.6"
category = "Internal"
# 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 = "Audio Property Widget"
description="View and Edit Audio Property Values"
# URL of the extension source repository.
repository = ""
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Keywords for the extension
keywords = ["kit", "usd", "property", "audio", "sound"]
# 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"
[dependencies]
"omni.usd" = {}
"omni.ui" = {}
"omni.kit.window.property" = {}
"omni.kit.property.usd" = {}
"omni.kit.property.layer" = {}
[[python.module]]
name = "omni.kit.property.audio"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test"
]
| 1,470 | TOML | 25.745454 | 93 | 0.704762 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/__init__.py | from .scripts import *
| 23 | Python | 10.999995 | 22 | 0.73913 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/scripts/audio_properties.py | import os
import carb
import omni.ext
from pathlib import Path
from .audio_settings_widget import AudioSettingsWidget
from pxr import Sdf, OmniAudioSchema, UsdMedia
TEST_DATA_PATH = ""
class AudioPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_shutdown(self):
if self._registered:
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget, MultiSchemaPropertiesWidget
w = p.get_window()
if w:
w.register_widget("prim", "media", SchemaPropertiesWidget("Media", UsdMedia.SpatialAudio, False))
w.register_widget("prim", "audio_sound", SchemaPropertiesWidget("Sound", OmniAudioSchema.OmniSound, False))
w.register_widget("prim", "audio_listener", SchemaPropertiesWidget("Listener", OmniAudioSchema.OmniListener, False))
w.register_widget("layers", "audio_settings", AudioSettingsWidget())
self._registered = True
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "media")
w.unregister_widget("prim", "audio_sound")
w.unregister_widget("prim", "audio_listener")
w.unregister_widget("layers", "audio_settings")
self._registered = False
| 1,899 | Python | 36.999999 | 128 | 0.657188 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/scripts/__init__.py | from .audio_properties import *
| 32 | Python | 15.499992 | 31 | 0.78125 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/scripts/audio_settings_widget.py | # Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.kit.app
import omni.kit.ui
import omni.ui as ui
from pxr import Usd
import omni.usd
import omni.usd.audio
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import SimplePropertyWidget
class AudioSettingsWidget(SimplePropertyWidget):
def __init__(self):
super().__init__(title="Audio Settings", collapsed=False)
self._stage = None
self._audio = omni.usd.audio.get_stage_audio_interface()
self._listener_setting_model = None
self._events = self._audio.get_metadata_change_stream()
if self._events is not None:
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_metadata_event, name="audio settings window"
)
self._doppler_setting = None
self._distance_delay_setting = None
self._interaural_delay_setting = None
self._concurrent_voices_setting = None
self._speed_of_sound_setting = None
self._doppler_scale_setting = None
self._doppler_limit_setting = None
self._spatial_timescale_setting = None
self._nonspatial_timescale_setting = None
def __del__(self):
self._stage_event_sub = None
self._events = None
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
# stage is not part of LayerItem payload
self.set_stage(omni.usd.get_context().get_stage())
return payload is not None
class ListenerComboBoxNotifier(omni.ui.AbstractItemModel):
class MinimalItem(omni.ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = omni.ui.SimpleStringModel(text)
def __init__(self, refresh_items_callback, set_callback):
super().__init__()
self._current_index = omni.ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._changed_model)
self._set_callback = set_callback
self._refresh_items_callback = refresh_items_callback
self._options = []
self.refresh_items()
self._path = ""
def get_value_as_string(self):
return self._path
def refresh_items(self):
self._options = ["Active Camera"]
self._options.extend(self._refresh_items_callback())
self._items = [
AudioSettingsWidget.ListenerComboBoxNotifier.MinimalItem(text) for text in self._options
]
return self._items
def _changed_model(self, model):
self._set_callback(model.as_int - 1)
self._item_changed(None)
def set_value(self, value):
# item 0 will always be "Active Camera" => handle 'None' or an empty string specially
# as if it were that value.
if value is None or value == "":
self._current_index.as_int = 0
self._path = ""
return
for i in range(0, len(self._options)):
if self._options[i] == value:
self._current_index.as_int = i
break
self._path = value
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 DefaultsComboBoxNotifier(omni.ui.AbstractItemModel):
class MinimalItem(omni.ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = omni.ui.SimpleStringModel(text)
def __init__(self, set_callback):
super().__init__()
self._options = [
["on", omni.usd.audio.FeatureDefault.ON],
["off", omni.usd.audio.FeatureDefault.OFF],
["force on", omni.usd.audio.FeatureDefault.FORCE_ON],
["force off", omni.usd.audio.FeatureDefault.FORCE_OFF],
]
self._current_index = omni.ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._changed_model)
self._set_callback = set_callback
self._items = [
AudioSettingsWidget.DefaultsComboBoxNotifier.MinimalItem(text) for (text, value) in self._options
]
def _changed_model(self, model):
self._set_callback(self._options[model.as_int][1])
self._item_changed(None)
def set_value(self, value):
for i in range(0, len(self._options) - 1):
if self._options[i][1] == value:
self._current_index.as_int = i
break
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 ChangeNotifier(omni.ui.AbstractValueModel):
def __init__(self, update_callback):
super(AudioSettingsWidget.ChangeNotifier, self).__init__()
self._update_callback = update_callback
self._value = 0
def get_value_as_string(self):
return str(self._value)
def get_value_as_int(self):
return int(self._value)
def get_value_as_float(self):
return float(self._value)
def begin_edit(self):
pass
class SlowChangeNotifier(ChangeNotifier):
def __init__(self, update_callback):
super(AudioSettingsWidget.SlowChangeNotifier, self).__init__(update_callback)
def set_value(self, value):
self._value = value
self._value_changed()
def end_edit(self):
self._update_callback(self._value)
pass
class FastChangeNotifier(ChangeNotifier):
def __init__(self, update_callback):
super(AudioSettingsWidget.FastChangeNotifier, self).__init__(update_callback)
def set_value(self, value):
self._value = value
self._value_changed()
self._update_callback(self._value)
def end_edit(self):
pass
def set_stage(self, stage: Usd.Stage):
self._stage = stage
def _caption(self, text, width=150):
"""Create a formated heading"""
with omni.ui.ZStack():
omni.ui.Rectangle(name="caption", width=width, style={"background_color": 0x454545})
omni.ui.Label(text, name="caption")
def _create_tooltip(self, text):
"""Create a tooltip in a fixed style"""
with omni.ui.VStack(width=400, style={"Label": {"color": 0xFF3B494B}}):
omni.ui.Label(text, word_wrap=True)
def _refresh_active_listener(self):
if not self._listener_setting_model:
return
active_listener = self._audio.get_active_listener()
if active_listener is None:
self._listener_setting_model.set_value(None)
else:
self._listener_setting_model.set_value(str(active_listener.GetPath()))
def _refresh(self):
self._refresh_active_listener()
if not self._listener_setting_model:
return
if self._doppler_setting:
self._doppler_setting.model.set_value(self._audio.get_doppler_default())
if self._distance_delay_setting:
self._distance_delay_setting.model.set_value(self._audio.get_distance_delay_default())
if self._interaural_delay_setting:
self._interaural_delay_setting.model.set_value(self._audio.get_interaural_delay_default())
if self._concurrent_voices_setting:
self._concurrent_voices_setting.model.set_value(self._audio.get_concurrent_voices())
if self._speed_of_sound_setting:
self._speed_of_sound_setting.model.set_value(self._audio.get_speed_of_sound())
if self._doppler_scale_setting:
self._doppler_scale_setting.model.set_value(self._audio.get_doppler_scale())
if self._doppler_limit_setting:
self._doppler_limit_setting.model.set_value(self._audio.get_doppler_limit())
if self._spatial_timescale_setting:
self._spatial_timescale_setting.model.set_value(self._audio.get_spatial_time_scale())
if self._nonspatial_timescale_setting:
self._nonspatial_timescale_setting.model.set_value(self._audio.get_nonspatial_time_scale())
def _on_metadata_event(self, event):
if event.type == int(omni.usd.audio.EventType.METADATA_CHANGE):
self._refresh()
elif event.type == int(omni.usd.audio.EventType.LISTENER_LIST_CHANGE):
if self._listener_setting_model is not None:
self._listener_setting_model.refresh_items()
elif event.type == int(omni.usd.audio.EventType.ACTIVE_LISTENER_CHANGE):
self._refresh_active_listener()
def _refresh_listeners(self):
list = []
count = self._audio.get_listener_count()
for i in range(0, count):
list.append(str(self._audio.get_listener_by_index(i).GetPath()))
return list
def _set_active_listener(self, index):
# a negative index means the active camera should be used as the listener.
if index < 0:
self._audio.set_active_listener(None)
# all other indices are assumed to be an index into the listener list.
else:
prim = self._audio.get_listener_by_index(index)
if prim is None:
return
self._audio.set_active_listener(prim)
def _add_label(self, label: str):
filter_text = self._filter.name
UsdPropertiesWidgetBuilder._create_label(label, {}, {"highlight": filter_text})
self._any_item_visible = True
def build_items(self):
def item_visible(label: str) -> bool:
return not self._filter or self._filter.matches(label)
with omni.ui.VStack(height=0, spacing=8):
if item_visible("Active Listener"):
with ui.HStack():
self._add_label("Active Listener")
self._listener_setting_model = AudioSettingsWidget.ListenerComboBoxNotifier(
self._refresh_listeners, self._set_active_listener
)
self._listener_setting = omni.ui.ComboBox(
self._listener_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"The path to the active Listener prim in the current USD scene. "
+ "Spatial audio calculations use the active listener as the position "
+ "(and optionally orientation) in 3D space, where the audio is heard "
+ "from. This value must be set to a valid Listener prim if 'Use "
+ "active camera as listener' is unchecked."
),
)
if item_visible("Doppler default"):
with ui.HStack():
self._add_label("Doppler default")
self._doppler_setting_model = AudioSettingsWidget.DefaultsComboBoxNotifier(
self._audio.set_doppler_default
)
self._doppler_setting = omni.ui.ComboBox(
self._doppler_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"This sets the value that Sound prims will use for enableDoppler "
+ "when that parameter is set to 'default'. This also allows the "
+ "setting to be forced on or off on all prims for testing purposes, "
+ "using the 'force on' and 'force off' values"
),
)
if item_visible("Distance delay default"):
with ui.HStack():
self._add_label("Distance delay default")
self._distance_delay_setting_model = AudioSettingsWidget.DefaultsComboBoxNotifier(
self._audio.set_distance_delay_default
)
self._distance_delay_setting = omni.ui.ComboBox(
self._distance_delay_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"The value that Sound prims will use for enableDistanceDelay when "
+ "that parameter is set to 'default'. This also allows the setting "
+ "to be forced on or off on all prims for testing purposes, using "
+ "the 'force on' and 'force off' values"
),
)
if item_visible("Interaural delay default"):
with ui.HStack():
self._add_label("Interaural delay default")
self._interaural_delay_setting_model = AudioSettingsWidget.DefaultsComboBoxNotifier(
self._audio.set_interaural_delay_default
)
self._interaural_delay_setting = omni.ui.ComboBox(
self._interaural_delay_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"The value that Sound prims will use for enableInterauralDelay when "
+ "that parameter is set to 'default'. This also allows the setting "
+ "to be forced on or off on all prims for testing purposes, using "
+ "the 'force on' and 'force off' values"
),
)
if item_visible("Concurrent voices"):
with ui.HStack():
self._add_label("Concurrent voices")
self._concurrent_voices_setting_notifier = AudioSettingsWidget.SlowChangeNotifier(
self._audio.set_concurrent_voices
)
self._concurrent_voices_setting = omni.ui.IntDrag(
self._concurrent_voices_setting_notifier,
min=2,
max=4096,
tooltip_fn=lambda: self._create_tooltip(
"The number of sounds in a scene that can be played concurrently. "
+ "In a scene where there this is set to N and N + 1 sounds are "
+ "played concurrently, the N + 1th sound will be simulated instead "
+ "of playing on the audio device and instead simulate that voice. "
+ "The simulated voice will begin playing again when fewer than N "
+ "voices are playing"
),
)
if item_visible("Speed of sound"):
with ui.HStack():
self._add_label("Speed of sound")
self._speed_of_sound_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_speed_of_sound
)
self._speed_of_sound_setting = omni.ui.FloatDrag(
self._speed_of_sound_setting_notifier,
min=0.0001,
max=float("inf"),
step=1.0,
tooltip_fn=lambda: self._create_tooltip(
"Sets the speed of sound in the medium surrounding the listener "
+ "(typically air). This is measured in meters per second. This would "
+ "typically be adjusted when doing an underwater scene (as an "
+ "example). The speed of sound in dry air at sea level is "
+ "approximately 340.0m/s."
),
)
if item_visible("Doppler scale"):
with ui.HStack():
self._add_label("Doppler scale")
self._doppler_scale_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_doppler_scale
)
self._doppler_scale_setting = omni.ui.FloatDrag(
self._doppler_scale_setting_notifier,
min=0.0001,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"The scaler that can exaggerate or lessen the Doppler effect. Setting "
+ "this above 1.0 will exaggerate the Doppler effect. Setting this "
+ "below 1.0 will lessen the Doppler effect."
),
)
if item_visible("Doppler limit"):
with ui.HStack():
self._add_label("Doppler limit")
self._doppler_limit_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_doppler_limit
)
self._doppler_limit_setting = omni.ui.FloatDrag(
self._doppler_limit_setting_notifier,
min=1.0,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"A Limit on the maximum Doppler pitch shift that can be applied to "
+ "a playing voice. Since supersonic spatial audio is not handled, a "
+ "maximum frequency shift must be set for prims that move toward the "
+ "listener at or faster than the speed of sound."
),
)
if item_visible("Spatial time scale"):
with ui.HStack():
self._add_label("Spatial time scale")
self._spatial_timescale_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_spatial_time_scale
)
self._spatial_timescale_setting = omni.ui.FloatDrag(
self._spatial_timescale_setting_notifier,
min=0.0001,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"The timescale modifier for all spatial voices. Each spatial Sound "
+ "prim multiplies its timeScale attribute by this value. For "
+ "example, setting this to 0.5 will play all spatial sounds at half "
+ "speed and setting this to 2.0 will play all spatial sounds at "
+ "double speed. This affects delay times for the distance delay "
+ "effect. This feature is intended to allow time-dilation to be "
+ "performed with the sound effects in the scene without affecting "
+ "non-spatial elements like the background music."
),
)
if item_visible("Non-spatial time scale"):
with ui.HStack():
self._add_label("Non-spatial time scale")
self._nonspatial_timescale_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_nonspatial_time_scale
)
self._nonspatial_timescale_setting = omni.ui.FloatDrag(
self._nonspatial_timescale_setting_notifier,
min=0.0001,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"The timescale modifier for all non-spatial voices. Each non-spatial "
+ "Sound prim multiplies its timeScale attribute by this value. For "
+ "example, setting this to 0.5 will play all non-spatial sounds at "
+ "half speed and setting this to 2.0 will play all non-spatial "
+ "sounds at double speed."
),
)
self._refresh()
| 21,187 | Python | 44.176972 | 113 | 0.539576 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/tests/test_audio.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.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf
import pathlib
class TestAudioWidget(OmniUiTest): # pragma: no cover
# Before running each test
async def setUp(self):
await super().setUp()
from omni.kit.property.audio.scripts.audio_properties import TEST_DATA_PATH
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
self._usd_path = TEST_DATA_PATH.absolute()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_sound_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=675,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("audio_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/World/Sound"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_sound_ui.png")
async def test_listener_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=295,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("audio_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/World/Listener"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_listener_ui.png")
| 3,085 | Python | 37.098765 | 109 | 0.673582 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/tests/__init__.py | from .test_audio import *
from .test_layer_audio import *
| 58 | Python | 18.66666 | 31 | 0.741379 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/tests/test_layer_audio.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.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class TestLayerAudioWidget(OmniUiTest): # pragma: no cover
# Before running each test
async def setUp(self):
await super().setUp()
await arrange_windows("Layer")
from omni.kit.property.audio.scripts.audio_properties import TEST_DATA_PATH
self._usd_path = TEST_DATA_PATH.absolute()
usd_context = omni.usd.get_context()
test_file_path = self._usd_path.joinpath("audio_test.usda").absolute()
usd_context.open_stage(str(test_file_path))
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_layer_sound_ui(self):
await ui_test.find("Layer").focus()
await ui_test.find("Layer//Frame/**/TreeView[*]").find(f"**/Label[*].text=='Root Layer (Authoring Layer)'").click()
await ui_test.human_delay(50)
| 1,565 | Python | 39.153845 | 123 | 0.714377 |
omniverse-code/kit/exts/omni.kit.property.audio/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.6] - 2022-08-17
### Changes
- Updated golden image due to SdfAssetPath widget change.
## [1.0.5] - 2021-07-16
### Changes
- Fixed audio active listener tooltip color
## [1.0.4] - 2021-02-16
### Changes
- Added UI image test
## [1.0.3] - 2020-12-09
### Changes
- Added extension icon
- Added readme
- Updated preview image
## [1.0.2] - 2020-11-10
### Changes
- Moved audio settings window onto layer property window
## [1.0.1] - 2020-11-03
### Changes
- Moved audio settings window into property window
## [1.0.0] - 2020-10-13
### Changes
- Created
| 657 | Markdown | 18.352941 | 80 | 0.665145 |
omniverse-code/kit/exts/omni.kit.property.audio/docs/README.md | # omni.kit.property.audio
## Introduction
Property window extensions are for viewing and editing Usd Prim Attributes
## This extension supports editing of these Usd Types;
- UsdMedia.SpatialAudio
- AudioSchema.Sound
- AudioSchema.Listener
| 244 | Markdown | 17.846152 | 74 | 0.795082 |
omniverse-code/kit/exts/omni.kit.property.audio/docs/index.rst | omni.kit.property.audio
###########################
Property Audio Values
.. toctree::
:maxdepth: 1
CHANGELOG
| 121 | reStructuredText | 9.166666 | 27 | 0.528926 |
omniverse-code/kit/exts/omni.kit.test_async_rendering/omni/kit/test_async_rendering/__init__.py | from .test_async_rendering import *
| 36 | Python | 17.499991 | 35 | 0.777778 |
omniverse-code/kit/exts/omni.kit.test_async_rendering/omni/kit/test_async_rendering/test_async_rendering.py | import pathlib
import asyncio
import carb
import carb.settings
import carb.tokens
import omni.kit.app
import omni.kit.test
import omni.hydratexture
import omni.usd
from typing import Callable
# FIXME: omni.ui.ImageProvider holds the carb.Format conversion routine
import omni.ui
EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
DATA_DIR = EXTENSION_FOLDER_PATH.joinpath("data/tests")
class AsyncRenderingTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.acquire_settings_interface()
self._hydra_texture_factory = omni.hydratexture.acquire_hydra_texture_factory_interface()
self._usd_context_name = ''
self._usd_context = omni.usd.get_context(self._usd_context_name)
await self._usd_context.new_stage_async()
async def tearDown(self):
print("Tearing down..")
self._usd_context.close_stage()
omni.usd.release_all_hydra_engines(self._usd_context)
self._hydra_texture_factory = None
self._settings = None
wait_iterations = 6
for i in range(wait_iterations):
await omni.kit.app.get_app().next_update_async()
async def test_1_simple_context_attach(self):
renderer = "rtx"
if renderer not in self._usd_context.get_attached_hydra_engine_names():
omni.usd.add_hydra_engine(renderer, self._usd_context)
test_usd_asset = DATA_DIR.joinpath("simple_cubes_mat.usda")
print("Opening '%s'" % (test_usd_asset))
await self._usd_context.open_stage_async(str(test_usd_asset))
app = omni.kit.app.get_app()
self._update_counter = 0
self._render_counter = 0
self._asset_loaded = False
def on_update(event):
self._update_counter += 1
self._app_update_sub = app.get_update_event_stream().create_subscription_to_pop(on_update, name='async rendering test update')
is_async = self._settings.get("/app/asyncRendering")
print("Async is %s" % (is_async))
self._hydra_texture = self._hydra_texture_factory.create_hydra_texture(
"test_viewport",
1280,
720,
self._usd_context_name,
"/test_cam",
renderer,
is_async=is_async
)
def _on_stage_event(event):
ASSETS_LOADED = int(omni.usd.StageEventType.ASSETS_LOADED)
if (self._asset_loaded == False) and (event.type is ASSETS_LOADED):
self._asset_loaded = True
print("Assets loaded. UI frame: %d" % (self._update_counter))
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(_on_stage_event, name="stage events")
def on_drawable_changed(event: carb.events.IEvent):
# Renderer counter should start after usd assets are completely loaded in async mode
if self._asset_loaded or (is_async == False):
# +1 because the frame number is zero-based.
self._render_counter = self._hydra_texture.get_frame_info(event.payload['result_handle']).get('frame_number') + 1
print("Rendered %d frames (UI frames drawn: %d)" % (self._render_counter, self._update_counter))
self._drawable_changed_sub = self._hydra_texture.get_event_stream().create_subscription_to_push_by_type(
omni.hydratexture.EVENT_TYPE_DRAWABLE_CHANGED,
on_drawable_changed,
name='async rendering test drawable update',
)
print("Waiting the RTX renderer to load and start draw pictures")
MAX_WAIT_FRAMES_INIT = 50000
wait_frames_left = MAX_WAIT_FRAMES_INIT
while True:
await app.next_update_async()
if self._render_counter > 0 or wait_frames_left <= 0:
break
wait_frames_left -= 1
print("Waited %d frames before renderer initialized" % (MAX_WAIT_FRAMES_INIT - wait_frames_left))
# Set render mode and settings
self._settings.set("/rtx/rendermode", "PathTracing")
self._settings.set("/rtx/pathtracing/totalSpp", 0)
self._settings.set("/rtx/pathtracing/spp", 256)
self._settings.set("/rtx/pathtracing/clampSpp", 256)
print("Starting render loop")
test_updates_before = self._update_counter
test_renders_before = self._render_counter
wait_frames_left = 10000
while True:
await app.next_update_async()
if self._render_counter - test_renders_before > 10 or wait_frames_left <= 0:
break
wait_frames_left -= 1
self.assertTrue(self._render_counter > 10)
test_updates_delta = self._update_counter - test_updates_before
test_renders_delta = self._render_counter - test_renders_before
updates_renders_ratio = test_updates_delta / test_renders_delta
updates_renders_difference = test_updates_delta - test_renders_delta
print("Updates: %d, renders: %d, difference %d, ratio %3.2f" % (test_updates_delta, test_renders_delta, updates_renders_difference, updates_renders_ratio))
# Verify results, this depends on the Async mode
if is_async:
# When Async is On - we expect much more UI updates than render delegate renders
# R525+ drivers showing 3X+ UI draws than 10X+ in comparison to R470.
# OM-78715: lowering threshold even further since it occasionally fails on IPP agents.
self.assertTrue(updates_renders_ratio > 2.3)
else:
# When Async is Off - we expect UI updates come in a lockstep with render delegate renders
# Add some leeway for potential frame offsetting
self.assertTrue(updates_renders_ratio < 1.9)
NUM_FRAMES_IN_FLIGHT = 3
# The UI should be no more than NUM_FRAMES_IN_FLIGHT + 1 frames ahead of the renderer.
self.assertTrue(0 <= updates_renders_difference and updates_renders_difference <= NUM_FRAMES_IN_FLIGHT + 1)
self._drawable_changed_sub = None
self._hydra_texture = None
self._app_update_sub = None
self._stage_event_sub = None
| 6,284 | Python | 41.181208 | 163 | 0.635742 |
omniverse-code/kit/exts/omni.audioplayer/PACKAGE-LICENSES/omni.audioplayer-LICENSE.md | 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. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.audioplayer/config/extension.toml | [package]
title = "Kit Audio Player"
category = "Audio"
feature = true
version = "0.2.0"
description = "An audio player API which is available from python and C++"
detailedDescription = """This is an audio player that's intended to be used for playing back audio assets.
The audio player only offers are few voices for he entire process, so this is
mainly suitable for tasks such as asset previewing.
For audio tasks that require more advanced audio functionality, carb.audio is
recommended.
This API is available in python and C++.
See omni.kit.window.audioplayer for an example use of this API.
"""
authors = ["NVIDIA"]
keywords = ["audio", "playback"]
[dependencies]
"carb.audio" = {}
"omni.usd.core" = {}
"omni.kit.audiodeviceenum" = {}
"omni.client" = {} # needed for carb.datasource-omniclient.plugin
[[native.plugin]]
path = "bin/*.plugin"
[[python.module]]
name = "omni.audioplayer"
[[test]]
dependencies = [
"omni.kit.test_helpers_gfx",
]
unreliable = true
| 975 | TOML | 26.11111 | 106 | 0.725128 |
omniverse-code/kit/exts/omni.audioplayer/omni/audioplayer/__init__.py | """
This module contains bindings to the C++ omni::audio::IAudioPlayer interface.
This provides functionality for playing sound assets. This is intended only
as a basic audio player interface for previewing assets. This is not intended
to play sounds in a USD stage or in the Kit UI. For sounds in the USD stage,
the omni.usd.audio interface should be used instead. For UI sounds, the
omni.kit.uiaudio interface should be used.
Sound files may be in RIFF/WAV, Ogg, or FLAC format.
Data in the sound files may use 8, 16, 24, or 32 bit integer samples,
or 32 bit floating point samples. Channel counts may be from 1 to 64
If more channels of data are provided than the audio device can play,
some channels will be blended together automatically.
"""
from ._audioplayer import *
| 872 | Python | 47.499997 | 86 | 0.694954 |
omniverse-code/kit/exts/omni.audioplayer/omni/audioplayer/_audio.pyi | """
This module contains bindings to the C++ omni::audio::IAudioPlayer interface.
This provides functionality for playing sound assets. This is intended only
as a basic audio player interface for previewing assets. This is not intended
to play sounds in a USD stage or in the Kit UI. For sounds in the USD stage,
the omni.usd.audio interface should be used instead. For UI sounds, the
omni.kit.uiaudio interface should be used.
Sound files may be in RIFF/WAV, Ogg, or FLAC format.
Data in the sound files may use 8, 16, 24, or 32 bit integer samples,
or 32 bit floating point samples. Channel counts may be from 1 to 64
If more channels of data are provided than the audio device can play,
some channels will be blended together automatically.
"""
import omni.audioplayer._audio
import typing
import carb._carb
import carb.events._events
__all__ = [
"AudioPlayer",
"CallbackType",
"create_audio_player"
]
class AudioPlayer():
"""
An individual audio player instance.
This must be created in order to have something to play sounds from.
"""
def draw_waveform(self, arg0: int, arg1: int, arg2: carb._carb.Float4, arg3: carb._carb.Float4) -> typing.List[int]:
"""
Render the waveform to an image to a buffer.
The functionality of writing to a file is a temporary workaround.
This will eventually be changed to output a memory buffer.
Args:
player The player whose image will be rendered.
width The width of the output image, in pixels.
height The height of the output image, in pixels.
fgColor The foreground color in normalized RGBA color.
bgColor The background color in normalized RGBA color.
Returns:
A list containing the raw RGBA8888 values for the image.
An empty array on failure.
"""
def draw_waveform_to_file(self, arg0: str, arg1: int, arg2: int, arg3: carb._carb.Float4, arg4: carb._carb.Float4) -> bool:
"""
Render the waveform to an image to a file.
The functionality of writing to a file is a temporary workaround.
This will eventually be changed to output a memory buffer.
Args:
player The player whose image will be rendered.
filename The name for the output image file.
width The width of the output image, in pixels.
height The height of the output image, in pixels.
fgColor The foreground color in normalized RGBA color.
bgColor The background color in normalized RGBA color.
Returns:
True if the operation was successful.
False if the file could not be generated.
"""
def get_event_stream(self) -> carb.events._events.IEventStream: ...
def get_play_cursor(self) -> float:
"""
Get the play cursor position in the currently playing sound.
Args:
No arguments
Returns:
The play cursor position in the currently playing sound in seconds.
0.0 if there is no playing sound.
"""
def get_sound_length(self) -> float:
"""
Get the length of the currently playing sound.
Args:
No arguments
Returns:
The length of the currently playing sound in seconds.
0.0 if there is no playing sound.
"""
def load_sound(self, path: str) -> None: ...
def pause_sound(self) -> None:
"""
Pause playback of a sound on a specific audio player.
Each player has only one voice, so this call pauses that voice.
Args:
No arguments
Returns:
No return value.
"""
def play_sound(self, path: str, startTime: float = 0.0) -> None: ...
def set_play_cursor(self, startTime: float = 0.0) -> None: ...
def stop_sound(self) -> None:
"""
Immediately stops the playback on a specific audio player
Each player has only one voice, so this call stops that voice.
Args:
No arguments
Returns:
No return value.
"""
def unpause_sound(self) -> None:
"""
Unpause playback of a sound on a specific audio player.
Each player has only one voice, so this call unpauses that voice.
If no voice is paused, this does nothing.
Args:
No arguments
Returns:
No return value.
"""
pass
class CallbackType():
"""
Members:
LOADED
ENDED
"""
def __init__(self, arg0: int) -> None: ...
def __int__(self) -> int: ...
@property
def name(self) -> str:
"""
(self: handle) -> str
:type: str
"""
ENDED: omni.audioplayer._audio.CallbackType # value = CallbackType.ENDED
LOADED: omni.audioplayer._audio.CallbackType # value = CallbackType.LOADED
__members__: dict # value = {'LOADED': CallbackType.LOADED, 'ENDED': CallbackType.ENDED}
pass
def create_audio_player(*args, **kwargs) -> typing.Any:
pass
| 5,779 | unknown | 33.819277 | 128 | 0.549057 |
omniverse-code/kit/exts/omni.audioplayer/omni/audioplayer/_audioplayer.pyi | """
This module contains bindings to the C++ omni::audio::IAudioPlayer interface.
This provides functionality for playing sound assets. This is intended only
as a basic audio player interface for previewing assets. This is not intended
to play sounds in a USD stage or in the Kit UI. For sounds in the USD stage,
the omni.usd.audio interface should be used instead. For UI sounds, the
omni.kit.uiaudio interface should be used.
Sound files may be in RIFF/WAV, Ogg, or FLAC format.
Data in the sound files may use 8, 16, 24, or 32 bit integer samples,
or 32 bit floating point samples. Channel counts may be from 1 to 64
If more channels of data are provided than the audio device can play,
some channels will be blended together automatically.
"""
from __future__ import annotations
import omni.audioplayer._audioplayer
import typing
import carb._carb
import carb.events._events
__all__ = [
"AudioPlayer",
"CallbackType",
"FLAG_FORCE_RELOAD",
"FLAG_RAW_DATA",
"RawPcmFormat",
"create_audio_player"
]
class AudioPlayer():
"""
An individual audio player instance.
This must be created in order to have something to play sounds from.
"""
def draw_waveform(self, width: int, height: int, fgColor: carb._carb.Float4, bgColor: carb._carb.Float4) -> typing.List[int]:
"""
Render the waveform to an image to a buffer.
The functionality of writing to a file is a temporary workaround.
This will eventually be changed to output a memory buffer.
Args:
width The width of the output image, in pixels.
height The height of the output image, in pixels.
fgColor The foreground color in normalized RGBA color.
bgColor The background color in normalized RGBA color.
Returns:
A list containing the raw RGBA8888 values for the image.
An empty array on failure.
"""
def draw_waveform_to_file(self, filename: str, width: int, height: int, fgColor: carb._carb.Float4, bgColor: carb._carb.Float4) -> bool:
"""
Render the waveform to an image to a file.
The functionality of writing to a file is a temporary workaround.
This will eventually be changed to output a memory buffer.
Args:
filename The name for the output image file.
width The width of the output image, in pixels.
height The height of the output image, in pixels.
fgColor The foreground color in normalized RGBA color.
bgColor The background color in normalized RGBA color.
Returns:
True if the operation was successful.
False if the file could not be generated.
"""
def get_event_stream(self) -> carb.events._events.IEventStream:
"""
Get a reference to the IEventStream for this audio player instance
The following event types will be sent:
CallbackType.LOADED when the requested audio has finished loading.
CallbackType.ENDED when the requested audio has finished playing.
You should remove your settings subscription before shutting down your
audio player, since events are sent asynchronously, so you could get an
event after your player has been destroyed.
Returns:
The IEventStream for the audio player.
"""
def get_play_cursor(self) -> float:
"""
Get the play cursor position in the currently playing sound.
Args:
No arguments
Returns:
The play cursor position in the currently playing sound in seconds.
0.0 if there is no playing sound.
"""
def get_sound_length(self) -> float:
"""
Get the length of the currently playing sound.
Args:
No arguments
Returns:
The length of the currently playing sound in seconds.
0.0 if there is no playing sound.
"""
def load_sound(self, path: str) -> None:
"""
Load a sound asset for future playback.
This will fetch an asset so that the next call to play_sound()
can begin playing the sound immediately.
This will also stop the currently playing sound, if any.
This function will also cause get_sound_length() to begin
returning the length of this sound.
This will send a CallbackType.LOADED when the asset has loaded.
Args:
path: The string path to the sound asset to play.
This must be an absolute file path to a sound asset.
startTime: The time offset, in seconds, to begin playing this
sound at.
Returns:
No return value.
"""
def load_sound_in_memory(self, name: str, bytes: str, frame_rate: int = 0, channels: int = 0, format: RawPcmFormat = RawPcmFormat.PCM_16, flags: int = 0) -> None:
"""
Loads a sound asset from a blob in memory for future playback.
The sound asset will not start playing when the asset has loaded.
It will however be cached so that a later request with the same
data and name can play the sound. The asset is given as a data
blob in memory as a `bytes` object. The data may either be a full
file loaded into memory or just raw PCM data. If raw PCM data is
given, additional parameters must be used to specify the sample
type, channel count, and frame rate so that the data can be
successfully decoded.
Args:
name: The name to give to this asset. This is only used
for caching purposes so the sound can be played
multiple times without having to reload it.
This must not be `None` or an empty string otherwise
the operation will just be ignored.
bytes: The `bytes` object that contains the data for the
sound. This is treated as a single binary blob of
data. This may not be `None`.
frame_rate: The frame rate to play the sound data at. If the
binary blob contains format information, this is
ignored. This is only needed if the `FLAG_RAW_DATA`
flag is specified in `flags`.
channels: The number of channels in each frame of the sound
data. If the binary block contains format information,
this can be ignored. This is only needed if the
`FLAG_RAW_DATA` flag is specified in `flags`.
format: The format of each sample of data. This must be
one of the `RawPcmFormat` values. This is only used
if the blob does not already contain format information.
flags: Flags to control how the sound data is loaded and cached.
If the data blob does not contain format information and
is just raw PCM sample data, the `FLAG_RAW_DATA` flag must be
specified and the `frame_rate`, `channels`, and `format`
arguments must also be given. Without these, the sound
data cannot be properly loaded.
Returns:
No return value.
"""
def pause_sound(self) -> None:
"""
Pause playback of a sound on a specific audio player.
Each player has only one voice, so this call pauses that voice.
Args:
No arguments
Returns:
No return value.
"""
def play_sound(self, path: str, startTime: float = 0.0) -> None:
"""
Play a sound asset.
The sound asset will start playing asynchronously when the asset has
loaded.
Args:
path: The string path to the sound asset to play.
This must be an absolute file path to a sound asset.
startTime: The time offset, in seconds, to begin playing this
sound at.
Returns:
No return value.
"""
@staticmethod
def play_sound_in_memory(*args, **kwargs) -> typing.Any:
"""
Play a sound asset from data in memory.
The sound asset will start playing asynchronously when the asset has
loaded. The asset is given as a data blob in memory as a `bytes`
object. The data may either be a full file loaded into memory or
just raw PCM data. If raw PCM data is given, additional parameters
must be used to specify the sample type, channel count, and frame
rate so that the data can be successfully decoded.
Args:
name: The name to give to this asset. This is only used
for caching purposes so the sound can be played
multiple times without having to reload it or so
it can be preloaded with load_sound_in_memory().
Set this to `None` or an empty string to disable
caching the sound and just play it. Note that if
the `FLAG_FORCE_RELOAD` flag is used, the cache check
will be ignored and the sound will be loaded and
cached again.
bytes: The `bytes` object that contains the data for the
sound. This is treated as a single binary blob of
data. This may not be `None`.
frame_rate: The frame rate to play the sound data at. If the
binary blob contains format information, this is
ignored. This is only needed if the `FLAG_RAW_DATA`
flag is specified in `flags`.
channels: The number of channels in each frame of the sound
data. If the binary block contains format information,
this can be ignored. This is only needed if the
`FLAG_RAW_DATA` flag is specified in `flags`.
format: The format of each sample of data. This must be
one of the `RawPcmFormat` values. This is only used
if the blob does not already contain format information.
startTime: The time offset, in seconds, to begin playing this
sound at.
flags: Flags to control how the sound data is loaded and cached.
If the data blob does not contain format information and
is just raw PCM sample data, the `FLAG_RAW_DATA` flag must be
specified and the `frame_rate`, `channels`, and `format`
arguments must also be given. Without these, the sound
data cannot be properly loaded.
Returns:
No return value.
"""
def set_play_cursor(self, startTime: float = 0.0) -> None:
"""
Set the play cursor position in the currently playing sound.
Args:
startTime: The time to set the cursor to in the sound.
Returns:
No return value.
"""
def stop_sound(self) -> None:
"""
Immediately stops the playback on a specific audio player
Each player has only one voice, so this call stops that voice.
Args:
No arguments
Returns:
No return value.
"""
def unpause_sound(self) -> None:
"""
Unpause playback of a sound on a specific audio player.
Each player has only one voice, so this call unpauses that voice.
If no voice is paused, this does nothing.
Args:
No arguments
Returns:
No return value.
"""
pass
class CallbackType():
"""
Members:
LOADED
ENDED
"""
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
"""
ENDED: omni.audioplayer._audioplayer.CallbackType # value = <CallbackType.ENDED: 1>
LOADED: omni.audioplayer._audioplayer.CallbackType # value = <CallbackType.LOADED: 0>
__members__: dict # value = {'LOADED': <CallbackType.LOADED: 0>, 'ENDED': <CallbackType.ENDED: 1>}
pass
class RawPcmFormat():
"""
Members:
PCM_8 : Provided raw 8-bit unsigned PCM data.
PCM_16 : Provided raw 16-bit signed PCM data.
PCM_32 : Provided raw 32-bit signed PCM data.
PCM_FLOAT : Provided raw 32-bit floating point PCM data.
"""
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
"""
PCM_16: omni.audioplayer._audioplayer.RawPcmFormat # value = <RawPcmFormat.PCM_16: 1>
PCM_32: omni.audioplayer._audioplayer.RawPcmFormat # value = <RawPcmFormat.PCM_32: 2>
PCM_8: omni.audioplayer._audioplayer.RawPcmFormat # value = <RawPcmFormat.PCM_8: 0>
PCM_FLOAT: omni.audioplayer._audioplayer.RawPcmFormat # value = <RawPcmFormat.PCM_FLOAT: 3>
__members__: dict # value = {'PCM_8': <RawPcmFormat.PCM_8: 0>, 'PCM_16': <RawPcmFormat.PCM_16: 1>, 'PCM_32': <RawPcmFormat.PCM_32: 2>, 'PCM_FLOAT': <RawPcmFormat.PCM_FLOAT: 3>}
pass
def create_audio_player(*args, **kwargs) -> typing.Any:
pass
FLAG_FORCE_RELOAD = 2
FLAG_RAW_DATA = 1
| 14,613 | unknown | 39.821229 | 180 | 0.581263 |
omniverse-code/kit/exts/omni.audioplayer/omni/audioplayer/tests/__init__.py | from .test_audio_player import * # pragma: no cover
| 54 | Python | 17.333328 | 52 | 0.703704 |
omniverse-code/kit/exts/omni.audioplayer/omni/audioplayer/tests/test_audio_player.py | import pathlib
import time
import pathlib
from PIL import Image
import carb.tokens
import omni.audioplayer
import os
import omni.kit.test
import omni.kit.test_helpers_gfx.compare_utils
OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path())
# This test needs to come first alphabetically since the bug this tests didn't
# trigger if the plugin was already loaded and carb plugins don't ever unload
# during normal kit operations.
class Test0AudioPlayerHang(omni.kit.test.AsyncTestCase): # pragma: no cover
def setUp(self):
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.audioplayer}")
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
self._player = omni.audioplayer.create_audio_player()
self.assertIsNotNone(self._player)
def tearDown(self):
# if you don't do this, the player never gets destroyed until plugin unload
self._player = None
def test_unload_during_load(self):
self._player.load_sound(str(self._test_path.joinpath("long.oga")))
# Finish the test so the player will close and the plugin will unload.
# At one point, this caused a GIL deadlock in ~AudioPlayer().
# This test should verify that this deadlock no longer happens.
class TestAudioPlayer(omni.kit.test.AsyncTestCase): # pragma: no cover
def setUp(self):
self._player = omni.audioplayer.create_audio_player()
self.assertIsNotNone(self._player)
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.audioplayer}")
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
self._golden_path = self._test_path.joinpath("golden")
def tearDown(self):
self._player = None
def test_basic(self):
events = []
expected_load_result = True
def event_callback(event):
nonlocal events
nonlocal expected_load_result
events.append(event.type)
if event.type == int(omni.audioplayer.CallbackType.LOADED):
self.assertEqual(event.payload["success"], expected_load_result)
sub = self._player.get_event_stream().create_subscription_to_pop(event_callback)
# load the sound and verify that a loaded event shows up
last = len(events)
self._player.load_sound(str(self._test_path.joinpath("long.oga")))
i = 0
while len(events) == last:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# check that get_sound_length() works
self.assertLess(abs(self._player.get_sound_length() - 120.0), 0.001)
# play the sound and verify that a load event is sent
last = len(events)
self._player.play_sound(str(self._test_path.joinpath("long.oga")))
# it should load quickly since it's already been loaded once
time.sleep(1)
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# pause and unpause it a few times
last = len(events)
self._player.pause_sound()
time.sleep(1)
self._player.unpause_sound()
time.sleep(1)
self._player.pause_sound()
time.sleep(1)
# nothing should have been sent
self.assertEqual(len(events), last)
self.assertGreater(self._player.get_play_cursor(), 0.0)
# modify the play cursor, this should send an ended then loaded event
last = len(events)
self._player.set_play_cursor(60.0)
i = 0
while len(events) <= last + 1:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 2)
self.assertEqual(events[-2], int(omni.audioplayer.CallbackType.ENDED))
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
self.assertGreaterEqual(self._player.get_play_cursor(), 60.0)
# stop it and verify that the ended event is sent
last = len(events)
self._player.stop_sound()
i = 0
while len(events) == last:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.ENDED))
# play the same sound again and see if events are sent
last = len(events)
self._player.play_sound(str(self._test_path.joinpath("long.oga")))
i = 0
while len(events) == last:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# play again to see the ended and loaded event
last = len(events)
self._player.play_sound(str(self._test_path.joinpath("long.oga")))
i = 0
while len(events) <= last + 1:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 2)
self.assertEqual(events[-2], int(omni.audioplayer.CallbackType.ENDED))
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# Note: there is no test for callbacks with play_sound() 2 times back to back
# because whether callbacks for both calls are sent is dependent on timing.
# The less recent sound playback may just be cancelled.
def test_draw_waveform(self):
# toggle in case you want to regenerate waveforms
GENERATE_GOLDEN_IMAGES = False
W = 256
H = 256
loaded = False
def event_callback(event):
if event.type == int(omni.audioplayer.CallbackType.LOADED):
nonlocal loaded
loaded = True
sub = self._player.get_event_stream().create_subscription_to_pop(event_callback)
self._player.load_sound(str(self._test_path.joinpath("short-2ch.oga")))
i = 0
while not loaded:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self._player.draw_waveform_to_file(str(OUTPUTS_DIR.joinpath("waveform.png")), W, H, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath("waveform.png"),
self._golden_path.joinpath("waveform.png"),
pathlib.Path(OUTPUTS_DIR).joinpath("waveform.png.diff.png")),
0.1)
raw = self._player.draw_waveform(W, H, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(OUTPUTS_DIR.joinpath("waveform.raw.png")))
if not GENERATE_GOLDEN_IMAGES:
# this image is slightly different than the original and this compare
# helper function cannot handle even a slight difference, so we need to
# have a separate golden image for this
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath("waveform.raw.png"),
self._golden_path.joinpath("waveform.raw.png"),
pathlib.Path(OUTPUTS_DIR).joinpath("waveform.raw.png.diff.png")),
0.1)
def _load_and_play_data_in_memory(self, filename, frame_rate, channels, format, flags = 0, expected_length = 2.0):
events = []
expected_load_result = True
def event_callback(event):
nonlocal events
nonlocal expected_load_result
events.append(event.type)
if event.type == int(omni.audioplayer.CallbackType.LOADED):
self.assertEqual(event.payload["success"], expected_load_result)
# subscribe to events from the player.
sub = self._player.get_event_stream().create_subscription_to_pop(event_callback)
# load the test file into a bytes object.
file_data = pathlib.Path(self._test_path.joinpath(filename)).read_bytes()
# load the sound and verify that a 'loaded' event shows up.
last = len(events)
self._player.load_sound_in_memory(filename, file_data, frame_rate, channels, format, flags)
i = 0
while len(events) == last:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# check that get_sound_length() works.
self.assertLess(abs(self._player.get_sound_length() - expected_length), 0.001)
# play the sound and verify that a load event is sent.
last = len(events)
self._player.play_sound_in_memory(filename, file_data, frame_rate, channels, format, 0.0, flags)
# it should load quickly since it's already been loaded once.
time.sleep(1)
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# stop it and verify that the ended event is sent.
last = len(events)
self._player.stop_sound()
i = 0
while len(events) == last:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.ENDED))
# clean up.
sub = None
def test_data_in_memory(self):
self._load_and_play_data_in_memory("tone-440-8.wav", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_8)
self._load_and_play_data_in_memory("tone-440-16.wav", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_16)
self._load_and_play_data_in_memory("tone-440-32.wav", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_32)
self._load_and_play_data_in_memory("tone-440-float.wav", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_FLOAT)
def test_raw_data_in_memory(self):
self._load_and_play_data_in_memory("tone-440-8.raw", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_8, omni.audioplayer.FLAG_RAW_DATA)
self._load_and_play_data_in_memory("tone-440-16.raw", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_16, omni.audioplayer.FLAG_RAW_DATA)
self._load_and_play_data_in_memory("tone-440-32.raw", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_32, omni.audioplayer.FLAG_RAW_DATA)
self._load_and_play_data_in_memory("tone-440-float.raw", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_FLOAT, omni.audioplayer.FLAG_RAW_DATA)
| 11,500 | Python | 39.354386 | 147 | 0.61913 |
omniverse-code/kit/exts/omni.rtx.shadercache.d3d12/omni/rtx/shadercache/d3d12/__init__.py | from .shadercache_d3d12 import ShaderCacheConfig
| 49 | Python | 23.999988 | 48 | 0.877551 |
omniverse-code/kit/exts/omni.rtx.shadercache.d3d12/omni/rtx/shadercache/d3d12/shadercache_d3d12.py | import omni.ext
class ShaderCacheConfig(omni.ext.IExt):
def on_startup(self, ext_id):
"""Callback when the extension is starting up"""
pass
def on_shutdown(self):
"""Callback when the extension is shutting down"""
pass
| 261 | Python | 22.81818 | 58 | 0.636015 |
omniverse-code/kit/exts/omni.kit.clipboard/PACKAGE-LICENSES/omni.kit.clipboard-LICENSE.md | 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. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.clipboard/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 primarly for displaying extension info in UI
title = "Clipboard Utilities"
description="Cross-platform clipboard utilities for copy & paste functionality."
# URL of the extension source repository.
repository = ""
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Keywords for the extension
keywords = ["kit", "clipboard", "copy", "paste"]
# 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"
# Main python module this extension provides, it will be publicly available as "import omni.kit.clipboard".
[[python.module]]
name = "omni.kit.clipboard"
[[test]]
dependencies = [
"omni.ui",
"omni.kit.ui_test",
]
| 1,168 | TOML | 28.974358 | 107 | 0.734589 |
omniverse-code/kit/exts/omni.kit.clipboard/omni/kit/clipboard/__init__.py |
def _clipboard_prep():
import omni.appwindow
import carb.windowing
_app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
_app_window = _app_window_factory.get_default_window()
_carb_window = _app_window.get_window()
_windowing = carb.windowing.acquire_windowing_interface()
return _windowing, _carb_window
def copy(value_str):
"""
Platform-independent copy functionality.
Args:
value_str (str): String to put in the clipboard.
"""
_windowing, _carb_window = _clipboard_prep()
_windowing.set_clipboard(_carb_window, value_str)
def paste():
"""
Platform-independent paste functionality.
Returns:
str: Value pulled from the clipboard.
"""
_windowing, _carb_window = _clipboard_prep()
value_str = _windowing.get_clipboard(_carb_window)
return value_str
| 877 | Python | 23.388888 | 79 | 0.667047 |
omniverse-code/kit/exts/omni.kit.clipboard/omni/kit/clipboard/tests/__init__.py | from .test_clipboard import *
| 30 | Python | 14.499993 | 29 | 0.766667 |
omniverse-code/kit/exts/omni.kit.clipboard/omni/kit/clipboard/tests/test_clipboard.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 omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from .. import copy, paste
class ClipboardTest(OmniUiTest):
async def test_clipboard(self):
await self.create_test_window(width=400, height=40)
human_delay_speed = 2
await ui_test.wait_n_updates(human_delay_speed)
str_to_copy = "Testing, testing, 1, 2, 3."
copy(str_to_copy)
pasted_str = paste()
self.assertEqual(str_to_copy, pasted_str)
| 917 | Python | 31.785713 | 77 | 0.720829 |
omniverse-code/kit/exts/omni.kit.clipboard/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2022-11-29
### Added
- Initial Add
| 144 | Markdown | 15.111109 | 80 | 0.652778 |
omniverse-code/kit/exts/omni.kit.clipboard/docs/README.md | # omni.kit.clipboard
## Introduction
This extension contains basic clipboard utilities like copy and paste, that are meant to be
cross-platform.
| 147 | Markdown | 20.142854 | 91 | 0.795918 |
omniverse-code/kit/exts/omni.kit.clipboard/docs/index.rst | omni.kit.clipboard: Clipboard Utilities Extension
#################################################
.. toctree::
:maxdepth: 1
CHANGELOG
Clipboard
=========
.. automodule:: omni.kit.clipboard
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
| 301 | reStructuredText | 17.874999 | 49 | 0.554817 |
omniverse-code/kit/exts/omni.kit.usd.collect/docs/index.rst | omni.kit.usd.collect
#######################
Python extension to collect all dependencies of a USD.
| 101 | reStructuredText | 19.399996 | 54 | 0.613861 |
omniverse-code/kit/exts/omni.activity.freeze_monitor/PACKAGE-LICENSES/omni.activity.freeze_monitor-LICENSE.md | 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. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.activity.freeze_monitor/config/extension.toml | [package]
title = "Omni Activity Freeze Monitor"
category = "Telemetry"
version = "1.0.1"
description = "Freeze Window"
authors = ["NVIDIA"]
keywords = ["activity"]
changelog = "docs/CHANGELOG.md"
[[python.module]]
name = "omni.activity.freeze_monitor"
[dependencies]
"omni.activity.core" = {}
[[native.plugin]]
path = "bin/*.plugin"
[settings]
exts."omni.activity.freeze_monitor".threshold_ms = 1000
exts."omni.activity.freeze_monitor".after_ms = 1000
exts."omni.activity.freeze_monitor".force = false
exts."omni.activity.freeze_monitor".wheel_image = "${kit}/exts/omni.activity.freeze_monitor/icons/kit.png"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.mainwindow",
"omni.kit.renderer.capture",
"omni.ui",
"omni.usd",
]
| 848 | TOML | 21.342105 | 106 | 0.686321 |
omniverse-code/kit/exts/omni.activity.freeze_monitor/omni/activity/freeze_monitor/__init__.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.
##
# Required to be able to instantiate the object types
import omni.core
| 508 | Python | 41.416663 | 77 | 0.793307 |
omniverse-code/kit/exts/omni.activity.freeze_monitor/omni/activity/freeze_monitor/tests/test_skip.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.activity.core as act
import omni.kit.app
import omni.kit.test
class TestSkip(omni.kit.test.AsyncTestCase):
async def test_general(self):
"""
Temporarly placeholder for tests
"""
self.assertTrue(True)
| 686 | Python | 33.349998 | 77 | 0.747813 |
omniverse-code/kit/exts/omni.activity.freeze_monitor/omni/activity/freeze_monitor/tests/__init__.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 .test_skip import TestSkip
| 469 | Python | 41.727269 | 77 | 0.793177 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/style.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 Dict
from omni.ui import color as cl
COLOR_X = 0xFF6060AA
COLOR_Y = 0xFF76A371
COLOR_Z = 0xFFA07D4F
COLOR_SCREEN = 0x8AFEF68E
COLOR_FREE = 0x40404040
COLOR_FOCAL = 0xE6CCCCCC
def get_default_style():
return {
"Translate.Axis::x": {"color": COLOR_X},
"Translate.Axis::y": {"color": COLOR_Y},
"Translate.Axis::z": {"color": COLOR_Z},
"Translate.Plane::x_y": {"color": COLOR_Z},
"Translate.Plane::y_z": {"color": COLOR_X},
"Translate.Plane::z_x": {"color": COLOR_Y},
"Translate.Point": {"color": COLOR_SCREEN, "type": "point"},
"Translate.Focal": {"color": COLOR_FOCAL, "visible": False},
"Rotate.Arc::x": {"color": COLOR_X},
"Rotate.Arc::y": {"color": COLOR_Y},
"Rotate.Arc::z": {"color": COLOR_Z},
"Rotate.Arc::screen": {"color": COLOR_SCREEN},
"Rotate.Arc::free": {"color": COLOR_FREE},
"Scale.Axis::x": {"color": COLOR_X},
"Scale.Axis::y": {"color": COLOR_Y},
"Scale.Axis::z": {"color": COLOR_Z},
"Scale.Plane::x_y": {"color": COLOR_Z},
"Scale.Plane::y_z": {"color": COLOR_X},
"Scale.Plane::z_x": {"color": COLOR_Y},
"Scale.Point": {"color": COLOR_SCREEN},
}
def get_default_toolbar_style():
return {
"CollapsableFrame": {
"background_color": 0x00,
"secondary_color": 0x00,
"border_color": 0x0,
"border_width": 0,
"padding": 0,
"margin_height": 5,
"margin_width": 0,
},
"CollapsableFrame:hovered": {"secondary_color": 0x00},
"CollapsableFrame:pressed": {"secondary_color": 0x00},
"Line": {"color": 0xFFA1A1A1, "border_width": 2},
"Rectangle": {"background_color": 0x8F000000},
}
def abgr_to_color(abgr: int) -> cl:
# cl in rgba order
return cl((abgr & 0xFF) / 255, (abgr >> 8 & 0xFF) / 255, (abgr >> 16 & 0xFF) / 255, (abgr >> 24 & 0xFF) / 255)
# style is nested dict, can't simply call to_style.update(from_style)
def update_style(to_style: Dict, from_style: Dict):
if from_style:
for k, v in from_style.items():
if isinstance(v, dict):
to_style[k] = update_style(to_style.get(k, {}), v)
else:
to_style[k] = v
return to_style
| 2,774 | Python | 34.126582 | 114 | 0.583273 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/extension.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.ext
from .style import get_default_style
SHOW_EXAMPLE = False
class TransformManipulatorExt(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
if SHOW_EXAMPLE:
from .example import SimpleManipulatorExample
self._example = SimpleManipulatorExample()
def on_shutdown(self):
if SHOW_EXAMPLE:
self._example.destroy()
self._example = None
| 1,015 | Python | 32.866666 | 119 | 0.733005 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/__init__.py | from .extension import *
from .model import *
| 46 | Python | 14.666662 | 24 | 0.73913 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/subscription.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 Callable
class Subscription:
def __init__(self, unsubscribe_fn: Callable):
self._unsubscribe_fn = unsubscribe_fn
def __del__(self):
self.unsubscribe()
def unsubscribe(self):
if self._unsubscribe_fn:
self._unsubscribe_fn()
self._unsubscribe_fn = None
| 762 | Python | 30.791665 | 76 | 0.720472 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/settings_contants.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.
#
# typo in file name
# keep for backward compatibility
from .settings_constants import *
| 517 | Python | 38.846151 | 76 | 0.802708 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/settings_listener.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 weakref
from enum import Enum, auto
from typing import Callable
import carb.dictionary
import carb.settings
from .settings_constants import c
from .subscription import Subscription
class Listener:
def __init__(self):
self._callback_id = 0
self._callbacks = {}
def add_listener(self, callback: Callable) -> int:
self._callback_id += 1
self._callbacks[self._callback_id] = callback
return self._callback_id
def remove_listener(self, id: int):
self._callbacks.pop(id)
def subscribe_listener(self, callback: Callable) -> Subscription:
id = self.add_listener(callback)
return Subscription(
lambda listener=weakref.ref(self), id=id: listener().remove_listener(id) if listener() else None
)
def _invoke_callbacks(self, *args, **kwargs):
for cb in self._callbacks.values():
cb(*args, **kwargs)
class OpSettingsListener(Listener):
class CallbackType(Enum):
OP_CHANGED = auto()
TRANSLATION_MODE_CHANGED = auto()
ROTATION_MODE_CHANGED = auto()
def __init__(self) -> None:
super().__init__()
self._dict = carb.dictionary.get_dictionary()
self._settings = carb.settings.get_settings()
self._op_sub = self._settings.subscribe_to_node_change_events(c.TRANSFORM_OP_SETTING, self._on_op_changed)
self.selected_op = self._settings.get(c.TRANSFORM_OP_SETTING)
self._translation_mode_sub = self._settings.subscribe_to_node_change_events(
c.TRANSFORM_MOVE_MODE_SETTING, self._on_translate_mode_changed
)
self.translation_mode = self._settings.get(c.TRANSFORM_MOVE_MODE_SETTING)
self._rotation_mode_sub = self._settings.subscribe_to_node_change_events(
c.TRANSFORM_ROTATE_MODE_SETTING, self._on_rotation_mode_changed
)
self.rotation_mode = self._settings.get(c.TRANSFORM_ROTATE_MODE_SETTING)
def __del__(self):
self.destroy()
def destroy(self):
if self._op_sub:
self._settings.unsubscribe_to_change_events(self._op_sub)
self._op_sub = None
if self._translation_mode_sub:
self._settings.unsubscribe_to_change_events(self._translation_mode_sub)
self._translation_mode_sub = None
if self._rotation_mode_sub:
self._settings.unsubscribe_to_change_events(self._rotation_mode_sub)
self._rotation_mode_sub = None
def _on_op_changed(self, item, event_type):
selected_op = self._dict.get(item)
if selected_op != self.selected_op:
self.selected_op = selected_op
self._invoke_callbacks(OpSettingsListener.CallbackType.OP_CHANGED, self.selected_op)
def _on_translate_mode_changed(self, item, event_type):
translation_mode = self._dict.get(item)
if self.translation_mode != translation_mode:
self.translation_mode = translation_mode
self._invoke_callbacks(OpSettingsListener.CallbackType.TRANSLATION_MODE_CHANGED, self.translation_mode)
def _on_rotation_mode_changed(self, item, event_type):
rotation_mode = self._dict.get(item)
if self.rotation_mode != rotation_mode:
self.rotation_mode = rotation_mode
self._invoke_callbacks(OpSettingsListener.CallbackType.ROTATION_MODE_CHANGED, self.rotation_mode)
class SnapSettingsListener(Listener):
def __init__(
self,
enabled_setting_path: str = None,
move_x_setting_path: str = None,
move_y_setting_path: str = None,
move_z_setting_path: str = None,
rotate_setting_path: str = None,
scale_setting_path: str = None,
provider_setting_path: str = None,
) -> None:
super().__init__()
self._dict = carb.dictionary.get_dictionary()
self._settings = carb.settings.get_settings()
# keep around for backward compatibility
SNAP_ENABLED_SETTING = "/app/viewport/snapEnabled"
SNAP_MOVE_X_SETTING = "/persistent/app/viewport/stepMove/x"
SNAP_MOVE_Y_SETTING = "/persistent/app/viewport/stepMove/y"
SNAP_MOVE_Z_SETTING = "/persistent/app/viewport/stepMove/z"
SNAP_ROTATE_SETTING = "/persistent/app/viewport/stepRotate"
SNAP_SCALE_SETTING = "/persistent/app/viewport/stepScale"
SNAP_TO_SURFACE_SETTING = "/persistent/app/viewport/snapToSurface"
if not enabled_setting_path:
enabled_setting_path = SNAP_ENABLED_SETTING
if not move_x_setting_path:
move_x_setting_path = SNAP_MOVE_X_SETTING
if not move_y_setting_path:
move_y_setting_path = SNAP_MOVE_Y_SETTING
if not move_z_setting_path:
move_z_setting_path = SNAP_MOVE_Z_SETTING
if not rotate_setting_path:
rotate_setting_path = SNAP_ROTATE_SETTING
if not scale_setting_path:
scale_setting_path = SNAP_SCALE_SETTING
if not provider_setting_path:
provider_setting_path = SNAP_TO_SURFACE_SETTING
# subscribe to snap events
def subscribe_to_value_and_get_current(setting_val_name: str, setting_path: str):
def on_settings_changed(tree_item, changed_item, type):
# do not use `value = self._dict.get(tree_item)`, Dict does not work well with array setting
value = self._settings.get(setting_path)
setattr(self, setting_val_name, value)
self._invoke_callbacks(setting_val_name, value)
sub = self._settings.subscribe_to_tree_change_events(setting_path, on_settings_changed)
value = self._settings.get(setting_path)
setattr(self, setting_val_name, value)
return sub
self._snap_enabled_sub = subscribe_to_value_and_get_current("snap_enabled", enabled_setting_path)
self._snap_move_x_sub = subscribe_to_value_and_get_current("snap_move_x", move_x_setting_path)
self._snap_move_y_sub = subscribe_to_value_and_get_current("snap_move_y", move_y_setting_path)
self._snap_move_z_sub = subscribe_to_value_and_get_current("snap_move_z", move_z_setting_path)
self._snap_rotate_sub = subscribe_to_value_and_get_current("snap_rotate", rotate_setting_path)
self._snap_scale_sub = subscribe_to_value_and_get_current("snap_scale", scale_setting_path)
self._snap_to_surface_sub = subscribe_to_value_and_get_current("snap_to_surface", provider_setting_path)
self._snap_provider_sub = subscribe_to_value_and_get_current("snap_provider", provider_setting_path)
def __del__(self):
self.destroy()
def destroy(self):
if self._snap_enabled_sub:
self._settings.unsubscribe_to_change_events(self._snap_enabled_sub)
self._snap_enabled_sub = None
if self._snap_move_x_sub:
self._settings.unsubscribe_to_change_events(self._snap_move_x_sub)
self._snap_move_x_sub = None
if self._snap_move_y_sub:
self._settings.unsubscribe_to_change_events(self._snap_move_y_sub)
self._snap_move_y_sub = None
if self._snap_move_z_sub:
self._settings.unsubscribe_to_change_events(self._snap_move_z_sub)
self._snap_move_z_sub = None
if self._snap_rotate_sub:
self._settings.unsubscribe_to_change_events(self._snap_rotate_sub)
self._snap_rotate_sub = None
if self._snap_scale_sub:
self._settings.unsubscribe_to_change_events(self._snap_scale_sub)
self._snap_scale_sub = None
if self._snap_to_surface_sub:
self._settings.unsubscribe_to_change_events(self._snap_to_surface_sub)
self._snap_to_surface_sub = None
if self._snap_provider_sub:
self._settings.unsubscribe_to_change_events(self._snap_provider_sub)
self._snap_provider_sub = None
| 8,383 | Python | 40.92 | 115 | 0.646189 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/example.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.ui as ui
from omni.ui import scene as sc
from .manipulator import Axis, TransformManipulator
from .simple_transform_model import (
SimpleRotateChangedGesture,
SimpleScaleChangedGesture,
SimpleTranslateChangedGesture,
)
from .types import Operation
class Select(sc.ClickGesture):
def __init__(self, example):
super().__init__()
self._example = example
def on_ended(self):
self._example.on_point_clicked(self.sender)
class SimpleManipulatorExample:
def __init__(self):
projection = [0.011730205278592375, 0.0, 0.0, 0.0]
projection += [0.0, 0.02055498458376156, 0.0, 0.0]
projection += [0.0, 0.0, 2.00000020000002e-07, 0.0]
projection += [-0.0, -0.0, 1.00000020000002, 1.0]
view = [1.0, 0.0, 0.0, 0.0]
view += [0.0, 1.0, 0.0, 0.0]
view += [0.0, 0.0, 1.0, 0.0]
view += [-2.2368736267089844, 13.669827461242786, -5.0, 1.0]
self._selected_shape = None
self._window = ui.Window("Simple Manipulator Example")
with self._window.frame:
scene_view = sc.SceneView(projection=projection, view=view)
with scene_view.scene:
self._ma = TransformManipulator(
size=1,
axes=Axis.ALL & ~Axis.Z & ~Axis.SCREEN,
enabled=False,
gestures=[
SimpleTranslateChangedGesture(),
SimpleRotateChangedGesture(),
SimpleScaleChangedGesture(),
],
)
self._sub = self._ma.model.subscribe_item_changed_fn(self._on_item_changed)
sc.Points([[0, 0, 0]], colors=[ui.color.white], sizes=[10], gestures=[Select(self)])
sc.Points([[50, 0, 0]], colors=[ui.color.white], sizes=[10], gestures=[Select(self)])
sc.Points([[50, -50, 0]], colors=[ui.color.white], sizes=[10], gestures=[Select(self)])
sc.Points([[0, -50, 0]], colors=[ui.color.white], sizes=[10], gestures=[Select(self)])
def __del__(self):
self.destroy()
def destroy(self):
self._window = None
def on_point_clicked(self, shape):
self._selected_shape = shape
self._ma.enabled = True
model = self._ma.model
model.set_floats(
model.get_item("translate"),
[
self._selected_shape.positions[0][0],
self._selected_shape.positions[0][1],
self._selected_shape.positions[0][2],
],
)
def _on_item_changed(self, model, item):
if self._selected_shape is not None:
if item.operation == Operation.TRANSLATE:
self._selected_shape.positions = model.get_as_floats(item)
| 3,258 | Python | 35.211111 | 103 | 0.584408 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/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:
TRANSFORM_MOVE_MODE_SETTING = "/app/transform/moveMode"
TRANSFORM_ROTATE_MODE_SETTING = "/app/transform/rotateMode"
TRANSFORM_MODE_GLOBAL = "global"
TRANSFORM_MODE_LOCAL = "local"
TRANSFORM_OP_SETTING = "/app/transform/operation"
TRANSFORM_OP_SELECT = "select"
TRANSFORM_OP_MOVE = "move"
TRANSFORM_OP_ROTATE = "rotate"
TRANSFORM_OP_SCALE = "scale"
MANIPULATOR_SCALE_SETTING = "/persistent/exts/omni.kit.manipulator.transform/manipulator/scaleMultiplier"
FREE_ROTATION_ENABLED_SETTING = "/persistent/exts/omni.kit.manipulator.transform/manipulator/freeRotationEnabled"
FREE_ROTATION_TYPE_SETTING = "/persistent/exts/omni.kit.manipulator.transform/manipulator/freeRotationType"
FREE_ROTATION_TYPE_CLAMPED = "Clamped"
FREE_ROTATION_TYPE_CONTINUOUS = "Continuous"
INTERSECTION_THICKNESS_SETTING = "/persistent/exts/omni.kit.manipulator.transform/manipulator/intersectionThickness"
TOOLS_DEFAULT_COLLAPSED_SETTING = "/persistent/exts/omni.kit.manipulator.transform/tools/defaultCollapsed"
# backward compatibility
c = Constants
| 1,542 | Python | 39.605262 | 120 | 0.772374 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/toolbar_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.
#
from __future__ import annotations
import weakref
from weakref import ReferenceType
from typing import Any, Callable, Dict, List, Tuple, Type
from .toolbar_tool import ToolbarTool
class ToolbarRegistry:
class Subscription:
def __init__(self, registry: ReferenceType[ToolbarRegistry], id: str):
self._registry = registry
self._id = id
def __del__(self):
self.release()
def release(self):
registry = self._registry()
if self._id is not None and registry is not None:
registry.unsubscribe_to_registry_change(id)
self._id = None
def __init__(self):
self._tools: Dict[str, Type[ToolbarTool]] = {}
self._change_subscribers: Dict[int, Callable] = {}
self._next_change_subscriber_id: int = 1
self._sorted_tools: List[Type[ToolbarTool]] = []
self._sort_key: Callable[[Tuple[str, Type[ToolbarTool]]], Any] = None
@property
def tools(self) -> List[Type[ToolbarTool]]:
"""Gets a sorted list of all tool classes."""
return self._sorted_tools
def register_tool(self, tool_class: Type[ToolbarTool], id: str):
"""
Registers a tool class to the registry.
Args:
tool_class (Type[ToolbarTool]): The class of the tool to be registered.
id (str): Unique id of the tool. It must not already exist.
"""
if id in self._tools:
raise ValueError(f"{id} already exist!")
self._tools[id] = tool_class
self._notify_registry_changed()
def unregister_tool(self, id: str):
"""
Unregisters a tool class using its id.
Args:
id (str): The id used in `register_tool`
"""
self._tools.pop(id, None)
self._notify_registry_changed()
def subscribe_to_registry_change(self, callback: Callable[[], None]) -> int:
"""
Subscribes to registry changed event. Callback will be called when tool classes are registered or unregistered.
Args:
callback (Callable[[], None]): the callback to be called. It is called immediately before function returns.
Return:
An Subscription object. Call sub.release() to unsubscribe.
"""
id = self._next_change_subscriber_id
self._next_change_subscriber_id += 1
self._change_subscribers[id] = callback
self._notify_registry_changed(callback)
return ToolbarRegistry.Subscription(weakref.ref(self), id)
def unsubscribe_to_registry_change(self, id: int):
"""
Called be Subscription.release to unsubscribe from registry changed event. Do not call this function directly.
User should use Subscription object to unsubscribe.
Args:
id (int): id returned from subscribe_to_registry_change
"""
self._change_subscribers.pop(id, None)
def set_sort_key_function(self, key: Callable[[Tuple[str, Type[ToolbarTool]]], Any]):
"""
Set a custom key function to sort the registered tool classes.
Args:
key (Callable[[Tuple[str, Type[ToolbarTool]]], Any]): key function used for sorting.
"""
self._sort_key = key
def _notify_registry_changed(self, callback: Callable[[], None] = None):
self._sorted_tools = [value for key, value in sorted(self._tools.items(), key=self._sort_key)]
if not callback:
for sub in self._change_subscribers.values():
sub()
else:
callback()
| 4,027 | Python | 33.724138 | 119 | 0.625776 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/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
from typing import List
from omni.ui import scene as sc
from .types import Operation
class AbstractTransformManipulatorModel(sc.AbstractManipulatorModel):
class OperationItem(sc.AbstractManipulatorItem):
def __init__(self, op: Operation):
super().__init__()
self._op = op
@property
def operation(self):
return self._op
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._translate_item = AbstractTransformManipulatorModel.OperationItem(Operation.TRANSLATE)
self._rotate_item = AbstractTransformManipulatorModel.OperationItem(Operation.ROTATE)
self._scale_item = AbstractTransformManipulatorModel.OperationItem(Operation.SCALE)
self._transform_item = sc.AbstractManipulatorItem()
self._translate_delta_item = AbstractTransformManipulatorModel.OperationItem(Operation.TRANSLATE_DELTA)
self._rotate_delta_item = AbstractTransformManipulatorModel.OperationItem(Operation.ROTATE_DELTA)
self._scale_delta_item = AbstractTransformManipulatorModel.OperationItem(Operation.SCALE_DELTA)
self._items = {
"translate": self._translate_item,
"rotate": self._rotate_item,
"scale": self._scale_item,
"transform": self._transform_item,
"translate_delta": self._translate_delta_item,
"rotate_delta": self._rotate_delta_item,
"scale_delta": self._scale_delta_item,
}
def get_as_floats(self, item: sc.AbstractManipulatorItem) -> List[float]:
"""
Called by manipulator to fetch item values.
Returns a composed Matrix4x4 transform in world space as a list of float.
"""
...
def get_as_floats(self, item: sc.AbstractManipulatorItem) -> List[int]:
"""
Called by manipulator to fetch item values.
Returns a composed Matrix4x4 transform in world space as a list of int.
"""
...
def get_item(self, name: str) -> sc.AbstractManipulatorItem:
"""
See AbstractManipulatorItem.get_item
"""
return self._items.get(name, None)
def widget_enabled(self):
"""
Called by hosting manipulator widget(s) when they're enabled.
It can be used to track if any hosting manipulator is active to skip background model update (i.e. running listener for changes).
"""
...
def widget_disabled(self):
"""
Called by hosting manipulator widget(s) when they're disabled.
It can be used to track if any hosting manipulator is active to skip background model update (i.e. running listener for changes).
"""
...
def set_floats(self, item: sc.AbstractManipulatorItem, value: List[float]):
"""
Called when the manipulator is being dragged and value changes, or set by external code to overwrite the value.
The model should update value to underlying data holder(s) (e.g. a USD prim(s)).
Depending on the model implemetation, item and value can be customized to model's needs.
"""
...
def set_ints(self, item: sc.AbstractManipulatorItem, value: List[int]):
"""
Called when the manipulator is being dragged and value changes, or set by external code to overwrite the value.
The model should update value to underlying data holder(s) (e.g. a USD prim(s)).
Depending on the model implemetation, item and value can be customized to model's needs.
"""
...
def get_operation(self) -> Operation:
"""
Called by the manipulator to determine which operation is active.
"""
...
def get_snap(self, item: sc.AbstractManipulatorItem):
"""
Called by the manipulator, returns the minimal increment step for each operation. None if no snap should be performed.
Different Operation requires different return values:
- TRANSLATE: Tuple[float, float, float]. One entry for X/Y/Z axis.
- ROTATE: float. Angle in degree.
- SCALE: float
"""
return None
| 4,631 | Python | 37.924369 | 137 | 0.658821 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/simple_transform_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 math
from typing import List
import carb
from omni.kit.manipulator.transform.gestures import (
RotateChangedGesture,
RotateDragGesturePayload,
ScaleChangedGesture,
ScaleDragGesturePayload,
TransformDragGesturePayload,
TranslateChangedGesture,
TranslateDragGesturePayload,
)
from omni.ui import scene as sc
from .model import AbstractTransformManipulatorModel
from .types import Operation
class SimpleTranslateChangedGesture(TranslateChangedGesture):
def on_changed(self):
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, TranslateDragGesturePayload):
return
model = self.sender.model
item = self.gesture_payload.changing_item
translated = self.gesture_payload.moved_delta
translation = [a + b for a, b in zip(translated, model.get_as_floats(item))]
model.set_floats(item, translation)
class SimpleRotateChangedGesture(RotateChangedGesture):
def on_began(self):
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, RotateDragGesturePayload):
return
model = self.sender.model
item = self.gesture_payload.changing_item
self._begin_rotation = model.get_as_floats(item).copy()
self._begin_rotation_matrix = sc.Matrix44.get_rotation_matrix(
self._begin_rotation[0], self._begin_rotation[1], self._begin_rotation[2], True
)
def on_changed(self):
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, RotateDragGesturePayload):
return
model = self.sender.model
item = self.gesture_payload.changing_item
axis = self.gesture_payload.axis
angle = self.gesture_payload.angle
# always reset begin_rotation in local rotation mode
if not model.global_mode:
self._begin_rotation = model.get_as_floats(item).copy()
self._begin_rotation_matrix = sc.Matrix44.get_rotation_matrix(
self._begin_rotation[0], self._begin_rotation[1], self._begin_rotation[2], True
)
# convert to radian
angle = angle / 180.0 * math.pi
# calculate rotation matrix around axis for angle in radian
matrix = [
math.cos(angle) + axis[0] ** 2 * (1 - math.cos(angle)),
axis[0] * axis[1] * (1 - math.cos(angle)) + axis[2] * math.sin(angle),
axis[0] * axis[2] * (1 - math.cos(angle)) - axis[1] * math.sin(angle),
0,
]
matrix += [
axis[0] * axis[1] * (1 - math.cos(angle)) - axis[2] * math.sin(angle),
math.cos(angle) + axis[1] ** 2 * (1 - math.cos(angle)),
axis[1] * axis[2] * (1 - math.cos(angle)) + axis[0] * math.sin(angle),
0,
]
matrix += [
axis[0] * axis[2] * (1 - math.cos(angle)) + axis[1] * math.sin(angle),
axis[1] * axis[2] * (1 - math.cos(angle)) - axis[0] * math.sin(angle),
math.cos(angle) + axis[2] ** 2 * (1 - math.cos(angle)),
0,
]
matrix += [0, 0, 0, 1]
matrix = sc.Matrix44(*matrix) # each 4 elements in list is a COLUMN in a row-vector matrix!
rotate = self._begin_rotation_matrix * matrix
# decompose back to x y z euler angle
sy = math.sqrt(rotate[0] ** 2 + rotate[1] ** 2)
is_singular = sy < 10 ** -6
if not is_singular:
z = math.atan2(rotate[1], rotate[0])
y = math.atan2(-rotate[2], sy)
x = math.atan2(rotate[6], rotate[10])
else:
z = math.atan2(-rotate[9], rotate[5])
y = math.atan2(-rotate[2], sy)
x = 0
x = x / math.pi * 180.0
y = y / math.pi * 180.0
z = z / math.pi * 180.0
model.set_floats(item, [x, y, z])
class SimpleScaleChangedGesture(ScaleChangedGesture):
def on_began(self):
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, ScaleDragGesturePayload):
return
model = self.sender.model
item = self.gesture_payload.changing_item
self._begin_scale = model.get_as_floats(item).copy()
def on_changed(self):
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, ScaleDragGesturePayload):
return
model = self.sender.model
item = self.gesture_payload.changing_item
axis = self.gesture_payload.axis
scale = self.gesture_payload.scale
scale_delta = [scale * v for v in axis]
scale_vec = [0, 0, 0]
for i in range(3):
scale_vec[i] = self._begin_scale[i] * scale_delta[i] if scale_delta[i] else self._scale[i]
model.set_floats(item, [scale_vec[0], scale_vec[1], scale_vec[2]])
class SimpleTransformModel(AbstractTransformManipulatorModel):
"""
SimpleTransformModel is a model that provides basic S/R/T transform data processing. You can subscribe to callback
to get manipulated data. Rotation is stored in degree and applis in XYZ order.
"""
def __init__(self):
super().__init__()
self._translation = [0, 0, 0]
self._rotation = [0, 0, 0]
self._scale = [1, 1, 1]
self._transform = sc.Matrix44(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
self._op = Operation.TRANSLATE
self._global_mode = True
self._dirty = True
@property
def global_mode(self) -> bool:
"""
The Global vs Local transform mode.
"""
return self._global_mode
@global_mode.setter
def global_mode(self, value: bool):
if self._global_mode != value:
self._global_mode = value
self._dirty = True # global vs local mode returns different Transform matrix
self._item_changed(self._transform_item)
def set_floats(self, item: AbstractTransformManipulatorModel.OperationItem, value: List[float]):
if item == self._translate_item:
self._translation[0] = value[0]
self._translation[1] = value[1]
self._translation[2] = value[2]
self._dirty = True
self._item_changed(self._translate_item)
elif item == self._rotate_item:
self._rotation[0] = value[0]
self._rotation[1] = value[1]
self._rotation[2] = value[2]
self._dirty = True
self._item_changed(self._rotate_item)
elif item == self._scale_item:
self._scale[0] = value[0]
self._scale[1] = value[1]
self._scale[2] = value[2]
self._dirty = True
self._item_changed(self._scale_item)
else:
carb.log_warn(f"Unsupported item {item}")
def get_as_floats(self, item: AbstractTransformManipulatorModel.OperationItem) -> List[float]:
if item == self._translate_item:
return self._translation
elif item == self._rotate_item:
return self._rotation
elif item == self._scale_item:
return self._scale
elif item is None or item == self._transform_item:
if self._dirty:
# Scale is not put into the Transform matrix because we don't want the TransformManipulator itself to scale
# For a "global" style rotation gizmo (where the gizmo doesn't rotate), we don't want to put the rotation into Transform either.
if self._global_mode:
self._transform = sc.Matrix44.get_translation_matrix(
self._translation[0], self._translation[1], self._translation[2]
)
else:
self._transform = sc.Matrix44.get_translation_matrix(
self._translation[0], self._translation[1], self._translation[2]
) * sc.Matrix44.get_rotation_matrix(self._rotation[0], self._rotation[1], self._rotation[2], True)
self._dirty = False
return self._transform
else:
carb.log_warn(f"Unsupported item {item}")
return None
def get_operation(self) -> Operation:
return self._op
def set_operation(self, op: Operation):
if self._op != op:
self._op = op
self._item_changed(self._transform_item)
| 8,900 | Python | 37.532467 | 144 | 0.598764 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/toolbar_tool.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 weakref
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict
from weakref import ProxyType
import carb
import omni.kit.app
import omni.kit.context_menu
import omni.ui as ui
from .manipulator import TransformManipulator
from .types import Operation
ICON_FOLDER_PATH = Path(
f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons"
)
class ToolbarTool(ABC):
def __init__(
self,
manipulator: ProxyType[TransformManipulator],
operation: Operation,
toolbar_height: int,
toolbar_payload: Dict[str, Any] = {},
tooltip_update_fn: Callable[[str, bool, float], None] = None,
):
self._manipulator = manipulator
self._operation = operation
self._model = manipulator.model
self._toolbar_height = toolbar_height
self._toolbar_payload = toolbar_payload
self._tooltip_update_fn = tooltip_update_fn
def destroy(self):
self._manipulator = None
self._model = None
self._toolbar_payload = None
self._tooltip_update_fn = None
def __del__(self):
self.destroy()
@classmethod
@abstractmethod
def can_build(cls, manipulator: TransformManipulator, operation: Operation) -> bool:
"""
Called right before a tool instance is to be instantiated to determine if this tool can be built on current toolbar.
Args:
manipulator (TransformManipulator): manipulator that hosts the toolbar
operation (Operation): The transform Operation the tool will be built for.
Return:
True if the tool can be built. Its constructor will be called.
False if not. The tool will be skipped and not placed on toolbar.
"""
raise NotImplementedError("You must override `can_build` in your derived class!")
return False
class DefaultMenuDelegate(ui.MenuDelegate):
def get_style(self):
from omni.kit.context_menu import style
return style.MENU_STYLE
class SimpleToolButton(ToolbarTool):
def __init__(self, menu_delegate: ui.MenuDelegate = None, *args, **kwargs):
super().__init__(*args, **kwargs)
self._show_menu_task = None
self._cancel_next_value_changed = False # workaround context menu triggering button state change
self._ignore_model_change = False
self._button = None
self._stack = None
self._menu_delegate = menu_delegate if menu_delegate else DefaultMenuDelegate()
def destroy(self):
self._menu_delegate = None
if self._show_menu_task is not None:
self._show_menu_task.cancel()
self._show_menu_task = None
if self._button:
self._button.set_mouse_hovered_fn(None)
self._sub = None
self._button = None
self._stack = None
super().destroy()
def _get_style(self) -> Dict:
return {
"Button": {"background_color": 0x0},
"Button:checked": {"background_color": 0x8FD1912E},
"Button:hovered": {"background_color": 0x0},
"Button:pressed": {"background_color": 0x0},
}
def _build_widget(
self,
button_name: str,
model: ui.AbstractValueModel,
enabled_img_url: str,
disabled_img_url: str = None,
menu_index: str = None,
menu_extension_id: str = None,
no_toggle: bool = False,
menu_on_left_click: bool = False,
menu_payload: Dict[str, Any] = {},
tooltip: str = "",
disabled_tooltip: str = "",
):
self._button_name = button_name
self._model = model
self._enabled_img_url = enabled_img_url
self._disabled_img_url = disabled_img_url
self._menu_index = menu_index
self._menu_extension_id = menu_extension_id
self._no_toggle = no_toggle
self._menu_on_left_click = menu_on_left_click
self._menu_payload = menu_payload
self._tooltip = tooltip
self._disabled_tooltip = disabled_tooltip
self._button_hovered = False
style = {}
if self._disabled_img_url:
style[f"Button.Image::{self._button_name}_enabled"] = {"image_url": f"{self._enabled_img_url}"}
style[f"Button.Image::{self._button_name}_disabled"] = {"image_url": f"{self._disabled_img_url}"}
else:
style[f"Button.Image::{self._button_name}"] = {"image_url": f"{self._enabled_img_url}"}
style.update(self._get_style())
self._stack = ui.ZStack(width=0, height=0, style=style)
with self._stack:
dimension = self._toolbar_height
self._button = ui.ToolButton(
name=self._button_name,
model=self._model,
image_width=dimension,
image_height=dimension,
)
self._button.set_mouse_hovered_fn(self._on_hovered)
if self._menu_index is not None and self._menu_extension_id is not None:
self._button.set_mouse_pressed_fn(lambda x, y, b, _: self._on_mouse_pressed(b, self._menu_index))
self._button.set_mouse_released_fn(lambda x, y, b, _: self._on_mouse_released(b))
self._build_flyout_indicator(dimension, dimension, self._menu_index, self._menu_extension_id)
# only update name if enabled and disabled imgs are different
if self._disabled_img_url or self._tooltip != self._disabled_tooltip:
self._update_name(self._button, self._button.model.as_bool)
self._sub = self._button.model.subscribe_value_changed_fn(self._on_model_changed)
def _on_hovered(self, state: bool):
self._button_hovered = state
if self._tooltip and self._tooltip_update_fn:
tooltip = self._disabled_tooltip if not self._button.model.as_bool and self._disabled_tooltip else self._tooltip
self._tooltip_update_fn(tooltip, state, self._button.screen_position_x)
def _on_model_changed(self, model):
if self._ignore_model_change:
return
if self._no_toggle:
self._ignore_model_change = True
model.set_value(not model.as_bool)
self._ignore_model_change = False
return
if self._cancel_next_value_changed:
self._cancel_next_value_changed = False
model.set_value(not model.as_bool)
if self._disabled_img_url or self._tooltip != self._disabled_tooltip:
self._update_name(self._button, model.as_bool)
def _update_name(self, button: ui.ToolButton, enabled: bool):
if self._disabled_img_url:
button.name = f"{self._button_name}_{'enabled' if enabled else 'disabled'}"
self._on_hovered(self._button_hovered)
self._manipulator.refresh_toolbar()
def _invoke_context_menu(self, button_id: str, right_click: bool, min_menu_entries: int = 1):
context_menu = omni.kit.context_menu.get_instance()
objects = {"widget_name": button_id, "manipulator": self._manipulator, "model": self._model}
objects.update(self._toolbar_payload)
objects.update(self._menu_payload)
menu_list = omni.kit.context_menu.get_menu_dict(self._menu_index, self._menu_extension_id)
context_menu.show_context_menu(
self._menu_index, objects, menu_list, min_menu_entries, delegate=self._menu_delegate
)
# if from long LMB hold
if not right_click:
self._cancel_next_value_changed = True
def _on_mouse_pressed(self, button, button_id: str, min_menu_entries: int = 1):
"""
Function to handle flyout menu. Either with LMB long press or RMB click.
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).
"""
if button == 1 or button == 0 and self._menu_on_left_click: # show immediately
# We cannot call self._invoke_context_menu directly inside of sc.Widget's context, otherwise it will be draw
# on the auxiliary window. Schedule a async task so the menu is still in main window
self._show_menu_task = asyncio.ensure_future(
self._schedule_show_menu(button_id, wait_seconds=0.0, min_menu_entries=min_menu_entries)
)
elif button == 0: # Schedule a task if hold LMB long enough
self._show_menu_task = asyncio.ensure_future(
self._schedule_show_menu(button_id, min_menu_entries=min_menu_entries)
)
def _on_mouse_released(self, button):
if button == 0:
if self._show_menu_task:
self._show_menu_task.cancel()
async def _schedule_show_menu(self, button_id: str, min_menu_entries: int = 1, wait_seconds: float = 0.3):
if wait_seconds > 0.0:
await asyncio.sleep(wait_seconds)
try:
self._invoke_context_menu(button_id, False, min_menu_entries)
except Exception:
import traceback
carb.log_error(traceback.format_exc())
self._show_menu_task = None
def _build_flyout_indicator(self, width, height, index: str, extension_id: str, padding=-8, min_menu_count=1):
indicator_size = 4
with ui.Placer(offset_x=width - indicator_size - padding, offset_y=height - indicator_size - padding):
indicator = ui.Image(
f"{ICON_FOLDER_PATH}/flyout_indicator_dark.svg",
width=indicator_size,
height=indicator_size,
)
def on_menu_changed(evt: carb.events.IEvent):
try:
menu_list = omni.kit.context_menu.get_menu_dict(index, extension_id)
# TODO check the actual menu entry visibility with show_fn
indicator.visible = len(menu_list) >= min_menu_count
except AttributeError as exc:
carb.log_warn(f"on_menu_changed error {exc}")
# Check initial state
on_menu_changed(None)
event_stream = omni.kit.context_menu.get_menu_event_stream()
return event_stream.create_subscription_to_pop(on_menu_changed)
| 10,826 | Python | 38.370909 | 124 | 0.620081 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/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.
#
from __future__ import annotations
import weakref
from collections import defaultdict
from typing import TYPE_CHECKING
from weakref import ProxyType
if TYPE_CHECKING:
from .model import AbstractTransformManipulatorModel
from .toolbar_registry import ToolbarRegistry
from .toolbar_tool import ToolbarTool
from pathlib import Path
from typing import Any, DefaultDict, Dict, List, Type
import carb.dictionary
import carb.settings
import omni.kit.app
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import scene as sc
from .gestures import (
DummyClickGesture,
DummyGesture,
HighlightControl,
HighlightGesture,
RotationGesture,
ScaleGesture,
TranslateGesture,
)
from .settings_constants import c
from .simple_transform_model import SimpleTransformModel
from .style import abgr_to_color, get_default_style, get_default_toolbar_style, update_style
from .types import Axis, Operation
ARROW_WIDTH = 4
ARROW_HEIGHT = 14
ARROW_P = [
[ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, -ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, ARROW_WIDTH, 0],
[ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[ARROW_WIDTH, -ARROW_WIDTH, 0],
]
ARROW_VC = [3, 3, 3, 3, 4]
ARROW_VI = [i for i in range(sum(ARROW_VC))]
LINE_THICKNESS = 2
ICON_FOLDER_PATH = Path(
f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons"
)
TOOLBAR_WIDGET_HEIGHT = 114
class TransformManipulator(sc.Manipulator):
def __init__(
self,
size: float = 1.0,
enabled: bool = True,
axes: Axis = Axis.ALL,
model: AbstractTransformManipulatorModel = None,
style: Dict = {},
gestures: List[sc.ManipulatorGesture] = [],
tool_registry: ToolbarRegistry = None,
tool_button_additional_payload: Dict[str, Any] = {},
tools_default_collapsed: bool | None = None,
):
"""
Create a Transform Manipulator.
Args:
size: size of the TransformManipulator.
enabled: If false, Manipulator will be created but disabled (invisible).
axes: which axes to enable for the Manipulator. You can use this to create 2D or 1D manipulator.
model: The model for the Manipulator. If None provided, a default SimpleTransformModel will be created.
style: Use this to override the default style of the Manipulator.
tool_registry: Registry to hold the classes of ToolbarTool.
tool_button_additional_payload: Additional payload to be passed into toolbar's context menu.
tools_default_collapsed: Whether the toolbar should be collapsed by default. It overrides the carb setting so each manipulator may tweak this behavior differently.
"""
if model is None:
model = SimpleTransformModel()
super().__init__(model=model, gestures=gestures)
self._size: float = size
self._enabled: bool = enabled
self._transform = None
self._transform_screen = None
self._translate_gizmo = None
self._rotation_gizmo = None
self._scale_gizmo = None
self._toolbar_root = None
self._toolbar_height_offset_transform = None
self._toolbar_collapsable_frame = None
self._toolbars: Dict[Operation, ui.Frame] = {}
self._toolbar_widget: sc.Widget = None
self._header_line = None
self._tools_stacks: Dict[Operation, ui.HStack] = {}
self._tools: List[ToolbarTool] = []
self._operation = None
self._style = get_default_style()
self._style = update_style(self._style, style)
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._scale_sub = self._settings.subscribe_to_node_change_events(
c.MANIPULATOR_SCALE_SETTING, self._on_scale_changed
)
self._scale = self._settings.get(c.MANIPULATOR_SCALE_SETTING)
self._thickness_sub = self._settings.subscribe_to_node_change_events(
c.INTERSECTION_THICKNESS_SETTING, self._on_intersection_thickness_changed
)
self._free_rotation_enabled_sub = self._settings.subscribe_to_node_change_events(
c.FREE_ROTATION_ENABLED_SETTING, self._on_free_rotation_enabled_changed
)
self._axes = axes
self._tool_button_additional_payload = tool_button_additional_payload
self._toolbar_collapsed = (
tools_default_collapsed
if tools_default_collapsed is not None
else self._settings.get(c.TOOLS_DEFAULT_COLLAPSED_SETTING)
)
self._tool_registry = tool_registry
self._tool_registry_sub = None
if self._tool_registry:
self._tool_registry_sub = self._tool_registry.subscribe_to_registry_change(self._on_toolbar_changed)
if self.model:
if self._enabled:
self.model.widget_enabled()
def __del__(self):
self.destroy()
def destroy(self):
if self._scale_sub:
self._settings.unsubscribe_to_change_events(self._scale_sub)
self._scale_sub = None
if self._thickness_sub:
self._settings.unsubscribe_to_change_events(self._thickness_sub)
self._thickness_sub = None
if self._free_rotation_enabled_sub:
self._settings.unsubscribe_to_change_events(self._free_rotation_enabled_sub)
self._free_rotation_enabled_sub = None
if self._tool_registry and self._tool_registry_sub:
self._tool_registry_sub.release()
self._tool_registry_sub = None
for tool in self._tools:
tool.destroy()
self._tools.clear()
self._toolbar_widget = None
for key, stack in self._tools_stacks.items():
stack.set_computed_content_size_changed_fn(None)
self._tools_stacks.clear()
self.enabled = False
def on_build(self):
"""
if build_items_on_init = False is passed into __init__ function, you can manually call build_scene_items.
It has to be within a SceneView.scene scope.
"""
self._transform = sc.Transform(visible=self.enabled)
with self._transform:
final_size = self._get_final_size()
self._transform_screen = sc.Transform(
transform=sc.Matrix44.get_scale_matrix(final_size, final_size, final_size), scale_to=sc.Space.SCREEN
)
with self._transform_screen:
self._create_translate_manipulator()
self._create_rotation_manipulator()
self._create_scale_manipulator()
with sc.Transform(scale_to=sc.Space.SCREEN):
self._create_toolbar()
self._translate_gizmo.visible = True
self._update_axes_visibility()
self._update_from_model()
@property
def enabled(self) -> bool:
return self._enabled
@enabled.setter
def enabled(self, value: bool):
if value != self._enabled:
if self._transform:
self._transform.visible = value
self._enabled = value
if self.model:
if self._enabled:
self.model.widget_enabled()
else:
self.model.widget_disabled()
@property
def size(self) -> float:
return self._size
@size.setter
def size(self, value: float):
if self._size != value:
self._size = value
self._update_manipulator_final_size()
@property
def axes(self) -> float:
return self._axes
@axes.setter
def axes(self, value: float):
if self._axes != value:
self._axes = value
self._update_axes_visibility()
@property
def style(self) -> Dict:
return self._style
@style.setter
def style(self, value: Dict):
default_style = get_default_style()
style = update_style(default_style, value)
if self._style != style:
if self._transform:
self._translate_line_x.color = abgr_to_color(style["Translate.Axis::x"]["color"])
self._translate_line_y.color = abgr_to_color(style["Translate.Axis::y"]["color"])
self._translate_line_z.color = abgr_to_color(style["Translate.Axis::z"]["color"])
vert_count = len(ARROW_VI)
self._translate_arrow_x.colors = [abgr_to_color(style["Translate.Axis::x"]["color"])] * vert_count
self._translate_arrow_y.colors = [abgr_to_color(style["Translate.Axis::y"]["color"])] * vert_count
self._translate_arrow_z.colors = [abgr_to_color(style["Translate.Axis::z"]["color"])] * vert_count
self._translate_plane_yz.color = abgr_to_color(style["Translate.Axis::x"]["color"])
self._translate_plane_zx.color = abgr_to_color(style["Translate.Axis::y"]["color"])
self._translate_plane_xy.color = abgr_to_color(style["Translate.Axis::z"]["color"])
self._translate_point.color = abgr_to_color(style["Translate.Point"]["color"])
self._translate_point_square.color = abgr_to_color(style["Translate.Point"]["color"])
use_point = style["Translate.Point"]["type"] == "point"
self._translate_point.visible = use_point
self._translate_point_square.visible = not use_point
self._translate_point_focal_transform.visible = style["Translate.Focal"]["visible"]
self._rotation_arc_x.color = abgr_to_color(style["Rotate.Arc::x"]["color"])
self._rotation_arc_y.color = abgr_to_color(style["Rotate.Arc::y"]["color"])
self._rotation_arc_z.color = abgr_to_color(style["Rotate.Arc::z"]["color"])
self._rotation_arc_screen.color = abgr_to_color(style["Rotate.Arc::screen"]["color"])
self._scale_line_x.color = abgr_to_color(style["Scale.Axis::x"]["color"])
self._scale_line_y.color = abgr_to_color(style["Scale.Axis::y"]["color"])
self._scale_line_z.color = abgr_to_color(style["Scale.Axis::z"]["color"])
self._scale_point_x.color = abgr_to_color(style["Scale.Axis::x"]["color"])
self._scale_point_y.color = abgr_to_color(style["Scale.Axis::y"]["color"])
self._scale_point_z.color = abgr_to_color(style["Scale.Axis::z"]["color"])
self._scale_plane_yz.color = abgr_to_color(style["Scale.Axis::x"]["color"])
self._scale_plane_zx.color = abgr_to_color(style["Scale.Axis::y"]["color"])
self._scale_plane_xy.color = abgr_to_color(style["Scale.Axis::z"]["color"])
self._scale_point.color = abgr_to_color(style["Scale.Point"]["color"])
self._style = style
@sc.Manipulator.model.setter
def model(self, model):
if self.model is not None and self.enabled:
self.model.widget_disabled()
sc.Manipulator.model.fset(self, model)
if self.model is not None and self.enabled:
self.model.widget_enabled()
@property
def tool_registry(self) -> ToolbarRegistry:
return self._tool_registry
@tool_registry.setter
def tool_registry(self, value: ToolbarRegistry):
if self._tool_registry != value:
if self._tool_registry_sub:
self._tool_registry_sub.release()
self._tool_registry_sub = None
self._tool_registry = value
if self._tool_registry:
self._tool_registry_sub = self._tool_registry.subscribe_to_registry_change(self._on_toolbar_changed)
@property
def toolbar_visible(self) -> bool:
if self._toolbar_root:
return self._toolbar_root.visible
return False
@toolbar_visible.setter
def toolbar_visible(self, value: bool):
if self._toolbar_root:
self._toolbar_root.visible = value
def refresh_toolbar(self):
if self._toolbar_widget:
self._toolbar_widget.invalidate()
#############################################
# Beginning of internal functions. Do not use.
#############################################
def _create_translate_manipulator(self):
self._translate_gizmo = sc.Transform()
self._translate_gizmo.visible = False
AXIS_LEN = 100
RECT_SIZE = 50
POINT_RADIUS = 7
FOCAL_SIZE = 16
intersection_thickness = self._settings.get(c.INTERSECTION_THICKNESS_SETTING)
with self._translate_gizmo:
# Arrows
def make_arrow(
rot,
translate,
color,
):
vert_count = len(ARROW_VI)
with sc.Transform(
transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])
* sc.Matrix44.get_rotation_matrix(rot[0], rot[1], rot[2], True)
):
return sc.PolygonMesh(ARROW_P, [color] * vert_count, ARROW_VC, ARROW_VI)
self._translate_arrow_x = make_arrow(
(0, 90, 0), (AXIS_LEN - ARROW_HEIGHT / 2, 0, 0), abgr_to_color(self.style["Translate.Axis::x"]["color"])
)
self._translate_arrow_y = make_arrow(
(-90, 0, 0),
(0, AXIS_LEN - ARROW_HEIGHT / 2, 0),
abgr_to_color(self.style["Translate.Axis::y"]["color"]),
)
self._translate_arrow_z = make_arrow(
(0, 0, 0), (0, 0, AXIS_LEN - ARROW_HEIGHT / 2), abgr_to_color(self.style["Translate.Axis::z"]["color"])
)
# Lines
def make_line(axis, color, arrow):
line = sc.Line(
[v * POINT_RADIUS for v in axis],
[v * AXIS_LEN for v in axis],
color=color,
thickness=LINE_THICKNESS,
intersection_thickness=intersection_thickness,
)
highlight_ctrl = HighlightControl([line, arrow])
line.gestures = [
TranslateGesture(self, axis, highlight_ctrl),
HighlightGesture(highlight_ctrl),
]
return line
self._translate_line_x = make_line(
[1, 0, 0], abgr_to_color(self.style["Translate.Axis::x"]["color"]), self._translate_arrow_x
)
self._translate_line_y = make_line(
[0, 1, 0], abgr_to_color(self.style["Translate.Axis::y"]["color"]), self._translate_arrow_y
)
self._translate_line_z = make_line(
[0, 0, 1], abgr_to_color(self.style["Translate.Axis::z"]["color"]), self._translate_arrow_z
)
# Rectangles
def make_plane(axis, color, axis_vec):
translate = [v * (AXIS_LEN - RECT_SIZE * 0.5) for v in axis_vec]
with sc.Transform(
transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])
):
highlight_ctrl = HighlightControl()
return sc.Rectangle(
axis=axis,
width=RECT_SIZE / 2,
height=RECT_SIZE / 2,
color=color,
gestures=[TranslateGesture(self, axis_vec, highlight_ctrl), HighlightGesture(highlight_ctrl)],
)
self._translate_plane_yz = make_plane(0, abgr_to_color(self.style["Translate.Axis::x"]["color"]), (0, 1, 1))
self._translate_plane_zx = make_plane(1, abgr_to_color(self.style["Translate.Axis::y"]["color"]), (1, 0, 1))
self._translate_plane_xy = make_plane(2, abgr_to_color(self.style["Translate.Axis::z"]["color"]), (1, 1, 0))
# Points
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
use_point = self.style["Translate.Point"]["type"] == "point"
self._translate_point = sc.Arc(
POINT_RADIUS,
tesselation=16,
color=abgr_to_color(self.style["Translate.Point"]["color"]),
visible=use_point,
)
highlight_ctrl = HighlightControl(
[
self._translate_plane_yz,
self._translate_plane_zx,
self._translate_plane_xy,
self._translate_point,
]
)
self._translate_point.gestures = [
TranslateGesture(self, [1, 1, 1], highlight_ctrl, order=-1),
HighlightGesture(highlight_ctrl=highlight_ctrl, order=-1),
]
self._translate_point_square = sc.Rectangle(
width=FOCAL_SIZE,
height=FOCAL_SIZE,
color=abgr_to_color(self.style["Translate.Point"]["color"]),
visible=not use_point,
)
highlight_ctrl = HighlightControl(
[
self._translate_plane_yz,
self._translate_plane_zx,
self._translate_plane_xy,
self._translate_point_square,
]
)
self._translate_point_square.gestures = [
TranslateGesture(self, [1, 1, 1], highlight_ctrl, order=-1),
HighlightGesture(highlight_ctrl=highlight_ctrl, order=-1),
]
show_focal = self.style["Translate.Focal"]["visible"]
self._translate_point_focal_transform = sc.Transform(visible=show_focal)
with self._translate_point_focal_transform:
def create_corner_line(begin, end):
sc.Line(
begin,
end,
color=abgr_to_color(self.style["Translate.Focal"]["color"]),
thickness=2,
)
offset_outer = FOCAL_SIZE
offset_inner = FOCAL_SIZE * 0.4
v_buffer = [
[offset_outer, offset_inner, 0], # 0
[offset_outer, offset_outer, 0],
[offset_inner, offset_outer, 0],
[-offset_outer, offset_inner, 0], # 1
[-offset_outer, offset_outer, 0],
[-offset_inner, offset_outer, 0],
[offset_outer, -offset_inner, 0], # 2
[offset_outer, -offset_outer, 0],
[offset_inner, -offset_outer, 0],
[-offset_outer, -offset_inner, 0], # 3
[-offset_outer, -offset_outer, 0],
[-offset_inner, -offset_outer, 0],
]
i_buffer = [(0, 1), (1, 2), (3, 4), (4, 5), (6, 7), (7, 8), (9, 10), (10, 11)]
for i in i_buffer:
create_corner_line(v_buffer[i[0]], v_buffer[i[1]])
def _create_rotation_manipulator(self):
self._rotation_gizmo = sc.Transform()
self._rotation_gizmo.visible = False
ARC_RADIUS = 100
intersection_thickness = self._settings.get(c.INTERSECTION_THICKNESS_SETTING)
with self._rotation_gizmo:
def make_arc(
radius, axis_vec, color, culling: sc.Culling, wireframe: bool = True, highlight_color=None, **kwargs
):
viz_color = [1.0, 1.0, 0.0, 0.3]
viz_arc = sc.Arc(radius, tesselation=36 * 3, color=viz_color, visible=False, **kwargs)
highlight_ctrl = HighlightControl(color=highlight_color)
return sc.Arc(
radius,
wireframe=wireframe,
tesselation=36 * 3,
thickness=LINE_THICKNESS,
intersection_thickness=intersection_thickness,
culling=culling,
color=color,
gestures=[
RotationGesture(self, axis_vec, viz_arc, highlight_ctrl),
HighlightGesture(highlight_ctrl),
],
**kwargs,
)
self._rotation_arc_x = make_arc(
ARC_RADIUS, [1, 0, 0], abgr_to_color(self.style["Rotate.Arc::x"]["color"]), sc.Culling.BACK, axis=0
)
self._rotation_arc_y = make_arc(
ARC_RADIUS, [0, 1, 0], abgr_to_color(self.style["Rotate.Arc::y"]["color"]), sc.Culling.BACK, axis=1
)
self._rotation_arc_z = make_arc(
ARC_RADIUS, [0, 0, 1], abgr_to_color(self.style["Rotate.Arc::z"]["color"]), sc.Culling.BACK, axis=2
)
self._screen_space_rotation_transform = sc.Transform(look_at=sc.Transform.LookAt.CAMERA)
with self._screen_space_rotation_transform:
self._rotation_arc_screen = make_arc(
ARC_RADIUS + 20,
[0, 0, 0],
abgr_to_color(self.style["Rotate.Arc::screen"]["color"]),
sc.Culling.NONE,
)
self._rotation_arc_free = make_arc(
ARC_RADIUS - 5,
None,
abgr_to_color(self.style["Rotate.Arc::free"]["color"]),
sc.Culling.NONE,
False,
highlight_color=cl("#8F8F8F8F"),
)
self._rotation_arc_free.visible = self._settings.get(c.FREE_ROTATION_ENABLED_SETTING)
def _create_scale_manipulator(self):
AXIS_LEN = 100
RECT_SIZE = 50
POINT_RADIUS = 7
intersection_thickness = self._settings.get(c.INTERSECTION_THICKNESS_SETTING)
self._scale_gizmo = sc.Transform()
self._scale_gizmo.visible = False
with self._scale_gizmo:
# Point
def make_point(translate, color):
scale_point_tr = sc.Transform(
transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])
)
with scale_point_tr:
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
scale_point = sc.Arc(POINT_RADIUS, tesselation=16, color=color)
return (scale_point_tr, scale_point)
(scale_point_tr_x, self._scale_point_x) = make_point(
(AXIS_LEN, 0, 0), abgr_to_color(self.style["Scale.Axis::x"]["color"])
)
(scale_point_tr_y, self._scale_point_y) = make_point(
(0, AXIS_LEN, 0), abgr_to_color(self.style["Scale.Axis::y"]["color"])
)
(scale_point_tr_z, self._scale_point_z) = make_point(
(0, 0, AXIS_LEN), abgr_to_color(self.style["Scale.Axis::z"]["color"])
)
# Line
def make_line(axis_vec, color, point_tr, point):
line_begin = [v * POINT_RADIUS for v in axis_vec]
line_end = [v * AXIS_LEN for v in axis_vec]
viz_line = sc.Line(line_begin, line_end, color=[0.5, 0.5, 0.5, 0.5], thickness=2)
scale_line = sc.Line(
line_begin,
line_end,
color=color,
thickness=LINE_THICKNESS,
intersection_thickness=intersection_thickness,
)
highlight_ctrl = HighlightControl([scale_line, point])
scale_line.gestures = [
ScaleGesture(self, axis_vec, highlight_ctrl, [viz_line], [point_tr]),
HighlightGesture(highlight_ctrl),
]
return (viz_line, scale_line)
(line_x, self._scale_line_x) = make_line(
[1, 0, 0], abgr_to_color(self.style["Scale.Axis::x"]["color"]), scale_point_tr_x, self._scale_point_x
)
(line_y, self._scale_line_y) = make_line(
[0, 1, 0], abgr_to_color(self.style["Scale.Axis::y"]["color"]), scale_point_tr_y, self._scale_point_y
)
(line_z, self._scale_line_z) = make_line(
[0, 0, 1], abgr_to_color(self.style["Scale.Axis::z"]["color"]), scale_point_tr_z, self._scale_point_z
)
# Rectangles
def make_plane(axis, axis_vec, color, lines, points):
axis_vec_t = [v * (AXIS_LEN - RECT_SIZE * 0.5) for v in axis_vec]
with sc.Transform(
transform=sc.Matrix44.get_translation_matrix(axis_vec_t[0], axis_vec_t[1], axis_vec_t[2])
):
highlight_ctrl = HighlightControl()
return sc.Rectangle(
axis=axis,
width=RECT_SIZE * 0.5,
height=RECT_SIZE * 0.5,
color=color,
gestures=[
ScaleGesture(self, axis_vec, highlight_ctrl, lines, points),
HighlightGesture(highlight_ctrl),
],
)
self._scale_plane_yz = make_plane(
0,
(0, 1, 1),
abgr_to_color(self.style["Scale.Axis::x"]["color"]),
[line_y, line_z],
[scale_point_tr_y, scale_point_tr_z],
)
self._scale_plane_zx = make_plane(
1,
(1, 0, 1),
abgr_to_color(self.style["Scale.Axis::y"]["color"]),
[line_x, line_z],
[scale_point_tr_x, scale_point_tr_z],
)
self._scale_plane_xy = make_plane(
2,
(1, 1, 0),
abgr_to_color(self.style["Scale.Axis::z"]["color"]),
[line_x, line_y],
[scale_point_tr_x, scale_point_tr_y],
)
# Points
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
highlight_ctrl = HighlightControl()
self._scale_point = sc.Arc(
POINT_RADIUS, tesselation=16, color=abgr_to_color(self.style["Scale.Point"]["color"])
)
highlight_ctrl = HighlightControl(
[
self._scale_plane_yz,
self._scale_plane_zx,
self._scale_plane_xy,
self._scale_point,
]
)
self._scale_point.gestures = [
ScaleGesture(
self,
[1, 1, 1],
highlight_ctrl,
[line_x, line_y, line_z],
[scale_point_tr_x, scale_point_tr_y, scale_point_tr_z],
order=-1,
),
HighlightGesture(highlight_ctrl, order=-1),
]
def _create_toolbar(self):
self._toolbar_root = sc.Transform(look_at=sc.Transform.LookAt.CAMERA)
self._build_tools_widgets(self._toolbar_root)
def _get_toolbar_height_offset(self):
final_size = self._get_final_size()
return -120 * final_size - TOOLBAR_WIDGET_HEIGHT
def _build_tools_widgets(self, root: sc.Transform):
# clear existing widgets under root
root.clear()
self._toolbar_widget = None
if self._tool_registry is None:
return None
OPERATIONS = [Operation.TRANSLATE, Operation.ROTATE, Operation.SCALE]
tools = self._tool_registry.tools
tools_can_build: DefaultDict[Operation, List[Type[ToolbarTool]]] = defaultdict(list)
for op in OPERATIONS:
for tool in tools:
if tool.can_build(self, op):
tools_can_build[op].append(tool)
# Don't build toolbar if there's no tool
if len(tools_can_build) == 0:
return
with root:
# values for omni.ui inside of sc.Widget
CARAT_SIZE = 44
CRATE_SPACING = 10
TOOLBAR_HEIGHT = 44
TOOLBAR_SPACING = 5
height_offset = self._get_toolbar_height_offset()
toolbar_to_content_scale = 1.4 # a guesstimate
toolbar_widget_width = (
max(max([len(t) for t in tools_can_build.values()]), 3)
* ((TOOLBAR_HEIGHT + TOOLBAR_SPACING) * toolbar_to_content_scale)
+ TOOLBAR_SPACING
)
self._toolbar_height_offset_transform = sc.Transform(
sc.Matrix44.get_translation_matrix(0, height_offset + TOOLBAR_WIDGET_HEIGHT / 2, 0)
)
with self._toolbar_height_offset_transform:
# create a sc.Rectangle behind the widget to stop the click into Viewport with DummyGesture
dummy_transform = sc.Transform(sc.Matrix44.get_translation_matrix(0, 0, -1))
with dummy_transform:
dummy_rect = sc.Rectangle(
width=toolbar_widget_width,
height=TOOLBAR_WIDGET_HEIGHT,
color=0x0,
gestures=[
DummyGesture(self), # needed for VP1 only
DummyClickGesture(mouse_button=0),
DummyClickGesture(mouse_button=1),
DummyClickGesture(mouse_button=2),
], # hijack left/right/middle mouse click on the toolbar so it doesn't click into viewport
)
# Build a set of scene items to emulate the tooltip for omni.ui item inside of sc.Widget.
# This is to workaround chopped off tooltip in sc.Widget OM-49626
tooltip_style = ui.style.default["Tooltip"]
tooltip_color = tooltip_style["color"]
tooltip_bg_color = tooltip_style["background_color"]
tooltip_border_width = tooltip_style["border_width"]
with sc.Transform(
transform=sc.Matrix44.get_translation_matrix(-toolbar_widget_width / 2, TOOLBAR_HEIGHT, 10)
):
tooltip_transform = sc.Transform(visible=False)
with tooltip_transform:
tooltip_label = sc.Label("Tooltip", alignment=ui.Alignment.CENTER, color=tooltip_color, size=16)
tooltip_bg_outline = sc.Rectangle(
color=tooltip_color,
height=0,
width=0,
wireframe=True,
)
tooltip_bg = sc.Rectangle(
color=tooltip_bg_color,
height=0,
width=0,
thickness=tooltip_border_width,
)
def update_tooltip(label: str, visible: bool, x_offset: float):
tooltip_transform.visible = visible
if visible:
tooltip_transform.transform = sc.Matrix44.get_translation_matrix(
x_offset * toolbar_to_content_scale, 0, 0
)
padding = 10
tooltip_label.text = label
# / 1.2 due to no way to get a calculated width of string and not each character has same width
tooltip_bg.width = (tooltip_label.size * len(tooltip_label.text) + padding * 2) / 1.2
tooltip_bg.height = tooltip_label.size + padding * 2
tooltip_bg_outline.width = tooltip_bg.width + tooltip_border_width * 2
tooltip_bg_outline.height = tooltip_bg.height + tooltip_border_width * 2
self._toolbar_widget = sc.Widget(
toolbar_widget_width, TOOLBAR_WIDGET_HEIGHT, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED
)
with self._toolbar_widget.frame:
def build_frame_header(manip: ProxyType[TransformManipulator], collapsed: bool, text: str):
header_stack = ui.HStack(spacing=8)
with header_stack:
with ui.VStack(width=0):
ui.Spacer()
styles = [
{
"": {"image_url": f"{ICON_FOLDER_PATH}/carat_close.svg"},
":hovered": {"image_url": f"{ICON_FOLDER_PATH}/carat_close_hover.svg"},
":pressed": {"image_url": f"{ICON_FOLDER_PATH}/carat_close_hover.svg"},
},
{
"": {"image_url": f"{ICON_FOLDER_PATH}/carat_open.svg"},
":hovered": {"image_url": f"{ICON_FOLDER_PATH}/carat_open_hover.svg"},
":pressed": {"image_url": f"{ICON_FOLDER_PATH}/carat_open_hover.svg"},
},
]
ui.Image(
width=CARAT_SIZE, height=CARAT_SIZE, style=styles[0] if collapsed else styles[1]
)
ui.Spacer()
if not collapsed:
operation = self.model.get_operation()
tools_stack = self._tools_stacks.get(operation, None)
self._header_line = ui.Line(
width=ui.Pixel(tools_stack.computed_width - CARAT_SIZE - CRATE_SPACING)
if tools_stack
else ui.Percent(100)
)
dummy_rect.height = TOOLBAR_WIDGET_HEIGHT
dummy_transform.transform = sc.Matrix44.get_translation_matrix(0, 0, -1)
else:
self._header_line = None
ui.Spacer(width=ui.Percent(100))
dummy_rect.height = TOOLBAR_WIDGET_HEIGHT * 0.4
dummy_transform.transform = sc.Matrix44.get_translation_matrix(
0, TOOLBAR_WIDGET_HEIGHT / 4, -1
)
with ui.HStack(style=get_default_toolbar_style(), content_clipping=True):
self._toolbar_collapsable_frame = ui.CollapsableFrame(
build_header_fn=lambda collapsed, text, manip=weakref.proxy(self): build_frame_header(
manip, collapsed, text
),
collapsed=self._toolbar_collapsed,
)
with self._toolbar_collapsable_frame:
with ui.ZStack():
def build_toolbar_frame(operation: Operation, visible: bool) -> ui.Frame:
toolbar_frame = ui.Frame(visible=visible)
with toolbar_frame:
with ui.ZStack():
with ui.VStack():
ui.Spacer(height=2)
with ui.ZStack():
bg = ui.Rectangle()
self._tools_stacks[operation] = ui.HStack(
width=0, spacing=TOOLBAR_SPACING
)
with self._tools_stacks[operation]:
ui.Spacer()
for tool in tools_can_build[operation]:
t = tool(
manipulator=weakref.proxy(self),
operation=operation,
toolbar_height=TOOLBAR_HEIGHT,
toolbar_payload=self._tool_button_additional_payload,
tooltip_update_fn=update_tooltip,
)
self._tools.append(t)
ui.Spacer()
def update_bg_width():
bg.width = ui.Pixel(
self._tools_stacks[operation].computed_width
)
if self._header_line:
self._header_line.width = ui.Pixel(
self._tools_stacks[operation].computed_width
- CARAT_SIZE
- CRATE_SPACING
)
self._tools_stacks[operation].set_computed_content_size_changed_fn(
update_bg_width
)
ui.Spacer(height=2)
return toolbar_frame
for op in OPERATIONS:
self._toolbars[op] = build_toolbar_frame(op, self._operation == op)
def _on_toolbar_changed(self):
if not self._toolbar_root:
return
for tool in self._tools:
tool.destroy()
self._tools.clear()
self._toolbars.clear()
self._build_tools_widgets(self._toolbar_root)
def on_model_updated(self, item):
self._update_from_model()
def _update_from_model(self):
if not self._transform:
return
if not self.model:
return
self._transform.transform = self.model.get_as_floats(self.model.get_item("transform"))
operation = self.model.get_operation()
if operation != self._operation:
self._operation = operation
self._translate_gizmo.visible = False
self._rotation_gizmo.visible = False
self._scale_gizmo.visible = False
for op, toolbar_frame in self._toolbars.items():
toolbar_frame.visible = False
if operation == Operation.TRANSLATE:
self._translate_gizmo.visible = True
elif operation == Operation.ROTATE:
self._rotation_gizmo.visible = True
elif operation == Operation.SCALE:
self._scale_gizmo.visible = True
if operation == Operation.NONE:
self._toolbar_root.visible = False
else:
self._toolbar_root.visible = True
if operation in self._toolbars:
self._toolbars[operation].visible = True
# update line width
if self._toolbar_collapsable_frame:
self._toolbar_collapsable_frame.rebuild()
# toolbar render must be manually updated
self.refresh_toolbar()
def _on_scale_changed(self, item, event_type):
scale = self._dict.get(item)
if scale != self._scale:
self._scale = scale
self._update_manipulator_final_size()
def _get_final_size(self):
return self._size * self._scale
def _update_manipulator_final_size(self):
final_size = self._get_final_size()
if self._transform_screen:
self._transform_screen.transform = sc.Matrix44.get_scale_matrix(final_size, final_size, final_size)
if self._toolbar_height_offset_transform:
self._toolbar_height_offset_transform.transform = sc.Matrix44.get_translation_matrix(
0, self._get_toolbar_height_offset(), 0
)
def _on_intersection_thickness_changed(self, item, event_type):
if self._transform:
thickness = self._dict.get(item)
self._translate_line_x.intersection_thickness = thickness
self._translate_line_y.intersection_thickness = thickness
self._translate_line_z.intersection_thickness = thickness
self._rotation_arc_x.intersection_thickness = thickness
self._rotation_arc_y.intersection_thickness = thickness
self._rotation_arc_z.intersection_thickness = thickness
self._rotation_arc_screen.intersection_thickness = thickness
self._scale_line_x.intersection_thickness = thickness
self._scale_line_y.intersection_thickness = thickness
self._scale_line_z.intersection_thickness = thickness
def _on_free_rotation_enabled_changed(self, item, event_type):
if self._transform:
enabled = self._dict.get(item)
self._rotation_arc_free.visible = enabled
def _update_axes_visibility(self):
if self._transform:
enable_x = bool(self.axes & Axis.X)
enable_y = bool(self.axes & Axis.Y)
enable_z = bool(self.axes & Axis.Z)
enable_screen = bool(self.axes & Axis.SCREEN)
self._translate_line_x.visible = (
self._translate_arrow_x.visible
) = self._rotation_arc_x.visible = self._scale_point_x.visible = self._scale_line_x.visible = enable_x
self._translate_line_y.visible = (
self._translate_arrow_y.visible
) = self._rotation_arc_y.visible = self._scale_point_y.visible = self._scale_line_y.visible = enable_y
self._translate_line_z.visible = (
self._translate_arrow_z.visible
) = self._rotation_arc_z.visible = self._scale_point_z.visible = self._scale_line_z.visible = enable_z
self._translate_plane_yz.visible = self._scale_plane_yz.visible = enable_y & enable_z
self._translate_plane_zx.visible = self._scale_plane_zx.visible = enable_z & enable_x
self._translate_plane_xy.visible = self._scale_plane_xy.visible = enable_x & enable_y
self._translate_point.visible = (
self._rotation_arc_screen.visible
) = self._scale_point.visible = enable_screen
self._rotation_arc_free.visible = self._settings.get(c.FREE_ROTATION_ENABLED_SETTING) and enable_screen
| 44,834 | Python | 42.826979 | 175 | 0.505286 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/types.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 enum import Enum, Flag, auto
class Axis(Flag):
X = auto()
Y = auto()
Z = auto()
SCREEN = auto()
ALL = X | Y | Z | SCREEN
class Operation(Enum):
TRANSLATE = auto()
ROTATE = auto()
SCALE = auto()
NONE = auto()
TRANSLATE_DELTA = auto()
ROTATE_DELTA = auto()
SCALE_DELTA = auto()
| 762 | Python | 25.310344 | 76 | 0.691601 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/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 __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
from typing import TYPE_CHECKING, List, Sequence, Tuple
if TYPE_CHECKING:
from .manipulator import TransformManipulator
import copy
import math
from functools import lru_cache
import carb.input
import carb.settings
import numpy as np
from omni.ui import color as cl
from omni.ui import scene as sc
from .settings_constants import c as CONSTANTS
@lru_cache()
def __get_input() -> carb.input.IInput:
return carb.input.acquire_input_interface()
def _is_alt_down() -> bool:
input = __get_input()
return (
input.get_keyboard_value(None, carb.input.KeyboardInput.LEFT_ALT)
+ input.get_keyboard_value(None, carb.input.KeyboardInput.RIGHT_ALT)
> 0
)
class PreventOthers(sc.GestureManager):
"""
Manager makes TransformGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle or at the end of drag
return (
gesture.state != sc.GestureState.CHANGED
and gesture.state != sc.GestureState.ENDED
and gesture.state != sc.GestureState.CANCELED
)
def should_prevent(self, gesture, preventer):
if (
(isinstance(preventer, TransformGesture) or isinstance(preventer, DummyClickGesture))
and (preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED)
and not _is_alt_down() # don't prevent other gesture if alt (camera manip) is down
):
if isinstance(gesture, TransformGesture):
if gesture.order > preventer.order:
return True
elif gesture.order == preventer.order:
# Transform vs Transform depth test
return gesture.gesture_payload.ray_distance > preventer.gesture_payload.ray_distance
else:
# Transform is the priority when it's against any other gesture
return True
return super().should_prevent(gesture, preventer)
class HoverDepthTest(sc.GestureManager):
"""
Manager that is doing depth test for hover gestures
"""
def can_be_prevented(self, gesture):
return isinstance(gesture, HighlightGesture)
def should_prevent(self, gesture, preventer):
if (
isinstance(gesture, HighlightGesture) and not _is_alt_down()
): # don't prevent other gesture if alt (camera manip) is down
if isinstance(preventer, HighlightGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
if gesture.order > preventer.order:
return True
elif gesture.order == preventer.order:
# Hover vs Hover depth test
return gesture.gesture_payload.ray_distance > preventer.gesture_payload.ray_distance
return False
class TransformDragGesturePayload(sc.AbstractGesture.GesturePayload):
def __init__(self, base: sc.AbstractGesture.GesturePayload, changing_item: sc.AbstractManipulatorItem):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.changing_item = changing_item
@dataclass(init=False)
class TranslateDragGesturePayload(TransformDragGesturePayload):
"""
Payload this class has:
- axis (float3): The axis along which the translation happened.
- moved_delta (float3): Moved delta since last change for each axis.
- moved (float3): Total moved distance since beginning of the drag.
"""
axis: Sequence[float]
moved_delta: Sequence[float]
moved: Sequence[float]
@dataclass(init=False)
class RotateDragGesturePayload(TransformDragGesturePayload):
"""
Payload this class has:
- axis (float3): The axis around which the rotation happened.
- angle_delta (float): Rotated delta since last change.
- angle (float): Total angle rotated distance since beginning of the drag.
- screen_space (bool): If the rotation happened in screen space.
- free_rotation (bool): If the rotation is a free rotation (dragging on the center sphere).
"""
axis: Sequence[float]
angle_delta: float
angle: float
screen_space: bool
free_rotation: bool
@dataclass(init=False)
class ScaleDragGesturePayload(TransformDragGesturePayload):
"""
Payload this class has:
- axis (float3): The axis along which the scaling happened.
- scale (float3): Scaled value on each axis.
"""
axis: Sequence[float]
scale: Sequence[float]
class TransformChangedGesture(sc.ManipulatorGesture):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
if not self.gesture_payload:
return
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
elif self.state == sc.GestureState.CANCELED:
self.on_canceled()
# Public API:
def on_began(self):
...
def on_changed(self):
...
def on_ended(self):
...
def on_canceled(self):
...
class TranslateChangedGesture(TransformChangedGesture):
...
class RotateChangedGesture(TransformChangedGesture):
...
class ScaleChangedGesture(TransformChangedGesture):
...
####################
# Internal gestures
####################
class HighlightControl:
# Use static member to track across ALL HighlightControl instances,
# because more than one HighlightControl can highlight the same widget (e.g. translate center and plane quads)
__status_tracker = defaultdict(int)
__original_colors = {}
def __init__(self, items=None, color=None):
self._items = items
# From rendering\source\plugins\carb.imguizmo\ImGuizmo.cpp
# static const ImU32 selectionColor = 0x8A1CE6E6;
self._selection_color = color if color else cl("#e6e61c8a")
def highlight(self, sender):
if self._items is None:
HighlightControl.__status_tracker[sender] += 1
if HighlightControl.__status_tracker[sender] == 1:
self._highlight(sender)
else:
for item in self._items:
HighlightControl.__status_tracker[item] += 1
if HighlightControl.__status_tracker[item] == 1:
self._highlight(item)
def dehighlight(self, sender):
if self._items is None:
HighlightControl.__status_tracker[sender] -= 1
if HighlightControl.__status_tracker[sender] <= 0:
self._dehighlight(sender)
HighlightControl.__status_tracker.pop(sender)
else:
for item in self._items:
HighlightControl.__status_tracker[item] -= 1
if HighlightControl.__status_tracker[item] <= 0:
self._dehighlight(item)
HighlightControl.__status_tracker.pop(item)
def _highlight(self, item):
if hasattr(item, "color"):
HighlightControl.__original_colors[item] = item.color
item.color = self._selection_color
if hasattr(item, "colors"):
HighlightControl.__original_colors[item] = item.colors.copy()
colors = item.colors.copy()
for i in range(len(colors)):
colors[i] = self._selection_color
item.colors = colors
def _dehighlight(self, item):
if hasattr(item, "color"):
item.color = HighlightControl.__original_colors[item]
if hasattr(item, "colors"):
item.colors = HighlightControl.__original_colors[item]
class HighlightGesture(sc.HoverGesture):
def __init__(self, highlight_ctrl: HighlightControl, order: int = 0):
super().__init__(manager=HoverDepthTest())
self._highlight_ctrl = highlight_ctrl
self._begun = False
self._order = order
@property
def order(self) -> int:
return self._order
def process(self):
if isinstance(self.sender, sc.Arc) and self.sender.gesture_payload.culled:
# Turn down the gesture if it on the wrong side of the arc
if self.state == sc.GestureState.BEGAN:
self.state = sc.GestureState.POSSIBLE
if self.state == sc.GestureState.CHANGED:
self.state = sc.GestureState.ENDED
if _is_alt_down():
# Turn down the gesture if manipulating camera
# If gesture already began, don't turn it down as ALT won't trigger camera manipulation at this point
if self.state == sc.GestureState.BEGAN:
self.state = sc.GestureState.POSSIBLE
if self.state == sc.GestureState.BEGAN:
self._on_began()
elif self.state == sc.GestureState.ENDED:
self._on_ended()
elif self.state == sc.GestureState.CANCELED:
self._on_canceled()
elif self.state == sc.GestureState.CHANGED:
self._on_changed()
elif self.state == sc.GestureState.PREVENTED:
self._on_prevented()
super().process()
def _on_began(self):
self._begun = True
self._highlight_ctrl.highlight(self.sender)
def _on_ended(self):
if self._begun:
self._begun = False
self._highlight_ctrl.dehighlight(self.sender)
def _on_changed(self):
...
def _on_canceled(self):
self._on_ended()
def _on_prevented(self):
self._on_ended()
class TransformGesture(sc.DragGesture):
def __init__(
self, manipulator: TransformManipulator, highlight_ctrl: HighlightControl, order: int = 0, *args, **kwargs
):
super().__init__(*args, **kwargs)
self._manipulator = manipulator
self._highlight_ctrl = highlight_ctrl
self._order = order
self._toolbar_was_visible = None
self._began = False
@property
def order(self) -> int:
return self._order
def process(self):
if _is_alt_down():
# Turn down the gesture if manipulating camera
# If gesture already began, don't turn it down as ALT won't trigger camera manipulation at this point
if self.state == sc.GestureState.BEGAN:
self.state = sc.GestureState.POSSIBLE
if self.state == sc.GestureState.BEGAN:
self._on_began()
elif self.state == sc.GestureState.ENDED:
self._on_ended()
elif self.state == sc.GestureState.CANCELED:
self._on_canceled()
elif self.state == sc.GestureState.CHANGED:
self._on_changed()
elif self.state == sc.GestureState.PREVENTED:
self._on_prevented()
super().process()
def _on_began(self):
self._began = True
self._toolbar_was_visible = self._manipulator.toolbar_visible
self._manipulator.toolbar_visible = False
def _on_ended(self):
if self._began and self._toolbar_was_visible is not None:
self._manipulator.toolbar_visible = self._toolbar_was_visible
self._toolbar_was_visible = None
self._began = False
def _on_changed(self):
...
def _on_canceled(self):
if self._began:
self._on_ended()
if self._toolbar_was_visible is not None:
self._manipulator.toolbar_visible = self._toolbar_was_visible
self._toolbar_was_visible = None
def _on_prevented(self):
if self._began:
self._on_ended()
class TranslateGesture(TransformGesture):
def __init__(self, manipulator: TransformManipulator, axis, highlight_ctrl: HighlightControl, order: int = 0):
super().__init__(manipulator=manipulator, highlight_ctrl=highlight_ctrl, order=order, manager=PreventOthers())
self._axis = axis
def _on_began(self):
super()._on_began()
self._moved = [0, 0, 0] # moved since begin edit, non-snapped
self._moved_snap = [0, 0, 0]
self._changing_item = self._manipulator.model.get_item("translate")
payload = TranslateDragGesturePayload(self.gesture_payload, self._changing_item)
payload.axis = self._axis
self._manipulator._process_gesture(TranslateChangedGesture, self.state, payload)
if self._highlight_ctrl:
self._highlight_ctrl.highlight(self.sender)
def _on_changed(self):
super()._on_changed()
moved_delta = self.sender.gesture_payload.moved
moved_delta = self._manipulator._transform.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, [moved_delta[0], moved_delta[1], moved_delta[2], 0]
)
moved_delta = moved_delta[0:3]
moved_prev = self._moved_snap[:]
self._moved = [sum(x) for x in zip(self._moved, moved_delta)]
self._moved_snap = self._moved.copy()
snap = self._manipulator.model.get_snap(self._changing_item)
if snap is not None:
for i, snap_axis in enumerate(snap):
if snap_axis:
self._moved_snap[i] = math.copysign(abs(self._moved[i]) // snap_axis * snap_axis, self._moved[i])
moved_delta = [m - mp for m, mp in zip(self._moved_snap, moved_prev)]
if moved_delta != [0, 0, 0]:
new_gesture_payload = TranslateDragGesturePayload(self.gesture_payload, self._changing_item)
new_gesture_payload.axis = self._axis
new_gesture_payload.moved_delta = moved_delta
new_gesture_payload.moved = self._moved_snap
self._manipulator._process_gesture(TranslateChangedGesture, self.state, new_gesture_payload)
def _on_ended(self):
super()._on_ended()
payload = TranslateDragGesturePayload(self.gesture_payload, self._changing_item)
payload.axis = self._axis
self._manipulator._process_gesture(TranslateChangedGesture, self.state, payload)
if self._highlight_ctrl:
self._highlight_ctrl.dehighlight(self.sender)
def _on_canceled(self):
self._on_ended()
class RotationGesture(TransformGesture):
def __init__(
self, manipulator: TransformManipulator, axis, viz_arc, highlight_ctrl: HighlightControl, order: int = 0
):
super().__init__(manipulator=manipulator, highlight_ctrl=highlight_ctrl, order=order, manager=PreventOthers())
self._viz_arc = viz_arc
self._axis = axis
self._angle = 0
self._last_free_intersect = None
self._settings = carb.settings.get_settings()
def process(self):
if isinstance(self.sender, sc.Arc) and self.sender.gesture_payload.culled:
# Turn down the gesture if it on the wrong side of the arc
if self.state == sc.GestureState.BEGAN:
self.state = sc.GestureState.POSSIBLE
super().process()
def _on_began(self):
super()._on_began()
self._original_tickness = self.sender.thickness
self.sender.thickness = self._original_tickness + 1
self._begin_angle = self.sender.gesture_payload.angle
if self._viz_arc:
self._viz_arc.begin = self._begin_angle
if self._axis is None:
self._last_free_intersect, _ = self._sphere_intersect()
self._changing_item = self._manipulator.model.get_item("rotate")
self._manipulator._process_gesture(
RotateChangedGesture, self.state, RotateDragGesturePayload(self.gesture_payload, self._changing_item)
)
if self._highlight_ctrl:
self._highlight_ctrl.highlight(self.sender)
def _on_changed(self):
super()._on_changed()
prev_angle = self._angle
self._angle = self.sender.gesture_payload.angle - self._begin_angle
self._angle = self._angle / math.pi * 180 # convert to degree
snap = self._manipulator.model.get_snap(self._changing_item)
if snap: # Not None and not zero
self._angle = self._angle // snap * snap
angle_delta = self._angle - prev_angle
else:
angle_delta = self.sender.gesture_payload.moved_angle
angle_delta = angle_delta / math.pi * 180 # convert to degree
screen_space = False
free_rotation = False
# handle the free rotation mode when grabbing the center of rotation manipulator
if self._axis is None:
axis, angle_delta = self._handle_free_rotation()
if axis is not None and angle_delta is not None:
free_rotation = True
else:
# early return, no gesture is generated for invalid free rotation
return
elif self._axis == [0, 0, 0]:
axis = self.sender.transform_space(sc.Space.OBJECT, sc.Space.WORLD, [0, 0, 1, 0])
screen_space = True
else:
axis = self._axis
# normalize
axis_len = math.sqrt(axis[0] ** 2 + axis[1] ** 2 + axis[2] ** 2)
axis = [v / axis_len for v in axis]
if not free_rotation:
# confine angle in [-180, 180) range so the overlay doesn't block manipulated object too much
angle = (self._angle - 360.0 * math.floor(self._angle / 360.0 + 0.5)) / 180.0 * math.pi
self._viz_arc.end = angle + self._viz_arc.begin
self._viz_arc.visible = True
if angle_delta:
new_gesture_payload = RotateDragGesturePayload(self.gesture_payload, self._changing_item)
new_gesture_payload.axis = axis
new_gesture_payload.angle = self._angle
new_gesture_payload.angle_delta = angle_delta
new_gesture_payload.screen_space = screen_space
new_gesture_payload.free_rotation = free_rotation
self._manipulator._process_gesture(RotateChangedGesture, self.state, new_gesture_payload)
def _on_ended(self):
super()._on_ended()
self.sender.thickness = self._original_tickness
if self._viz_arc:
self._viz_arc.visible = False
self._manipulator._process_gesture(
RotateChangedGesture, self.state, RotateDragGesturePayload(self.gesture_payload, self._changing_item)
)
if self._highlight_ctrl:
self._highlight_ctrl.dehighlight(self.sender)
if self._axis is None:
self._last_free_intersect = None
def _on_canceled(self):
self._on_ended()
def _sphere_intersect(self) -> Tuple[List[float], bool]:
intersect = self.sender.gesture_payload.ray_closest_point
ndc_location = self.sender.transform_space(sc.Space.WORLD, sc.Space.NDC, intersect)
ndc_ray_origin = copy.copy(ndc_location)
ndc_ray_origin[2] = 0.0
object_ray_origin = np.array(self.sender.transform_space(sc.Space.NDC, sc.Space.OBJECT, ndc_ray_origin))
object_ray_end = np.array(self.sender.transform_space(sc.Space.NDC, sc.Space.OBJECT, ndc_location))
dir = object_ray_end - object_ray_origin
dir = dir / np.linalg.norm(dir)
a = np.dot(dir, dir)
b = 2.0 * np.dot(object_ray_origin, dir)
c = np.dot(object_ray_origin, object_ray_origin) - self.sender.radius * self.sender.radius
discriminant = b * b - 4 * a * c
if discriminant >= 0.0:
sqrt_discriminant = math.sqrt(discriminant)
t = (-b - sqrt_discriminant) / (2.0 * a)
if t >= 0:
point = object_ray_origin + t * dir
world = self.sender.transform_space(sc.Space.OBJECT, sc.Space.WORLD, point.tolist())
return world, True
# If no intersection, get the neareast point on the ray to the sphere
nearest_dist = np.dot(-object_ray_origin, dir)
point = object_ray_origin + dir * nearest_dist
world = self.sender.transform_space(sc.Space.OBJECT, sc.Space.WORLD, point.tolist())
return world, False
def _handle_free_rotation(self) -> Tuple[List[float], float]:
with np.errstate(all="raise"):
try:
axis = None
angle_delta = None
nearest_ray_point, intersected = self._sphere_intersect()
last_intersect = copy.copy(self._last_free_intersect)
self._last_free_intersect = nearest_ray_point
mode = self._settings.get(CONSTANTS.FREE_ROTATION_TYPE_SETTING)
if intersected or mode == CONSTANTS.FREE_ROTATION_TYPE_CLAMPED:
# Use clamped mode as long as ray intersects with sphere to maintain consistent behavior when dragging within the sphere
# clamped at the edge of free rotation sphere
if nearest_ray_point is not None and last_intersect is not None:
# calculate everything in world space
origin = np.array(self.sender.transform_space(sc.Space.OBJECT, sc.Space.WORLD, [0, 0, 0]))
vec1 = last_intersect - origin
vec1 = vec1 / np.linalg.norm(vec1)
vec2 = nearest_ray_point - origin
vec2 = vec2 / np.linalg.norm(vec2)
axis = np.cross(vec1, vec2)
mag = np.linalg.norm(axis)
if mag > 0:
axis = axis / mag
dot = np.dot(vec1, vec2)
if dot >= -1 and dot <= 1:
angle_delta = np.arccos(dot) / math.pi * 180
if not math.isfinite(angle_delta):
raise FloatingPointError()
elif mode == CONSTANTS.FREE_ROTATION_TYPE_CONTINUOUS:
# Continuous mode. Only fallback to it if not intersected and continuous_mode is on.
# extend beyond sphere edge for free rotation based on moved distance
moved = np.array(self.sender.gesture_payload.moved)
forward = self.sender.transform_space(sc.Space.OBJECT, sc.Space.WORLD, [0, 0, 1, 0])
forward = np.array([forward[0], forward[1], forward[2]])
moved_len = math.sqrt(np.dot(moved, moved))
if moved_len > 0:
moved_dir = moved / moved_len
forward = forward / np.linalg.norm(forward)
axis = np.cross(forward, moved_dir).tolist()
angle_delta = moved_len
except Exception:
axis = None
angle_delta = None
finally:
return axis, angle_delta
class ScaleGesture(TransformGesture):
def __init__(
self,
manipulator: TransformManipulator,
axis,
highlight_ctrl: HighlightControl,
handle_lines=[],
handle_dots=[],
order: int = 0,
):
super().__init__(manipulator=manipulator, highlight_ctrl=highlight_ctrl, order=order, manager=PreventOthers())
self._axis = axis
self._handle_lines = handle_lines
self._handle_dots = handle_dots
def _get_dir_and_length_from_origin(self, point):
point = self.sender.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.sender.gesture_payload.item_closest_point
)
transform = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("transform"))
origin_in_local = self.sender.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, [transform[12], transform[13], transform[14]]
)
diff = [s - o for s, o in zip(point, origin_in_local)]
length = math.sqrt(diff[0] ** 2 + diff[1] ** 2 + diff[2] ** 2)
dir = [x / length for x in diff]
return point, dir, length
def _on_began(self):
super()._on_began()
self._original_ends = [line.end.copy() for line in self._handle_lines]
self._original_dot_transform = [
[dot.transform[12], dot.transform[13], dot.transform[14]] for dot in self._handle_dots
]
self._start_point, self._direction, self._start_length = self._get_dir_and_length_from_origin(
self.sender.gesture_payload.item_closest_point
)
self._accumulated_distance = self._start_length
self._changing_item = self._manipulator.model.get_item("scale")
self._scale_prev = None
self._manipulator._process_gesture(
ScaleChangedGesture, self.state, ScaleDragGesturePayload(self.gesture_payload, self._changing_item)
)
if self._highlight_ctrl:
self._highlight_ctrl.highlight(self.sender)
self._first_change = False
def _on_changed(self):
super()._on_changed()
if isinstance(self.sender, sc.Arc) and self._first_change is False:
# handle the omni scale (center point) differently as the start point is very close to origin
# so we do it when it has enough distance
if self.sender.gesture_payload.distance_to_center > 10:
start_point, direction, length = self._get_dir_and_length_from_origin(
self.sender.gesture_payload.ray_closest_point
)
self._start_point = start_point
self._direction = direction
self._accumulated_distance = self._start_length = length * 5 # make the step smaller
self._first_change = True
else:
# early return. don't start change before we can determine those values
return
# use object space delta
moved = self.sender.gesture_payload.moved
moved = self.sender.transform_space(sc.Space.WORLD, sc.Space.OBJECT, [moved[0], moved[1], moved[2], 0])
distance = moved[0] * self._direction[0] + moved[1] * self._direction[1] + moved[2] * self._direction[2]
self._accumulated_distance += distance
if self._accumulated_distance == 0:
self._accumulated_distance = 0.001
scale = self._accumulated_distance / self._start_length
snap = self._manipulator.model.get_snap(self._changing_item)
if snap: # Not None and not zero
if abs(scale) < snap:
scale = math.copysign(1, scale)
else:
snap_scale = (abs(scale) - 1) // snap * snap + 1
scale = math.copysign(snap_scale, scale)
for i, line in enumerate(self._handle_lines):
line.end = [
self._original_ends[i][0] * scale,
self._original_ends[i][1] * scale,
self._original_ends[i][2] * scale,
]
for i, dot in enumerate(self._handle_dots):
t = dot.transform
t[12] = self._original_dot_transform[i][0] * scale
t[13] = self._original_dot_transform[i][1] * scale
t[14] = self._original_dot_transform[i][2] * scale
dot.transform = t
if scale != self._scale_prev:
self._scale_prev = scale
new_gesture_payload = ScaleDragGesturePayload(self.gesture_payload, self._changing_item)
new_gesture_payload.axis = self._axis
new_gesture_payload.scale = scale
self._manipulator._process_gesture(ScaleChangedGesture, self.state, new_gesture_payload)
def _on_ended(self):
super()._on_ended()
for i, line in enumerate(self._handle_lines):
line.end = self._original_ends[i]
for i, dot in enumerate(self._handle_dots):
dot.transform[12] = self._original_dot_transform[i][0]
dot.transform[13] = self._original_dot_transform[i][1]
dot.transform[14] = self._original_dot_transform[i][2]
self._manipulator._process_gesture(
ScaleChangedGesture, self.state, ScaleDragGesturePayload(self.gesture_payload, self._changing_item)
)
if self._highlight_ctrl:
self._highlight_ctrl.dehighlight(self.sender)
def _on_canceled(self):
self._on_ended()
# The sole purpose of this dummy gesture is to prevent further viewport drag interaction by emitting a TransformChangedGesture,
# which:
# Turns of selection rect in VP1
# Prevents other gestures in VP2
class DummyGesture(TransformGesture):
def __init__(self, manipulator: TransformManipulator):
# toolbar always has smaller order value to take precedence over manipulator handles.
super().__init__(manipulator, None, order=-999, manager=PreventOthers())
def _on_began(self):
self._manipulator._process_gesture(
TransformChangedGesture, self.state, TransformDragGesturePayload(self.gesture_payload, None)
)
def _on_changed(self):
...
def _on_ended(self):
self._manipulator._process_gesture(
TransformChangedGesture, self.state, TransformDragGesturePayload(self.gesture_payload, None)
)
def _on_canceled(self):
self._on_ended()
# The sole purpose of this dummy gesture is to prevent further viewport click interaction which:
# Prevents other gestures in VP2 (e.g. right click on manipulator toolbar won't further trigger viewport context menu)
# (no VP1 support for this!)
class DummyClickGesture(sc.ClickGesture):
def __init__(self, mouse_button: int):
super().__init__(mouse_button=mouse_button, manager=PreventOthers())
@property
def order(self):
return -1000
| 30,371 | Python | 37.348485 | 140 | 0.60594 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/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_manipulator_transform import TestTransform
| 483 | Python | 42.999996 | 76 | 0.813665 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/tests/test_manipulator_transform.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 functools import lru_cache
from carb.input import MouseEventType
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from omni.ui import scene as sc
from omni.ui import color as cl
import carb
import omni.kit
import omni.kit.app
import omni.ui as ui
import omni.appwindow
import carb.windowing
from ..manipulator import TransformManipulator
from ..manipulator import Axis
from ..simple_transform_model import SimpleRotateChangedGesture
from ..simple_transform_model import SimpleScaleChangedGesture
from ..simple_transform_model import SimpleTranslateChangedGesture
from ..types import Operation
CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.manipulator.transform}/data"))
# TODO: use ui_test when it's moved to kit-sdk
@lru_cache()
def _get_windowing() -> carb.windowing.IWindowing:
return carb.windowing.acquire_windowing_interface()
# TODO: use ui_test when it's moved to kit-sdk
@lru_cache()
def _get_input_provider() -> carb.input.InputProvider:
return carb.input.acquire_input_provider()
# TODO: use ui_test when it's moved to kit-sdk
def emulate_mouse(event_type: MouseEventType, pos):
app_window = omni.appwindow.get_default_app_window()
mouse = app_window.get_mouse()
window_width = ui.Workspace.get_main_window_width()
window_height = ui.Workspace.get_main_window_height()
_get_input_provider().buffer_mouse_event(
mouse, event_type, (pos[0] / window_width, pos[1] / window_height), 0, pos
)
if event_type == MouseEventType.MOVE:
_get_windowing().set_cursor_position(app_window.get_window(), (int(pos[0]), int(pos[1])))
class TestTransform(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("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)
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)
# Selected point
self._selected_item = None
def _on_point_clicked(shape):
"""Called when the user clicks the point"""
self._selected_item = shape
pos = self._selected_item.positions[0]
model = self._manipulator.model
model.set_floats(model.get_item("translate"), [pos[0], pos[1], pos[2]])
def _on_item_changed(model, item):
"""
Called when the user moves the manipulator. We need to move
the point here.
"""
if self._selected_item is not None:
if item.operation == Operation.TRANSLATE:
self._selected_item.positions = model.get_as_floats(item)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
# The manipulator
self._manipulator = TransformManipulator(
size=1,
axes=Axis.ALL & ~Axis.Z & ~Axis.SCREEN,
gestures=[
SimpleTranslateChangedGesture(),
SimpleRotateChangedGesture(),
SimpleScaleChangedGesture(),
],
)
self._sub = \
self._manipulator.model.subscribe_item_changed_fn(_on_item_changed)
# 5 points
select = sc.ClickGesture(_on_point_clicked)
sc.Points([[-5, 5, 0]], colors=[ui.color.white], sizes=[10], gesture=select)
sc.Points([[5, 5, 0]], colors=[ui.color.white], sizes=[10], gesture=select)
sc.Points([[5, -5, 0]], colors=[ui.color.white], sizes=[10], gesture=select)
sc.Points([[-5, -5, 0]], colors=[ui.color.white], sizes=[10], gesture=select)
self._selected_item = sc.Points(
[[0, 0, 0]], colors=[ui.color.white], sizes=[10], gesture=select
)
for _ in range(30):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_hovering(self):
app_window = omni.appwindow.get_default_app_window()
dpi_scale = ui.Workspace.get_dpi_scale()
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)
# Selected point
self._selected_item = None
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
# The manipulator
self._manipulator = TransformManipulator(
size=1,
axes=Axis.ALL & ~Axis.Z & ~Axis.SCREEN,
)
await omni.kit.app.get_app().next_update_async()
# Get NDC position of World-space point
transformed = scene_view.scene.transform_space(sc.Space.WORLD, sc.Space.NDC, (30, 0, 0))
# Convert it to the Screen space
transformed = [transformed[0] * 0.5 + 0.5, transformed[1] * 0.5 + 0.5]
# Unblock mouse
app_window.set_input_blocking_state(carb.input.DeviceType.MOUSE, False)
# Go to the computed position
x = dpi_scale * (window.frame.computed_width * transformed[0] + window.frame.screen_position_x)
y = dpi_scale * (window.frame.computed_height * transformed[1] + window.frame.screen_position_y)
emulate_mouse(MouseEventType.MOVE, (x, y))
for i in range(5):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 6,769 | Python | 38.132948 | 105 | 0.603486 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/docs/index.rst | omni.kit.manipulator.transform
################################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule:: omni.kit.manipulator.transform
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 363 | reStructuredText | 16.333333 | 46 | 0.633609 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/sync_strategy.py | import enum
import omni.timeline
from carb import log_error
from typing import List
from .global_time import get_global_time_s
from .timeline_event import TimelineEvent
class SyncStrategyType(enum.Enum):
STRICT = 0
"""
Moves the time only when a new time update is received.
No difference is allowed from the last known current time.
"""
DIFFERENCE_LIMITED = 1
"""
When the timeline is not playing, no difference is allowed from the last
known current time.
When the timeline is playing, the listener's current time may differ from
that of the presenter. The maximum difference in seconds can be set in the
"max_time_diff_sec" parameter of the SyncStrategyDescriptor.
If the allowed difference is zero, this strategy falls back to "STRICT" mode.
Otherwise,
- the listener may run freely even if no new time update is received
until it reaches the maximum allowed difference, then it pauses to wait
for the presenter,
- when the listener is behind the presenter more than the maximum allowed
difference, it will speed up its playback speed for a short time to catch up
with the presenter instead of jumping directly to the last known current time.
"""
LOOSE = 2
"""
Synchronizes current time only when the timeline is not playing.
Useful when all we care about is whether the presented started playing and what
the current was before that.
Time difference can be unlimited if played for long.
"""
class SyncStrategyDescriptor:
def __init__(
self,
strategy_type: SyncStrategyType,
max_time_diff_sec: float = 1
) -> None:
self.strategy_type = strategy_type
self.max_time_diff_sec = max_time_diff_sec
class TimeInterpolator:
# wc_: wall clock time, sim_: simulation time
def __init__(self, sim_start = 0.0, sim_target = 0.0, wc_duration = 1.0):
self.start = sim_start
self.target = sim_target
self.wc_duration = min((sim_target - sim_start) / 4, wc_duration)
self.wc_start = get_global_time_s()
def get_interpolated(self, wc_time):
t = (wc_time - self.wc_start) / self.wc_duration # to [0,1]
t = min(max(0, t), 1)
t_sq = t * t
t = 3 * t_sq - 2 * t_sq * t # smoothstep
return (1 - t) * self.start + t * self.target # [0,1] to sim time
# TODO: find a better name...
class TimelineSyncStrategyExecutor:
def __init__(self, desc: SyncStrategyDescriptor, timeline):
self._strategy_desc = desc
self._timeline = timeline
self._is_presenter_playing = False
self.reset()
@property
def strategy_desc(self) -> SyncStrategyDescriptor:
return self._strategy_desc
@strategy_desc.setter
def strategy_desc(self, desc: SyncStrategyDescriptor):
# one of them is zero, reset status of diff limited
# (otherwise we do not need to)
if desc.max_time_diff_sec * self._strategy_desc.max_time_diff_sec < 0.00001:
self.reset()
self._strategy_desc = desc
def process_events(self, events: List[TimelineEvent]) -> List[TimelineEvent]:
"""
Processes the incoming timeline update events and decides what to do.
Returns a new list of timeline events that may not contain any of the input events.
"""
if self._strategy_desc.strategy_type == SyncStrategyType.STRICT:
return self._process_strict(events)
elif self._strategy_desc.strategy_type == SyncStrategyType.LOOSE:
return self._process_loose(events)
elif self.strategy_desc.strategy_type == SyncStrategyType.DIFFERENCE_LIMITED:
if self.strategy_desc.max_time_diff_sec < 0.0001:
return self._process_strict(events)
else:
return self._process_diff_limited(events)
else:
log_error(f'Sync strategy not implemented: {self._strategy_desc.strategy_type}')
def reset(self):
self._is_suspended = False # True: extrapolated too much, waiting
self._interpolating = False
self._time_interpolator = TimeInterpolator()
self._last_known_sim_time = None
# event processing shared between all strategy types
def _process_event_common(self, event: TimelineEvent, out_events: List[TimelineEvent]):
if event.type == int(omni.timeline.TimelineEventType.PLAY):
self._is_presenter_playing = True
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
self._is_presenter_playing = False
self.reset()
elif event.type == int(omni.timeline.TimelineEventType.STOP):
self._is_presenter_playing = False
self.reset()
elif event.type == int(omni.timeline.TimelineEventType.LOOP_MODE_CHANGED):
out_events.append(event)
elif event.type == int(omni.timeline.TimelineEventType.ZOOM_CHANGED):
out_events.append(event)
def _process_strict(self, events: List[TimelineEvent]) -> List[TimelineEvent]:
out_events = []
for event in events:
self._process_event_common(event, out_events)
if event.type == int(omni.timeline.TimelineEventType.PLAY):
# Play but then pause immediately
out_events.append(TimelineEvent(omni.timeline.TimelineEventType.PLAY, {}))
out_events.append(TimelineEvent(omni.timeline.TimelineEventType.PAUSE, {}))
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
out_events.append(event)
elif event.type == int(omni.timeline.TimelineEventType.STOP):
out_events.append(event)
elif event.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED):
self._last_known_sim_time = event.payload['currentTime']
# Play if needed, Sync the time then pause
if not self._timeline.is_playing():
out_events.append(TimelineEvent(omni.timeline.TimelineEventType.PLAY, {}))
out_events.append(event)
out_events.append(TimelineEvent(omni.timeline.TimelineEventType.PAUSE, {}))
return out_events
def _process_loose(self, events: List[TimelineEvent]) -> List[TimelineEvent]:
out_events = []
for event in events:
self._process_event_common(event, out_events)
if event.type == int(omni.timeline.TimelineEventType.PLAY):
out_events.append(event)
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
out_events.append(event)
elif event.type == int(omni.timeline.TimelineEventType.STOP):
out_events.append(event)
elif event.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED):
self._last_known_sim_time = event.payload['currentTime']
# Care about the time only when the not playing
if not self._timeline.is_playing():
out_events.append(event)
return out_events
def _start_interpolation(self, t0: float, t: float):
dt_max = self.strategy_desc.max_time_diff_sec
if not self._interpolating and t0 + dt_max < t:
self._interpolating = True
self._time_interpolator = TimeInterpolator(t0, t)
def _handle_time_difference(self, current_time: float, out_events: List[TimelineEvent]):
end_wait_scale_factor = 0.2
end_interpolation_scale_factor = 0.2
# Rules. Note that their order of application differs from this enumeration.
# Notation:
# current_time (new update from the presenter) -> t
# end_wait_scale_factor -> s
# end_interpolation_scale_factor -> si
# self._timeline.get_current_time() -> t0
# self.strategy_desc.max_time_diff_sec -> dt_max
# self._timeline.get_end_time() -> end
#
# 0. Looping is on and close to the end. end - K < t0 => set time and pause
# See below for K.
#
# 1. Suspend. t < t0 - dt_max => ahead of the presenter, pause and wait
#
# 2. Restart after suspend. is_suspended and t0 - s*dt_max < t => play
# The role of scale factor s is to avoid alternating pause/play when the presenter
# is slow/lagging. Instead, we let the listener run for a bit, then pause for longer.
# Thus, "s" basically controls the length of wait and extrapolation periods when
# the presenter is lagging behind.
#
# 3.1. Slightly behind, do nothing. Not interpolating and t0 < t < t0 + dt_max => ok
# 3.2. Got close enough, stop interpolation. t < t0 + si
#
# 4. Start interpolation (faster playback). t0 + dt_max < t => increase playback speed.
t = current_time
dt_max = self.strategy_desc.max_time_diff_sec
s = end_wait_scale_factor
si = end_interpolation_scale_factor
t0 = self._timeline.get_current_time()
K = max(0.5, dt_max)
end = self._timeline.get_end_time()
# 0. Close to the end: set and pause
if self._timeline.is_looping() and end - K < t0:
self._is_suspended = True
if t0 < t:
out_events.append(TimelineEvent(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
{'currentTime': t},
))
out_events.append(TimelineEvent(omni.timeline.TimelineEventType.PAUSE, {}))
self._interpolating = False
self._time_interpolator = TimeInterpolator()
return
# 1. time difference is too high, pause
if not self._is_suspended and t < t0 - dt_max:
out_events.append(TimelineEvent(omni.timeline.TimelineEventType.PAUSE, {}))
self._is_suspended = True
self._interpolating = False
return
# 2. end waiting
elif self._is_suspended and t0 - s * dt_max < t:
out_events.append(TimelineEvent(omni.timeline.TimelineEventType.PLAY, {}))
self._is_suspended = False
# 3.2
if self._interpolating and t < t0 + si:
self._interpolating = False
return
if self._interpolating:
self._time_interpolator.target = t
# 4. start interpolation
self._start_interpolation(t0, t)
def _process_diff_limited(self, events: List[TimelineEvent]) -> List[TimelineEvent]:
out_events = []
time_received = False
for event in events:
self._process_event_common(event, out_events)
if event.type == int(omni.timeline.TimelineEventType.PLAY):
out_events.append(TimelineEvent(omni.timeline.TimelineEventType.PLAY, {}))
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
out_events.append(event)
if 'currentTime' in event.payload.keys():
out_events.append(TimelineEvent(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
{'currentTime' : event.payload['currentTime']}
))
elif event.type == int(omni.timeline.TimelineEventType.STOP):
out_events.append(event)
elif event.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED):
time_received = True
presenter_rewind = False
# presenter's time restart because of looping
if self._last_known_sim_time is not None and \
event.payload['currentTime'] < self._last_known_sim_time:
presenter_rewind = True
is_previous_time_known = self._last_known_sim_time is not None
self._last_known_sim_time = event.payload['currentTime']
# not is_previous_time_known: avoid rule 1. of _handle_time_difference when
# the listener re-enabled sync.
# in this case we should always jump to the new time
if is_previous_time_known and not presenter_rewind and self._is_presenter_playing:
self._handle_time_difference(event.payload['currentTime'], out_events)
else:
# just set the new time, restart playback if necessary
out_events.append(event)
self._interpolating = False
if self._is_presenter_playing:
out_events.append(TimelineEvent(omni.timeline.TimelineEventType.PLAY, {}))
self._is_suspended = False
# still apply rule 4. (interpolation).
# this case happens when sync was re-enabled. this can be removed if we
# don't want interpolation when sync was re-enabled,
# jumping instantly to the new time might be better.
self._start_interpolation(
self._timeline.get_current_time(),
self._last_known_sim_time
)
# no new information, use the last known time
if self._is_presenter_playing and not time_received and \
self._last_known_sim_time is not None:
self._handle_time_difference(self._last_known_sim_time, out_events)
# interpolation
if self._interpolating and self._time_interpolator is not None:
# avoid being stuck when a different strategy was set during interpolation
# and it pauses the timeline
if not self._timeline.is_playing():
out_events.append(TimelineEvent(omni.timeline.TimelineEventType.PLAY, {}))
t_interpolated = self._time_interpolator.get_interpolated(get_global_time_s())
out_events.append(TimelineEvent(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
{'currentTime' : t_interpolated}
))
return out_events | 14,270 | Python | 45.485342 | 98 | 0.605676 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/global_time.py | import time
# For now we use system time, later we may use something from Nucleus
def get_global_time_s() -> float:
return time.time() | 140 | Python | 22.499996 | 69 | 0.714286 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/timeline_serializer.py | import carb
import omni.kit.usd.layers as layers
import omni.timeline
from pxr import Sdf, Usd
from typing import List, Tuple
from .global_time import get_global_time_s
from .timeline_event import TimelineEvent
from .timeline_state import (
get_timeline_state,
get_timeline_next_events,
get_timeline_next_state,
PlayState,
TimelineState
)
TIMELINE_PRIM_PATH = '/__session_shared_data__/Omni_Timeline_Live_Sync'
TIME_ATTR_NAME = 'timeline:time'
CONTROL_ID_PREF = 'timeline:control:ID_'
LOOPING_ATTR_NAME = 'timeline:looping'
OWNER_ID_ATTR_NAME = 'timeline:owner:id'
PLAYSTATE_ATTR_NAME = 'timeline:playstate'
OWNER_NAME_ATTR_NAME = 'timeline:owner:name'
PRESENTER_ID_ATTR_NAME = 'timeline:presenter:id'
GLB_TIMESTAMP_ATTR_NAME = 'timeline:timestamp'
PRESENTER_NAME_ATTR_NAME = 'timeline:presenter:name'
ZOOM_RANGE_END_ATTR_NAME = 'timeline:zoom_end'
ZOOM_RANGE_START_ATTR_NAME = 'timeline:zoom_start'
def prop_path(prop_name: str) -> str:
return TIMELINE_PRIM_PATH + '.' + prop_name
class TimelineStateSerializer:
def __init__(self):
self._timeline = None
self._stage = None
def initialize(self, timeline, synced_stage: Usd.Stage, sending: bool):
self._timeline = timeline
self._stage = synced_stage
self._timeline_state = TimelineState(timeline)
def finalize(self):
pass
def sendTimelineUpdate(self, e: TimelineEvent):
pass
def receiveTimelineUpdate(self) -> List[TimelineEvent]:
return []
def receiveTimestamp(self) -> float:
return 0
def sendOwnerUpdate(self, user: layers.LiveSessionUser):
pass
def receiveOwnerUpdate(self) -> str:
"""
Returns user ID
"""
pass
def sendPresenterUpdate(self, user: layers.LiveSessionUser):
pass
def receivePresenterUpdate(self) -> str:
"""
Returns user ID
"""
pass
def sendControlRequest(self, user_id: str, want_control: bool, from_owner: bool):
pass
def receiveControlRequests(self) -> List[Tuple[str, bool]]:
pass
class TimelinePrimSerializer(TimelineStateSerializer):
"""
Communicates timeline messages via attributes of a single shared prim.
It transforms events to state and vice versa.
"""
def __init__(self):
super().__init__()
self._layer = None
def initialize(self, timeline, synced_stage: Usd.Stage, sending: bool):
super().initialize(timeline, synced_stage, sending)
self._layer = self._stage.GetRootLayer() if self._stage is not None else None
self._timeline_prim_path = TIMELINE_PRIM_PATH
if sending:
self._setup_timeline_prim()
else:
self._timeline_prim = self._stage.GetPrimAtPath(self._timeline_prim_path)
if not self._timeline_prim.IsValid():
carb.log_warn(f'{self.__class__}: Could not find timeline prim')
def sendTimelineUpdate(self, e: TimelineEvent):
super().sendTimelineUpdate(e)
if self._stage is None or self._layer is None:
return
if not self._timeline_prim.IsValid():
self._setup_timeline_prim()
attr_names = []
values = []
if e.type == int(omni.timeline.TimelineEventType.PLAY) or\
e.type == int(omni.timeline.TimelineEventType.PAUSE) or\
e.type == int(omni.timeline.TimelineEventType.STOP):
next_state = get_timeline_next_state(self._timeline_state.state, e.type)
if next_state != self._timeline_state.state:
# TODO: omni.timeline should send a time changed event instead when stopped
if e.type == int(omni.timeline.TimelineEventType.STOP):
self._timeline_state.current_time = self._timeline.get_start_time()
self._timeline_state.state = next_state
attr_names.append(PLAYSTATE_ATTR_NAME)
values.append(next_state.value)
attr_names.append(TIME_ATTR_NAME)
values.append(self._timeline_state.current_time)
elif e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED):
self._timeline_state.current_time = e.payload['currentTime']
attr_names.append(TIME_ATTR_NAME)
values.append(self._timeline_state.current_time)
elif e.type == int(omni.timeline.TimelineEventType.LOOP_MODE_CHANGED):
self._timeline_state.looping = e.payload['looping']
attr_names.append(LOOPING_ATTR_NAME)
values.append(self._timeline_state.looping)
elif e.type == int(omni.timeline.TimelineEventType.ZOOM_CHANGED):
self._timeline_state.set_zoom_range(e.payload['startTime'], e.payload['endTime'])
attr_names.append(ZOOM_RANGE_START_ATTR_NAME)
values.append(self._timeline_state.zoom_range[0])
attr_names.append(ZOOM_RANGE_END_ATTR_NAME)
values.append(self._timeline_state.zoom_range[1])
with Sdf.ChangeBlock():
for attr_name, value in zip(attr_names, values):
self._layer.GetAttributeAtPath(prop_path(attr_name)).default = value
if len(attr_names) > 0 or \
e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT):
self._layer.GetAttributeAtPath(prop_path(GLB_TIMESTAMP_ATTR_NAME)).default = e.timestamp
def receiveTimelineUpdate(self) -> List[TimelineEvent]:
if self._stage is None or self._layer is None:
return []
if not self._timeline_prim.IsValid():
return []
events = []
play_state = self._layer.GetAttributeAtPath(prop_path(PLAYSTATE_ATTR_NAME)).default
try:
play_state = PlayState(play_state)
except:
carb.log_error(
f'Invalid invalid playstate in timeline event serialization: {play_state}')
play_state = self._timeline_state.state
current_time = self._layer.GetAttributeAtPath(prop_path(TIME_ATTR_NAME)).default
timestamp = self._layer.GetAttributeAtPath(prop_path(GLB_TIMESTAMP_ATTR_NAME)).default
looping = self._layer.GetAttributeAtPath(prop_path(LOOPING_ATTR_NAME)).default
zoom_start = self._layer.GetAttributeAtPath(prop_path(ZOOM_RANGE_START_ATTR_NAME)).default
zoom_end = self._layer.GetAttributeAtPath(prop_path(ZOOM_RANGE_END_ATTR_NAME)).default
if looping != self._timeline_state.looping:
self._timeline_state.looping = looping
event = TimelineEvent(
type=omni.timeline.TimelineEventType.LOOP_MODE_CHANGED,
payload={'looping' : looping},
timestamp=timestamp
)
events.append(event)
if play_state != self._timeline_state.state:
timeline_events = get_timeline_next_events(self._timeline_state.state, play_state)
self._timeline_state.state = play_state
for timeline_event in timeline_events:
event = TimelineEvent(
timeline_event,
payload={'currentTime' : current_time}, # for better sync strategies
timestamp=timestamp
)
events.append(event)
if current_time != self._timeline_state.current_time:
self._timeline_state.current_time = current_time
event = TimelineEvent(
type=omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
payload={'currentTime' : current_time},
timestamp=timestamp
)
events.append(event)
if zoom_start != self._timeline_state.zoom_range[0] or zoom_end != self._timeline_state.zoom_range[1]:
self._timeline_state.set_zoom_range(zoom_start, zoom_end)
event = TimelineEvent(
type=omni.timeline.TimelineEventType.ZOOM_CHANGED,
payload={'startTime' : zoom_start, 'endTime' : zoom_end},
timestamp=timestamp
)
events.append(event)
return events
def receiveTimestamp(self) -> float:
if self._stage is None or self._layer is None:
return 0
if not self._timeline_prim.IsValid():
return 0
return self._layer.GetAttributeAtPath(prop_path(GLB_TIMESTAMP_ATTR_NAME)).default
def sendOwnerUpdate(self, user: layers.LiveSessionUser):
super().sendOwnerUpdate(user)
if self._stage is None or self._layer is None:
return
if not self._timeline_prim.IsValid():
self._setup_timeline_prim()
self._layer.GetAttributeAtPath(prop_path(OWNER_ID_ATTR_NAME)).default = user.user_id
self._layer.GetAttributeAtPath(prop_path(OWNER_NAME_ATTR_NAME)).default = user.user_name
def receiveOwnerUpdate(self) -> str:
if self._stage is None or self._layer is None:
return None
if not self._timeline_prim.IsValid():
return None
return self._layer.GetAttributeAtPath(prop_path(OWNER_ID_ATTR_NAME)).default
def sendPresenterUpdate(self, user: layers.LiveSessionUser):
super().sendPresenterUpdate(user)
if self._stage is None or self._layer is None:
return
if not self._timeline_prim.IsValid():
self._setup_timeline_prim()
self._layer.GetAttributeAtPath(prop_path(PRESENTER_ID_ATTR_NAME)).default = user.user_id
self._layer.GetAttributeAtPath(prop_path(PRESENTER_NAME_ATTR_NAME)).default = user.user_name
def receivePresenterUpdate(self) -> str:
if self._stage is None or self._layer is None:
return None
if not self._timeline_prim.IsValid():
return None
return self._layer.GetAttributeAtPath(prop_path(PRESENTER_ID_ATTR_NAME)).default
def sendControlRequest(self, user_id: str, want_control: bool, from_owner: bool):
super().sendControlRequest(user_id, want_control, from_owner)
if self._stage is None or self._layer is None:
return
if not self._timeline_prim.IsValid():
if from_owner:
self._setup_timeline_prim()
else:
return
prim = self._timeline_prim
prefix = CONTROL_ID_PREF
attr_name = f'{prefix}{user_id}'
if want_control:
if not prim.HasAttribute(attr_name):
prim.CreateAttribute(attr_name, Sdf.ValueTypeNames.Int)
prim.GetAttribute(attr_name).Set(1)
elif prim.HasAttribute(attr_name): # Nothing to do if the attribute does not exist
if from_owner:
prim.RemoveProperty(attr_name)
else:
prim.GetAttribute(attr_name).Set(0)
def receiveControlRequests(self) -> List[Tuple[str, bool]]:
if self._stage is None or self._layer is None:
return []
if not self._timeline_prim.IsValid():
return []
requests = []
prim_spec = self._layer.GetPrimAtPath(self._timeline_prim_path)
for property in prim_spec.properties:
attr_name: str = property.name
prefix = CONTROL_ID_PREF
if attr_name.startswith(prefix):
user_id = attr_name.removeprefix(prefix)
want_control = property.default
requests.append([user_id, want_control != 0])
return requests
def _setup_timeline_prim(self):
self._stage.DefinePrim(self._timeline_prim_path)
self._timeline_prim = self._stage.GetPrimAtPath(self._timeline_prim_path)
prim = self._timeline_prim
prim.SetMetadata("hide_in_stage_window", True)
if not prim.IsValid():
carb.log_error("Coding error in TimelinePrimSerializer: trying to create attributes of an invalid prim")
return
if not prim.HasAttribute(PLAYSTATE_ATTR_NAME):
prim.CreateAttribute(PLAYSTATE_ATTR_NAME, Sdf.ValueTypeNames.Int)
if not prim.HasAttribute(TIME_ATTR_NAME):
prim.CreateAttribute(TIME_ATTR_NAME, Sdf.ValueTypeNames.Double)
if not prim.HasAttribute(LOOPING_ATTR_NAME):
prim.CreateAttribute(LOOPING_ATTR_NAME, Sdf.ValueTypeNames.Bool)
if not prim.HasAttribute(ZOOM_RANGE_START_ATTR_NAME):
prim.CreateAttribute(ZOOM_RANGE_START_ATTR_NAME, Sdf.ValueTypeNames.Double)
if not prim.HasAttribute(ZOOM_RANGE_END_ATTR_NAME):
prim.CreateAttribute(ZOOM_RANGE_END_ATTR_NAME, Sdf.ValueTypeNames.Double)
if not prim.HasAttribute(GLB_TIMESTAMP_ATTR_NAME):
prim.CreateAttribute(GLB_TIMESTAMP_ATTR_NAME, Sdf.ValueTypeNames.Double)
if not prim.HasAttribute(OWNER_ID_ATTR_NAME):
prim.CreateAttribute(OWNER_ID_ATTR_NAME, Sdf.ValueTypeNames.String)
if not prim.HasAttribute(OWNER_NAME_ATTR_NAME):
prim.CreateAttribute(OWNER_NAME_ATTR_NAME, Sdf.ValueTypeNames.String)
if not prim.HasAttribute(PRESENTER_ID_ATTR_NAME):
prim.CreateAttribute(PRESENTER_ID_ATTR_NAME, Sdf.ValueTypeNames.String)
if not prim.HasAttribute(PRESENTER_NAME_ATTR_NAME):
prim.CreateAttribute(PRESENTER_NAME_ATTR_NAME, Sdf.ValueTypeNames.String)
prim.GetAttribute(PLAYSTATE_ATTR_NAME).Set(get_timeline_state(self._timeline).value)
prim.GetAttribute(TIME_ATTR_NAME).Set(self._timeline.get_current_time())
prim.GetAttribute(LOOPING_ATTR_NAME).Set(self._timeline.is_looping())
prim.GetAttribute(ZOOM_RANGE_START_ATTR_NAME).Set(self._timeline.get_zoom_start_time())
prim.GetAttribute(ZOOM_RANGE_END_ATTR_NAME).Set(self._timeline.get_zoom_end_time())
prim.GetAttribute(GLB_TIMESTAMP_ATTR_NAME).Set(get_global_time_s())
| 13,867 | Python | 41.280488 | 116 | 0.635538 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/timeline_director.py | import omni.usd
import omni.timeline
import carb.events
from .timeline_event import TimelineEvent
from .timeline_serializer import TimelineStateSerializer
from .timeline_session_role import TimelineSessionRole
class TimelineDirector(TimelineSessionRole):
def __init__(self, usd_context_name: str, serializer: TimelineStateSerializer, session):
super().__init__(usd_context_name, serializer, session)
self._timeline = self._main_timeline
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_event
)
def start_session(self) -> bool:
if not super().start_session():
return False
self._serializer.initialize(
timeline=self._timeline,
synced_stage=self._synced_stage,
sending=True
)
return True
def enable_sync(self, enabled: bool):
if enabled == self._enable_sync:
return
super().enable_sync(enabled)
if enabled:
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_event
)
self._update_timeline_state()
else:
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_permanent_tick
)
def stop_session(self):
super().stop_session()
self._serializer.finalize()
self._timeline_sub = None
def _on_timeline_event(self, e: carb.events.IEvent):
self._serializer.sendTimelineUpdate(TimelineEvent.from_carb_event(e))
def _on_timeline_permanent_tick(self, e: carb.events.IEvent):
if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT):
self._serializer.sendTimelineUpdate(TimelineEvent.from_carb_event(e))
def _update_timeline_state(self):
event = TimelineEvent(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
{'currentTime' : self._timeline.get_current_time()}
)
self._serializer.sendTimelineUpdate(event)
event = TimelineEvent(
omni.timeline.TimelineEventType.LOOP_MODE_CHANGED,
{'looping' : self._timeline.is_looping()}
)
self._serializer.sendTimelineUpdate(event)
event = TimelineEvent(
omni.timeline.TimelineEventType.ZOOM_CHANGED,
{
'startTime' : self._timeline.get_zoom_start_time(),
'endTime' : self._timeline.get_zoom_end_time(),
}
)
self._serializer.sendTimelineUpdate(event)
event = TimelineEvent(omni.timeline.TimelineEventType.STOP)
if self._timeline.is_playing():
event = TimelineEvent(omni.timeline.TimelineEventType.PLAY)
elif not self._timeline.is_stopped():
event = TimelineEvent(omni.timeline.TimelineEventType.PAUSE)
self._serializer.sendTimelineUpdate(event) | 3,054 | Python | 36.256097 | 103 | 0.636215 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/timeline_event.py | import carb
import omni.timeline
from typing import Union
from .global_time import get_global_time_s
class TimelineEvent:
def __init__(
self,
type: Union[int, omni.timeline.TimelineEventType],
payload: dict = None,
timestamp: float = None
):
if isinstance(type, omni.timeline.TimelineEventType):
type = int(type)
self._type = type
if payload is None:
payload = {}
self._payload = payload
if timestamp is None:
self._timestamp = get_global_time_s()
else:
self._timestamp = timestamp
@classmethod
def from_carb_event(self, event: carb.events.IEvent):
return TimelineEvent(event.type, event.payload)
@property
def type(self) -> int:
return self._type
@property
def payload(self) -> dict:
return self._payload
@property
def timestamp(self) -> float:
return self._timestamp | 989 | Python | 24.384615 | 61 | 0.589484 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/__init__.py | from .live_session_extension import (
get_session_state,
get_session_window,
get_timeline_session,
TimelineLiveSessionExtension
)
from .timeline_session_role import TimelineSessionRoleType
from .session_state import SessionState
from .timeline_session import TimelineSession | 290 | Python | 31.33333 | 58 | 0.803448 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/session_watcher.py | import omni.kit.usd.layers as layers
import omni.usd
from omni.kit.collaboration.presence_layer import LAYER_SUBSCRIPTION_ORDER
from .session_state import SessionState
from .timeline_session import TimelineSession
from .timeline_session_role import TimelineSessionRoleType
class SessionWatcher:
def __init__(self, usd_context_name: str = ""):
self._usd_context = omni.usd.get_context(usd_context_name)
self._live_syncing = layers.get_live_syncing(self._usd_context)
self._layers = layers.get_layers(self._usd_context)
def start(self):
order = LAYER_SUBSCRIPTION_ORDER + 1
self._layers_event_subscription = None
self._layers_event_subscription = self._layers.get_event_stream().create_subscription_to_pop(
self._on_layers_event, name="omni.timeline.live_session", order=order
)
self._session_state = SessionState()
def stop(self):
if self._session_state.timeline_session is not None:
self._session_state.timeline_session.stop_session()
self._session_state.timeline_session = None
self._layers_event_subscription = None
self._session_state = None
def get_timeline_session(self) -> TimelineSession:
return self._session_state.timeline_session
def get_session_state(self) -> SessionState:
return self._session_state
def _on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
if not payload:
return
# Only events from root layer session are handled.
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if not payload.is_layer_influenced(self._usd_context.get_stage_url()):
return
self._on_session_state_changed()
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED:
if not payload.is_layer_influenced(self._usd_context.get_stage_url()):
return
self._on_user_joined(payload.user_id)
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
if not payload.is_layer_influenced(self._usd_context.get_stage_url()):
return
self._on_user_left(payload.user_id)
def _on_session_state_changed(self):
if not self._live_syncing.is_in_live_session():
if self._session_state.timeline_session is not None:
self._session_state.timeline_session.stop_session()
self._session_state.clear_users()
from .live_session_extension import get_session_window
window = get_session_window()
if window:
window.hide()
else:
self._session = self._get_current_session()
role = TimelineSessionRoleType.LISTENER
if self._is_owner(self._session):
role = TimelineSessionRoleType.PRESENTER
timeline_session = TimelineSession(
usd_context_name=self._usd_context.get_name(),
session_user=self._session.logged_user,
session_state=self._session_state,
role=role
)
self._session_state.add_users([self._session.logged_user])
self._session_state.timeline_session = timeline_session
timeline_session.start_session()
# This needs to happen after we have a session
if self._is_owner(self._session):
timeline_session.owner = self._session.logged_user
timeline_session.presenter = self._session.logged_user
def _on_user_joined(self, user_id):
user = self._session.get_peer_user_info(user_id)
if user is not None:
self._session_state.add_users([user])
timeline_session = self._session_state.timeline_session
if timeline_session is not None:
if timeline_session.owner_id == user_id:
timeline_session.owner = user
def _on_user_left(self, user_id):
self._session_state.remove_user(user_id)
def _get_current_session(self): # -> LiveSession, TODO: export it in omni.kit.usd.layers
return self._live_syncing.get_current_live_session()
def _is_owner(self, session) -> bool:
return session.merge_permission | 4,360 | Python | 41.339805 | 101 | 0.630734 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/timeline_listener.py | import asyncio
import carb
import omni.kit.app
import omni.timeline
import omni.usd
from typing import List
from .global_time import get_global_time_s
from .timeline_serializer import TimelineStateSerializer
from .sync_strategy import SyncStrategyDescriptor, SyncStrategyType, TimelineSyncStrategyExecutor
from .timeline_event import TimelineEvent
from .timeline_session_role import TimelineSessionRole
TIMESTAMP_SYNC_EPS = 1e-3 # 1 ms
class TimelineListener(TimelineSessionRole):
def __init__(
self,
usd_context_name: str,
serializer: TimelineStateSerializer,
session,
sync_strategy: SyncStrategyDescriptor = None
):
super().__init__(usd_context_name, serializer, session)
self._app_sub = None
self._is_director_timeline_supported = hasattr(self._main_timeline, 'set_director')
self._timeline_name = 'timeline_director'
if not self._is_director_timeline_supported:
carb.log_warn("Timeline sync: use a newer Kit version to support all features.")
self._director_timeline = self._main_timeline
self._controlled_timeline = None
else:
self._controlled_timeline = self._main_timeline
self._initialize_director_timeline()
if sync_strategy is None:
sync_strategy = SyncStrategyDescriptor(SyncStrategyType.DIFFERENCE_LIMITED)
self._timeline_sync_executor = TimelineSyncStrategyExecutor(sync_strategy, self._director_timeline)
def start_session(self, catch_up: bool = True) -> bool:
if not super().start_session():
return False
self._initialize_director_timeline()
self._serializer.initialize(
timeline=self._director_timeline,
synced_stage=self._synced_stage,
sending=False
)
asyncio.ensure_future(self._start_session(catch_up))
return True
@property
def sync_strategy(self):
return self._timeline_sync_executor
async def _start_session(self, catch_up):
# make sure the director is set before it recieves the updates
await omni.kit.app.get_app().next_update_async()
# catch up with the current state
if catch_up:
self._check_time(None)
self._app_sub = self._app_stream.create_subscription_to_pop(self._check_time)
def stop_session(self):
super().stop_session()
self._serializer.finalize()
if self._controlled_timeline is not None:
self._controlled_timeline.set_director(None)
omni.timeline.destroy_timeline(self._timeline_name)
self._app_sub = None
def enable_sync(self, enabled: bool):
if enabled == self._enable_sync:
return
super().enable_sync(enabled)
if enabled:
if self._synced_stage is None:
carb.log_error(f"{self.__class__}: could not find presence layer")
return
self._initialize_director_timeline()
self._serializer.initialize(
timeline=self._director_timeline,
synced_stage=self._synced_stage,
sending=False
)
self._timeline_sync_executor.reset()
asyncio.ensure_future(self._start_session(True))
else:
if self._controlled_timeline:
self._controlled_timeline.set_director(None)
self._app_sub = None
def get_latency_estimate(self) -> float:
return max(get_global_time_s() - self._last_update_timestamp, 0)
def _warn_once(self, tag: str, msg: str):
attr_name = "__logged_" + tag
if not hasattr(self, attr_name):
setattr(self, attr_name, False)
if not getattr(self, attr_name):
carb.log_warn(msg)
setattr(self, attr_name, True)
def _save_timestamp(self, timestamp: float):
if get_global_time_s() + TIMESTAMP_SYNC_EPS < timestamp:
self._warn_once(
"global_time_sync",
"Future timestamp received. Global time is inaccurate, latency estimates are unreliable."
)
self._last_update_timestamp = max(self._last_update_timestamp, timestamp)
def _update_latency_timestamp(self, events: List[TimelineEvent]):
if len(events) == 0:
self._save_timestamp(self._serializer.receiveTimestamp())
for event in events:
self._save_timestamp(event.timestamp)
def _check_time(self, _):
events = self._serializer.receiveTimelineUpdate()
actions_to_execute = events
self._update_latency_timestamp(events)
if self._timeline_sync_executor is not None:
actions_to_execute = self._timeline_sync_executor.process_events(events)
for event in actions_to_execute:
self._apply_time_event(event)
def _apply_time_event(self, event: TimelineEvent):
type_id = int(event.type)
if type_id == int(omni.timeline.TimelineEventType.PLAY):
self._director_timeline.play()
elif type_id == int(omni.timeline.TimelineEventType.PAUSE):
self._director_timeline.pause()
elif type_id == int(omni.timeline.TimelineEventType.STOP):
self._director_timeline.stop()
elif type_id == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED):
time = event.payload['currentTime']
self._director_timeline.set_current_time(time)
elif type_id == int(omni.timeline.TimelineEventType.LOOP_MODE_CHANGED):
looping = event.payload['looping']
self._director_timeline.set_looping(looping)
elif type_id == int(omni.timeline.TimelineEventType.ZOOM_CHANGED):
start_time, end_time = event.payload['startTime'], event.payload['endTime']
self._director_timeline.set_zoom_range(start_time, end_time)
def _initialize_director_timeline(self):
if self._controlled_timeline is None:
return
time = self._controlled_timeline.get_current_time()
playing = self._controlled_timeline.is_playing()
stopped = self._controlled_timeline.is_stopped()
self._director_timeline = omni.timeline.get_timeline_interface(self._timeline_name)
self._director_timeline.set_end_time(self._controlled_timeline.get_end_time())
self._director_timeline.set_start_time(self._controlled_timeline.get_start_time())
self._director_timeline.set_time_codes_per_second(self._controlled_timeline.get_time_codes_per_seconds())
self._director_timeline.set_current_time(time)
if not playing:
if stopped:
self._director_timeline.stop()
else:
self._director_timeline.pause()
self._director_timeline.commit()
self._controlled_timeline.set_director(self._director_timeline)
| 6,934 | Python | 39.086705 | 113 | 0.636141 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/timeline_session_role.py | import carb
import enum
import omni.timeline
import omni.usd
import omni.kit.collaboration.presence_layer as pl
from typing import Callable
from .timeline_serializer import TimelineStateSerializer
class TimelineSessionRoleType(enum.Enum):
LISTENER = 0,
PRESENTER = 1,
class TimelineSessionRole:
def __init__(self, usd_context_name: str, serializer: TimelineStateSerializer, session):
self._main_timeline = omni.usd.get_context(usd_context_name).get_timeline()
self._context = omni.usd.get_context()
self._synced_stage = pl.get_presence_layer_interface(self._context).get_shared_data_stage()
self._stage = self._context.get_stage()
self._app_stream = omni.kit.app.get_app().get_update_event_stream()
self._app_sub_user = None
self._enable_sync = True
self._serializer = serializer
from .timeline_session import TimelineSession
self._session: TimelineSession = session
self._last_update_timestamp: float = 0
def start_session(self) -> bool:
if self._synced_stage is None:
carb.log_error(f"{self.__class__}: could not find presence layer")
return False
self._app_sub_user = self._app_stream.create_subscription_to_pop(self._check_user_updates)
return True
def stop_session(self):
self._app_sub_user = None
def enable_sync(self, enabled: bool):
self._enable_sync = enabled
self._session._on_enable_sync(enabled)
def is_sync_enabled(self) -> bool:
return self._enable_sync
def get_latency_estimate(self) -> float:
"""
Returns estimated latency in seconds.
The accuracy depends on the error of synchronized global time.
"""
return 0
# TODO: consider moving _check methods to TimelineSession
def _check_user_updates(self, _):
self._check_presenter()
self._check_control_requests()
def _check_presenter(self):
presenter_id = self._serializer.receivePresenterUpdate()
if (self._session.presenter is None and presenter_id is None) or\
(self._session.presenter is not None and self._session.presenter.user_id == presenter_id):
return
self._session._on_presenter_changed(presenter_id)
def _check_control_requests(self):
request_list = self._serializer.receiveControlRequests()
users_want_control = self._session.get_request_control_ids()
# current behavior of receiveControlRequests:
# - returns _all_ positive requests (want_control=True)
# - returns some of the negative requests but not necessarily all of them
all_want_control = []
for request in request_list:
user_id = request[0]
want_control = request[1]
if want_control:
all_want_control.append(user_id)
if (want_control and user_id not in users_want_control) or\
(not want_control and user_id in users_want_control):
self._session._on_control_request_received(user_id, want_control)
for user_id in self._session.get_request_control_ids():
# Remove if not in the set of all users that want control
if user_id not in all_want_control:
self._session._on_control_request_received(user_id, False)
| 3,373 | Python | 38.232558 | 102 | 0.648088 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/ui_user_window.py | import omni.ui as ui
from .session_state import SessionState
from .sync_strategy import SyncStrategyType
from .timeline_listener import TimelineListener
from .timeline_session import TimelineSession
from .timeline_session_role import TimelineSessionRoleType
from functools import partial
scrollingframe_style = {
"background_color": 0xFF23211F,
"Label:selected": {"color": 0xFFFFFF00}
}
class UserWindow:
def __init__(self, session_state: SessionState):
self._session_state: SessionState = session_state
self._window = ui.Window(
"Timeline Session",
width=400,
height=500,
visible=False,
flags=0,
visibility_changed_fn=self.on_window_visibility_changed,
)
with self._window.frame:
self._ui_container = ui.Frame(build_fn=self._build_ui)
self._labels = []
self._selected_user = None
self._presenter_button = None
self._diff_slider = None
def show(self):
self._window.visible = True
self._ui_container.rebuild()
def hide(self):
self._window.visible = False
self._selected_user = None
def on_window_visibility_changed(self, visible):
if self._session_state is None:
return
if visible:
self._session_state.add_users_changed_fn(self._on_user_changed)
else:
self._session_state.remove_users_changed_fn(self._on_user_changed)
timeline_session = self._session_state.timeline_session
if timeline_session is not None:
if visible:
timeline_session.add_presenter_changed_fn(self._on_user_changed)
timeline_session.add_control_request_changed_fn(self._on_user_changed)
else:
timeline_session.remove_presenter_changed_fn(self._on_user_changed)
timeline_session.remove_control_request_changed_fn(self._on_user_changed)
def destroy(self):
self._presenter_button = None
self._diff_slider = None
self._ui_container.destroy()
self._ui_container = None
self._window.set_visibility_changed_fn(None)
self._window.destroy()
self._window = None
self._session_state = None
self._labels = []
self._selected_user = None
def _build_ui(self):
users = self._session_state.users
self._selected_user = None
timeline_session = self._session_state.timeline_session
if timeline_session is None:
with ui.HStack():
ui.Label("Timeline session is not available")
return
with ui.VStack():
ui.Label("Session Users", height=30)
self._labels = []
with ui.ScrollingFrame(width=390, height=200, style=scrollingframe_style):
with ui.VStack():
for user in users:
self._create_user_label(timeline_session, user)
ui.Label("Timeline Control Requests", height=30)
with ui.ScrollingFrame(width=390, height=100, style=scrollingframe_style):
with ui.VStack():
for user in timeline_session.get_request_controls():
self._create_user_label(timeline_session, user)
if timeline_session.am_i_owner():
with ui.HStack(height=50):
self._presenter_button = ui.Button("Set as Timeline Presenter",
clicked_fn=self._on_make_presenter_clicked,
visible=False)
elif not timeline_session.am_i_presenter():
with ui.HStack(height=50):
title = "Request Timeline Control"
if timeline_session.live_session_user in timeline_session.get_request_controls():
title = "Revoke Request"
self._presenter_button = ui.Button(title,
clicked_fn=self._on_request_control_clicked)
if not timeline_session.am_i_presenter():
with ui.VStack(height=50):
ui.Spacer()
with ui.HStack():
ui.Label('Allowed time difference from Presenter (sec): ')
self._diff_slider = ui.FloatSlider(name='tsync_maxdiff_slider', min=0, max=2)
if timeline_session.role is not None and\
hasattr(timeline_session.role, 'sync_strategy'):
listener: TimelineListener = timeline_session.role
strategy_desc = listener.sync_strategy.strategy_desc
self._diff_slider.model.set_value(strategy_desc.max_time_diff_sec)
self._diff_slider.model.add_value_changed_fn(self._on_diff_slider_changed)
ui.Spacer()
def _create_user_label(self, timeline_session: TimelineSession, user):
logged_str = f"[Current user]" if timeline_session.is_logged_user(user) else ""
owner_str = "[Owner]" if timeline_session.is_owner(user) else ""
presenter_str = "[Presenter]" if timeline_session.is_presenter(user) else ""
label = ui.Label(f'{user.user_name} ({user.from_app}) {owner_str}{presenter_str}{logged_str}',
height=0)
label.set_mouse_pressed_fn(partial(self._on_user_pressed, label, user))
self._labels.append(label)
def _on_user_pressed(self, label, user, x, y, a, b):
for l in self._labels:
l.selected = False
label.selected = True
self._selected_user = user
timeline_session = self._session_state.timeline_session
if self._presenter_button is not None and timeline_session is not None:
if timeline_session.am_i_owner():
self._presenter_button.visible = not timeline_session.is_presenter(user)
def _on_make_presenter_clicked(self):
if self._selected_user is not None and self._session_state.timeline_session is not None:
self._session_state.timeline_session.presenter = self._selected_user
def _on_request_control_clicked(self):
timeline_session = self._session_state.timeline_session
if timeline_session is not None:
current_user = timeline_session.live_session_user
want_control = current_user not in timeline_session.get_request_controls()
timeline_session.request_control(want_control)
def _on_user_changed(self, *_):
self._ui_container.rebuild()
def _on_diff_slider_changed(self, value):
timeline_session = self._session_state.timeline_session
if timeline_session is not None and timeline_session.role is not None and\
timeline_session.role_type == TimelineSessionRoleType.LISTENER and \
hasattr(timeline_session.role, 'sync_strategy'):
listener: TimelineListener = timeline_session.role
max_diff = value.as_float
strategy_desc = listener.sync_strategy.strategy_desc
strategy_desc.max_time_diff_sec = max_diff
strategy_desc.strategy_type = SyncStrategyType.DIFFERENCE_LIMITED
listener.sync_strategy.strategy_desc = strategy_desc
strategy_desc = listener.sync_strategy.strategy_desc
| 7,517 | Python | 44.289156 | 102 | 0.592657 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/live_session_extension.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 .session_state import SessionState
from .session_watcher import SessionWatcher
from .timeline_session import TimelineSession
from .ui_user_window import UserWindow
import omni.ext
_session_watcher = None
_window = None
class TimelineLiveSessionExtension(omni.ext.IExt):
def on_startup(self, ext_id):
usd_context_name = ""
global _session_watcher
_session_watcher = SessionWatcher(usd_context_name)
_session_watcher.start()
global _window
_window = UserWindow(_session_watcher.get_session_state())
def on_shutdown(self):
global _session_watcher
if _session_watcher is not None:
_session_watcher.stop()
# TODO: _session_watcher.destroy()
_session_watcher = None
global _window
if _window is not None:
_window.hide()
_window.destroy()
_window = None
def get_timeline_session() -> TimelineSession:
global _session_watcher
if _session_watcher is None:
return None
return _session_watcher.get_timeline_session()
def get_session_state() -> SessionState:
global _session_watcher
if _session_watcher is None:
return None
return _session_watcher.get_session_state()
def get_session_window() -> UserWindow:
global _window
return _window
| 1,771 | Python | 28.533333 | 76 | 0.693958 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/timeline_state.py | import enum
import omni.timeline
from typing import List, Union
# Consider moving these to the omni.timeline API
class PlayState(enum.Enum):
PLAYING = 0
PAUSED = 1
STOPPED = 2
def get_timeline_state(timeline) -> PlayState:
if timeline is None:
return None
if timeline.is_playing():
return PlayState.PLAYING
elif timeline.is_stopped():
return PlayState.STOPPED
return PlayState.PAUSED
def get_timeline_next_state(
current_state: PlayState,
event: Union[int, omni.timeline.TimelineEventType]
) -> PlayState:
if isinstance(event, omni.timeline.TimelineEventType):
event = int(event)
if current_state == PlayState.PLAYING:
if event == int(omni.timeline.TimelineEventType.STOP):
return PlayState.STOPPED
elif event == int(omni.timeline.TimelineEventType.PAUSE):
return PlayState.PAUSED
else:
return current_state
elif current_state == PlayState.PAUSED:
if event == int(omni.timeline.TimelineEventType.STOP):
return PlayState.STOPPED
elif event == int(omni.timeline.TimelineEventType.PLAY):
return PlayState.PLAYING
else:
return current_state
elif current_state == PlayState.STOPPED:
if event == int(omni.timeline.TimelineEventType.PLAY):
return PlayState.PLAYING
else:
return current_state
# Should not be called
return current_state
def get_timeline_next_events(
current_state: PlayState,
next_state: PlayState
) -> List[omni.timeline.TimelineEventType]:
if current_state == PlayState.PLAYING:
if next_state == PlayState.PAUSED:
return [omni.timeline.TimelineEventType.PAUSE]
elif next_state == PlayState.STOPPED:
return [omni.timeline.TimelineEventType.STOP]
elif current_state == PlayState.PAUSED:
if next_state == PlayState.PLAYING:
return [omni.timeline.TimelineEventType.PLAY]
elif next_state == PlayState.STOPPED:
return [omni.timeline.TimelineEventType.STOP]
elif current_state == PlayState.STOPPED:
if next_state == PlayState.PLAYING:
return [omni.timeline.TimelineEventType.PLAY]
elif next_state == PlayState.PAUSED:
return [omni.timeline.TimelineEventType.PLAY, omni.timeline.TimelineEventType.PAUSE]
return []
class TimelineState:
"""
All information that is required to cache timeline state.
Usually it is better to cache the state instead of using the timeline itself
because the timeline postpones state changes by one frame and we have no information
about its state change queue.
"""
def __init__(self, timeline = None):
state = PlayState.STOPPED
time = 0
looping = True
zoom_range = [0, 0]
if timeline is not None:
state = get_timeline_state(timeline)
time = timeline.get_current_time()
looping = timeline.is_looping()
zoom_range = [timeline.get_zoom_start_time(), timeline.get_zoom_end_time()]
self._state: PlayState = state
self._current_time: float = time
self._looping: bool = looping
self._zoom_range = zoom_range
@property
def state(self) -> PlayState:
return self._state
@state.setter
def state(self, state: PlayState):
self._state = state
@property
def current_time(self) -> float:
return self._current_time
@current_time.setter
def current_time(self, time: float):
self._current_time = time
@property
def looping(self) -> bool:
return self._looping
@looping.setter
def looping(self, value: bool):
self._looping = value
@property
def zoom_range(self):
return self._zoom_range
def set_zoom_range(self, start_time: float, end_time: float):
self._zoom_range = [start_time, end_time]
| 4,000 | Python | 29.541985 | 96 | 0.643 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/timeline_session.py | from carb import log_error
import omni.kit.usd.layers as layers
from typing import Callable, List
from .timeline_director import TimelineDirector
from .timeline_listener import TimelineListener
from .timeline_session_role import TimelineSessionRoleType, TimelineSessionRole
from .timeline_serializer import TimelinePrimSerializer
import omni.kit.notification_manager as nm
class TimelineSession:
def __init__(
self,
usd_context_name: str,
session_user: layers.LiveSessionUser,
session_state,
role: TimelineSessionRoleType = None
):
self._usd_context_name = usd_context_name
self._serializer = TimelinePrimSerializer()
self._session_user = session_user
self._is_running: bool = False
from .session_state import SessionState
self._session_state: SessionState = session_state
role_type = role
if role_type is None:
role_type = TimelineSessionRoleType.LISTENER
self._role: TimelineSessionRole = None
self._role_type: TimelineSessionRoleType = None
self._change_role(role_type)
self._owner: layers.LiveSessionUser = None
# We may not have the user when we can query the ID already
self._owner_id: str = None
self._presenter: layers.LiveSessionUser = None
self._control_requests: List[str] = [] # List of user IDs
self._presenter_changed_callbacks = []
self._request_control_callbacks = []
self._enable_sync_callbacks = []
def __del__(self):
self.destroy()
def destroy(self):
# TODO: role, is_running, serializer, etc.
self._presenter_changed_callbacks = []
self._control_requests = []
self._request_control_callbacks = []
self._enable_sync_callbacks = []
@property
def live_session_user(self) -> layers.LiveSessionUser:
return self._session_user
@property
def role_type(self) -> TimelineSessionRoleType:
return self._role_type
@property
def role(self) -> TimelineSessionRole:
return self._role
def start_session(self):
if self._role is None:
return
self._is_running = True
success = self._role.start_session()
self._control_requests = []
if success:
self._owner_id = self._serializer.receiveOwnerUpdate()
def stop_session(self):
if self._role is None:
return
self._is_running = False
self._role.stop_session()
self._control_requests = []
def is_running(self) -> bool:
return self._is_running
def enable_sync(self, enabled: bool):
if self._role is not None:
self._role.enable_sync(enabled)
def is_sync_enabled(self) -> bool:
return self._role is not None and self._role.is_sync_enabled()
@property
def owner_id(self) -> str:
if self.owner is not None:
return self.owner.user_id
elif self._owner_id is not None:
return self._owner_id
return None
@property
def owner(self) -> layers.LiveSessionUser:
return self._owner
@owner.setter
def owner(self, user: layers.LiveSessionUser):
if not self._is_running:
log_error(f'Session must be running to set the owner')
return
if user is not None:
self._owner_id = user.user_id
if (self._owner is None and user is None) or\
self._owner is not None and user is not None and\
self._owner.user_id == user.user_id:
# No change
return
self._owner = user
self._serializer.sendOwnerUpdate(user)
# clear all requests
if self.am_i_owner():
requests = self._serializer.receiveControlRequests()
for request in requests:
self._serializer.sendControlRequest(
user_id=request[0],
want_control=False,
from_owner=True
)
@property
def presenter(self) -> layers.LiveSessionUser:
return self._presenter
@presenter.setter
def presenter(self, user: layers.LiveSessionUser):
if not self._is_running:
log_error(f'Session must be running to set the presenter')
return
if (self._presenter is None and user is None) or\
self._presenter is not None and user is not None and\
self._presenter.user_id == user.user_id:
# No change
return
if not self.am_i_owner():
log_error(f'Only the session owner is allowed to set the presenter')
return
# Remove user from control requests
if user.user_id in self._control_requests:
self._on_control_request_received(user.user_id, False)
self._serializer.sendControlRequest(user.user_id, False, self.am_i_owner())
if user is not None:
self._on_presenter_changed(user.user_id)
self._serializer.sendPresenterUpdate(user)
def request_control(self, want_control: bool = True):
if not self._is_running:
log_error(f'Session must be running to request timeline control')
return
user = self._session_user
if user is not None:
if (want_control and user.user_id not in self._control_requests) or \
(not want_control and user.user_id in self._control_requests):
self._on_control_request_received(user.user_id, want_control)
self._serializer.sendControlRequest(user.user_id, want_control, self.am_i_owner())
def get_request_controls(self) -> List[layers.LiveSessionUser]:
users = []
for user_id in self._control_requests:
user = self._session_state.find_user(user_id)
if user is not None:
users.append(user)
return users
def get_request_control_ids(self) -> List[str]:
return self._control_requests
def add_presenter_changed_fn(self, callback: Callable[[layers.LiveSessionUser], None]):
if callback not in self._presenter_changed_callbacks:
self._presenter_changed_callbacks.append(callback)
def remove_presenter_changed_fn(self, callback: Callable[[layers.LiveSessionUser], None]):
if callback in self._presenter_changed_callbacks:
self._presenter_changed_callbacks.remove(callback)
def add_control_request_changed_fn(self, callback: Callable[[layers.LiveSessionUser, bool], None]):
if callback not in self._request_control_callbacks:
self._request_control_callbacks.append(callback)
def remove_control_request_changed_fn(self, callback: Callable[[layers.LiveSessionUser, bool], None]):
if callback in self._request_control_callbacks:
self._request_control_callbacks.remove(callback)
def add_enable_sync_changed_fn(self, callback: Callable[[bool], None]):
if callback not in self._enable_sync_callbacks:
self._enable_sync_callbacks.append(callback)
def remove_enable_sync_changed_fn(self, callback: Callable[[bool], None]):
if callback in self._enable_sync_callbacks:
self._enable_sync_callbacks.remove(callback)
def is_owner(self, user: layers.LiveSessionUser) -> bool:
return user is not None and self._owner is not None and\
user.user_id == self._owner.user_id
def is_presenter(self, user: layers.LiveSessionUser) -> bool:
return user is not None and self._presenter is not None and\
user.user_id == self._presenter.user_id
def is_logged_user(self, user: layers.LiveSessionUser) -> bool:
return user is not None and self._session_user is not None and\
user.user_id == self._session_user.user_id
def am_i_owner(self) -> bool:
return self.is_owner(self._session_user)
def am_i_presenter(self) -> bool:
return self.is_presenter(self._session_user)
def _do_change_role(self, role_type: TimelineSessionRoleType):
# TODO: we don't really need the user change listener at the owner client
# (the owner sets it)
if self._role_type == TimelineSessionRoleType.LISTENER:
self._role = TimelineListener(self._usd_context_name, self._serializer, self)
elif self._role_type == TimelineSessionRoleType.PRESENTER:
self._role = TimelineDirector(self._usd_context_name, self._serializer, self)
def _change_role(self, role_type: TimelineSessionRoleType):
if self._role_type is not None and self._role_type == role_type:
return
self._role_type = role_type
if self._role is not None:
if self._is_running:
self._role.stop_session()
self._do_change_role(role_type)
if self._is_running:
# This also calls self._role.start_session()
self.start_session()
def _on_presenter_changed(self, user_id: str):
user = self._session_state.find_user(user_id)
if user is None:
# TODO: if None and we are Presenters, become listener?
return
was_current_user_presenter = self.am_i_presenter()
self._presenter = user
if user_id is not None and self._session_user is not None and\
user_id == self._session_user.user_id:
self._change_role(TimelineSessionRoleType.PRESENTER)
nm.post_notification(
"You are now the timeline presenter.",
status=nm.NotificationStatus.INFO
)
else:
if was_current_user_presenter:
nm.post_notification(
"You are no longer the timeline presenter.",
status=nm.NotificationStatus.INFO
)
self._change_role(TimelineSessionRoleType.LISTENER)
for callback in self._presenter_changed_callbacks:
callback(self._presenter)
def _on_control_request_received(self, user_id: str, want_control: bool):
user = self._session_state.find_user(user_id)
if user is None:
return
if self.am_i_owner() and want_control:
nm.post_notification(
f"User {user.user_name} requested to control the timeline.",
status=nm.NotificationStatus.INFO
)
# NOTE: checks are done on the caller side
if want_control:
self._control_requests.append(user_id)
else:
self._control_requests.remove(user_id)
for callback in self._request_control_callbacks:
callback(user, want_control)
def _on_enable_sync(self, is_sync_enabled: bool):
for callback in self._enable_sync_callbacks:
callback(is_sync_enabled)
| 10,930 | Python | 36.307167 | 106 | 0.617475 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/session_state.py | from carb import log_error
import omni.kit.usd.layers as layers
from .timeline_session import TimelineSession
from typing import List, Callable
User = layers.LiveSessionUser
class SessionState:
def __init__(self):
self._users: List[User] = []
self._timeline_session: TimelineSession = None
self._users_changed_callbacks = []
def add_users(self, users: List[User]):
self._users.extend(users)
self._notify_users_changed(users)
def remove_user(self, user_id: str):
self._users = list(filter(lambda user: user.user_id != user_id, self._users))
# TODO: pass the removed user
self._notify_users_changed([])
def destroy(self):
self.clear_users()
self._timeline_session = None
self._users_changed_callbacks = []
def clear_users(self):
users = self._users
self._users = []
self._notify_users_changed(users)
def find_user(self, user_id: str) -> User:
for user in self._users:
if user.user_id == user_id:
return user
return None
@property
def users(self) -> List[User]:
return self._users
@property
def timeline_session(self) -> TimelineSession:
return self._timeline_session
@timeline_session.setter
def timeline_session(self, session: TimelineSession):
self._timeline_session = session
def add_users_changed_fn(self, callback: Callable[[List[User]], None]):
if callback not in self._users_changed_callbacks:
self._users_changed_callbacks.append(callback)
def remove_users_changed_fn(self, callback: Callable[[List[User]], None]):
if callback in self._users_changed_callbacks:
self._users_changed_callbacks.remove(callback)
def _notify_users_changed(self, users: List[User]):
for callback in self._users_changed_callbacks:
callback(users)
| 1,953 | Python | 29.53125 | 85 | 0.631848 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/tests/test_ui_window.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 omni.kit.ui_test as ui_test
import omni.kit.usd.layers as layers
import omni.ui
import omni.usd
from omni.timeline.live_session.session_state import SessionState
from omni.timeline.live_session.timeline_session import TimelineSession
from omni.timeline.live_session.timeline_session_role import TimelineSessionRoleType
from omni.timeline.live_session.ui_user_window import UserWindow
from omni.ui.tests.test_base import OmniUiTest
# for clean up state
from ..live_session_extension import _session_watcher as g_session_watcher
class TestUiWindow(OmniUiTest):
fail_on_log_error = False
async def setUp(self):
await super().setUp()
self._window: UserWindow = None
self._usd_context = None
self._layers = None
self._live_syncing = None
g_session_watcher.start()
async def tearDown(self):
g_session_watcher.stop()
if self._window is not None:
self._window.hide()
self._window.destroy()
self._destroy_stage()
await super().tearDown()
async def _setup_stage(self):
self._usd_context = omni.usd.get_context()
self._layers = layers.get_layers(self._usd_context)
self._live_syncing = layers.get_live_syncing(self._usd_context)
await self._usd_context.new_stage_async()
def _destroy_stage(self):
self._usd_context = None
self._layers = None
self._live_syncing = None
async def test_show_hide_window(self):
self._window = UserWindow(SessionState())
self._window._window.title = "Timeline Session Test"
window_ref = ui_test.find("Timeline Session Test")
self.assertIsNotNone(window_ref)
self.assertFalse(window_ref.window.visible)
self._window.show()
self.assertTrue(window_ref.window.visible)
self._window.hide()
self.assertFalse(window_ref.window.visible)
async def test_no_session(self):
self._window = UserWindow(SessionState())
self._window._window.title = "Timeline Session Test"
window_ref = ui_test.find("Timeline Session Test")
label = window_ref.find_all("**/Label[*]")
self.assertEqual(len(label), 1)
self.assertTrue(label[0].widget.text == "Timeline session is not available")
async def test_display_user(self):
session_state = SessionState()
owner = layers.LiveSessionUser("owner", "owner_id", "test")
user1 = layers.LiveSessionUser("user1", "user1_id", "test")
user2 = layers.LiveSessionUser("user2", "user2_id", "test")
timeline_session = TimelineSession("", owner, session_state, TimelineSessionRoleType.PRESENTER)
session_state.timeline_session = timeline_session
self._window = UserWindow(session_state)
self._window._window.title = "Timeline Session Test"
# register ui building callback
self._window.show()
window_ref = ui_test.find("Timeline Session Test")
labels = window_ref.find_all("**/Label[*]")
# without users
field_texts = ["Session Users", "Timeline Control Requests", "Allowed time difference from Presenter (sec): "]
for index, label in enumerate(labels):
self.assertTrue(label.widget.text, field_texts[index])
# add users
session_state.add_users([owner, user1])
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
self.assertEqual(len(users), 2)
current_users = ["owner (test) [Current user]", "user1 (test)"]
for index, user in enumerate(users):
self.assertTrue(user.widget.text, current_users[index])
session_state.add_users([user2])
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
self.assertEqual(len(users), 3)
self.assertTrue(users[2].widget.text, "user2 (test)")
# remove user
session_state.remove_user("user2_id")
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
self.assertEqual(len(users), 2)
for index, user in enumerate(users):
self.assertTrue(user.widget.text, current_users[index])
async def test_requst_control_list(self):
session_state = SessionState()
owner = layers.LiveSessionUser("owner", "owner_id", "test")
user1 = layers.LiveSessionUser("user1", "user1_id", "test")
timeline_session = TimelineSession("", owner, session_state, TimelineSessionRoleType.PRESENTER)
session_state.timeline_session = timeline_session
self._window = UserWindow(session_state)
self._window._window.title = "Timeline Session Test"
# register ui building callback
self._window.show()
window_ref = ui_test.find("Timeline Session Test")
session_state.add_users([owner, user1])
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
# workaround to request timeline control for UI tests
timeline_session._is_running = True
request_control_btn = window_ref.find('**/Button[*].text == "Request Timeline Control"')
self.assertIsNotNone(request_control_btn)
await request_control_btn.click()
self.assertIsNotNone(
window_ref.find(f'**/ScrollingFrame[1]/VStack[0]/Label[0].text == "{users[0].widget.text}"')
)
revoke_btn = window_ref.find('**/Button[*].text == "Revoke Request"')
self.assertIsNotNone(revoke_btn)
await revoke_btn.click()
self.assertEqual(len(window_ref.find_all(f"**/ScrollingFrame[1]/VStack[0]/Label[*]")), 0)
# click user
await users[0].click()
self.assertIsNone(window_ref.find('**/Button[*].text == "Set as Timeline Presenter"'))
## request control list user click
request_ids = ["owner_id", "user1_id"]
timeline_session._control_requests.extend(request_ids)
## force rebuild ui
self._window.show()
request_control_users = window_ref.find_all("**/ScrollingFrame[1]/VStack[0]/Label[*]")
await request_control_users[0].click()
self.assertIsNone(window_ref.find('**/Button[*].text == "Set as Timeline Presenter"'))
async def test_btns(self):
session_state = SessionState()
owner = layers.LiveSessionUser("owner", "owner_id", "test")
user1 = layers.LiveSessionUser("user1", "user1_id", "test")
timeline_session = TimelineSession("", owner, session_state, TimelineSessionRoleType.PRESENTER)
session_state.timeline_session = timeline_session
self._window = UserWindow(session_state)
self._window._window.title = "Timeline Session Test"
# register ui building callback
self._window.show()
window_ref = ui_test.find("Timeline Session Test")
session_state.add_users([owner, user1])
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
# non-owner buttons
self.assertIsNone(window_ref.find('**/Button[*].text == "Set as Timeline Presenter"'))
# set owner
# workaround to set owner for UI tests
timeline_session._is_running = True
timeline_session.owner = owner
## force rebuild ui
self._window.show()
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
owner = window_ref.find("**/ScrollingFrame[0]/VStack[0]/Label[0]")
self.assertIsNotNone(owner)
self.assertTrue(users[0].widget.text, "owner (test) [Owner][Current user]")
presenter_btn = window_ref.find('**/Button[*].text == "Set as Timeline Presenter"')
self.assertIsNotNone(presenter_btn)
self.assertFalse(presenter_btn.widget.visible)
self.assertIsNone(window_ref.find('**/Button[*].text == "Request Timeline Control"'))
# click user as a onwer
## make myself as a presenter
await users[0].click()
self.assertTrue(presenter_btn.widget.visible)
await presenter_btn.click()
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
owner = window_ref.find("**/ScrollingFrame[0]/VStack[0]/Label[0]")
self.assertIsNotNone(owner)
self.assertTrue(users[0].widget.text, "owner (test) [Owner][Presenter][Current user]")
self.assertIsNone(window_ref.find('**/Label[*].text == "Allowed time difference from Presenter (sec): "'))
presenter_btn = window_ref.find('**/Button[*].text == "Set as Timeline Presenter"')
self.assertFalse(presenter_btn.widget.visible)
await users[0].click()
self.assertFalse(presenter_btn.widget.visible)
## make user1 as a presenter from control request list
request_ids = ["owner_id", "user1_id"]
timeline_session._control_requests = request_ids
## force rebuild ui
self._window.show()
await window_ref.find('**/ScrollingFrame[1]/**/Label[*].text == "user1 (test) "').click()
presenter_btn = window_ref.find('**/Button[*].text == "Set as Timeline Presenter"')
self.assertTrue(presenter_btn.widget.visible)
# workaround for being a listener to test UI
timeline_session._role_type = TimelineSessionRoleType.LISTENER
await presenter_btn.click()
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
self.assertIsNotNone(
window_ref.find('**/ScrollingFrame[0]/VStack[0]/Label[*].text == "user1 (test) [Presenter]"')
)
self.assertIsNone(window_ref.find('**/ScrollingFrame[1]/VStack[0]/Label[*].text == "user1 (test) "'))
self.assertIsNone(window_ref.find('**/ScrollingFrame[1]/VStack[0]/Label[*].text == "user1 (test) [Presenter]"'))
## make myself as a presenter from control request list
request_control_users = window_ref.find_all("**/ScrollingFrame[1]/VStack[0]/Label[*]")
await request_control_users[0].click()
self.assertTrue(presenter_btn.widget.visible)
# workaround for being a presenter to test UI
timeline_session._role_type = TimelineSessionRoleType.PRESENTER
await presenter_btn.click()
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
self.assertIsNotNone(
window_ref.find(
'**/ScrollingFrame[0]/VStack[0]/Label[*].text == "owner (test) [Owner][Presenter][Current user]"'
)
)
self.assertIsNone(
window_ref.find('**/ScrollingFrame[1]/VStack[0]/Label[*].text == "owner (test) [Owner][Current user]"')
)
self.assertIsNone(
window_ref.find(
'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "owner (test) [Owner][Presenter][Current user]"'
)
)
## make user1 as a presenter
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
await users[1].click()
self.assertTrue(presenter_btn.widget.visible)
### workaround for not printing error log of timeline_session_role
### since we do not care the functionalities timeline_session_role in this test
timeline_session._role_type = TimelineSessionRoleType.LISTENER
await presenter_btn.click()
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
self.assertIsNotNone(
window_ref.find('**/ScrollingFrame[0]/VStack[0]/Label[*].text == "user1 (test) [Presenter]"')
)
async def test_time_difference_slider(self):
session_state = SessionState()
owner = layers.LiveSessionUser("owner", "owner_id", "test")
user1 = layers.LiveSessionUser("user1", "user1_id", "test")
timeline_session = TimelineSession("", owner, session_state, TimelineSessionRoleType.LISTENER)
session_state.timeline_session = timeline_session
self._window = UserWindow(session_state)
self._window._window.title = "Timeline Session Test"
# register ui building callback
self._window.show()
window_ref = ui_test.find("Timeline Session Test")
session_state.add_users([owner, user1])
users = window_ref.find_all("**/ScrollingFrame[0]/VStack[0]/Label[*]")
slider = window_ref.find('**/FloatSlider[*].name == "tsync_maxdiff_slider"')
self.assertIsNotNone(slider)
await slider.input("0")
self.assertEqual(timeline_session.role.sync_strategy.strategy_desc.max_time_diff_sec, 0)
await slider.input("1")
self.assertEqual(timeline_session.role.sync_strategy.strategy_desc.max_time_diff_sec, 1.0)
await slider.input("1.7")
self.assertEqual(timeline_session.role.sync_strategy.strategy_desc.max_time_diff_sec, 1.7)
await slider.input("2")
self.assertEqual(timeline_session.role.sync_strategy.strategy_desc.max_time_diff_sec, 2.0)
| 13,361 | Python | 41.826923 | 120 | 0.642317 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/tests/mock_utils.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 typing import List
import omni.kit.usd.layers as layers
import omni.timeline
import omni.ui
import omni.usd
from ..session_state import SessionState
from ..sync_strategy import SyncStrategyDescriptor, SyncStrategyType, TimelineSyncStrategyExecutor
from ..timeline_session import TimelineSession
from ..timeline_session_role import TimelineSessionRoleType
from ..ui_user_window import UserWindow
def print_widget_tree(widget: omni.ui.Widget, level: int = 0):
# Prints the widget tree to the console
print(" " * level + str(widget.__class__.__name__))
for child in omni.ui.Inspector.get_children(widget):
print_widget_tree(child, level + 1)
# making sure context and timeline are unique
_cnt = 0
# need to re-write this once we have mock live session joiner
# for now, it hacks timeline to simulate joiner
class MockTimelineSession(TimelineSession):
def __init__(
self,
usd_context_name: str,
session_user: layers.LiveSessionUser,
session_state,
role: TimelineSessionRoleType,
hijack_timeline_fn,
):
self._hijack_timeline_fn = hijack_timeline_fn
super().__init__(usd_context_name, session_user, session_state, role)
# hijack _do_change_role role inorder to hijack director timeline
def _do_change_role(self, role_type: TimelineSessionRoleType):
super()._do_change_role(role_type)
self._hijack_timeline_fn(self)
class MockJoiner:
def __init__(
self,
main_timeline: omni.timeline.Timeline,
user: layers.LiveSessionUser,
sync_strategy_type: SyncStrategyType = SyncStrategyType.DIFFERENCE_LIMITED,
):
# hijack director timeline for making sure `mock_timeline_session` the timeline could achieve the same state as the main timeline
self.joiner = user
self.mock_timeline_usd_context = omni.usd.create_context(f"test_another_timeline_contex_{self.joiner.user_id}")
self.mock_timeline_usd_context.set_timeline(f"mock timeline {self.joiner.user_id}")
self.mock_timeline = self.mock_timeline_usd_context.get_timeline()
self.mock_director_timeline_name = f"mock director timeline: {user.user_id}"
self.mock_director_timeline = omni.timeline.get_timeline_interface(self.mock_director_timeline_name)
self.has_copied_from_main_timeline = False
def hijack_timeline_fn(mock_timeline_session: MockTimelineSession):
if mock_timeline_session.role_type != TimelineSessionRoleType.LISTENER:
return
self._copy_from_main_timeline(self.mock_timeline, main_timeline)
mock_timeline_session.role._director_timeline = None
mock_timeline_session.role._timeline_sync_executor._timeline = None
omni.timeline.destroy_timeline(mock_timeline_session.role._timeline_name)
mock_timeline_session.role._timeline_name = self.mock_director_timeline_name
mock_timeline_session.role._timeline_sync_executor = TimelineSyncStrategyExecutor(
SyncStrategyDescriptor(sync_strategy_type), self.mock_director_timeline
)
# mock timeline session
self.mock_session_state = SessionState()
self.mock_timeline_session = MockTimelineSession(
self.mock_timeline_usd_context.get_name(),
self.joiner,
self.mock_session_state,
TimelineSessionRoleType.LISTENER,
hijack_timeline_fn,
)
self.mock_session_state.timeline_session = self.mock_timeline_session
self.mock_session_state.add_users([self.joiner])
# mock window
self.window = UserWindow(self.mock_session_state)
self.window._window.title = f"Timeline Session Test {user.user_name}"
def set_current_time(self, time: float) -> None:
self.mock_timeline.set_current_time(time)
def get_current_time(self) -> float:
return self.mock_timeline.get_current_time()
def get_time_codes_per_seconds(self) -> float:
return self.mock_timeline.get_time_codes_per_seconds()
def is_playing(self) -> bool:
return self.mock_timeline.is_playing()
def is_stopped(self) -> bool:
return self.mock_timeline.is_stopped()
def is_looping(self) -> bool:
return self.mock_timeline.is_looping()
def play(self) -> None:
self.mock_timeline.play()
def commit_received_update_timeline_events(self) -> None:
self.mock_director_timeline.commit()
def commit(self) -> None:
self.mock_timeline.commit()
def get_window_title(self) -> str:
return self.window._window.title
def destroy(self) -> None:
self.window.destroy()
self.mock_timeline_session.stop_session()
self.mock_timeline.set_director(None)
self.mock_timeline.stop()
self.mock_timeline.commit()
self.mock_timeline = None
self.mock_director_timeline = None
omni.timeline.destroy_timeline(self.mock_timeline_usd_context.get_timeline_name())
omni.timeline.destroy_timeline(self.mock_director_timeline_name)
omni.usd.destroy_context(self.mock_timeline_usd_context.get_name())
self.mock_timeline_usd_context = None
# simulate open main timeline from live layer
def _copy_from_main_timeline(self, mock_timeline: omni.timeline.Timeline, main_timeline: omni.timeline.Timeline):
if self.has_copied_from_main_timeline:
return
self.has_copied_from_main_timeline = True
mock_timeline.set_end_time(main_timeline.get_end_time())
mock_timeline.set_start_time(main_timeline.get_start_time())
mock_timeline.set_time_codes_per_second(main_timeline.get_time_codes_per_seconds())
mock_timeline.commit()
return mock_timeline
# need to replace this session_watcher once we have mock live session joiner
class MockJoinerManager:
def __init__(self):
self._joiners: List[MockJoiner] = []
def create_joiner(
self,
main_timeline: omni.timeline.Timeline,
user_name: str,
user_id: str,
owner: layers.LiveSessionUser,
sync_strategy_type: SyncStrategyType = SyncStrategyType.DIFFERENCE_LIMITED,
) -> MockJoiner:
global _cnt
cnt = _cnt
_cnt += 1
joiner_id = len(self._joiners)
mock_joiner = MockJoiner(
main_timeline,
layers.LiveSessionUser(
f"{user_name}_{joiner_id}", f"{user_id}_{joiner_id}_test_cnt_{cnt}", "timeline live_session test"
),
sync_strategy_type,
)
# simulate session watcher
mock_joiner.mock_session_state.add_users([owner])
for joiner in self._joiners:
joiner.mock_session_state.add_users([mock_joiner.joiner])
mock_joiner.mock_session_state.add_users([joiner.joiner])
self._joiners.append(mock_joiner)
return mock_joiner
def destroy_joiners(self):
for mock_joiner in self._joiners:
mock_joiner.destroy()
self._joiners = []
| 7,546 | Python | 37.116161 | 137 | 0.672012 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/tests/tests.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 unittest
import asyncio
from typing import List
import carb
import omni.kit.collaboration.presence_layer as pl
import omni.kit.test
import omni.kit.ui_test as ui_test
import omni.kit.usd.layers as layers
import omni.timeline
import omni.timeline.live_session as ls
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi
from pxr import Sdf, Usd
# for clean up state
from ..live_session_extension import _session_watcher as g_session_watcher
from ..sync_strategy import SyncStrategyType
from ..timeline_serializer import LOOPING_ATTR_NAME, PLAYSTATE_ATTR_NAME, TIME_ATTR_NAME, TIMELINE_PRIM_PATH
from ..timeline_session import TimelineSession
from ..ui_user_window import UserWindow
from .mock_utils import MockJoiner, MockJoinerManager
_fake_layer = None
class TestTimeline(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._app = omni.kit.app.get_app()
self._usd_context = omni.usd.get_context()
self._layers = layers.get_layers(self._usd_context)
self._live_syncing = layers.get_live_syncing(self._usd_context)
self._timeline = self._usd_context.get_timeline()
self._end_time = 94874897
self._simulated_user_name = "test"
self._simulated_user_id = "abcde"
self._users = None
self._presenter = None
self._control_request = None
self._want_control = False
g_session_watcher.start()
self._mock_joiner_manager = MockJoinerManager()
# need to create new window for every test case
self._window = UserWindow(ls.get_session_state())
self._window_title = "Timeline Session Test Owner"
self._window._window.title = self._window_title
async def tearDown(self):
self._window.destroy()
self._window = None
self._mock_joiner_manager.destroy_joiners()
self._mock_joiner_manager = None
g_session_watcher.stop()
if self._usd_context.get_stage():
await self._usd_context.close_stage_async()
self._stage = None
self._fake_layer.Clear()
await self._reset_timeline()
self._live_syncing.stop_all_live_sessions()
self._layers.get_event_stream().pump()
await self.wait(50)
async def wait(self, frames=10):
for _ in range(frames):
await self._app.next_update_async()
async def _reset_timeline(self):
self._timeline.stop()
self._timeline.clear_zoom()
self._timeline.set_current_time(0.0)
self._timeline.set_end_time(self._end_time)
self._timeline.set_start_time(0.0)
self._timeline.set_director(None)
self._timeline.commit()
async def _create_session(self):
self._stage_url = "omniverse://__faked_omniverse_server__/test/test.usd"
global _fake_layer
if _fake_layer is None:
_fake_layer = Sdf.Layer.New(Sdf.FileFormat.FindByExtension(".usd"), self._stage_url)
self._fake_layer = _fake_layer
self._stage = Usd.Stage.Open(self._fake_layer)
await self._usd_context.attach_stage_async(self._stage)
session = self._live_syncing.find_live_session_by_name(self._stage_url, "test")
if not session:
session = self._live_syncing.create_live_session("test", self._stage_url)
self.assertTrue(session, "Failed to create live session.")
await self._reset_timeline()
self.assertTrue(self._live_syncing.join_live_session(session))
await self.wait()
self.assertTrue(self._live_syncing.is_in_live_session())
presence_layer = pl.get_presence_layer_interface(self._usd_context)
self.assertIsNotNone(presence_layer)
self._presence_stage: Usd.Stage = presence_layer.get_shared_data_stage()
self.assertIsNotNone(self._presence_stage)
async def _simulate_user_join(self, user_name, user_id) -> layers.LiveSessionUser:
user = layers.LiveSessionUser(user_name, user_id, "Create")
await self._simulate_user_join_with_user_object(user)
return user
async def _simulate_user_join_with_user_object(self, user: layers.LiveSessionUser):
# Access private variable to simulate user login.
current_session = self._live_syncing.get_current_live_session()
session_channel = current_session._session_channel()
session_channel._peer_users[user.user_id] = user
session_channel._send_layer_event(
layers.LayerEventType.LIVE_SESSION_USER_JOINED, {"user_name": user.user_name, "user_id": user.user_id}
)
await self.wait()
@MockLiveSyncingApi
async def test_state(self):
state = ls.get_session_state()
# Initial state, no live session
session = ls.get_timeline_session()
self.assertIsNone(session)
self.assertIsNotNone(state)
self.assertEqual(len(state.users), 0)
# Create live session, test TimelineSession
state.add_users_changed_fn(self._on_users_changed)
await self._create_session()
session = ls.get_timeline_session()
self.assertTrue(session.is_running())
self.assertIsNotNone(session.live_session_user)
self.assertIsNotNone(session.owner)
self.assertIsNotNone(session.presenter)
self.assertTrue(session.am_i_owner())
self.assertTrue(session.am_i_presenter())
self.assertEqual(session.owner_id, session.live_session_user.user_id)
self.assertTrue(session.is_logged_user(session.live_session_user))
self.assertTrue(session.is_owner(session.live_session_user))
self.assertTrue(session.is_presenter(session.live_session_user))
self.assertEqual(len(session.get_request_controls()), 0)
self.assertEqual(len(session.get_request_control_ids()), 0)
self.assertTrue(session.is_sync_enabled())
self.assertIsNotNone(session.role)
self.assertEqual(session.role_type, ls.TimelineSessionRoleType.PRESENTER)
self.assertEqual(len(state.users), 1)
self.assertEqual(state.users[0], session.live_session_user)
self._assert_users_and_clear(1, session.live_session_user)
# Join a new user
new_user = await self._simulate_user_join(self._simulated_user_name, self._simulated_user_id)
users_with_new_id = [user for user in state.users if user.user_id == self._simulated_user_id]
self.assertEqual(len(users_with_new_id), 1)
new_user_from_session = users_with_new_id[0]
self._assert_users_and_clear(1, new_user_from_session)
self.assertTrue(session.am_i_owner())
self.assertTrue(session.am_i_presenter())
self.assertFalse(session.is_owner(new_user_from_session))
self.assertFalse(session.is_presenter(new_user_from_session))
self.assertEqual(len(session.get_request_controls()), 0)
# Timeline state is sent properly
await self._test_timeline_send(session, state)
# Make the new user a presenter
session.add_presenter_changed_fn(self._on_presenter_changed)
session.presenter = new_user_from_session
await self.wait() # for timeline changes to become active
self.assertEqual(self._presenter, new_user_from_session) # callback
self.assertTrue(session.am_i_owner())
self.assertFalse(session.am_i_presenter())
self.assertFalse(session.is_owner(new_user_from_session))
self.assertTrue(session.is_presenter(new_user_from_session))
self.assertEqual(session.role_type, ls.TimelineSessionRoleType.LISTENER)
# We are listeners, cannot change the timeline
self.assertTrue(self._timeline.is_stopped()) # make sure synchronization does not interfere with the test
self._timeline.set_current_time(50)
self._timeline.play()
self._timeline.commit()
self.assertAlmostEqual(self._timeline.get_current_time(), 0)
self.assertTrue(self._timeline.is_stopped())
# Control request
session.add_control_request_changed_fn(self._on_control_request)
session.request_control(True)
await self.wait()
self.assertEqual(self._control_request, session.live_session_user) # callback
self.assertEqual(self._want_control, True) # callback
self.assertEqual(len(session.get_request_controls()), 1)
self.assertEqual(len(session.get_request_control_ids()), 1)
self.assertTrue(session.live_session_user in session.get_request_controls())
self.assertTrue(session.live_session_user.user_id in session.get_request_control_ids())
session.request_control(True) # send another control request, test that it is not duplicated
await self.wait()
self.assertEqual(len(session.get_request_controls()), 1)
self.assertEqual(len(session.get_request_control_ids()), 1)
session.request_control(False)
await self.wait()
self.assertEqual(self._control_request, session.live_session_user) # callback
self.assertEqual(self._want_control, False) # callback
self.assertEqual(len(session.get_request_controls()), 0)
self.assertEqual(len(session.get_request_control_ids()), 0)
self._control_request = None
session.request_control(False) # test that we don't crash when we remove the request twice
await self.wait()
self.assertIsNone(self._control_request)
self.assertEqual(len(session.get_request_controls()), 0)
self.assertEqual(len(session.get_request_control_ids()), 0)
# Timeline state is read properly
await self._test_timeline_receive(session, state)
# Stop session
session.stop_session()
self.assertFalse(session.is_running())
state.remove_users_changed_fn(self._on_users_changed)
session.remove_presenter_changed_fn(self._on_presenter_changed)
session.remove_control_request_changed_fn(self._on_control_request)
# This is implementation specific, used in the function below.
def _get_timeline_playstate(self) -> int:
if self._timeline.is_playing():
return 0
if self._timeline.is_stopped():
return 2
return 1
# As we don't have two clients, we test that the serializer changes the synchronization prim
# when the timeline is changed.
# This needs to be rewritten when the transmission protocol is changed.
async def _test_timeline_send(self, session, state):
timeline_prim: Usd.Prim = self._presence_stage.GetPrimAtPath(TIMELINE_PRIM_PATH)
self.assertTrue(timeline_prim.IsValid(), "Timeline prim needs to be created")
time = self._timeline.get_current_time()
looping = self._timeline.is_looping()
playstate = self._get_timeline_playstate()
time_attr = timeline_prim.GetAttribute(TIME_ATTR_NAME)
looping_attr = timeline_prim.GetAttribute(LOOPING_ATTR_NAME)
playstate_attr = timeline_prim.GetAttribute(PLAYSTATE_ATTR_NAME)
self.assertTrue(time_attr.IsValid())
self.assertTrue(looping_attr.IsValid())
self.assertTrue(playstate_attr.IsValid())
self.assertEqual(time_attr.Get(), time)
self.assertEqual(looping_attr.Get(), looping)
self.assertEqual(playstate_attr.Get(), playstate)
# change timeline values
time = time + 1
looping = not looping
self._timeline.set_current_time(time)
self._timeline.set_looping(looping)
self.assertFalse(self._timeline.is_playing()) # make sure time is not changed automatically
await self.wait()
self.assertEqual(time_attr.Get(), time)
self.assertEqual(looping_attr.Get(), looping)
self._timeline.play()
await self.wait()
self.assertEqual(playstate_attr.Get(), self._get_timeline_playstate())
# restore
self._timeline.stop()
self._timeline.set_current_time(0)
self._timeline.commit()
# As we don't have two clients, we test that the serializer reads the result
# when the synchronization prim is changed and applies it to the timeline.
# This needs to be rewritten when the transmission protocol is changed.
async def _test_timeline_receive(self, sesssion, state):
timeline_prim: Usd.Prim = self._presence_stage.GetPrimAtPath(TIMELINE_PRIM_PATH)
self.assertTrue(timeline_prim.IsValid(), "Timeline prim needs to be created")
time = self._timeline.get_current_time()
looping = self._timeline.is_looping()
self.assertFalse(self._timeline.is_playing())
playstate = self._get_timeline_playstate()
time_attr = timeline_prim.GetAttribute(TIME_ATTR_NAME)
looping_attr = timeline_prim.GetAttribute(LOOPING_ATTR_NAME)
playstate_attr = timeline_prim.GetAttribute(PLAYSTATE_ATTR_NAME)
self.assertTrue(time_attr.IsValid())
self.assertTrue(looping_attr.IsValid())
self.assertTrue(playstate_attr.IsValid())
self.assertEqual(time_attr.Get(), time)
self.assertEqual(looping_attr.Get(), looping)
self.assertEqual(playstate_attr.Get(), playstate)
# change prim values
time = time + 1
looping = not looping
time_attr.Set(time)
looping_attr.Set(looping)
await self.wait()
self.assertEqual(self._timeline.get_current_time(), time)
self.assertEqual(self._timeline.is_looping(), looping)
playstate_attr.Set(0)
await self.wait()
self.assertFalse(self._timeline.is_stopped()) # sync strategies may set to paused but not stopped
# restore
self._timeline.stop()
self._timeline.set_current_time(0)
self._timeline.commit()
def _on_users_changed(self, user_list):
self._users = user_list
def _assert_users_and_clear(self, expected_size, must_have_user):
self.assertIsNotNone(self._users)
self.assertEqual(len(self._users), expected_size)
if must_have_user is not None:
self.assertTrue(must_have_user in self._users)
self._users = None
def _on_presenter_changed(self, user):
self._presenter = user
def _on_control_request(self, user, want_control):
self._control_request = user
self._want_control = want_control
async def _mock_join_session(
self, sync_strategy_type: SyncStrategyType = SyncStrategyType.DIFFERENCE_LIMITED
) -> MockJoiner:
mock_joiner = self._mock_joiner_manager.create_joiner(
self._timeline,
self._simulated_user_name,
self._simulated_user_id,
ls.get_timeline_session().live_session_user,
sync_strategy_type,
)
mock_joiner.mock_timeline_session.start_session()
await self._simulate_user_join_with_user_object(mock_joiner.joiner)
return mock_joiner
async def _sync_received_update_events_from_presenter(
self, mock_joiners: List[MockJoiner], wait_frame: int = 10
) -> None:
await self.wait(wait_frame)
for mock_joiner in mock_joiners:
mock_joiner.commit_received_update_timeline_events()
# The following tests are written based on
# this doc: https://docs.google.com/document/d/1vx2OBSDVKa1GgKwswSY7qmqgpQq46Qnha8L92GCPQNs/edit?pli=1#heading=h.5tno0u5x49br
## 1. User (owner) creates a new session and joins it
### a. Expected: User becomes timeline presenter immediately
@MockLiveSyncingApi
async def test_create_and_join_session(self):
await self._create_session()
session = ls.get_timeline_session()
self.assertTrue(session.is_running())
self.assertIsNotNone(session.live_session_user)
self.assertIsNotNone(session.presenter)
self.assertTrue(session.am_i_presenter())
self.assertTrue(session.is_presenter(session.live_session_user))
## 2. Set state (e.g. time) to non-default for the presenter. Other users join.
### a Expected:
#### i. joining users become listeners, owner stays presenter
#### ii. joining users should pick up the synced state immediately
#### (test that this is also happening when the timeline is not playing!)
async def _test_change_state_before_other_joining(self, playing: bool):
await self._create_session()
# update timeline
modified_time = self._timeline.get_current_time() + 10
self._timeline.set_current_time(modified_time)
if playing:
# enable playing
self._timeline.play()
self._timeline.commit()
mock_joiner = await self._mock_join_session()
await self._sync_received_update_events_from_presenter([mock_joiner])
# make sure presenter does not change
origin_session = ls.get_timeline_session()
self.assertTrue(origin_session.is_presenter(origin_session.live_session_user))
self.assertEqual(len(ls.get_session_state().users), 2)
self.assertFalse(
mock_joiner.mock_timeline_session.is_presenter(mock_joiner.mock_timeline_session.live_session_user)
)
self.assertTrue(mock_joiner.mock_timeline_session.is_presenter(origin_session.live_session_user))
## joining users should pick up the synced state immediately
self.assertEqual(mock_joiner.get_time_codes_per_seconds(), self._timeline.get_time_codes_per_seconds())
self.assertEqual(mock_joiner.is_looping(), self._timeline.is_looping())
self.assertEqual(mock_joiner.is_playing(), self._timeline.is_playing())
self.assertEqual(mock_joiner.is_playing(), playing)
if not playing:
self.assertEqual(mock_joiner.get_current_time(), modified_time)
self.assertEqual(mock_joiner.get_current_time(), self._timeline.get_current_time())
else:
# By default, listeners employ interpolation to synchronize with the presenter's state.
# Therefore, we must introduce a delay to ensure smooth synchronization.
self.assertLessEqual(mock_joiner.get_current_time(), modified_time)
await self._sync_received_update_events_from_presenter([mock_joiner], 100)
self.assertGreaterEqual(mock_joiner.get_current_time(), modified_time)
self.assertAlmostEqual(mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1)
@MockLiveSyncingApi
async def test_change_state_before_other_joining_in_play_mode(self):
await self._test_change_state_before_other_joining(True)
@MockLiveSyncingApi
async def test_change_state_before_other_joining_in_stop_mode(self):
await self._test_change_state_before_other_joining(False)
## 3. Change time for the presenter
## 4. Same with playing, pause, stop
### i Expected: time should change for all listeners accordingly
async def _test_change_time_and_timeline_state(
self, presenter_timeline: omni.timeline.Timeline, listener_timelines: [omni.timeline.Timeline]
):
# change time
modified_time = presenter_timeline.get_current_time() + 10
presenter_timeline.set_current_time(modified_time)
presenter_timeline.commit()
self.assertEqual(presenter_timeline.get_current_time(), modified_time)
await self.wait()
for timeline in listener_timelines:
timeline.commit()
self.assertEqual(timeline.get_current_time(), modified_time)
self.assertEqual(timeline.get_current_time(), presenter_timeline.get_current_time())
# play
presenter_timeline.play()
presenter_timeline.commit()
self.assertTrue(presenter_timeline.is_playing())
await self.wait()
for timeline in listener_timelines:
timeline.commit()
self.assertAlmostEqual(timeline.get_current_time(), self._timeline.get_current_time(), delta=1)
self.assertEqual(timeline.is_playing(), self._timeline.is_playing())
self.assertEqual(timeline.is_playing(), True)
# pause
presenter_timeline.pause()
presenter_timeline.commit()
self.assertFalse(presenter_timeline.is_playing())
self.assertFalse(presenter_timeline.is_stopped())
await self.wait()
for timeline in listener_timelines:
timeline.commit()
self.assertAlmostEqual(timeline.get_current_time(), presenter_timeline.get_current_time(), delta=1)
self.assertEqual(timeline.is_playing(), presenter_timeline.is_playing())
self.assertEqual(timeline.is_playing(), False)
self.assertEqual(timeline.is_stopped(), presenter_timeline.is_stopped())
self.assertEqual(timeline.is_stopped(), False)
# stop
presenter_timeline.stop()
presenter_timeline.commit()
self.assertFalse(presenter_timeline.is_playing())
self.assertTrue(presenter_timeline.is_stopped())
await self.wait()
for timeline in listener_timelines:
timeline.commit()
self.assertEqual(timeline.get_current_time(), presenter_timeline.get_current_time())
self.assertEqual(timeline.is_playing(), presenter_timeline.is_playing())
self.assertEqual(timeline.is_playing(), False)
self.assertEqual(timeline.is_stopped(), presenter_timeline.is_stopped())
self.assertEqual(timeline.is_stopped(), True)
@MockLiveSyncingApi
async def test_change_time_and_timeline_state_for_presenter(self):
await self._create_session()
mock_joiner = await self._mock_join_session()
for _ in range(3):
await self._test_change_time_and_timeline_state(self._timeline, [mock_joiner.mock_timeline])
# 5. Turn timeline sync off for presenter, start changing time, playing, etc.
## a. Expected:
### i. time is unchanged for all listeners
### ii. UI that shows sync state at the presenter's Kit instance should show sync is off (`is_sync_enabled()` should be false)
### iii. UI at listeners shows they are still receiving updates (`is_sync_enabled()` should be true)
### and they still cannot control their own timeline (in fact we might change this design)
# 6. Turn back timeline sync for presenter.
## a. Expected: changes that are made for the presenter are synced at listeners;
## presenter's UI shows sync is on again (`is_sync_enabled()` should be true)
@MockLiveSyncingApi
async def test_presenter_turn_sync_off(self):
await self._create_session()
mock_joiner = await self._mock_join_session()
# sync up state
await self._sync_received_update_events_from_presenter([mock_joiner])
old_time = mock_joiner.get_current_time()
playing = mock_joiner.is_playing()
# turn off sync
def expect_false(enabled: bool) -> None:
return self.assertFalse(enabled)
ls.get_timeline_session().add_enable_sync_changed_fn(expect_false)
ls.get_timeline_session().enable_sync(False)
self.assertFalse(ls.get_timeline_session().is_sync_enabled())
# change time
modified_time = self._timeline.get_current_time() + 10
self._timeline.set_current_time(modified_time)
self._timeline.commit()
await self._sync_received_update_events_from_presenter([mock_joiner])
# listener is still in sync mode
self.assertTrue(mock_joiner.mock_timeline_session.is_sync_enabled())
self.assertEqual(mock_joiner.get_current_time(), old_time)
self.assertNotEqual(mock_joiner.get_current_time(), modified_time)
# play
self._timeline.play()
self._timeline.commit()
# play for a while
await self._sync_received_update_events_from_presenter([mock_joiner], 50)
self.assertEqual(mock_joiner.get_current_time(), old_time)
self.assertNotAlmostEqual(mock_joiner.get_current_time(), self._timeline.get_current_time())
self.assertNotEqual(mock_joiner.is_playing(), self._timeline.is_playing())
self.assertEqual(mock_joiner.is_playing(), playing)
# listenr try to modify timeline but fail
mock_joiner.set_current_time(modified_time)
mock_joiner.commit()
self.assertNotEqual(mock_joiner.get_current_time(), modified_time)
self.assertEqual(mock_joiner.get_current_time(), old_time)
mock_joiner.play()
await self._sync_received_update_events_from_presenter([mock_joiner])
self.assertEqual(mock_joiner.is_playing(), playing)
# make sure this callback is removed
ls.get_timeline_session().remove_enable_sync_changed_fn(expect_false)
ls.get_timeline_session().enable_sync(True)
self.assertTrue(ls.get_timeline_session().is_sync_enabled())
# listener should pick up the state from the presenter
await self._sync_received_update_events_from_presenter([mock_joiner])
self.assertEqual(mock_joiner.is_playing(), self._timeline.is_playing())
# By default, listeners employ interpolation to synchronize with the presenter's state.
# Therefore, we must introduce a delay to ensure smooth synchronization.
self.assertLessEqual(mock_joiner.get_current_time(), self._timeline.get_current_time())
await self._sync_received_update_events_from_presenter([mock_joiner], 100)
self.assertAlmostEqual(mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1)
# 7. Similar to the previous one,
# but testing allowed time difference: turn on and off timeline sync during playback.
## a. Expected:
### i. when sync is turned off during playback,
### listeners should pause after a while
### (which is determined by the allowed time difference setting,
### 0 = immediately, 1 sec = listeners should be 1 sec ahead when they pause).
### Test this carefully with looping, playing/pausing/stopping several times.
### ii. when sync is turned off and then on very rapidly,
### there should be minimal lag at listeners (which depends on the allowed time difference setting)
@MockLiveSyncingApi
async def test_presenter_turn_sync_on_and_off_during_playback(self):
# rounding to 1e-5
STRICT_MODE_EPS = 1e-5
await self._create_session()
default_mode_mock_joiner = await self._mock_join_session()
strict_mode_mock_joiner = await self._mock_join_session(SyncStrategyType.STRICT)
loose_mode_mock_joiner = await self._mock_join_session(SyncStrategyType.LOOSE)
async def play() -> None:
self._timeline.play()
self._timeline.commit()
await self._sync_received_update_events_from_presenter(
[default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner]
)
self.assertTrue(default_mode_mock_joiner.is_playing())
# In strict mode, the system adheres strictly to the presenter's timeline.
# Thus, we validate that the mock joiner isn't playing in this mode.
self.assertFalse(strict_mode_mock_joiner.is_playing())
self.assertTrue(loose_mode_mock_joiner.is_playing())
async def disable_sync_during_playing_and_wait_for_a_while():
ls.get_timeline_session().enable_sync(False)
self.assertFalse(ls.get_timeline_session().is_sync_enabled())
last_seen_time_from_presenter = self._timeline.get_current_time()
# wait for a while
await self._sync_received_update_events_from_presenter(
[default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner], 300
)
self.assertTrue(default_mode_mock_joiner.mock_timeline_session.is_sync_enabled())
self.assertTrue(strict_mode_mock_joiner.mock_timeline_session.is_sync_enabled())
self.assertTrue(loose_mode_mock_joiner.mock_timeline_session.is_sync_enabled())
self.assertFalse(default_mode_mock_joiner.is_playing())
self.assertFalse(strict_mode_mock_joiner.is_playing())
self.assertTrue(loose_mode_mock_joiner.is_playing())
# only follow the presenter
self.assertAlmostEqual(
last_seen_time_from_presenter, strict_mode_mock_joiner.get_current_time(), delta=STRICT_MODE_EPS
)
self.assertLess(last_seen_time_from_presenter, default_mode_mock_joiner.get_current_time())
# stop after listener's time is 1 + some eps ahead the last seen presenter time
self.assertAlmostEqual(
last_seen_time_from_presenter, default_mode_mock_joiner.get_current_time(), delta=1.5
)
# keep playing
self.assertLess(last_seen_time_from_presenter, loose_mode_mock_joiner.get_current_time())
async def enable_sync_during_playing() -> None:
# sync back
ls.get_timeline_session().enable_sync(True)
self.assertTrue(ls.get_timeline_session().is_sync_enabled())
await self._sync_received_update_events_from_presenter(
[default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner]
)
self.assertTrue(default_mode_mock_joiner.is_playing())
self.assertFalse(strict_mode_mock_joiner.is_playing())
self.assertTrue(loose_mode_mock_joiner.is_playing())
# in default mode, listeners employ interpolation to synchronize with the presenter's state.
# So it will not catch up immediately
self.assertLessEqual(default_mode_mock_joiner.get_current_time(), self._timeline.get_current_time())
# in strict mode, time should be synced with the presenter immediately
self.assertAlmostEqual(
strict_mode_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1
)
# in default mode, listeners employ interpolation to synchronize with the presenter's state.
# Therefore, we must introduce a delay to ensure smooth synchronization.
await self._sync_received_update_events_from_presenter(
[default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner], 100
)
self.assertAlmostEqual(
default_mode_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1
)
self.assertAlmostEqual(
strict_mode_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1
)
async def pause() -> None:
self._timeline.pause()
self._timeline.commit()
await self._sync_received_update_events_from_presenter(
[default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner]
)
self.assertFalse(default_mode_mock_joiner.is_playing())
self.assertFalse(strict_mode_mock_joiner.is_playing())
self.assertFalse(loose_mode_mock_joiner.is_playing())
self.assertAlmostEqual(
default_mode_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1
)
self.assertAlmostEqual(
strict_mode_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=STRICT_MODE_EPS
)
async def trigger_loop() -> None:
# trigger loop
self._timeline.set_current_time(self._end_time - 1)
self._timeline.commit()
await self._sync_received_update_events_from_presenter(
[default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner]
)
self.assertEqual(default_mode_mock_joiner.get_current_time(), self._timeline.get_current_time())
self.assertEqual(strict_mode_mock_joiner.get_current_time(), self._timeline.get_current_time())
self.assertEqual(loose_mode_mock_joiner.get_current_time(), self._timeline.get_current_time())
# play for a while to start from the begining
self._timeline.play()
self._timeline.commit()
await self._sync_received_update_events_from_presenter(
[default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner], 100
)
self.assertTrue(default_mode_mock_joiner.is_playing())
self.assertFalse(strict_mode_mock_joiner.is_playing())
self.assertTrue(loose_mode_mock_joiner.is_playing())
self.assertGreaterEqual(default_mode_mock_joiner.get_current_time(), 0)
self.assertGreaterEqual(strict_mode_mock_joiner.get_current_time(), 0)
self.assertGreaterEqual(loose_mode_mock_joiner.get_current_time(), 0)
async def stop() -> None:
self._timeline.stop()
self._timeline.commit()
await self._sync_received_update_events_from_presenter(
[default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner]
)
self.assertFalse(default_mode_mock_joiner.is_playing())
self.assertFalse(strict_mode_mock_joiner.is_playing())
self.assertFalse(loose_mode_mock_joiner.is_playing())
self.assertEqual(default_mode_mock_joiner.get_current_time(), 0)
self.assertEqual(strict_mode_mock_joiner.get_current_time(), 0)
self.assertEqual(loose_mode_mock_joiner.get_current_time(), 0)
# for joiners to sync up
await self._sync_received_update_events_from_presenter(
[default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner]
)
for _ in range(3):
for _ in range(2):
await play()
await disable_sync_during_playing_and_wait_for_a_while()
await enable_sync_during_playing()
# pause
await pause()
await play()
await disable_sync_during_playing_and_wait_for_a_while()
await enable_sync_during_playing()
await pause()
# loop
await trigger_loop()
await disable_sync_during_playing_and_wait_for_a_while()
await enable_sync_during_playing()
# stop
await stop()
await play()
await disable_sync_during_playing_and_wait_for_a_while()
await enable_sync_during_playing()
await stop()
# turn on and off very rapidly
await play()
# making sure default_mode_listener never pause
for _ in range(50):
ls.get_timeline_session().enable_sync(False)
ls.get_timeline_session().enable_sync(True)
self.assertTrue(default_mode_mock_joiner.is_playing())
await self.wait(1)
# 8. Leave timeline sync on for presenter, turn it off for some of the listeners
## a. Expected: these listeners can control their own timeline
## and receive nothing from the synced state; corresponding UI shows sync is off (`is_sync_enabled()` is the state of the UI)
# 9. Turn sync back for listeners
## a. Expected:
### i. If the synced (the presenter's) timeline is playing, it should start playing for the listeners again
### ii. If the synced (the presenter's) timeline is not playing,
### the time at the listeners should jump to the synced time.
### This is a bit different than the previous case,
### as we want to make sure that listeners pick up the synced state
### even if it has not changed since they re-enabled timeline sync. (In the previous case, if the timeline is playing they keep getting new time updates)
@MockLiveSyncingApi
async def test_listeners_turn_sync_off_and_on(self):
await self._create_session()
disable_sync_mock_joiner = await self._mock_join_session()
enable_sync_mock_joiner = await self._mock_join_session()
disable_sync_mock_joiner.mock_timeline_session.enable_sync(False)
self.assertFalse(disable_sync_mock_joiner.mock_timeline_session.is_sync_enabled())
old_time = disable_sync_mock_joiner.get_current_time()
# change time
modified_time = self._timeline.get_current_time() + 10
self._timeline.set_current_time(modified_time)
self._timeline.commit()
await self._sync_received_update_events_from_presenter([disable_sync_mock_joiner, enable_sync_mock_joiner])
self.assertEqual(disable_sync_mock_joiner.get_current_time(), old_time)
self.assertNotEqual(disable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time())
self.assertEqual(enable_sync_mock_joiner.get_current_time(), modified_time)
self.assertEqual(enable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time())
# manipluate time
new_time = old_time + 3
disable_sync_mock_joiner.set_current_time(new_time)
disable_sync_mock_joiner.commit()
self.assertEqual(disable_sync_mock_joiner.get_current_time(), new_time)
self.assertNotEqual(disable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time())
# should pick up state after enable_sync
disable_sync_mock_joiner.mock_timeline_session.enable_sync(True)
self.assertTrue(disable_sync_mock_joiner.mock_timeline_session.is_sync_enabled())
await self._sync_received_update_events_from_presenter([disable_sync_mock_joiner])
self.assertEqual(disable_sync_mock_joiner.get_current_time(), modified_time)
self.assertEqual(disable_sync_mock_joiner.is_playing(), self._timeline.is_playing())
# disbale again and make presenter playing
disable_sync_mock_joiner.mock_timeline_session.enable_sync(False)
self.assertFalse(disable_sync_mock_joiner.mock_timeline_session.is_sync_enabled())
old_time = disable_sync_mock_joiner.get_current_time()
self._timeline.play()
self._timeline.commit()
# play for a while
await self._sync_received_update_events_from_presenter([disable_sync_mock_joiner, enable_sync_mock_joiner], 50)
self.assertNotEqual(disable_sync_mock_joiner.is_playing(), self._timeline.is_playing())
self.assertEqual(enable_sync_mock_joiner.is_playing(), self._timeline.is_playing())
self.assertFalse(disable_sync_mock_joiner.is_playing())
self.assertTrue(enable_sync_mock_joiner.is_playing())
self.assertAlmostEqual(enable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1)
self.assertLess(disable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time())
# should pick up state after enable_sync
disable_sync_mock_joiner.mock_timeline_session.enable_sync(True)
self.assertTrue(disable_sync_mock_joiner.mock_timeline_session.is_sync_enabled())
await self._sync_received_update_events_from_presenter([disable_sync_mock_joiner, enable_sync_mock_joiner])
self.assertEqual(disable_sync_mock_joiner.is_playing(), self._timeline.is_playing())
self.assertEqual(enable_sync_mock_joiner.is_playing(), self._timeline.is_playing())
self.assertTrue(disable_sync_mock_joiner.is_playing())
self.assertTrue(enable_sync_mock_joiner.is_playing())
self.assertGreater(disable_sync_mock_joiner.get_current_time(), modified_time)
self.assertAlmostEqual(disable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1)
self.assertAlmostEqual(enable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1)
# 10. Owner passes the presenter role (timeline control) to another user.
# The new presenter changes its (and thus the synced) timeline, set time, play/pause/stop etc.
## a. Expected:
### i. Owner (previous presenter) is no longer able to control its own timeline
### ii. Everything that the new presenter is doing is synced to all listeners (including the previous presenter!)
### iii. Owner is not allowed to pass the presenter role to the same user again (UI: "give control"-like messages turn to "withdraw control" or something similar)
### iv. All UI that somehow marks/shows who the presenter is should show the new presenter (user icons, timeline window etc.)
# 11. Owner passes the presenter role to a new user.
# Essentially the same as the previous case,
# except that presenter role passed from a non-owner user to another non-owner.
# Repeat this several times for several (or all) users.
# 12. Owner returns the presenter role to him/herself (edge case).
# Everything should be the same as in the cases above.
async def _set_as_presenter(self, new_presenter_timeline_session: TimelineSession) -> None:
owner_session = ls.get_timeline_session()
owner_session.presenter = new_presenter_timeline_session.live_session_user
await self.wait()
async def _validate_presenter_state(
self,
old_presenter_timeline: omni.timeline.Timeline,
new_presenter_timeline: omni.timeline.Timeline,
new_presenter_timeline_session: TimelineSession,
new_presenter_window: UserWindow,
non_presenter_mock_joiners: List[MockJoiner],
pass_to_owner: bool,
) -> None:
owner_session = ls.get_timeline_session()
# i. previous presenter could not change timeline
old_time = old_presenter_timeline.get_current_time()
new_time = old_time + self._end_time / 10
old_presenter_timeline.set_current_time(new_time)
old_presenter_timeline.commit()
self.assertEqual(old_presenter_timeline.get_current_time(), old_time)
self.assertNotEqual(old_presenter_timeline.get_current_time(), new_time)
old_presenter_timeline.play()
old_presenter_timeline.commit()
self.assertFalse(old_presenter_timeline.is_playing())
# ii. new presenter manipulate
listener_timelines: List[omni.timeline.Timeline] = [old_presenter_timeline]
for mock_joiner in non_presenter_mock_joiners:
listener_timelines.append(mock_joiner.mock_timeline)
for _ in range(3):
await self._test_change_time_and_timeline_state(new_presenter_timeline, listener_timelines)
# iv. new presenter
self.assertEqual(
new_presenter_timeline_session.is_presenter(owner_session.live_session_user), pass_to_owner, ""
)
self.assertEqual(owner_session.is_presenter(owner_session.live_session_user), pass_to_owner, "")
self.assertEqual(owner_session.am_i_presenter(), pass_to_owner, "")
self.assertTrue(owner_session.is_presenter(new_presenter_timeline_session.live_session_user))
self.assertTrue(new_presenter_timeline_session.is_presenter(new_presenter_timeline_session.live_session_user))
self.assertTrue(new_presenter_timeline_session.am_i_presenter())
for mock_joiner in non_presenter_mock_joiners:
self.assertEqual(
mock_joiner.mock_timeline_session.is_presenter(owner_session.live_session_user), pass_to_owner
)
self.assertFalse(new_presenter_timeline_session.is_presenter(mock_joiner.joiner))
self.assertFalse(
new_presenter_timeline_session.is_presenter(mock_joiner.mock_timeline_session.live_session_user)
)
self.assertFalse(owner_session.is_presenter(mock_joiner.joiner))
self.assertFalse(owner_session.is_presenter(mock_joiner.mock_timeline_session.live_session_user))
self.assertFalse(mock_joiner.mock_timeline_session.is_presenter(mock_joiner.joiner))
self.assertFalse(
mock_joiner.mock_timeline_session.is_presenter(mock_joiner.mock_timeline_session.live_session_user)
)
self.assertTrue(
mock_joiner.mock_timeline_session.is_presenter(new_presenter_timeline_session.live_session_user)
)
self.assertFalse(mock_joiner.mock_timeline_session.am_i_presenter())
# iii and iv. UI
owner_window = ui_test.find(self._window_title)
new_presenter_window_ref = ui_test.find(new_presenter_window._window.title)
self._window.show()
new_presenter_window.show()
await self.wait()
new_presenter = new_presenter_timeline_session.live_session_user
search_text = f'**/ScrollingFrame[0]/VStack[0]/Label[*].text == "{new_presenter.user_name} ({new_presenter.from_app}) [Presenter]"'
if pass_to_owner:
new_presenter_in_owner_window = owner_window.find(
f'**/ScrollingFrame[0]/VStack[0]/Label[*].text == "{new_presenter.user_name} ({new_presenter.from_app}) [Owner][Presenter][Current user]"'
)
else:
new_presenter_in_owner_window = owner_window.find(search_text)
self.assertIsNotNone(new_presenter_window_ref.find(f'{search_text[:-1]}[Current user]"'))
self.assertIsNotNone(new_presenter_in_owner_window)
await new_presenter_in_owner_window.click()
btn = owner_window.find('**/Button[*].text == "Set as Timeline Presenter"')
self.assertIsNotNone(btn)
self.assertFalse(btn.widget.visible)
for mock_joiner in non_presenter_mock_joiners:
mock_joiner_window = ui_test.find(mock_joiner.get_window_title())
mock_joiner.window.show()
await self.wait()
self.assertIsNotNone(mock_joiner_window.find(search_text))
non_presenter = mock_joiner.mock_timeline_session.live_session_user
non_presenter_text = f'**/ScrollingFrame[0]/VStack[0]/Label[*].text == "{non_presenter.user_name} ({non_presenter.from_app}) "'
non_presenter_in_owner_window = owner_window.find(non_presenter_text)
self.assertIsNotNone(non_presenter_in_owner_window)
await non_presenter_in_owner_window.click()
btn = owner_window.find('**/Button[*].text == "Set as Timeline Presenter"')
self.assertIsNotNone(btn)
self.assertTrue(btn.widget.visible)
@MockLiveSyncingApi
async def test_pass_presenter(self):
await self._create_session()
mock_joiners: List[MockJoiner] = []
for _ in range(2):
mock_joiners.append(await self._mock_join_session())
for _ in range(2):
# 10, 11
previous_presenter_timeline = self._timeline
for _ in range(2):
for mock_joiner in mock_joiners:
non_presenters = filter(
lambda other: other.joiner.user_id != mock_joiner.joiner.user_id, mock_joiners
)
await self._set_as_presenter(mock_joiner.mock_timeline_session)
await self._validate_presenter_state(
previous_presenter_timeline,
mock_joiner.mock_timeline,
mock_joiner.mock_timeline_session,
mock_joiner.window,
list(non_presenters),
False,
)
previous_presenter_timeline = mock_joiner.mock_timeline
# 12
await self._set_as_presenter(ls.get_timeline_session())
await self._validate_presenter_state(
previous_presenter_timeline,
self._timeline,
ls.get_timeline_session(),
self._window,
mock_joiners,
True,
)
# 13. A listener sends a request to become presenter.
# Potentially do this with multiple listeners at the same time.
## a. Expected: The UI for the listener changes and he can no longer send a request,
## instead, he can withdraw it
# 14. The owner receives a notification about the request and the user(s) that sent the request appear(s) on the "requests" list.
# The owner is able to select it and has the option to pass the presenter role.
# 15. A listener revokes its request
## a. Expected: the owner no longer sees this user among the requests.
# 16. Pass presenter role to a user that requested it. 1) listener sends a request, 2) owner gives timeline control
## a. Expected, once timeline control is passed:
### i. the requester should disappear from the request list at the owner
### ii. everything else should be the same (and tested similarly) as when the owner passes the presenter role to another user
async def _list_check(self, control_requesters: List[MockJoiner]) -> None:
self.assertEqual(len(ls.get_timeline_session().get_request_control_ids()), len(control_requesters))
owner_window = ui_test.find(self._window_title)
for mock_joiner in control_requesters:
user = mock_joiner.joiner
control_req_in_owner_window = owner_window.find(
f'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "{user.user_name} ({user.from_app}) "'
)
self.assertIsNotNone(control_req_in_owner_window)
await control_req_in_owner_window.click()
self.assertTrue(control_req_in_owner_window.widget.selected)
self.assertIsNotNone(owner_window.find('**/Button[*].text == "Set as Timeline Presenter"'))
mock_joiner_window_ref = ui_test.find(mock_joiner.get_window_title())
self.assertIsNone(mock_joiner_window_ref.find('**/Button[*].text == "Request Timeline Control"'))
self.assertIsNotNone(mock_joiner_window_ref.find('**/Button[*].text == "Revoke Request"'))
self.assertTrue(
any(
user_id == mock_joiner.joiner.user_id
for user_id in ls.get_timeline_session().get_request_control_ids()
)
)
for other in filter(lambda other: other.joiner.user_id != mock_joiner.joiner.user_id, control_requesters):
other_user = other.joiner
self.assertIsNotNone(
mock_joiner_window_ref.find(
f'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "{other_user.user_name} ({other_user.from_app}) "'
)
)
async def _remove_user_from_control_list(
self, set_as_presenter: bool, control_requesters: List[MockJoiner], mock_joiners: List[MockJoiner]
) -> None:
owner_window = ui_test.find(self._window_title)
chosen_user = control_requesters.pop()
if set_as_presenter:
user = chosen_user.joiner
control_req_in_owner_window = owner_window.find(
f'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "{user.user_name} ({user.from_app}) "'
)
self.assertIsNotNone(control_req_in_owner_window)
await control_req_in_owner_window.click()
self.assertTrue(control_req_in_owner_window.widget.selected)
set_presenter_btn = owner_window.find('**/Button[*].text == "Set as Timeline Presenter"')
self.assertIsNotNone(set_presenter_btn)
await set_presenter_btn.click()
else:
# revoke
chosen_user_window_ref = ui_test.find(chosen_user.get_window_title())
revoke_btn = chosen_user_window_ref.find('**/Button[*].text == "Revoke Request"')
self.assertIsNotNone(revoke_btn)
await revoke_btn.click()
chosen_user.window.show()
for mock_joiner in mock_joiners:
mock_joiner.window.show()
self._window.show()
await self.wait()
self.assertIsNone(
owner_window.find(
f'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "{chosen_user.joiner.user_name} ({chosen_user.joiner.from_app}) "'
)
)
await self._list_check(control_requesters)
for mock_joiner in mock_joiners:
self.assertIsNone(
owner_window.find(
f'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "{chosen_user.joiner.user_name} ({chosen_user.joiner.from_app}) "'
)
)
if not set_as_presenter:
return
await self._validate_presenter_state(
self._timeline,
chosen_user.mock_timeline,
chosen_user.mock_timeline_session,
chosen_user.window,
list(filter(lambda other: other.joiner.user_id != chosen_user.joiner.user_id, mock_joiners)),
False,
)
@MockLiveSyncingApi
async def test_request_control(self):
await self._create_session()
mock_joiners: List[MockJoiner] = []
for _ in range(5):
mock_joiners.append(await self._mock_join_session())
control_req_list = list(mock_joiners)
# 13
self.assertEqual(len(ls.get_timeline_session().get_request_control_ids()), 0)
for mock_joiner in mock_joiners:
mock_joiner_window_ref = ui_test.find(mock_joiner.get_window_title())
self.assertIsNotNone(mock_joiner_window_ref.find('**/Button[*].text == "Request Timeline Control"'))
self.assertIsNone(mock_joiner_window_ref.find('**/Button[*].text == "Revoke Request"'))
mock_joiner.mock_timeline_session.request_control(True)
for mock_joiner in mock_joiners:
mock_joiner.window.show()
self._window.show()
await self.wait()
# 14
await self._list_check(control_req_list)
# 15 revoke
await self._remove_user_from_control_list(False, control_req_list, mock_joiners)
# 16
await self._remove_user_from_control_list(True, control_req_list, mock_joiners)
# 17. Latency estimate: TBD
## a. So far I have tested that it returns zero for the presenter and something meaningful or everyone else.
## b. Latency for listeners should increase when there's a lag (e.g. artificially introduced sleep) at the presenter
## c. Turning timeline sync off for the presenter should not affect the latency
@MockLiveSyncingApi
async def test_latency_estimate(self):
await self._create_session()
self._timeline.play()
self._timeline.commit()
mock_joiners: List[MockJoiner] = []
for _ in range(3):
mock_joiners.append(await self._mock_join_session())
await self._sync_received_update_events_from_presenter(mock_joiners)
# latency estimate from presenter is 0
self.assertEqual(ls.get_timeline_session().role.get_latency_estimate(), 0)
avg_latency = 0.0
cnt = 50
for _ in range(cnt):
await self.wait(1)
for mock_joiner in mock_joiners:
avg_latency += mock_joiner.mock_timeline_session.role.get_latency_estimate()
avg_latency /= cnt
# turn off sync does not affect latency
ls.get_timeline_session().enable_sync(False)
await self._sync_received_update_events_from_presenter(mock_joiners)
avg_turn_off_sync_latency = 0.0
cnt = 50
for _ in range(cnt):
await self.wait(1)
for mock_joiner in mock_joiners:
avg_turn_off_sync_latency += mock_joiner.mock_timeline_session.role.get_latency_estimate()
avg_turn_off_sync_latency /= cnt
self.assertAlmostEqual(avg_latency, avg_turn_off_sync_latency, delta=1)
# simulate lag
ls.get_timeline_session().stop_session()
await asyncio.sleep(1.5)
lag_latency = 0.0
for _ in range(cnt):
await self.wait(1)
for mock_joiner in mock_joiners:
lag_latency += mock_joiner.mock_timeline_session.role.get_latency_estimate()
lag_latency /= cnt
self.assertNotAlmostEqual(avg_latency, lag_latency, delta=1)
ls.get_timeline_session().start_session()
await self._sync_received_update_events_from_presenter(mock_joiners)
# 18. Everyone leaves the session, then owner joins an existing session while there are no other users.
# (There was a bug at some point when this didn't work.)
## a. Expected: owner should become the presenter
@MockLiveSyncingApi
@unittest.skip("Need to fix MockLiveSyncingApi to fully mock live session")
async def test_new_owner(self):
await self._create_session()
mock_joiners: List[MockJoiner] = []
for _ in range(3):
mock_joiners.append(await self._mock_join_session())
self._timeline.play()
self._timeline.commit()
await self._sync_received_update_events_from_presenter(mock_joiners)
user_cnt = len(mock_joiners) + 1
for mock_joiner in mock_joiners:
user = mock_joiner.joiner
current_session = self._live_syncing.get_current_live_session()
session_channel = current_session._session_channel()
del session_channel._peer_users[user.user_id]
session_channel._send_layer_event(
layers.LayerEventType.LIVE_SESSION_USER_LEFT, {"user_name": user.user_name, "user_id": user.user_id}
)
await self.wait()
self.assertIsNone(ls.get_session_state().find_user(user.user_id))
user_cnt -= 1
self.assertEqual(len(ls.get_session_state().users), user_cnt)
# leave
self._live_syncing.stop_all_live_sessions()
await self.wait()
self.assertEqual(len(ls.get_session_state().users), 0)
# rejoin
session = self._live_syncing.find_live_session_by_name(self._stage_url, "test")
self.assertTrue(session, "Failed to find live session.")
self.assertTrue(self._live_syncing.join_live_session(session))
await self.wait()
self.assertTrue(self._live_syncing.is_in_live_session())
# become presenter
owner_timeline_session = ls.get_timeline_session()
self.assertTrue(owner_timeline_session.am_i_presenter())
self.assertTrue(owner_timeline_session.is_presenter(owner_timeline_session.live_session_user))
self.assertEqual(owner_timeline_session.role_type, ls.TimelineSessionRoleType.PRESENTER)
| 59,064 | Python | 45.216745 | 166 | 0.651141 |
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/tests/__init__.py | from .test_ui_window import *
from .tests import *
| 51 | Python | 16.333328 | 29 | 0.72549 |
omniverse-code/kit/exts/omni.timeline.live_session/docs/examples.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.
#
# This file shows API usage examples for omni.timeline.live_session
import omni.kit.usd.layers as layers
import omni.timeline.live_session
import omni.usd
class Examples:
# Example: Watch for connection to live session, then register to presenter changed event and react to it
def example_presenter_changed_watcher(self):
usd_context_name: str = ""
self.usd_context = omni.usd.get_context(usd_context_name)
live_syncing = layers.get_live_syncing(self.usd_context)
self.layers = layers.get_layers(self.usd_context)
self.layers_event_subscription = self.layers.get_event_stream().create_subscription_to_pop(
self._on_layers_event, name="my_example_sub"
)
# Make sure to set self.layers_event_subscription to None somewhere, omitted from the example
# When a live session is joined, register callback for presenter changed events
def _on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
if not payload:
return
# Only events from root layer session are handled.
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if not payload.is_layer_influenced(self.usd_context.get_stage_url()):
return
# Get the timeline session and register our own callback for presenter changed
self.timeline_session = omni.timeline.live_session.get_timeline_session()
if self.timeline_session is not None:
self.timeline_session.add_presenter_changed_fn(self._on_presenter_changed)
# Make sure to call session.remove_presenter_changed_fn somewhere, this is omitted here
# Our callback that is called by the timeline sync extension when the presenter is changed. We get the new user.
def _on_presenter_changed(self, user: layers.LiveSessionUser):
print(f'The new Timeline Presenter is {user.user_name}')
if self.timeline_session.am_i_presenter():
print('I am the Timeline Presenter!')
else:
print('I am a Timeline Listener.')
# Example: Turn the timeline sync on or off.
# For Listeners turning off stops receiving updates and gives them back the ability to control their own timeline.
# For the Presenter turning off stops sending updates to Listeners.
def example_toggle_sync(self):
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None:
syncing = timeline_session.is_sync_enabled()
if syncing:
print('Timeline sync is enabled, turning it off')
else:
print('Timeline sync is disabled, turning it on')
timeline_session.enable_sync(not syncing)
# Example: Subscribe to changes in timeline sync (enabled/disabled)
def example_enable_sync_changed(self):
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None:
timeline_session.add_enable_sync_changed_fn(self._on_enable_sync_changed)
# Make sure to call session.remove_enable_sync_changed_fn somewhere, this is omitted here
def _on_enable_sync_changed(self, enabled: bool):
print(f'Timeline synchronization was {"enabled" if enabled else "disabled"}')
# Example: Query the estimated latency from the timeline session
def example_query_latency(self):
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None:
latency = timeline_session.role.get_latency_estimate()
print(f'The estimated latency from the Timeline Presenter is {latency}')
# Example: Register to control request received event
def example_control_requests(self):
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None:
timeline_session.add_control_request_changed_fn(self._on_control_requests_changed)
# Make sure to call session.remove_control_request_changed_fn somewhere, this is omitted here
# Our callback that is called by the timeline sync extension when a user sends or withdraws control request.
def _on_control_requests_changed(self, user: layers.LiveSessionUser, wants_control: bool):
if wants_control:
print(f'User {user.user_name} requested to control the Timeline')
else:
print(f'User {user.user_name} withdrew the request to control the Timeline')
# Print all users who have requested control
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None:
all_users = timeline_session.get_request_controls()
if len(all_users) == 0:
print('There are no requests to control the Timeline')
else:
print('List of users requested to control the Timeline:')
for request_user in all_users:
print(f'\t{request_user.user_name}')
| 5,559 | Python | 49.545454 | 120 | 0.686095 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/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.rtx.window.settings import RendererSettingsFactory
from .importers import IndeXImporters
from .widgets import IndeXCommonSettingStack, IndeXClusterSettingStack
class IndeXSettingsExtension(omni.ext.IExt):
"""The entry point for IndeX Settings Window"""
renderer_name = "Scientific (IndeX)"
def on_startup(self):
RendererSettingsFactory.register_renderer(self.renderer_name, ["IndeX Cluster", "IndeX Common"])
RendererSettingsFactory.register_stack("IndeX Cluster", IndeXClusterSettingStack)
RendererSettingsFactory.register_stack("IndeX Common", IndeXCommonSettingStack)
try:
import omni.kit.window.property as p
except ImportError:
# Likely running headless
return
w = p.get_window()
if not w:
return
from .widgets.colormap_properties_widget import ColormapPropertiesWidget
from .widgets.shader_properties_widget import ShaderPropertiesWidget
from .widgets.volume_properties_widget import VolumePropertiesWidget
self.colormap_widget = ColormapPropertiesWidget()
self.shader_widget = ShaderPropertiesWidget()
self.volume_widget = VolumePropertiesWidget()
IndeXImporters.register_bindings(self)
def on_shutdown(self):
RendererSettingsFactory.unregister_renderer(self.renderer_name)
RendererSettingsFactory.unregister_stack("IndeX Cluster")
RendererSettingsFactory.unregister_stack("IndeX Common")
RendererSettingsFactory.build_ui()
try:
import omni.kit.window.property as p
except ImportError:
# Likely running headless
return
w = p.get_window()
if not w:
return
w.unregister_widget("prim", "shader")
self.colormap_widget.on_shutdown()
self.colormap_widget = None
self.shader_widget.on_shutdown()
self.shader_widget = None
self.volume_widget.on_shutdown()
self.volume_widget = None
IndeXImporters.deregister_bindings(self)
| 2,544 | Python | 34.347222 | 104 | 0.704796 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/importers/__init__.py | from .importers import IndeXImporters
| 38 | Python | 18.499991 | 37 | 0.868421 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/importers/importers.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 carb
import omni.usd
import omni.kit.commands
import omni.kit.window.content_browser as content
from omni.kit.window.popup_dialog import FormDialog, MessageDialog
import omni.ui as ui
from pxr import Sdf, Gf, UsdVol, UsdShade
from enum import Enum
import os
import re
from ..presets import ColormapPresets, ShaderPresets
class ComboListModel(ui.AbstractItemModel):
class ComboListItem(ui.AbstractItem):
def __init__(self, item):
super().__init__()
self.model = ui.SimpleStringModel(item)
def __init__(self, item_list, default_index):
super().__init__()
self._default_index = default_index
self._current_index = ui.SimpleIntModel(default_index)
self._current_index.add_value_changed_fn(lambda a: self._item_changed(None))
self._item_list = item_list
self._items = []
if item_list:
for item in item_list:
self._items.append(ComboListModel.ComboListItem(item))
def get_item_children(self, item):
return self._items
def get_item_list(self):
return self._item_list
def get_item_value_model(self, item=None, column_id=-1):
if item is None:
return self._current_index
return item.model
def get_current_index(self):
return self._current_index.get_value_as_int()
def set_current_index(self, index):
self._current_index.set_value(index)
def get_current_string(self):
return self._items[self._current_index.get_value_as_int()].model.get_value_as_string()
def is_default(self):
return self.get_current_index() == self._default_index
class IndeXAddVolume:
class VolumeFormat(Enum):
RAW, OPENVDB, PARTICLE_VOLUME = range(3)
VOLUME_REPRESENTATIONS = {
"NanoVDB": "vdb",
"IndeX Sparse": "sparse_volume",
}
LABEL_ORDER_ROW_MAJOR = "Row-major (C-style)"
LABEL_ORDER_COLUMN_MAJOR = "Column-major (Fortran-style)"
LABEL_DEFAULT = "Default"
LABEL_NONE = "None"
def __init__(self, volume_format, ext, asset_file_path):
self.volume_format = volume_format
self.ext = ext
self.asset_file_path = asset_file_path
self.non_importer_field_names = []
self.importer_name = None
self.extra_importer_settings = {}
self.file_format = None
def _on_add(self, dlg):
importer_settings = self.extra_importer_settings
render_settings = {}
colormap = None
shader = None
volume_usd_path = dlg.get_value("volume_usd_path")
valid = Sdf.Path.IsValidPathString(volume_usd_path)
if not valid:
dlg.hide()
def on_error_ok(msg_dlg):
msg_dlg.hide()
# Show the main dialog again after showing the error
# message. Having two modal dialogs visible at the same
# time doesn't seem to be possible.
dlg.show()
#FIXME: This pops up at the top-left, not the center
MessageDialog(
message=f"Invalid USD path: '{volume_usd_path}'\nReason: '{valid[1]}'\nPlease ensure that the specified path is valid.",
title="Error",
ok_handler=on_error_ok,
disable_cancel_button=True
).show()
return False
# Pass through generic importer arguments directly
for key, value in dlg.get_values().items():
if key not in self.non_importer_field_names:
if isinstance(value, bool):
value = str(value).lower() # convert 'True' to 'true'
importer_settings[key] = str(value)
if self.volume_format == IndeXAddVolume.VolumeFormat.RAW:
dims_model = dlg.get_field("dims").model
sub_models = dims_model.get_item_children()
dims = (
dims_model.get_item_value_model(sub_models[0]).as_int,
dims_model.get_item_value_model(sub_models[1]).as_int,
dims_model.get_item_value_model(sub_models[2]).as_int,
)
for dim in dims:
if dim <= 0:
dlg.hide()
def on_error_ok(msg_dlg):
msg_dlg.hide()
# Show the main dialog again after showing the error
# message. Having two modal dialogs visible at the same
# time doesn't seem to be possible.
dlg.show()
#FIXME: This pops up at the top-left, not the center
MessageDialog(
message=f"Invalid volume dimension specified: {dims}\nAll components must be positive.",
title="Error",
ok_handler=on_error_ok,
disable_cancel_button=True
).show()
return False
importer_settings["size"] = dims
importer_settings["voxel_format"] = dlg.get_field("voxel_format").model.get_current_string()
importer_settings["convert_zyx_to_xyz"] = (dlg.get_field("data_order").model.get_current_string() == self.LABEL_ORDER_ROW_MAJOR)
importer_settings["type"] = "sparse_volume"
importer_settings["importer"] = "nv::index::plugin::base_importer.Sparse_volume_importer_raw"
elif self.volume_format == IndeXAddVolume.VolumeFormat.OPENVDB:
volume_type = dlg.get_field("type").model.get_current_string()
if volume_type in IndeXAddVolume.VOLUME_REPRESENTATIONS:
importer_settings["type"] = IndeXAddVolume.VOLUME_REPRESENTATIONS[volume_type]
elif self.volume_format == IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME:
importer_settings["importer"] = self.importer_name
importer_settings["type"] = "particle_volume"
colormap = ColormapPresets.DEFAULT
render_settings["renderingMode"] = dlg.get_field("renderingMode").model.get_current_string()
fixed_point_width = dlg.get_value("fixedPointWidth")
if (fixed_point_width > 0):
importer_settings["fixed_radius"] = str(fixed_point_width / 2.0)
subdivision_mode = dlg.get_field("subdivisionMode").model.get_current_string()
if subdivision_mode != "current":
carb.settings.get_settings().set("/rtx/index/overrideSubdivisionMode", subdivision_mode)
subdivision_part_count = dlg.get_value("subdivisionPartCount")
if subdivision_part_count > 0:
carb.settings.get_settings().set("/rtx/index/overrideSubdivisionPartCount", subdivision_part_count)
dlg.hide()
colormap_field = dlg.get_field("colormap")
if colormap_field and not colormap:
colormap = colormap_field.model.get_current_string()
if not ColormapPresets.has(colormap):
colormap = None
shader_field = dlg.get_field("shader")
if shader_field and not shader:
shader = shader_field.model.get_current_string()
if not ShaderPresets.has(shader):
shader = None
omni.kit.commands.execute(
"AddVolumeFileToStage",
ext=self.ext,
volume_path=volume_usd_path,
asset_file_path=self.asset_file_path,
volume_format=self.volume_format,
importer_settings=importer_settings,
render_settings=render_settings,
colormap=colormap,
shader=shader
)
return True
def show(self):
def on_okay(dlg: FormDialog):
return self._on_add(dlg)
def combo_field(name, label, items, default=0):
return FormDialog.FieldDef(name, label, lambda **kwargs: ui.ComboBox(ComboListModel(items, default), **kwargs), 0)
fields = []
self.non_importer_field_names = []
file_name = os.path.basename(self.asset_file_path)
(file_root, file_ext) = os.path.splitext(file_name)
# Replace characters with special meaning in SdfPath by underscores
file_root_usd_safe = file_root
for ch in ['.', ':', '[', ']', '-', ' ']:
file_root_usd_safe = file_root_usd_safe.replace(ch, '_')
default_usd_path = f"/World/volume_{file_root_usd_safe}"
fields.append(FormDialog.FieldDef("volume_usd_path", "USD Path: ", ui.StringField, default_usd_path))
self.non_importer_field_names.append("volume_usd_path")
if self.volume_format == IndeXAddVolume.VolumeFormat.RAW:
volume_format_label = 'RAW'
default_dims = [0, 0, 0]
# Look for dimensions encoded in the filename
m = re.match('.*_(\d+)_(\d+)_(\d+)(_.*|$)', file_root)
if m:
default_dims = [ int(m[1]), int(m[2]), int(m[3]) ]
fields.append(FormDialog.FieldDef(
"dims", "Dimensions: ",
lambda **kwargs: ui.MultiIntField(default_dims[0], default_dims[1], default_dims[2], **kwargs), 0))
self.non_importer_field_names.append("dims")
voxel_format_list = [ 'uint8', 'uint16', 'sint16', 'rgba8', 'float16', 'float32', 'float32_4' ]
fields.append(combo_field("voxel_format", "Voxel Format: ", voxel_format_list))
self.non_importer_field_names.append("voxel_format")
fields.append(combo_field("data_order", "Data Order: ", [ self.LABEL_ORDER_ROW_MAJOR, self.LABEL_ORDER_COLUMN_MAJOR ]))
self.non_importer_field_names.append("data_order")
elif self.volume_format == IndeXAddVolume.VolumeFormat.OPENVDB:
volume_format_label = 'OpenVDB'
fields.append(FormDialog.FieldDef("input_file_field", "OpenVDB Data Field (optional): ", ui.StringField, ""))
fields.append(combo_field("type", "Volume Representation: ", [ self.LABEL_DEFAULT ] + list(self.VOLUME_REPRESENTATIONS.keys())))
self.non_importer_field_names.append("type")
elif self.volume_format == IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME:
volume_format_label = 'particle'
rendering_modes_list = ["rbf", "solid_box", "solid_cone", "solid_cylinder", "solid_sphere", "solid_disc"]
fields.append(combo_field("renderingMode", "Rendering Mode: ", rendering_modes_list, rendering_modes_list.index("solid_sphere")))
self.non_importer_field_names.append("renderingMode")
fields.append(FormDialog.FieldDef("fixedPointWidth", "Fixed Point Width: ", ui.FloatField, 0.0))
self.non_importer_field_names.append("fixedPointWidth")
file_format = file_ext.replace('.', '').lower()
self.file_format = file_format
if file_format == 'las':
self.importer_name = "nv::index::plugin::base_importer.Particle_volume_importer_las"
fields.append(FormDialog.FieldDef("offset_point_mode", "Offset Point Mode: ", ui.IntField, 2))
fields.append(FormDialog.FieldDef("radius_min", "Radius Min: ", ui.FloatField, 0.0))
fields.append(FormDialog.FieldDef("radius_max", "Radius Max: ", ui.FloatField, -1.0))
fields.append(FormDialog.FieldDef("radius_scale", "Radius Scale: ", ui.FloatField, 1.0))
fields.append(FormDialog.FieldDef("scale_color", "Color Scale: ", ui.FloatField, 1.0))
fields.append(FormDialog.FieldDef("ignore_las_offset", "Ignore LAS Offset: ", ui.CheckBox, True))
fields.append(FormDialog.FieldDef("ignore_zero_points", "Ignore Zero Points: ", ui.CheckBox, False))
elif file_format == 'pcd':
self.importer_name = "nv::index::plugin::base_importer.Particle_volume_importer_point_cloud_data"
fields.append(FormDialog.FieldDef("is_little_endian", "Little Endian: ", ui.CheckBox, False))
elif file_format == 'ptx':
self.importer_name = "nv::index::plugin::base_importer.Particle_volume_importer_ptx"
fields.append(FormDialog.FieldDef("ignore_zero_points", "Ignore Zero Points: ", ui.CheckBox, False))
fields.append(FormDialog.FieldDef("color_type_uint8", "Color Type UInt8: ", ui.CheckBox, True))
elif file_format == 'e57':
self.importer_name = "nv::index::plugin::e57_importer.Particle_volume_importer_e57"
# Do not bake the transformation into the point data, but provide the transformation matrix
self.extra_importer_settings["apply_transform"] = "false"
fields.append(FormDialog.FieldDef("__ignore_dataset_transform", "Ignore transformation: ", ui.CheckBox, False))
else:
carb.log_error(f"ERROR: Unsupported particle volume format '{file_format} for file '{self.asset_file_path}.")
subdivision_modes_list = ["current", "grid", "kd_tree"]
fields.append(combo_field("subdivisionMode", "Subdivision Mode: ", subdivision_modes_list, subdivision_modes_list.index("current")))
self.non_importer_field_names.append("subdivisionMode")
fields.append(FormDialog.FieldDef("subdivisionPartCount", "Subdivision Part Count: ", ui.IntField, 0))
self.non_importer_field_names.append("subdivisionPartCount")
else:
return
if self.volume_format != IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME:
fields.append(combo_field("colormap", "Add Colormap: ", [ self.LABEL_NONE ] + ColormapPresets.get_labels()))
self.non_importer_field_names.append("colormap")
fields.append(combo_field("shader", "Add XAC Shader: ", [ self.LABEL_NONE ] + ShaderPresets.get_labels()))
self.non_importer_field_names.append("shader")
dlg = FormDialog(
width=600,
message=f"Adding {volume_format_label} volume asset '{file_name}' to the stage:",
title=f"Add {volume_format_label.capitalize()} Volume Asset",
ok_label="Add",
ok_handler=on_okay,
field_defs=fields,
)
dlg.show()
def is_openvdb_file(path):
return os.path.splitext(path)[1].lower() == ".vdb"
def is_raw_file(path):
return os.path.splitext(path)[1].lower() == ".raw"
def is_particle_volume_file(path):
supported_particle_volume_formats = []
file_formats = carb.settings.get_settings().get("/nvindex/state/supportedFileFormats")
if file_formats:
for f in file_formats:
if f in ["las", "pcd", "ptx", "e57"]:
supported_particle_volume_formats.append("." + f)
return os.path.splitext(path)[1].lower() in supported_particle_volume_formats
def is_maybe_raw_file(path):
return not (is_openvdb_file(path) or is_particle_volume_file(path))
class IndeXImporters:
OPENVDB_FILE_HANDLER_NAME = "IndeX OpenVDB File Open Handler"
RAW_FILE_HANDLER_NAME = "IndeX RAW File Open Handler"
PARTICLE_VOLUME_FILE_HANDLER_NAME = "IndeX ParticleVolume File Open Handler"
CONTEXT_MENU_NAME_ADD_OPENVDB = "Add OpenVDB Volume Asset to Stage"
CONTEXT_MENU_NAME_ADD_RAW = "Add RAW Volume Asset to Stage"
CONTEXT_MENU_NAME_ADD_PARTICLE_VOLUME = "Add Particle Volume Asset to Stage"
def register_bindings(ext):
content.get_instance().add_file_open_handler(
IndeXImporters.OPENVDB_FILE_HANDLER_NAME,
open_fn=lambda path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.OPENVDB, ext, path).show(),
file_type=is_openvdb_file
)
content.get_instance().add_file_open_handler(
IndeXImporters.RAW_FILE_HANDLER_NAME,
open_fn=lambda path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.RAW, ext, path).show(),
file_type=is_raw_file
)
content.get_instance().add_file_open_handler(
IndeXImporters.PARTICLE_VOLUME_FILE_HANDLER_NAME,
open_fn=lambda path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME, ext, path).show(),
file_type=is_particle_volume_file
)
content.get_instance().add_context_menu(
name=IndeXImporters.CONTEXT_MENU_NAME_ADD_RAW,
glyph="menu_add.svg",
click_fn=lambda name, path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.RAW, ext, path).show(),
show_fn=is_maybe_raw_file
)
content.get_instance().add_context_menu(
name=IndeXImporters.CONTEXT_MENU_NAME_ADD_OPENVDB,
glyph="menu_add.svg",
click_fn=lambda name, path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.OPENVDB, ext, path).show(),
show_fn=is_openvdb_file
)
content.get_instance().add_context_menu(
name=IndeXImporters.CONTEXT_MENU_NAME_ADD_PARTICLE_VOLUME,
glyph="menu_add.svg",
click_fn=lambda name, path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME, ext, path).show(),
show_fn=is_particle_volume_file
)
def deregister_bindings(ext):
content.get_instance().delete_file_open_handler(
IndeXImporters.OPENVDB_FILE_HANDLER_NAME)
content.get_instance().delete_file_open_handler(
IndeXImporters.RAW_FILE_HANDLER_NAME)
content.get_instance().delete_file_open_handler(
IndeXImporters.PARTICLE_VOLUME_FILE_HANDLER_NAME)
content.get_instance().delete_context_menu(
IndeXImporters.CONTEXT_MENU_NAME_ADD_OPENVDB)
content.get_instance().delete_context_menu(
IndeXImporters.CONTEXT_MENU_NAME_ADD_RAW)
content.get_instance().delete_context_menu(
IndeXImporters.CONTEXT_MENU_NAME_ADD_PARTICLE_VOLUME)
class AddVolumeFileToStage(omni.kit.commands.Command):
"""
Add an volume file to the stage.
Args:
ext: the calling extension
volume_path: USD path of the volume in the stage
asset_file_path: the volume assset being loaded
volume_format: 'openvdb' or 'raw'
importer_settings: dictionary containing setting to pass to IndeX importer
render_settings: dictionary containing settings for rendering the volume
"""
def __init__(self, ext, volume_path, asset_file_path, volume_format, importer_settings, render_settings, colormap, shader) -> None:
self.ext = ext
self.volume_path = volume_path
self.asset_file_path = asset_file_path
self.volume_format = volume_format
self.importer_settings = importer_settings
self.render_settings = render_settings
self.colormap = colormap
self.shader = shader
self.stage = omni.usd.get_context().get_stage()
self.volume_prim = None
def do(self):
if not self.ext:
carb.log_error(f"ERROR: Tried to add volume {self.asset_file_path} when extension is already shut down")
return False
if not self.asset_file_path:
carb.log_error(f"ERROR: Volume file {self.asset_file_path} is not defined")
return False
try:
asset_name = "VolumeAsset"
asset_path = f"{self.volume_path}/{asset_name}"
material_path = f"{self.volume_path}/Material"
colormap_path = f"{material_path}/Colormap"
shader_path = f"{material_path}/VolumeShader"
rel_name = "volume"
# Create volume asset
if self.volume_format == IndeXAddVolume.VolumeFormat.OPENVDB:
volume_asset = UsdVol.OpenVDBAsset.Define(self.stage, asset_path)
volume_asset_prim = volume_asset.GetPrim()
field_name = self.importer_settings["input_file_field"]
if field_name:
rel_name = field_name
volume_asset.GetFieldNameAttr().Set(field_name)
elif self.volume_format == IndeXAddVolume.VolumeFormat.RAW:
volume_asset_prim = self.stage.DefinePrim(asset_path, "FieldAsset")
volume_asset = UsdVol.FieldAsset(volume_asset_prim)
elif self.volume_format == IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME:
volume_asset_prim = self.stage.DefinePrim(asset_path, "FieldAsset")
volume_asset = UsdVol.FieldAsset(volume_asset_prim)
volume_asset.CreateFilePathAttr().Set(self.asset_file_path)
# Add generic importer settings as customData
for key, value in self.importer_settings.items():
# Skip keys that are handled explicitly
if key not in ["input_file_field", "size", "type"]:
volume_asset_prim.SetCustomDataByKey("nvindex.importerSettings:" + key, value)
# Create volume
volume = UsdVol.Volume.Define(self.stage, self.volume_path)
volume.CreateFieldRelationship(rel_name, volume_asset.GetPath())
self.volume_prim = volume.GetPrim()
# Mark the prim as to be handled by IndeX in compositing mode
if carb.settings.get_settings().get("/nvindex/compositeRenderingMode"):
self.volume_prim.CreateAttribute("nvindex:composite", Sdf.ValueTypeNames.Bool, custom=True).Set(True)
self.volume_prim.CreateAttribute("omni:rtx:skip", Sdf.ValueTypeNames.Bool, custom=True).Set(True)
if "size" in self.importer_settings:
extent_attr = volume.CreateExtentAttr()
extent_attr.Set([[0, 0, 0], self.importer_settings["size"]])
if "type" in self.importer_settings:
type_attr = volume.GetPrim().CreateAttribute("nvindex:type", Sdf.ValueTypeNames.Token, True)
type_attr.Set(self.importer_settings["type"])
# Add generic render settings as customData
for key, value in self.render_settings.items():
self.volume_prim.SetCustomDataByKey("nvindex.renderSettings:" + key, value)
if self.colormap or self.shader:
# Create and connect material and empty shader
material = UsdShade.Material.Define(self.stage, material_path)
UsdShade.MaterialBindingAPI(volume.GetPrim()).Bind(material)
shader = UsdShade.Shader.Define(self.stage, shader_path)
shader_output = shader.CreateOutput("volume", Sdf.ValueTypeNames.Token)
material.CreateVolumeOutput("nvindex").ConnectToSource(shader_output)
if self.volume_format == IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME:
# Create default Phong material for particle volumes
shader.SetShaderId("nvindex:phong_gl")
shader.CreateImplementationSourceAttr().Set("id")
shader.CreateInput("ambient", Sdf.ValueTypeNames.Float3).Set((0.1, 0.1, 0.1))
shader.CreateInput("diffuse", Sdf.ValueTypeNames.Float3).Set((1.0, 1.0, 1.0))
shader.CreateInput("specular", Sdf.ValueTypeNames.Float3).Set((0.4, 0.4, 0.4))
shader.CreateInput("shininess", Sdf.ValueTypeNames.Float).Set(10.0)
shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(0.0) # indicates that particle color should be used
if self.colormap:
# Add colormap
colormap = self.stage.DefinePrim(colormap_path, "Colormap")
colormap_output = colormap.CreateAttribute("outputs:colormap", Sdf.ValueTypeNames.Token)
shader.CreateInput("colormap", Sdf.ValueTypeNames.Token).ConnectToSource(colormap_output.GetPath())
colormapSource = "rgbaPoints"
colormap.CreateAttribute("colormapSource", Sdf.ValueTypeNames.Token).Set(colormapSource)
(xPoints, rgbaPoints) = ColormapPresets.generate(self.colormap, colormap_source=colormapSource)
colormap.CreateAttribute("xPoints", Sdf.ValueTypeNames.FloatArray).Set(xPoints)
colormap.CreateAttribute("rgbaPoints", Sdf.ValueTypeNames.Float4Array).Set(rgbaPoints)
colormap.CreateAttribute("domain", Sdf.ValueTypeNames.Float2).Set((0.0, 1.0))
if self.shader:
# Add shader source code
shader.SetSourceCode(ShaderPresets.get(self.shader), "xac")
return True
except Exception as e:
carb.log_warn(f"ERROR: Cannot add volume asset {self.asset_file_path}: {e}")
return False
def undo(self):
if not self.ext:
carb.log_error(f"Cannot undo adding volume {self.asset_file_path}. Extension is no longer loaded.")
return False
current_stage = omni.usd.get_context().get_stage()
if current_stage != self.stage or self.volume_prim is None or not self.volume_prim.IsValid():
carb.log_warn(f"Cannot undo adding volume {self.asset_file_path}. Stage is no longer loaded.")
return False
try:
self.stage.RemovePrim(self.volume_prim.GetPath())
self.volume_prim = None
return True
except Exception as e:
carb.log_warn(f"ERROR: Cannot remove volume {self.asset_file_path}: {e}")
return False
omni.kit.commands.register_all_commands_in_module(__name__)
| 25,920 | Python | 46.043557 | 145 | 0.618056 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/presets/colormap_presets.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.
#
class ColormapPresets:
DEFAULT = "Grayscale Ramp"
GENERATORS = {
# Simple color ramp from fully transparent white to semi-transparent gray
DEFAULT: lambda size, src : ColormapPresets._generate_ramp(size, src),
"Darker Grayscale Ramp": lambda size, src : ColormapPresets._generate_ramp(size, src, (1, 1, 1, 0), (0, 0, 0, 0.5)),
# Same, but with one color
"Red Ramp": lambda size, src : ColormapPresets._generate_ramp(size, src, (1, 0, 0, 0), (0.5, 0.0, 0.0, 0.5)),
"Green Ramp": lambda size, src : ColormapPresets._generate_ramp(size, src, (0, 1, 0, 0), (0.0, 0.0, 0.0, 0.5)),
"Blue Ramp": lambda size, src : ColormapPresets._generate_ramp(size, src, (0, 0, 1, 0), (0.0, 0.0, 0.0, 0.5)),
# Three colors
"White-Yellow-Red": lambda size, src : ColormapPresets._generate_three_colors(
size, src, (1.0, 1.0, 1.0), (1.0, 1.0, 0.0), (1.0, 0.0, 0.0), 0.0, 0.5),
"Red-Green-Blue": lambda size, src : ColormapPresets._generate_three_colors(
size, src, (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), 0.0, 0.5),
"Blue-White-Red": lambda size, src : ColormapPresets._generate_three_colors(
size, src, (0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0), 0.0, 0.5),
"Black-Red-Yellow": lambda size, src : ColormapPresets._generate_three_colors(
size, src, (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), 0.0, 0.5),
"Black-Blue-White": lambda size, src : ColormapPresets._generate_three_colors(
size, src, (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (1.0, 1.0, 1.0), 0.0, 0.5),
}
def _generate_ramp(colormap_size = 256, colormap_source = "", ramp_min = (1.0, 1.0, 1.0, 0.0), ramp_max = (0.5, 0.5, 0.5, 0.5)):
if colormap_source == "rgbaPoints":
return (
[0, 1], # xPoints
[ramp_min, ramp_max] # rgbaPoints
)
c = [0, 0, 0, 0]
colormap_data = [tuple(c)] * colormap_size
for i in range(colormap_size):
u = i / (colormap_size - 1)
for j in range(4):
c[j] = ramp_min[j] * (1.0 - u) + ramp_max[j] * u
colormap_data[i] = tuple(c)
return colormap_data
def _generate_three_colors(colormap_size, colormap_source, color1, color2, color3, opacity_ramp_min = 0.0, opacity_ramp_max = 0.5):
if colormap_source == "rgbaPoints":
opacity_ramp_mid = (opacity_ramp_min + opacity_ramp_max) / 2
return (
[0, 0.5, 1], # xPoints
[color1 + (opacity_ramp_min,), color2 + (opacity_ramp_mid,), color3 + (opacity_ramp_max,)] # rgbaPoints
)
c = [0, 0, 0, 0]
colormap_data = [tuple(c)] * colormap_size
for i in range(colormap_size):
u = i / (colormap_size - 1)
for j in range(3):
if u < 0.5:
c[j] = color1[j] * (1.0 - u) + color2[j] * u
else:
c[j] = color2[j] * (1.0 - u) + color3[j] * u
c[3] = opacity_ramp_min * (1.0 - u) + opacity_ramp_max * u
colormap_data[i] = tuple(c)
return colormap_data
def get_labels():
return list(ColormapPresets.GENERATORS.keys())
def generate(label, colormap_size = 256, colormap_source = ""):
if label in ColormapPresets.GENERATORS:
return ColormapPresets.GENERATORS[label](colormap_size, colormap_source)
else:
return None
def has(label):
return (label in ColormapPresets.GENERATORS)
| 4,152 | Python | 46.193181 | 135 | 0.544316 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/presets/__init__.py | from .colormap_presets import ColormapPresets
from .shader_presets import ShaderPresets
| 88 | Python | 28.666657 | 45 | 0.863636 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/presets/shader_presets.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.
#
class ShaderPresets:
SHADERS = {
"Minimal Volume Shader": """\
NV_IDX_XAC_VERSION_1_0
using namespace nv::index::xac;
class Volume_sample_program
{
NV_IDX_VOLUME_SAMPLE_PROGRAM
public:
NV_IDX_DEVICE_INLINE_MEMBER
void initialize() {}
NV_IDX_DEVICE_INLINE_MEMBER
int execute(
const Sample_info_self& sample_info,
Sample_output& sample_output)
{
// get reference to the volume and its colormap
const auto& volume = state.self;
const Colormap& colormap = state.self.get_colormap();
// generate a volume sampler
const auto sampler = volume.generate_sampler<float>();
// get current sample position
const float3& sample_position = sample_info.sample_position_object_space;
// sample the volume at the current position
const float sample_value = sampler.fetch_sample(sample_position);
// apply the colormap
const float4 sample_color = colormap.lookup(sample_value);
// store the output color
sample_output.set_color(sample_color);
return NV_IDX_PROG_OK;
}
};
""",
"Red Shader": """\
NV_IDX_XAC_VERSION_1_0
using namespace nv::index::xac;
class Volume_sample_program
{
NV_IDX_VOLUME_SAMPLE_PROGRAM
public:
NV_IDX_DEVICE_INLINE_MEMBER
void initialize() {}
NV_IDX_DEVICE_INLINE_MEMBER
int execute(
const Sample_info_self& sample_info,
Sample_output& sample_output)
{
// get reference to the volume and its colormap
const auto& volume = state.self;
const Colormap& colormap = state.self.get_colormap();
// generate a volume sampler
const auto sampler = volume.generate_sampler<float>();
// get current sample position
const float3& sample_position = sample_info.sample_position_object_space;
// sample the volume at the current position
const float sample_value = sampler.fetch_sample(sample_position);
// apply the colormap
float4 sample_color = colormap.lookup(sample_value);
// make it more reddish
sample_color.x = 1.f;
// store the output color
sample_output.set_color(sample_color);
return NV_IDX_PROG_OK;
}
};
""",
}
def get_labels():
return list(ShaderPresets.SHADERS.keys())
def get(label):
if label in ShaderPresets.SHADERS:
return ShaderPresets.SHADERS[label]
else:
return None
def has(label):
return (label in ShaderPresets.SHADERS)
| 3,027 | Python | 26.279279 | 81 | 0.65147 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/common_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.
#
from omni.kit.widget.settings import SettingType
import omni.ui as ui
import carb
import omni.kit.app
from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack
from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame
from omni.rtx.window.settings.rendersettingsdefaults import SettingsDefaultHandler
class SceneSettingsFrame(SettingsCollectionFrame):
def _build_ui(self):
self._add_setting(
SettingType.DOUBLE3,
"Region of Interest Min",
"/rtx/index/regionOfInterestMin",
tooltip="Start of region of interest",
has_reset=False,
)
self._add_setting(
SettingType.DOUBLE3,
"Region of Interest Max",
"/rtx/index/regionOfInterestMax",
tooltip="End of region of interest",
has_reset=False,
)
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/nvindex/dataBboxMin", self._on_change)
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/nvindex/dataBboxMax", self._on_change)
dataBboxMin = self._settings.get("/nvindex/dataBboxMin")
dataBboxMax = self._settings.get("/nvindex/dataBboxMax")
def do_reset_to_scene_extent():
self._settings.set("/rtx/index/regionOfInterestMin", dataBboxMin)
self._settings.set("/rtx/index/regionOfInterestMax", dataBboxMax)
if dataBboxMin and dataBboxMax:
dataBboxValid = True
for i in range(0, 3):
if (dataBboxMin[i] >= dataBboxMax[i]):
dataBboxValid = False
if dataBboxValid:
ui.Button("Reset to Data Extent", tooltip="Resets the region of interest to contain all scene element",
clicked_fn=do_reset_to_scene_extent)
self._add_setting(
SettingType.FLOAT,
"Default Point Width",
"/rtx/index/defaultPointWidth",
tooltip="Default point width for new point clouds loaded from USD. If set to 0, a simple heuristic will be used.",
)
if self._settings.get("/nvindex/showAdvancedSettings"):
subdivisionModeItems = {
"Default": "",
"Grid": "grid",
"KD-tree": "kd_tree",
}
self._add_setting_combo(
"Override Subdivision Mode",
"/rtx/index/overrideSubdivisionMode",
subdivisionModeItems,
tooltip="Override data subdivision mode, only affects newly added datasets."
)
self._add_setting(
SettingType.INT,
"Override Subdivision Part Count",
"/rtx/index/overrideSubdivisionPartCount",
0,
256,
tooltip="Override number of parts for kd_tree subdivision, only affects newly added datasets."
)
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
super().destroy()
class RenderSettingsFrame(SettingsCollectionFrame):
def _build_ui(self):
composite_rendering = self._settings.get("/nvindex/compositeRenderingMode")
if composite_rendering:
self._add_setting(
SettingType.FLOAT,
"Color Scaling",
"/rtx/index/colorScale",
0.0,
100.0,
tooltip="Scale factor for color output",
)
else:
self._add_setting(
SettingType.COLOR3,
"Background Color",
"/rtx/index/backgroundColor",
tooltip="Color of scene background",
)
if self._settings.get("/nvindex/showAdvancedSettings"):
self._add_setting(
SettingType.FLOAT,
"Background Opacity",
"/rtx/index/backgroundOpacity",
0.0,
1.0,
tooltip="Opacity of scene background",
)
self._add_setting(
SettingType.BOOL,
"Frame Buffer Blending",
"/rtx/index/frameBufferBlending",
tooltip="Blend rendering result to frame buffer",
)
self._add_setting(
SettingType.INT,
"Rendering Samples",
"/rtx/index/renderingSamples",
1,
32,
tooltip="Number of samples per pixel used during rendering",
)
class CompositingSettingsFrame(SettingsCollectionFrame):
def _build_ui(self):
self._add_setting(
SettingType.BOOL,
"Automatic Span Control",
"/rtx/index/automaticSpanControl",
tooltip="Automatically optimize the number of spans used for compositing",
)
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/index/automaticSpanControl", self._on_change)
if not self._settings.get("/rtx/index/automaticSpanControl"):
self._add_setting(
SettingType.INT,
"Horizontal spans",
"/rtx/index/nbSpans",
1,
100,
tooltip="Number of spans used for compositing, when automatic span control is not used",
)
self._add_setting(
SettingType.INT,
"Host Span Limit",
"/rtx/index/maxSpansPerMachine",
1,
100,
tooltip="Maximum number of spans per host",
)
def destroy(self):
self._change_cb = None
super().destroy()
class AdvancedSettingsFrame(SettingsCollectionFrame):
def _build_ui(self):
self._add_setting(
SettingType.BOOL,
"Monitor Performance Values",
"/rtx/index/monitorPerformanceValues",
tooltip="Print performance statistics to stdout",
)
self._add_setting(
SettingType.STRING,
"Session Export File (optional)",
"/nvindex/exportSessionFilename",
tooltip="Absolute path where to write the session export to. If empty, the log will be used.",
)
self._change_cb = omni.kit.app.SettingChangeSubscription("/nvindex/exportSessionFilename", self._on_change)
def do_export_session():
self._settings.set("/nvindex/exportSession", True)
exportTarget = "File" if self._settings.get("/nvindex/exportSessionFilename") else "Log"
ui.Button("Export Session to " + exportTarget, tooltip="Export session information", clicked_fn=do_export_session)
restart_msg = "changing it requires restarting IndeX"
logLevelItems = {
"Debug": "debug",
"Verbose": "verbose",
"Info": "info",
"Warning": "warning",
"Error": "error",
"Fatal": "fatal",
}
self._add_setting_combo(
"Log Level",
"/nvindex/logLevel",
logLevelItems,
tooltip="Log level for IndeX log message, " + restart_msg,
)
def do_restart_index():
self._settings.set("/nvindex/restartIndex", True)
ui.Button("Restart IndeX", tooltip="Restart the NVIDIA IndeX session, reloading all data", clicked_fn=do_restart_index)
def destroy(self):
self._change_cb = None
super().destroy()
class IndeXCommonSettingStack(RTXSettingsStack):
def __init__(self) -> None:
self._stack = ui.VStack(spacing=10)
self._settings = carb.settings.get_settings()
with self._stack:
SceneSettingsFrame("Scene Settings", parent=self)
RenderSettingsFrame("Render Settings", parent=self)
if self._settings.get("/nvindex/showAdvancedSettings"):
CompositingSettingsFrame("Compositing Settings", parent=self)
AdvancedSettingsFrame("Advanced", parent=self)
ui.Spacer()
| 8,550 | Python | 34.334711 | 127 | 0.579181 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/volume_properties_widget.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 carb.settings
import omni.kit.app
import omni.ui as ui
from pxr import Sdf, UsdShade
from ..presets import ColormapPresets
from .index_properties_base_widget import IndexPropertiesBaseWidget
class VolumePropertiesWidget(IndexPropertiesBaseWidget):
point_cloud_types = [ "PointCloud", "StreamingSettings"]
def __init__(self):
self.settings = carb.settings.get_settings()
super().__init__("IndeX Volume", ["Volume", "Points"] + VolumePropertiesWidget.point_cloud_types)
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/index/compositeEnabled", self._on_change)
def clean(self):
self._change_cb = None
super().clean()
def _on_change(self, *_):
self.request_rebuild()
def set_volume_type(self, combo_model, item):
prim = self.get_prim()
volume_type = combo_model.get_current_string()
if volume_type == "default":
prim.GetAttribute("nvindex:type").Clear()
else:
prim.CreateAttribute("nvindex:type", Sdf.ValueTypeNames.Token, True, Sdf.VariabilityUniform).Set(volume_type)
self.request_rebuild() # update UI to change mode
def get_compositing(self):
return self.get_prim().GetAttribute("nvindex:composite").Get() == True
def set_compositing(self, enable):
self.get_prim().CreateAttribute("nvindex:composite", Sdf.ValueTypeNames.Bool, custom=True).Set(enable)
if enable:
self.set_rtx_skip(True) # don't disable it here
self.request_rebuild() # update UI
def get_rtx_skip(self):
return self.get_prim().GetAttribute("omni:rtx:skip").Get() == True
def set_rtx_skip(self, skip):
self.get_prim().CreateAttribute("omni:rtx:skip", Sdf.ValueTypeNames.Bool, custom=True).Set(skip)
def create_material(self):
volume_prim = self.get_prim()
stage = volume_prim.GetStage()
material_path_base = str(volume_prim.GetPath()) + "/Material"
material_path = material_path_base
# Make material path unique
i = 0
while stage.GetPrimAtPath(material_path):
i += 1
material_path = material_path_base + str(i)
colormap_path = f"{material_path}/Colormap"
shader_path = f"{material_path}/VolumeShader"
colormap = stage.DefinePrim(colormap_path, "Colormap")
colormap_output = colormap.CreateAttribute("outputs:colormap", Sdf.ValueTypeNames.Token)
colormap.CreateAttribute("domain", Sdf.ValueTypeNames.Float2).Set((0.0, 1.0))
material = UsdShade.Material.Define(stage, material_path)
binding_api = UsdShade.MaterialBindingAPI.Apply(volume_prim)
binding_api.Bind(material)
shader = UsdShade.Shader.Define(stage, shader_path)
shader_output = shader.CreateOutput("volume", Sdf.ValueTypeNames.Token)
material.CreateVolumeOutput("nvindex").ConnectToSource(shader_output)
shader.CreateInput("colormap", Sdf.ValueTypeNames.Token).ConnectToSource(colormap_output.GetPath())
colormapSource = "rgbaPoints"
colormap.CreateAttribute("colormapSource", Sdf.ValueTypeNames.Token).Set(colormapSource)
(xPoints, rgbaPoints) = ColormapPresets.generate(ColormapPresets.DEFAULT, colormap_source=colormapSource)
colormap.CreateAttribute("xPoints", Sdf.ValueTypeNames.FloatArray).Set(xPoints)
colormap.CreateAttribute("rgbaPoints", Sdf.ValueTypeNames.Float4Array).Set(rgbaPoints)
def build_properties(self, stage, prim, prim_path):
with ui.VStack(spacing=5):
# Volume type
current_volume_type = prim.GetAttribute("nvindex:type").Get()
if not current_volume_type and (prim.GetTypeName() == "Points" or prim.GetTypeName() in VolumePropertiesWidget.point_cloud_types):
current_volume_type = "particle_volume"
if self._collapsable_frame:
self._collapsable_frame.title = "IndeX Points"
if self.settings.get("/nvindex/compositeRenderingMode") and prim.GetTypeName() not in VolumePropertiesWidget.point_cloud_types:
if not self.settings.get("/rtx/index/compositeEnabled"):
self.build_label(
"NVIDIA IndeX Compositing is currently not active. "
"You can enable it in 'Render Settings / Common / NVIDIA IndeX Compositing'.", full_width=True)
ui.Separator()
# Enable/disable composite rendering for this prim
with ui.HStack():
self.build_label("Use IndeX compositing")
widget = ui.CheckBox(name="nvindex_composite")
widget.model.set_value(self.get_compositing())
widget.model.add_value_changed_fn(lambda m: self.set_compositing(m.get_value_as_bool()))
with ui.HStack():
self.build_label("Skip in RTX renderer")
widget = ui.CheckBox(name="rtx_skip")
widget.model.set_value(self.get_rtx_skip())
widget.model.add_value_changed_fn(lambda m: self.set_rtx_skip(m.get_value_as_bool()))
# Skip rest of UI unless compositing is enabled
if not self.get_compositing():
return
ui.Separator()
with ui.HStack():
self.build_label("Volume Type")
volume_types_list = ["vdb", "sparse_volume"]
if current_volume_type is None or current_volume_type in volume_types_list:
self.volume_type_widget = ui.ComboBox(self.create_combo_list_model(current_volume_type, ["default"] + volume_types_list), name="volume_type")
self.volume_type_widget.model.add_item_changed_fn(self.set_volume_type)
else:
self.build_label(current_volume_type)
render_settings = prim.GetCustomDataByKey(self.USD_RENDERSETTINGS)
if current_volume_type != "irregular_volume":
# Common settings (except for irregular volumes)
self.build_render_setting_float(
"Sampling Distance", "samplingDistance",
-1.0,
render_settings)
self.build_render_setting_float(
"Reference Sampling Distance", "referenceSamplingDistance",
-1.0,
render_settings)
if current_volume_type == "sparse_volume":
# self.build_render_setting_int3(
# "Voxel Offsets", "voxelOffsets",
# [-1.0, -1.0, -1.0],
# render_settings)
# Filter Mode
self.build_render_setting_combo_box(
"Filter Mode", "filterMode",
["default", "nearest",
"trilinear", "trilinear_pre",
"tricubic_catmull", "tricubic_catmull_pre",
"tricubic_bspline", "tricubic_bspline_pre"],
render_settings)
self.build_render_setting_bool(
"LOD Rendering", "lodRenderingEnabled",
False,
render_settings)
self.build_render_setting_float(
"LOD Pixel Threshold", "lodPixelThreshold",
-1.0,
render_settings)
self.build_render_setting_bool(
"Preintegration", "preintegratedVolumeRendering",
False,
render_settings)
elif current_volume_type == "particle_volume":
self.build_render_setting_combo_box(
"Rendering Mode", "renderingMode",
["default", "rbf", "solid_box", "solid_cone", "solid_cylinder", "solid_sphere", "solid_disc"],
render_settings)
self.build_render_setting_combo_box(
"RBF Falloff Kernel", "rbfFalloffKernel",
["default", "constant", "linear", "hermite", "spline"],
render_settings)
# Prefer point width as it is used by USD, but also support IndeX point radius
if render_settings and "overrideFixedRadius" in render_settings:
self.build_render_setting_float(
"Override Fixed Radius", "overrideFixedRadius",
-1.0,
render_settings)
else:
self.build_render_setting_float(
"Override Fixed Width", "overrideFixedWidth",
-1.0,
render_settings)
if prim.GetTypeName() in VolumePropertiesWidget.point_cloud_types:
self.build_render_setting_float(
"Spacing Point Width Factor", "spacingPointWidthFactor",
-1.0,
render_settings)
elif current_volume_type == "irregular_volume":
self.build_render_setting_float(
"Halo Size", "haloSize",
-1.0,
render_settings)
self.build_render_setting_int(
"Sampling Mode", "samplingMode",
-1,
render_settings)
self.build_render_setting_float(
"Sampling Segment Length", "samplingSegmentLength",
-1.0,
render_settings)
self.build_render_setting_float(
"Sampling Reference Segment Length", "samplingReferenceSegmentLength",
-1.0,
render_settings)
else: # vdb (default)
# Filter Mode
self.build_render_setting_combo_box(
"Filter Mode", "filterMode",
["default", "nearest", "trilinear"],
render_settings)
self.build_render_setting_int(
"Subset Voxel Border", "subsetVoxelBorder",
-1,
render_settings)
if self.show_advanced_settings:
if current_volume_type == "irregular_volume":
self.build_render_setting_int(
"Diagnostics Mode", "diagnosticsMode",
0,
render_settings)
self.build_render_setting_int(
"Diagnostics Flags", "diagnosticsFlags",
0,
render_settings)
self.build_render_setting_float(
"Wireframe Size", "wireframeSize",
0.001,
render_settings)
self.build_render_setting_float(
"Wireframe Color Mod Begin", "wireframeColorModBegin",
0.0,
render_settings)
self.build_render_setting_float(
"Wireframe Color Mod Factor", "wireframeColorModFactor",
0.0,
render_settings)
else:
self.build_render_setting_int(
"Debug Visualization", "debugVisualizationOption",
0,
render_settings)
# Show timestep only if already defined
timestep = prim.GetAttribute("nvindex:timestep")
if timestep:
with ui.HStack():
self.build_label("Timestep")
widget = ui.FloatField(name="timestep")
widget.model.set_value(timestep.Get() or 0.0)
widget.model.add_value_changed_fn(lambda m: self.store_value("nvindex:timestep", m.get_value_as_float(), 0.0, Sdf.ValueTypeNames.Double))
with ui.HStack():
ui.Button("Create Volume Material", clicked_fn=self.create_material, name="createVolumeMaterial")
| 12,537 | Python | 42.839161 | 161 | 0.564011 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/cluster_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.
#
from omni.kit.widget.settings import SettingType
import omni.ui as ui
import carb
import omni.kit.app
from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack
from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame
from omni.rtx.window.settings.rendersettingsdefaults import SettingsDefaultHandler
class ClusterCompositingSettingsFrame(SettingsCollectionFrame):
def _build_ui(self):
compositingModeItems = {
"All": "COMPOSITING_ALL",
"Local Only": "COMPOSITING_LOCAL_ONLY",
"Remote Only": "COMPOSITING_REMOTE_ONLY",
"None": "NO_COMPOSITING"
}
self._add_setting_combo(
"Compositing Mode",
"/rtx/index/compositingMode",
compositingModeItems,
tooltip="Control distribution of the compositing workload",
)
if not self._settings.get("/nvindex/showAdvancedSettings"):
return
self._add_setting(
SettingType.BOOL,
"Transfer Span Alpha Channel",
"/rtx/index/spanAlphaChannel",
tooltip="Enable transfer of the alpha channel for horizontal span image data",
)
self._add_setting(
SettingType.BOOL,
"Span Image Encoding",
"/rtx/index/spanImageEncoding",
tooltip="Use special image encoding to improve compression for horizontal span image data",
)
self._add_setting(
SettingType.BOOL,
"Tile Image Encoding",
"/rtx/index/tileImageEncoding",
tooltip="Use special image encoding to improve compression for intermediate tile image data",
)
self._add_setting(
SettingType.INT,
"Span Compression Level",
"/rtx/index/spanCompressionLevel",
0,
9,
tooltip="Compression level for transfer of horizontal span image data",
)
self._add_setting(
SettingType.INT,
"Tile Compression Level",
"/rtx/index/tileCompressionLevel",
0,
9,
tooltip="Compression level for transfer of intermediate tiles image data",
)
self._add_setting(
SettingType.INT,
"Span Compression Mode",
"/rtx/index/spanCompressionMode",
0,
9,
tooltip="Compression mode for transfer of horizontal span image data",
)
self._add_setting(
SettingType.INT,
"Tile Compression Mode",
"/rtx/index/tileCompressionMode",
0,
9,
tooltip="Compression mode for transfer of intermediate tiles image data",
)
self._add_setting(
SettingType.INT,
"Span Compression Threads",
"/rtx/index/spanCompressionThreads",
0,
64,
tooltip="Number of threads to use for compressing horizontal span image data (0=default)",
)
self._add_setting(
SettingType.INT,
"Tile Compression Threads",
"/rtx/index/tileCompressionThreads",
0,
64,
tooltip="Number of threads to use for compressing intermediate tiles image data (0=default)",
)
if self._settings.get("/nvindex/compositeRenderingMode"):
self._add_setting(
SettingType.INT,
"Depth Buffer Compression Level",
"/rtx/index/depthBufferCompressionLevel",
0,
9,
tooltip="Compression level for transfer of depth buffer data",
)
self._add_setting(
SettingType.INT,
"Depth Buffer Compression Mode",
"/rtx/index/depthBufferCompressionMode",
0,
9,
tooltip="Compression mode for transfer of depth buffer data",
)
self._add_setting(
SettingType.INT,
"Depth Buffer Compression Threads",
"/rtx/index/depthBufferCompressionThreads",
0,
64,
tooltip="Number of threads to use for compressing depth buffer data (0=default)",
)
class ClusterNetworkSettingsFrame(SettingsCollectionFrame):
def _build_ui(self):
network_enabled_path = "/nvindex/state/networkEnabled"
cluster_message_path = "/nvindex/state/clusterMessage"
self._change_cb_network_enabled = omni.kit.app.SettingChangeSubscription(network_enabled_path, self._on_change)
self._change_cb_cluster_message = omni.kit.app.SettingChangeSubscription(cluster_message_path, self._on_change)
restart_msg = "changing it requires restarting IndeX"
networkModeItem = {
"UDP": "udp",
"TCP": "tcp",
"OFF": "off",
}
self._add_setting_combo(
"Network Mode",
"/nvindex/networkMode",
networkModeItem,
tooltip="Mode for IndeX cluster mode, " + restart_msg,
)
self._add_setting(
SettingType.STRING,
"Discovery Address",
"/nvindex/discoveryAddress",
tooltip="Discovery address for cluster mode, " + restart_msg,
)
self._add_setting(
SettingType.STRING,
"Multicast Address",
"/nvindex/multicastAddress",
tooltip="Multicast address for cluster mode, " + restart_msg
)
self._add_setting(
SettingType.STRING,
"Cluster Interface Address",
"/nvindex/clusterInterfaceAddress",
tooltip="Network interface to use cluster mode, " + restart_msg
)
self._add_setting(
SettingType.INT,
"Minimum Cluster Size",
"/nvindex/minimumClusterSize",
tooltip="Minimum size of the cluster to start rendering"
)
serviceModeItems = {
"Rendering + Compositing ": "rendering_and_compositing",
"Rendering only": "rendering",
"Compositing only": "compositing",
"None": "none",
}
self._add_setting_combo(
"Service Mode",
"/nvindex/clusterServiceMode",
serviceModeItems,
tooltip="Service mode of the current host, use 'None' render remotely only, " + restart_msg,
)
self._add_setting(
SettingType.STRING,
"Cluster Identifier",
"/nvindex/clusterIdentifier",
tooltip="Optional identifier, must be the same on all hosts, " + restart_msg,
)
def do_restart_index():
self._settings.set("/nvindex/restartIndex", True)
ui.Button("Restart IndeX", tooltip="Restart the NVIDIA IndeX session, reloading all data", clicked_fn=do_restart_index)
if self._settings.get(network_enabled_path):
ui.Label("Cluster State:", alignment=ui.Alignment.CENTER)
ui.Label(self._settings.get(cluster_message_path), word_wrap=True)
def destroy(self):
self._change_cb = None
self._change_cb_network_enabled = None
self._change_cb_cluster_message = None
super().destroy()
class IndeXClusterSettingStack(RTXSettingsStack):
def __init__(self) -> None:
self._stack = ui.VStack(spacing=10)
self._settings = carb.settings.get_settings()
with self._stack:
ClusterCompositingSettingsFrame("Cluster Compositing Settings", parent=self)
ClusterNetworkSettingsFrame("Network Settings", parent=self)
ui.Spacer()
| 8,227 | Python | 33.717299 | 127 | 0.587213 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.