file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_pmap.py
from collections.abc import Mapping, Hashable from itertools import chain from pyrsistent._pvector import pvector from pyrsistent._transformations import transform class PMapView: """View type for the persistent map/dict type `PMap`. Provides an equivalent of Python's built-in `dict_values` and `dict_items` types that result from expreessions such as `{}.values()` and `{}.items()`. The equivalent for `{}.keys()` is absent because the keys are instead represented by a `PSet` object, which can be created in `O(1)` time. The `PMapView` class is overloaded by the `PMapValues` and `PMapItems` classes which handle the specific case of values and items, respectively Parameters ---------- m : mapping The mapping/dict-like object of which a view is to be created. This should generally be a `PMap` object. """ # The public methods that use the above. def __init__(self, m): # Make sure this is a persistnt map if not isinstance(m, PMap): # We can convert mapping objects into pmap objects, I guess (but why?) if isinstance(m, Mapping): m = pmap(m) else: raise TypeError("PViewMap requires a Mapping object") object.__setattr__(self, '_map', m) def __len__(self): return len(self._map) def __setattr__(self, k, v): raise TypeError("%s is immutable" % (type(self),)) def __reversed__(self): raise TypeError("Persistent maps are not reversible") class PMapValues(PMapView): """View type for the values of the persistent map/dict type `PMap`. Provides an equivalent of Python's built-in `dict_values` type that result from expreessions such as `{}.values()`. See also `PMapView`. Parameters ---------- m : mapping The mapping/dict-like object of which a view is to be created. This should generally be a `PMap` object. """ def __iter__(self): return self._map.itervalues() def __contains__(self, arg): return arg in self._map.itervalues() # The str and repr methods imitate the dict_view style currently. def __str__(self): return f"pmap_values({list(iter(self))})" def __repr__(self): return f"pmap_values({list(iter(self))})" def __eq__(self, x): # For whatever reason, dict_values always seem to return False for == # (probably it's not implemented), so we mimic that. if x is self: return True else: return False class PMapItems(PMapView): """View type for the items of the persistent map/dict type `PMap`. Provides an equivalent of Python's built-in `dict_items` type that result from expreessions such as `{}.items()`. See also `PMapView`. Parameters ---------- m : mapping The mapping/dict-like object of which a view is to be created. This should generally be a `PMap` object. """ def __iter__(self): return self._map.iteritems() def __contains__(self, arg): try: (k,v) = arg except Exception: return False return k in self._map and self._map[k] == v # The str and repr methods mitate the dict_view style currently. def __str__(self): return f"pmap_items({list(iter(self))})" def __repr__(self): return f"pmap_items({list(iter(self))})" def __eq__(self, x): if x is self: return True elif not isinstance(x, type(self)): return False else: return self._map == x._map class PMap(object): """ Persistent map/dict. Tries to follow the same naming conventions as the built in dict where feasible. Do not instantiate directly, instead use the factory functions :py:func:`m` or :py:func:`pmap` to create an instance. Was originally written as a very close copy of the Clojure equivalent but was later rewritten to closer re-assemble the python dict. This means that a sparse vector (a PVector) of buckets is used. The keys are hashed and the elements inserted at position hash % len(bucket_vector). Whenever the map size exceeds 2/3 of the containing vectors size the map is reallocated to a vector of double the size. This is done to avoid excessive hash collisions. This structure corresponds most closely to the built in dict type and is intended as a replacement. Where the semantics are the same (more or less) the same function names have been used but for some cases it is not possible, for example assignments and deletion of values. PMap implements the Mapping protocol and is Hashable. It also supports dot-notation for element access. Random access and insert is log32(n) where n is the size of the map. The following are examples of some common operations on persistent maps >>> m1 = m(a=1, b=3) >>> m2 = m1.set('c', 3) >>> m3 = m2.remove('a') >>> m1 == {'a': 1, 'b': 3} True >>> m2 == {'a': 1, 'b': 3, 'c': 3} True >>> m3 == {'b': 3, 'c': 3} True >>> m3['c'] 3 >>> m3.c 3 """ __slots__ = ('_size', '_buckets', '__weakref__', '_cached_hash') def __new__(cls, size, buckets): self = super(PMap, cls).__new__(cls) self._size = size self._buckets = buckets return self @staticmethod def _get_bucket(buckets, key): index = hash(key) % len(buckets) bucket = buckets[index] return index, bucket @staticmethod def _getitem(buckets, key): _, bucket = PMap._get_bucket(buckets, key) if bucket: for k, v in bucket: if k == key: return v raise KeyError(key) def __getitem__(self, key): return PMap._getitem(self._buckets, key) @staticmethod def _contains(buckets, key): _, bucket = PMap._get_bucket(buckets, key) if bucket: for k, _ in bucket: if k == key: return True return False return False def __contains__(self, key): return self._contains(self._buckets, key) get = Mapping.get def __iter__(self): return self.iterkeys() # If this method is not defined, then reversed(pmap) will attempt to reverse # the map using len() and getitem, usually resulting in a mysterious # KeyError. def __reversed__(self): raise TypeError("Persistent maps are not reversible") def __getattr__(self, key): try: return self[key] except KeyError as e: raise AttributeError( "{0} has no attribute '{1}'".format(type(self).__name__, key) ) from e def iterkeys(self): for k, _ in self.iteritems(): yield k # These are more efficient implementations compared to the original # methods that are based on the keys iterator and then calls the # accessor functions to access the value for the corresponding key def itervalues(self): for _, v in self.iteritems(): yield v def iteritems(self): for bucket in self._buckets: if bucket: for k, v in bucket: yield k, v def values(self): return PMapValues(self) def keys(self): from ._pset import PSet return PSet(self) def items(self): return PMapItems(self) def __len__(self): return self._size def __repr__(self): return 'pmap({0})'.format(str(dict(self))) def __eq__(self, other): if self is other: return True if not isinstance(other, Mapping): return NotImplemented if len(self) != len(other): return False if isinstance(other, PMap): if (hasattr(self, '_cached_hash') and hasattr(other, '_cached_hash') and self._cached_hash != other._cached_hash): return False if self._buckets == other._buckets: return True return dict(self.iteritems()) == dict(other.iteritems()) elif isinstance(other, dict): return dict(self.iteritems()) == other return dict(self.iteritems()) == dict(other.items()) __ne__ = Mapping.__ne__ def __lt__(self, other): raise TypeError('PMaps are not orderable') __le__ = __lt__ __gt__ = __lt__ __ge__ = __lt__ def __str__(self): return self.__repr__() def __hash__(self): if not hasattr(self, '_cached_hash'): self._cached_hash = hash(frozenset(self.iteritems())) return self._cached_hash def set(self, key, val): """ Return a new PMap with key and val inserted. >>> m1 = m(a=1, b=2) >>> m2 = m1.set('a', 3) >>> m3 = m1.set('c' ,4) >>> m1 == {'a': 1, 'b': 2} True >>> m2 == {'a': 3, 'b': 2} True >>> m3 == {'a': 1, 'b': 2, 'c': 4} True """ return self.evolver().set(key, val).persistent() def remove(self, key): """ Return a new PMap without the element specified by key. Raises KeyError if the element is not present. >>> m1 = m(a=1, b=2) >>> m1.remove('a') pmap({'b': 2}) """ return self.evolver().remove(key).persistent() def discard(self, key): """ Return a new PMap without the element specified by key. Returns reference to itself if element is not present. >>> m1 = m(a=1, b=2) >>> m1.discard('a') pmap({'b': 2}) >>> m1 is m1.discard('c') True """ try: return self.remove(key) except KeyError: return self def update(self, *maps): """ Return a new PMap with the items in Mappings inserted. If the same key is present in multiple maps the rightmost (last) value is inserted. >>> m1 = m(a=1, b=2) >>> m1.update(m(a=2, c=3), {'a': 17, 'd': 35}) == {'a': 17, 'b': 2, 'c': 3, 'd': 35} True """ return self.update_with(lambda l, r: r, *maps) def update_with(self, update_fn, *maps): """ Return a new PMap with the items in Mappings maps inserted. If the same key is present in multiple maps the values will be merged using merge_fn going from left to right. >>> from operator import add >>> m1 = m(a=1, b=2) >>> m1.update_with(add, m(a=2)) == {'a': 3, 'b': 2} True The reverse behaviour of the regular merge. Keep the leftmost element instead of the rightmost. >>> m1 = m(a=1) >>> m1.update_with(lambda l, r: l, m(a=2), {'a':3}) pmap({'a': 1}) """ evolver = self.evolver() for map in maps: for key, value in map.items(): evolver.set(key, update_fn(evolver[key], value) if key in evolver else value) return evolver.persistent() def __add__(self, other): return self.update(other) __or__ = __add__ def __reduce__(self): # Pickling support return pmap, (dict(self),) def transform(self, *transformations): """ Transform arbitrarily complex combinations of PVectors and PMaps. A transformation consists of two parts. One match expression that specifies which elements to transform and one transformation function that performs the actual transformation. >>> from pyrsistent import freeze, ny >>> news_paper = freeze({'articles': [{'author': 'Sara', 'content': 'A short article'}, ... {'author': 'Steve', 'content': 'A slightly longer article'}], ... 'weather': {'temperature': '11C', 'wind': '5m/s'}}) >>> short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:25] + '...' if len(c) > 25 else c) >>> very_short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:15] + '...' if len(c) > 15 else c) >>> very_short_news.articles[0].content 'A short article' >>> very_short_news.articles[1].content 'A slightly long...' When nothing has been transformed the original data structure is kept >>> short_news is news_paper True >>> very_short_news is news_paper False >>> very_short_news.articles[0] is news_paper.articles[0] True """ return transform(self, transformations) def copy(self): return self class _Evolver(object): __slots__ = ('_buckets_evolver', '_size', '_original_pmap') def __init__(self, original_pmap): self._original_pmap = original_pmap self._buckets_evolver = original_pmap._buckets.evolver() self._size = original_pmap._size def __getitem__(self, key): return PMap._getitem(self._buckets_evolver, key) def __setitem__(self, key, val): self.set(key, val) def set(self, key, val): kv = (key, val) index, bucket = PMap._get_bucket(self._buckets_evolver, key) reallocation_required = len(self._buckets_evolver) < 0.67 * self._size if bucket: for k, v in bucket: if k == key: if v is not val: new_bucket = [(k2, v2) if k2 != k else (k2, val) for k2, v2 in bucket] self._buckets_evolver[index] = new_bucket return self # Only check and perform reallocation if not replacing an existing value. # This is a performance tweak, see #247. if reallocation_required: self._reallocate() return self.set(key, val) new_bucket = [kv] new_bucket.extend(bucket) self._buckets_evolver[index] = new_bucket self._size += 1 else: if reallocation_required: self._reallocate() return self.set(key, val) self._buckets_evolver[index] = [kv] self._size += 1 return self def _reallocate(self): new_size = 2 * len(self._buckets_evolver) new_list = new_size * [None] buckets = self._buckets_evolver.persistent() for k, v in chain.from_iterable(x for x in buckets if x): index = hash(k) % new_size if new_list[index]: new_list[index].append((k, v)) else: new_list[index] = [(k, v)] # A reallocation should always result in a dirty buckets evolver to avoid # possible loss of elements when doing the reallocation. self._buckets_evolver = pvector().evolver() self._buckets_evolver.extend(new_list) def is_dirty(self): return self._buckets_evolver.is_dirty() def persistent(self): if self.is_dirty(): self._original_pmap = PMap(self._size, self._buckets_evolver.persistent()) return self._original_pmap def __len__(self): return self._size def __contains__(self, key): return PMap._contains(self._buckets_evolver, key) def __delitem__(self, key): self.remove(key) def remove(self, key): index, bucket = PMap._get_bucket(self._buckets_evolver, key) if bucket: new_bucket = [(k, v) for (k, v) in bucket if k != key] if len(bucket) > len(new_bucket): self._buckets_evolver[index] = new_bucket if new_bucket else None self._size -= 1 return self raise KeyError('{0}'.format(key)) def evolver(self): """ Create a new evolver for this pmap. For a discussion on evolvers in general see the documentation for the pvector evolver. Create the evolver and perform various mutating updates to it: >>> m1 = m(a=1, b=2) >>> e = m1.evolver() >>> e['c'] = 3 >>> len(e) 3 >>> del e['a'] The underlying pmap remains the same: >>> m1 == {'a': 1, 'b': 2} True The changes are kept in the evolver. An updated pmap can be created using the persistent() function on the evolver. >>> m2 = e.persistent() >>> m2 == {'b': 2, 'c': 3} True The new pmap will share data with the original pmap in the same way that would have been done if only using operations on the pmap. """ return self._Evolver(self) Mapping.register(PMap) Hashable.register(PMap) def _turbo_mapping(initial, pre_size): if pre_size: size = pre_size else: try: size = 2 * len(initial) or 8 except Exception: # Guess we can't figure out the length. Give up on length hinting, # we can always reallocate later. size = 8 buckets = size * [None] if not isinstance(initial, Mapping): # Make a dictionary of the initial data if it isn't already, # that will save us some job further down since we can assume no # key collisions initial = dict(initial) for k, v in initial.items(): h = hash(k) index = h % size bucket = buckets[index] if bucket: bucket.append((k, v)) else: buckets[index] = [(k, v)] return PMap(len(initial), pvector().extend(buckets)) _EMPTY_PMAP = _turbo_mapping({}, 0) def pmap(initial={}, pre_size=0): """ Create new persistent map, inserts all elements in initial into the newly created map. The optional argument pre_size may be used to specify an initial size of the underlying bucket vector. This may have a positive performance impact in the cases where you know beforehand that a large number of elements will be inserted into the map eventually since it will reduce the number of reallocations required. >>> pmap({'a': 13, 'b': 14}) == {'a': 13, 'b': 14} True """ if not initial and pre_size == 0: return _EMPTY_PMAP return _turbo_mapping(initial, pre_size) def m(**kwargs): """ Creates a new persistent map. Inserts all key value arguments into the newly created map. >>> m(a=13, b=14) == {'a': 13, 'b': 14} True """ return pmap(kwargs)
18,781
Python
31.551126
127
0.559235
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_pbag.py
from collections.abc import Container, Iterable, Sized, Hashable from functools import reduce from pyrsistent._pmap import pmap def _add_to_counters(counters, element): return counters.set(element, counters.get(element, 0) + 1) class PBag(object): """ A persistent bag/multiset type. Requires elements to be hashable, and allows duplicates, but has no ordering. Bags are hashable. Do not instantiate directly, instead use the factory functions :py:func:`b` or :py:func:`pbag` to create an instance. Some examples: >>> s = pbag([1, 2, 3, 1]) >>> s2 = s.add(4) >>> s3 = s2.remove(1) >>> s pbag([1, 1, 2, 3]) >>> s2 pbag([1, 1, 2, 3, 4]) >>> s3 pbag([1, 2, 3, 4]) """ __slots__ = ('_counts', '__weakref__') def __init__(self, counts): self._counts = counts def add(self, element): """ Add an element to the bag. >>> s = pbag([1]) >>> s2 = s.add(1) >>> s3 = s.add(2) >>> s2 pbag([1, 1]) >>> s3 pbag([1, 2]) """ return PBag(_add_to_counters(self._counts, element)) def update(self, iterable): """ Update bag with all elements in iterable. >>> s = pbag([1]) >>> s.update([1, 2]) pbag([1, 1, 2]) """ if iterable: return PBag(reduce(_add_to_counters, iterable, self._counts)) return self def remove(self, element): """ Remove an element from the bag. >>> s = pbag([1, 1, 2]) >>> s2 = s.remove(1) >>> s3 = s.remove(2) >>> s2 pbag([1, 2]) >>> s3 pbag([1, 1]) """ if element not in self._counts: raise KeyError(element) elif self._counts[element] == 1: newc = self._counts.remove(element) else: newc = self._counts.set(element, self._counts[element] - 1) return PBag(newc) def count(self, element): """ Return the number of times an element appears. >>> pbag([]).count('non-existent') 0 >>> pbag([1, 1, 2]).count(1) 2 """ return self._counts.get(element, 0) def __len__(self): """ Return the length including duplicates. >>> len(pbag([1, 1, 2])) 3 """ return sum(self._counts.itervalues()) def __iter__(self): """ Return an iterator of all elements, including duplicates. >>> list(pbag([1, 1, 2])) [1, 1, 2] >>> list(pbag([1, 2])) [1, 2] """ for elt, count in self._counts.iteritems(): for i in range(count): yield elt def __contains__(self, elt): """ Check if an element is in the bag. >>> 1 in pbag([1, 1, 2]) True >>> 0 in pbag([1, 2]) False """ return elt in self._counts def __repr__(self): return "pbag({0})".format(list(self)) def __eq__(self, other): """ Check if two bags are equivalent, honoring the number of duplicates, and ignoring insertion order. >>> pbag([1, 1, 2]) == pbag([1, 2]) False >>> pbag([2, 1, 0]) == pbag([0, 1, 2]) True """ if type(other) is not PBag: raise TypeError("Can only compare PBag with PBags") return self._counts == other._counts def __lt__(self, other): raise TypeError('PBags are not orderable') __le__ = __lt__ __gt__ = __lt__ __ge__ = __lt__ # Multiset-style operations similar to collections.Counter def __add__(self, other): """ Combine elements from two PBags. >>> pbag([1, 2, 2]) + pbag([2, 3, 3]) pbag([1, 2, 2, 2, 3, 3]) """ if not isinstance(other, PBag): return NotImplemented result = self._counts.evolver() for elem, other_count in other._counts.iteritems(): result[elem] = self.count(elem) + other_count return PBag(result.persistent()) def __sub__(self, other): """ Remove elements from one PBag that are present in another. >>> pbag([1, 2, 2, 2, 3]) - pbag([2, 3, 3, 4]) pbag([1, 2, 2]) """ if not isinstance(other, PBag): return NotImplemented result = self._counts.evolver() for elem, other_count in other._counts.iteritems(): newcount = self.count(elem) - other_count if newcount > 0: result[elem] = newcount elif elem in self: result.remove(elem) return PBag(result.persistent()) def __or__(self, other): """ Union: Keep elements that are present in either of two PBags. >>> pbag([1, 2, 2, 2]) | pbag([2, 3, 3]) pbag([1, 2, 2, 2, 3, 3]) """ if not isinstance(other, PBag): return NotImplemented result = self._counts.evolver() for elem, other_count in other._counts.iteritems(): count = self.count(elem) newcount = max(count, other_count) result[elem] = newcount return PBag(result.persistent()) def __and__(self, other): """ Intersection: Only keep elements that are present in both PBags. >>> pbag([1, 2, 2, 2]) & pbag([2, 3, 3]) pbag([2]) """ if not isinstance(other, PBag): return NotImplemented result = pmap().evolver() for elem, count in self._counts.iteritems(): newcount = min(count, other.count(elem)) if newcount > 0: result[elem] = newcount return PBag(result.persistent()) def __hash__(self): """ Hash based on value of elements. >>> m = pmap({pbag([1, 2]): "it's here!"}) >>> m[pbag([2, 1])] "it's here!" >>> pbag([1, 1, 2]) in m False """ return hash(self._counts) Container.register(PBag) Iterable.register(PBag) Sized.register(PBag) Hashable.register(PBag) def b(*elements): """ Construct a persistent bag. Takes an arbitrary number of arguments to insert into the new persistent bag. >>> b(1, 2, 3, 2) pbag([1, 2, 2, 3]) """ return pbag(elements) def pbag(elements): """ Convert an iterable to a persistent bag. Takes an iterable with elements to insert. >>> pbag([1, 2, 3, 2]) pbag([1, 2, 2, 3]) """ if not elements: return _EMPTY_PBAG return PBag(reduce(_add_to_counters, elements, pmap())) _EMPTY_PBAG = PBag(pmap())
6,730
Python
24.115672
79
0.504903
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_checked_types.py
from enum import Enum from abc import abstractmethod, ABCMeta from collections.abc import Iterable from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PythonPVector, python_pvector class CheckedType(object): """ Marker class to enable creation and serialization of checked object graphs. """ __slots__ = () @classmethod @abstractmethod def create(cls, source_data, _factory_fields=None): raise NotImplementedError() @abstractmethod def serialize(self, format=None): raise NotImplementedError() def _restore_pickle(cls, data): return cls.create(data, _factory_fields=set()) class InvariantException(Exception): """ Exception raised from a :py:class:`CheckedType` when invariant tests fail or when a mandatory field is missing. Contains two fields of interest: invariant_errors, a tuple of error data for the failing invariants missing_fields, a tuple of strings specifying the missing names """ def __init__(self, error_codes=(), missing_fields=(), *args, **kwargs): self.invariant_errors = tuple(e() if callable(e) else e for e in error_codes) self.missing_fields = missing_fields super(InvariantException, self).__init__(*args, **kwargs) def __str__(self): return super(InvariantException, self).__str__() + \ ", invariant_errors=[{invariant_errors}], missing_fields=[{missing_fields}]".format( invariant_errors=', '.join(str(e) for e in self.invariant_errors), missing_fields=', '.join(self.missing_fields)) _preserved_iterable_types = ( Enum, ) """Some types are themselves iterable, but we want to use the type itself and not its members for the type specification. This defines a set of such types that we explicitly preserve. Note that strings are not such types because the string inputs we pass in are values, not types. """ def maybe_parse_user_type(t): """Try to coerce a user-supplied type directive into a list of types. This function should be used in all places where a user specifies a type, for consistency. The policy for what defines valid user input should be clear from the implementation. """ is_type = isinstance(t, type) is_preserved = isinstance(t, type) and issubclass(t, _preserved_iterable_types) is_string = isinstance(t, str) is_iterable = isinstance(t, Iterable) if is_preserved: return [t] elif is_string: return [t] elif is_type and not is_iterable: return [t] elif is_iterable: # Recur to validate contained types as well. ts = t return tuple(e for t in ts for e in maybe_parse_user_type(t)) else: # If this raises because `t` cannot be formatted, so be it. raise TypeError( 'Type specifications must be types or strings. Input: {}'.format(t) ) def maybe_parse_many_user_types(ts): # Just a different name to communicate that you're parsing multiple user # inputs. `maybe_parse_user_type` handles the iterable case anyway. return maybe_parse_user_type(ts) def _store_types(dct, bases, destination_name, source_name): maybe_types = maybe_parse_many_user_types([ d[source_name] for d in ([dct] + [b.__dict__ for b in bases]) if source_name in d ]) dct[destination_name] = maybe_types def _merge_invariant_results(result): verdict = True data = [] for verd, dat in result: if not verd: verdict = False data.append(dat) return verdict, tuple(data) def wrap_invariant(invariant): # Invariant functions may return the outcome of several tests # In those cases the results have to be merged before being passed # back to the client. def f(*args, **kwargs): result = invariant(*args, **kwargs) if isinstance(result[0], bool): return result return _merge_invariant_results(result) return f def _all_dicts(bases, seen=None): """ Yield each class in ``bases`` and each of their base classes. """ if seen is None: seen = set() for cls in bases: if cls in seen: continue seen.add(cls) yield cls.__dict__ for b in _all_dicts(cls.__bases__, seen): yield b def store_invariants(dct, bases, destination_name, source_name): # Invariants are inherited invariants = [] for ns in [dct] + list(_all_dicts(bases)): try: invariant = ns[source_name] except KeyError: continue invariants.append(invariant) if not all(callable(invariant) for invariant in invariants): raise TypeError('Invariants must be callable') dct[destination_name] = tuple(wrap_invariant(inv) for inv in invariants) class _CheckedTypeMeta(ABCMeta): def __new__(mcs, name, bases, dct): _store_types(dct, bases, '_checked_types', '__type__') store_invariants(dct, bases, '_checked_invariants', '__invariant__') def default_serializer(self, _, value): if isinstance(value, CheckedType): return value.serialize() return value dct.setdefault('__serializer__', default_serializer) dct['__slots__'] = () return super(_CheckedTypeMeta, mcs).__new__(mcs, name, bases, dct) class CheckedTypeError(TypeError): def __init__(self, source_class, expected_types, actual_type, actual_value, *args, **kwargs): super(CheckedTypeError, self).__init__(*args, **kwargs) self.source_class = source_class self.expected_types = expected_types self.actual_type = actual_type self.actual_value = actual_value class CheckedKeyTypeError(CheckedTypeError): """ Raised when trying to set a value using a key with a type that doesn't match the declared type. Attributes: source_class -- The class of the collection expected_types -- Allowed types actual_type -- The non matching type actual_value -- Value of the variable with the non matching type """ pass class CheckedValueTypeError(CheckedTypeError): """ Raised when trying to set a value using a key with a type that doesn't match the declared type. Attributes: source_class -- The class of the collection expected_types -- Allowed types actual_type -- The non matching type actual_value -- Value of the variable with the non matching type """ pass def _get_class(type_name): module_name, class_name = type_name.rsplit('.', 1) module = __import__(module_name, fromlist=[class_name]) return getattr(module, class_name) def get_type(typ): if isinstance(typ, type): return typ return _get_class(typ) def get_types(typs): return [get_type(typ) for typ in typs] def _check_types(it, expected_types, source_class, exception_type=CheckedValueTypeError): if expected_types: for e in it: if not any(isinstance(e, get_type(t)) for t in expected_types): actual_type = type(e) msg = "Type {source_class} can only be used with {expected_types}, not {actual_type}".format( source_class=source_class.__name__, expected_types=tuple(get_type(et).__name__ for et in expected_types), actual_type=actual_type.__name__) raise exception_type(source_class, expected_types, actual_type, e, msg) def _invariant_errors(elem, invariants): return [data for valid, data in (invariant(elem) for invariant in invariants) if not valid] def _invariant_errors_iterable(it, invariants): return sum([_invariant_errors(elem, invariants) for elem in it], []) def optional(*typs): """ Convenience function to specify that a value may be of any of the types in type 'typs' or None """ return tuple(typs) + (type(None),) def _checked_type_create(cls, source_data, _factory_fields=None, ignore_extra=False): if isinstance(source_data, cls): return source_data # Recursively apply create methods of checked types if the types of the supplied data # does not match any of the valid types. types = get_types(cls._checked_types) checked_type = next((t for t in types if issubclass(t, CheckedType)), None) if checked_type: return cls([checked_type.create(data, ignore_extra=ignore_extra) if not any(isinstance(data, t) for t in types) else data for data in source_data]) return cls(source_data) class CheckedPVector(PythonPVector, CheckedType, metaclass=_CheckedTypeMeta): """ A CheckedPVector is a PVector which allows specifying type and invariant checks. >>> class Positives(CheckedPVector): ... __type__ = (int, float) ... __invariant__ = lambda n: (n >= 0, 'Negative') ... >>> Positives([1, 2, 3]) Positives([1, 2, 3]) """ __slots__ = () def __new__(cls, initial=()): if type(initial) == PythonPVector: return super(CheckedPVector, cls).__new__(cls, initial._count, initial._shift, initial._root, initial._tail) return CheckedPVector.Evolver(cls, python_pvector()).extend(initial).persistent() def set(self, key, value): return self.evolver().set(key, value).persistent() def append(self, val): return self.evolver().append(val).persistent() def extend(self, it): return self.evolver().extend(it).persistent() create = classmethod(_checked_type_create) def serialize(self, format=None): serializer = self.__serializer__ return list(serializer(format, v) for v in self) def __reduce__(self): # Pickling support return _restore_pickle, (self.__class__, list(self),) class Evolver(PythonPVector.Evolver): __slots__ = ('_destination_class', '_invariant_errors') def __init__(self, destination_class, vector): super(CheckedPVector.Evolver, self).__init__(vector) self._destination_class = destination_class self._invariant_errors = [] def _check(self, it): _check_types(it, self._destination_class._checked_types, self._destination_class) error_data = _invariant_errors_iterable(it, self._destination_class._checked_invariants) self._invariant_errors.extend(error_data) def __setitem__(self, key, value): self._check([value]) return super(CheckedPVector.Evolver, self).__setitem__(key, value) def append(self, elem): self._check([elem]) return super(CheckedPVector.Evolver, self).append(elem) def extend(self, it): it = list(it) self._check(it) return super(CheckedPVector.Evolver, self).extend(it) def persistent(self): if self._invariant_errors: raise InvariantException(error_codes=self._invariant_errors) result = self._orig_pvector if self.is_dirty() or (self._destination_class != type(self._orig_pvector)): pv = super(CheckedPVector.Evolver, self).persistent().extend(self._extra_tail) result = self._destination_class(pv) self._reset(result) return result def __repr__(self): return self.__class__.__name__ + "({0})".format(self.tolist()) __str__ = __repr__ def evolver(self): return CheckedPVector.Evolver(self.__class__, self) class CheckedPSet(PSet, CheckedType, metaclass=_CheckedTypeMeta): """ A CheckedPSet is a PSet which allows specifying type and invariant checks. >>> class Positives(CheckedPSet): ... __type__ = (int, float) ... __invariant__ = lambda n: (n >= 0, 'Negative') ... >>> Positives([1, 2, 3]) Positives([1, 2, 3]) """ __slots__ = () def __new__(cls, initial=()): if type(initial) is PMap: return super(CheckedPSet, cls).__new__(cls, initial) evolver = CheckedPSet.Evolver(cls, pset()) for e in initial: evolver.add(e) return evolver.persistent() def __repr__(self): return self.__class__.__name__ + super(CheckedPSet, self).__repr__()[4:] def __str__(self): return self.__repr__() def serialize(self, format=None): serializer = self.__serializer__ return set(serializer(format, v) for v in self) create = classmethod(_checked_type_create) def __reduce__(self): # Pickling support return _restore_pickle, (self.__class__, list(self),) def evolver(self): return CheckedPSet.Evolver(self.__class__, self) class Evolver(PSet._Evolver): __slots__ = ('_destination_class', '_invariant_errors') def __init__(self, destination_class, original_set): super(CheckedPSet.Evolver, self).__init__(original_set) self._destination_class = destination_class self._invariant_errors = [] def _check(self, it): _check_types(it, self._destination_class._checked_types, self._destination_class) error_data = _invariant_errors_iterable(it, self._destination_class._checked_invariants) self._invariant_errors.extend(error_data) def add(self, element): self._check([element]) self._pmap_evolver[element] = True return self def persistent(self): if self._invariant_errors: raise InvariantException(error_codes=self._invariant_errors) if self.is_dirty() or self._destination_class != type(self._original_pset): return self._destination_class(self._pmap_evolver.persistent()) return self._original_pset class _CheckedMapTypeMeta(type): def __new__(mcs, name, bases, dct): _store_types(dct, bases, '_checked_key_types', '__key_type__') _store_types(dct, bases, '_checked_value_types', '__value_type__') store_invariants(dct, bases, '_checked_invariants', '__invariant__') def default_serializer(self, _, key, value): sk = key if isinstance(key, CheckedType): sk = key.serialize() sv = value if isinstance(value, CheckedType): sv = value.serialize() return sk, sv dct.setdefault('__serializer__', default_serializer) dct['__slots__'] = () return super(_CheckedMapTypeMeta, mcs).__new__(mcs, name, bases, dct) # Marker object _UNDEFINED_CHECKED_PMAP_SIZE = object() class CheckedPMap(PMap, CheckedType, metaclass=_CheckedMapTypeMeta): """ A CheckedPMap is a PMap which allows specifying type and invariant checks. >>> class IntToFloatMap(CheckedPMap): ... __key_type__ = int ... __value_type__ = float ... __invariant__ = lambda k, v: (int(v) == k, 'Invalid mapping') ... >>> IntToFloatMap({1: 1.5, 2: 2.25}) IntToFloatMap({1: 1.5, 2: 2.25}) """ __slots__ = () def __new__(cls, initial={}, size=_UNDEFINED_CHECKED_PMAP_SIZE): if size is not _UNDEFINED_CHECKED_PMAP_SIZE: return super(CheckedPMap, cls).__new__(cls, size, initial) evolver = CheckedPMap.Evolver(cls, pmap()) for k, v in initial.items(): evolver.set(k, v) return evolver.persistent() def evolver(self): return CheckedPMap.Evolver(self.__class__, self) def __repr__(self): return self.__class__.__name__ + "({0})".format(str(dict(self))) __str__ = __repr__ def serialize(self, format=None): serializer = self.__serializer__ return dict(serializer(format, k, v) for k, v in self.items()) @classmethod def create(cls, source_data, _factory_fields=None): if isinstance(source_data, cls): return source_data # Recursively apply create methods of checked types if the types of the supplied data # does not match any of the valid types. key_types = get_types(cls._checked_key_types) checked_key_type = next((t for t in key_types if issubclass(t, CheckedType)), None) value_types = get_types(cls._checked_value_types) checked_value_type = next((t for t in value_types if issubclass(t, CheckedType)), None) if checked_key_type or checked_value_type: return cls(dict((checked_key_type.create(key) if checked_key_type and not any(isinstance(key, t) for t in key_types) else key, checked_value_type.create(value) if checked_value_type and not any(isinstance(value, t) for t in value_types) else value) for key, value in source_data.items())) return cls(source_data) def __reduce__(self): # Pickling support return _restore_pickle, (self.__class__, dict(self),) class Evolver(PMap._Evolver): __slots__ = ('_destination_class', '_invariant_errors') def __init__(self, destination_class, original_map): super(CheckedPMap.Evolver, self).__init__(original_map) self._destination_class = destination_class self._invariant_errors = [] def set(self, key, value): _check_types([key], self._destination_class._checked_key_types, self._destination_class, CheckedKeyTypeError) _check_types([value], self._destination_class._checked_value_types, self._destination_class) self._invariant_errors.extend(data for valid, data in (invariant(key, value) for invariant in self._destination_class._checked_invariants) if not valid) return super(CheckedPMap.Evolver, self).set(key, value) def persistent(self): if self._invariant_errors: raise InvariantException(error_codes=self._invariant_errors) if self.is_dirty() or type(self._original_pmap) != self._destination_class: return self._destination_class(self._buckets_evolver.persistent(), self._size) return self._original_pmap
18,372
Python
32.836096
150
0.617897
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_plist.py
from collections.abc import Sequence, Hashable from numbers import Integral from functools import reduce class _PListBuilder(object): """ Helper class to allow construction of a list without having to reverse it in the end. """ __slots__ = ('_head', '_tail') def __init__(self): self._head = _EMPTY_PLIST self._tail = _EMPTY_PLIST def _append(self, elem, constructor): if not self._tail: self._head = constructor(elem) self._tail = self._head else: self._tail.rest = constructor(elem) self._tail = self._tail.rest return self._head def append_elem(self, elem): return self._append(elem, lambda e: PList(e, _EMPTY_PLIST)) def append_plist(self, pl): return self._append(pl, lambda l: l) def build(self): return self._head class _PListBase(object): __slots__ = ('__weakref__',) # Selected implementations can be taken straight from the Sequence # class, other are less suitable. Especially those that work with # index lookups. count = Sequence.count index = Sequence.index def __reduce__(self): # Pickling support return plist, (list(self),) def __len__(self): """ Return the length of the list, computed by traversing it. This is obviously O(n) but with the current implementation where a list is also a node the overhead of storing the length in every node would be quite significant. """ return sum(1 for _ in self) def __repr__(self): return "plist({0})".format(list(self)) __str__ = __repr__ def cons(self, elem): """ Return a new list with elem inserted as new head. >>> plist([1, 2]).cons(3) plist([3, 1, 2]) """ return PList(elem, self) def mcons(self, iterable): """ Return a new list with all elements of iterable repeatedly cons:ed to the current list. NB! The elements will be inserted in the reverse order of the iterable. Runs in O(len(iterable)). >>> plist([1, 2]).mcons([3, 4]) plist([4, 3, 1, 2]) """ head = self for elem in iterable: head = head.cons(elem) return head def reverse(self): """ Return a reversed version of list. Runs in O(n) where n is the length of the list. >>> plist([1, 2, 3]).reverse() plist([3, 2, 1]) Also supports the standard reversed function. >>> reversed(plist([1, 2, 3])) plist([3, 2, 1]) """ result = plist() head = self while head: result = result.cons(head.first) head = head.rest return result __reversed__ = reverse def split(self, index): """ Spilt the list at position specified by index. Returns a tuple containing the list up until index and the list after the index. Runs in O(index). >>> plist([1, 2, 3, 4]).split(2) (plist([1, 2]), plist([3, 4])) """ lb = _PListBuilder() right_list = self i = 0 while right_list and i < index: lb.append_elem(right_list.first) right_list = right_list.rest i += 1 if not right_list: # Just a small optimization in the cases where no split occurred return self, _EMPTY_PLIST return lb.build(), right_list def __iter__(self): li = self while li: yield li.first li = li.rest def __lt__(self, other): if not isinstance(other, _PListBase): return NotImplemented return tuple(self) < tuple(other) def __eq__(self, other): """ Traverses the lists, checking equality of elements. This is an O(n) operation, but preserves the standard semantics of list equality. """ if not isinstance(other, _PListBase): return NotImplemented self_head = self other_head = other while self_head and other_head: if not self_head.first == other_head.first: return False self_head = self_head.rest other_head = other_head.rest return not self_head and not other_head def __getitem__(self, index): # Don't use this this data structure if you plan to do a lot of indexing, it is # very inefficient! Use a PVector instead! if isinstance(index, slice): if index.start is not None and index.stop is None and (index.step is None or index.step == 1): return self._drop(index.start) # Take the easy way out for all other slicing cases, not much structural reuse possible anyway return plist(tuple(self)[index]) if not isinstance(index, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(index).__name__) if index < 0: # NB: O(n)! index += len(self) try: return self._drop(index).first except AttributeError as e: raise IndexError("PList index out of range") from e def _drop(self, count): if count < 0: raise IndexError("PList index out of range") head = self while count > 0: head = head.rest count -= 1 return head def __hash__(self): return hash(tuple(self)) def remove(self, elem): """ Return new list with first element equal to elem removed. O(k) where k is the position of the element that is removed. Raises ValueError if no matching element is found. >>> plist([1, 2, 1]).remove(1) plist([2, 1]) """ builder = _PListBuilder() head = self while head: if head.first == elem: return builder.append_plist(head.rest) builder.append_elem(head.first) head = head.rest raise ValueError('{0} not found in PList'.format(elem)) class PList(_PListBase): """ Classical Lisp style singly linked list. Adding elements to the head using cons is O(1). Element access is O(k) where k is the position of the element in the list. Taking the length of the list is O(n). Fully supports the Sequence and Hashable protocols including indexing and slicing but if you need fast random access go for the PVector instead. Do not instantiate directly, instead use the factory functions :py:func:`l` or :py:func:`plist` to create an instance. Some examples: >>> x = plist([1, 2]) >>> y = x.cons(3) >>> x plist([1, 2]) >>> y plist([3, 1, 2]) >>> y.first 3 >>> y.rest == x True >>> y[:2] plist([3, 1]) """ __slots__ = ('first', 'rest') def __new__(cls, first, rest): instance = super(PList, cls).__new__(cls) instance.first = first instance.rest = rest return instance def __bool__(self): return True __nonzero__ = __bool__ Sequence.register(PList) Hashable.register(PList) class _EmptyPList(_PListBase): __slots__ = () def __bool__(self): return False __nonzero__ = __bool__ @property def first(self): raise AttributeError("Empty PList has no first") @property def rest(self): return self Sequence.register(_EmptyPList) Hashable.register(_EmptyPList) _EMPTY_PLIST = _EmptyPList() def plist(iterable=(), reverse=False): """ Creates a new persistent list containing all elements of iterable. Optional parameter reverse specifies if the elements should be inserted in reverse order or not. >>> plist([1, 2, 3]) plist([1, 2, 3]) >>> plist([1, 2, 3], reverse=True) plist([3, 2, 1]) """ if not reverse: iterable = list(iterable) iterable.reverse() return reduce(lambda pl, elem: pl.cons(elem), iterable, _EMPTY_PLIST) def l(*elements): """ Creates a new persistent list containing all arguments. >>> l(1, 2, 3) plist([1, 2, 3]) """ return plist(elements)
8,293
Python
25.414013
106
0.566381
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_helpers.py
from functools import wraps from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PVector, pvector def freeze(o, strict=True): """ Recursively convert simple Python containers into pyrsistent versions of those containers. - list is converted to pvector, recursively - dict is converted to pmap, recursively on values (but not keys) - set is converted to pset, but not recursively - tuple is converted to tuple, recursively. If strict == True (default): - freeze is called on elements of pvectors - freeze is called on values of pmaps Sets and dict keys are not recursively frozen because they do not contain mutable data by convention. The main exception to this rule is that dict keys and set elements are often instances of mutable objects that support hash-by-id, which this function can't convert anyway. >>> freeze(set([1, 2])) pset([1, 2]) >>> freeze([1, {'a': 3}]) pvector([1, pmap({'a': 3})]) >>> freeze((1, [])) (1, pvector([])) """ typ = type(o) if typ is dict or (strict and isinstance(o, PMap)): return pmap({k: freeze(v, strict) for k, v in o.items()}) if typ is list or (strict and isinstance(o, PVector)): curried_freeze = lambda x: freeze(x, strict) return pvector(map(curried_freeze, o)) if typ is tuple: curried_freeze = lambda x: freeze(x, strict) return tuple(map(curried_freeze, o)) if typ is set: # impossible to have anything that needs freezing inside a set or pset return pset(o) return o def thaw(o, strict=True): """ Recursively convert pyrsistent containers into simple Python containers. - pvector is converted to list, recursively - pmap is converted to dict, recursively on values (but not keys) - pset is converted to set, but not recursively - tuple is converted to tuple, recursively. If strict == True (the default): - thaw is called on elements of lists - thaw is called on values in dicts >>> from pyrsistent import s, m, v >>> thaw(s(1, 2)) {1, 2} >>> thaw(v(1, m(a=3))) [1, {'a': 3}] >>> thaw((1, v())) (1, []) """ typ = type(o) if isinstance(o, PVector) or (strict and typ is list): curried_thaw = lambda x: thaw(x, strict) return list(map(curried_thaw, o)) if isinstance(o, PMap) or (strict and typ is dict): return {k: thaw(v, strict) for k, v in o.items()} if typ is tuple: curried_thaw = lambda x: thaw(x, strict) return tuple(map(curried_thaw, o)) if isinstance(o, PSet): # impossible to thaw inside psets or sets return set(o) return o def mutant(fn): """ Convenience decorator to isolate mutation to within the decorated function (with respect to the input arguments). All arguments to the decorated function will be frozen so that they are guaranteed not to change. The return value is also frozen. """ @wraps(fn) def inner_f(*args, **kwargs): return freeze(fn(*[freeze(e) for e in args], **dict(freeze(item) for item in kwargs.items()))) return inner_f
3,232
Python
31.989796
102
0.641708
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/__init__.py
# -*- coding: utf-8 -*- from pyrsistent._pmap import pmap, m, PMap from pyrsistent._pvector import pvector, v, PVector from pyrsistent._pset import pset, s, PSet from pyrsistent._pbag import pbag, b, PBag from pyrsistent._plist import plist, l, PList from pyrsistent._pdeque import pdeque, dq, PDeque from pyrsistent._checked_types import ( CheckedPMap, CheckedPVector, CheckedPSet, InvariantException, CheckedKeyTypeError, CheckedValueTypeError, CheckedType, optional) from pyrsistent._field_common import ( field, PTypeError, pset_field, pmap_field, pvector_field) from pyrsistent._precord import PRecord from pyrsistent._pclass import PClass, PClassMeta from pyrsistent._immutable import immutable from pyrsistent._helpers import freeze, thaw, mutant from pyrsistent._transformations import inc, discard, rex, ny from pyrsistent._toolz import get_in __all__ = ('pmap', 'm', 'PMap', 'pvector', 'v', 'PVector', 'pset', 's', 'PSet', 'pbag', 'b', 'PBag', 'plist', 'l', 'PList', 'pdeque', 'dq', 'PDeque', 'CheckedPMap', 'CheckedPVector', 'CheckedPSet', 'InvariantException', 'CheckedKeyTypeError', 'CheckedValueTypeError', 'CheckedType', 'optional', 'PRecord', 'field', 'pset_field', 'pmap_field', 'pvector_field', 'PClass', 'PClassMeta', 'immutable', 'freeze', 'thaw', 'mutant', 'get_in', 'inc', 'discard', 'rex', 'ny')
1,479
Python
29.833333
155
0.656525
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_toolz.py
""" Functionality copied from the toolz package to avoid having to add toolz as a dependency. See https://github.com/pytoolz/toolz/. toolz is released under BSD licence. Below is the licence text from toolz as it appeared when copying the code. -------------------------------------------------------------- Copyright (c) 2013 Matthew Rocklin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: a. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. b. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. c. Neither the name of toolz nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import operator from functools import reduce def get_in(keys, coll, default=None, no_default=False): """ NB: This is a straight copy of the get_in implementation found in the toolz library (https://github.com/pytoolz/toolz/). It works with persistent data structures as well as the corresponding datastructures from the stdlib. Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. If coll[i0][i1]...[iX] cannot be found, returns ``default``, unless ``no_default`` is specified, then it raises KeyError or IndexError. ``get_in`` is a generalization of ``operator.getitem`` for nested data structures such as dictionaries and lists. >>> from pyrsistent import freeze >>> transaction = freeze({'name': 'Alice', ... 'purchase': {'items': ['Apple', 'Orange'], ... 'costs': [0.50, 1.25]}, ... 'credit card': '5555-1234-1234-1234'}) >>> get_in(['purchase', 'items', 0], transaction) 'Apple' >>> get_in(['name'], transaction) 'Alice' >>> get_in(['purchase', 'total'], transaction) >>> get_in(['purchase', 'items', 'apple'], transaction) >>> get_in(['purchase', 'items', 10], transaction) >>> get_in(['purchase', 'total'], transaction, 0) 0 >>> get_in(['y'], {}, no_default=True) Traceback (most recent call last): ... KeyError: 'y' """ try: return reduce(operator.getitem, keys, coll) except (KeyError, IndexError, TypeError): if no_default: raise return default
3,425
Python
39.785714
75
0.676204
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_pvector.py
from abc import abstractmethod, ABCMeta from collections.abc import Sequence, Hashable from numbers import Integral import operator from pyrsistent._transformations import transform def _bitcount(val): return bin(val).count("1") BRANCH_FACTOR = 32 BIT_MASK = BRANCH_FACTOR - 1 SHIFT = _bitcount(BIT_MASK) def compare_pvector(v, other, operator): return operator(v.tolist(), other.tolist() if isinstance(other, PVector) else other) def _index_or_slice(index, stop): if stop is None: return index return slice(index, stop) class PythonPVector(object): """ Support structure for PVector that implements structural sharing for vectors using a trie. """ __slots__ = ('_count', '_shift', '_root', '_tail', '_tail_offset', '__weakref__') def __new__(cls, count, shift, root, tail): self = super(PythonPVector, cls).__new__(cls) self._count = count self._shift = shift self._root = root self._tail = tail # Derived attribute stored for performance self._tail_offset = self._count - len(self._tail) return self def __len__(self): return self._count def __getitem__(self, index): if isinstance(index, slice): # There are more conditions than the below where it would be OK to # return ourselves, implement those... if index.start is None and index.stop is None and index.step is None: return self # This is a bit nasty realizing the whole structure as a list before # slicing it but it is the fastest way I've found to date, and it's easy :-) return _EMPTY_PVECTOR.extend(self.tolist()[index]) if index < 0: index += self._count return PythonPVector._node_for(self, index)[index & BIT_MASK] def __add__(self, other): return self.extend(other) def __repr__(self): return 'pvector({0})'.format(str(self.tolist())) def __str__(self): return self.__repr__() def __iter__(self): # This is kind of lazy and will produce some memory overhead but it is the fasted method # by far of those tried since it uses the speed of the built in python list directly. return iter(self.tolist()) def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): return self is other or (hasattr(other, '__len__') and self._count == len(other)) and compare_pvector(self, other, operator.eq) def __gt__(self, other): return compare_pvector(self, other, operator.gt) def __lt__(self, other): return compare_pvector(self, other, operator.lt) def __ge__(self, other): return compare_pvector(self, other, operator.ge) def __le__(self, other): return compare_pvector(self, other, operator.le) def __mul__(self, times): if times <= 0 or self is _EMPTY_PVECTOR: return _EMPTY_PVECTOR if times == 1: return self return _EMPTY_PVECTOR.extend(times * self.tolist()) __rmul__ = __mul__ def _fill_list(self, node, shift, the_list): if shift: shift -= SHIFT for n in node: self._fill_list(n, shift, the_list) else: the_list.extend(node) def tolist(self): """ The fastest way to convert the vector into a python list. """ the_list = [] self._fill_list(self._root, self._shift, the_list) the_list.extend(self._tail) return the_list def _totuple(self): """ Returns the content as a python tuple. """ return tuple(self.tolist()) def __hash__(self): # Taking the easy way out again... return hash(self._totuple()) def transform(self, *transformations): return transform(self, transformations) def __reduce__(self): # Pickling support return pvector, (self.tolist(),) def mset(self, *args): if len(args) % 2: raise TypeError("mset expected an even number of arguments") evolver = self.evolver() for i in range(0, len(args), 2): evolver[args[i]] = args[i+1] return evolver.persistent() class Evolver(object): __slots__ = ('_count', '_shift', '_root', '_tail', '_tail_offset', '_dirty_nodes', '_extra_tail', '_cached_leafs', '_orig_pvector') def __init__(self, v): self._reset(v) def __getitem__(self, index): if not isinstance(index, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(index).__name__) if index < 0: index += self._count + len(self._extra_tail) if self._count <= index < self._count + len(self._extra_tail): return self._extra_tail[index - self._count] return PythonPVector._node_for(self, index)[index & BIT_MASK] def _reset(self, v): self._count = v._count self._shift = v._shift self._root = v._root self._tail = v._tail self._tail_offset = v._tail_offset self._dirty_nodes = {} self._cached_leafs = {} self._extra_tail = [] self._orig_pvector = v def append(self, element): self._extra_tail.append(element) return self def extend(self, iterable): self._extra_tail.extend(iterable) return self def set(self, index, val): self[index] = val return self def __setitem__(self, index, val): if not isinstance(index, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(index).__name__) if index < 0: index += self._count + len(self._extra_tail) if 0 <= index < self._count: node = self._cached_leafs.get(index >> SHIFT) if node: node[index & BIT_MASK] = val elif index >= self._tail_offset: if id(self._tail) not in self._dirty_nodes: self._tail = list(self._tail) self._dirty_nodes[id(self._tail)] = True self._cached_leafs[index >> SHIFT] = self._tail self._tail[index & BIT_MASK] = val else: self._root = self._do_set(self._shift, self._root, index, val) elif self._count <= index < self._count + len(self._extra_tail): self._extra_tail[index - self._count] = val elif index == self._count + len(self._extra_tail): self._extra_tail.append(val) else: raise IndexError("Index out of range: %s" % (index,)) def _do_set(self, level, node, i, val): if id(node) in self._dirty_nodes: ret = node else: ret = list(node) self._dirty_nodes[id(ret)] = True if level == 0: ret[i & BIT_MASK] = val self._cached_leafs[i >> SHIFT] = ret else: sub_index = (i >> level) & BIT_MASK # >>> ret[sub_index] = self._do_set(level - SHIFT, node[sub_index], i, val) return ret def delete(self, index): del self[index] return self def __delitem__(self, key): if self._orig_pvector: # All structural sharing bets are off, base evolver on _extra_tail only l = PythonPVector(self._count, self._shift, self._root, self._tail).tolist() l.extend(self._extra_tail) self._reset(_EMPTY_PVECTOR) self._extra_tail = l del self._extra_tail[key] def persistent(self): result = self._orig_pvector if self.is_dirty(): result = PythonPVector(self._count, self._shift, self._root, self._tail).extend(self._extra_tail) self._reset(result) return result def __len__(self): return self._count + len(self._extra_tail) def is_dirty(self): return bool(self._dirty_nodes or self._extra_tail) def evolver(self): return PythonPVector.Evolver(self) def set(self, i, val): # This method could be implemented by a call to mset() but doing so would cause # a ~5 X performance penalty on PyPy (considered the primary platform for this implementation # of PVector) so we're keeping this implementation for now. if not isinstance(i, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(i).__name__) if i < 0: i += self._count if 0 <= i < self._count: if i >= self._tail_offset: new_tail = list(self._tail) new_tail[i & BIT_MASK] = val return PythonPVector(self._count, self._shift, self._root, new_tail) return PythonPVector(self._count, self._shift, self._do_set(self._shift, self._root, i, val), self._tail) if i == self._count: return self.append(val) raise IndexError("Index out of range: %s" % (i,)) def _do_set(self, level, node, i, val): ret = list(node) if level == 0: ret[i & BIT_MASK] = val else: sub_index = (i >> level) & BIT_MASK # >>> ret[sub_index] = self._do_set(level - SHIFT, node[sub_index], i, val) return ret @staticmethod def _node_for(pvector_like, i): if 0 <= i < pvector_like._count: if i >= pvector_like._tail_offset: return pvector_like._tail node = pvector_like._root for level in range(pvector_like._shift, 0, -SHIFT): node = node[(i >> level) & BIT_MASK] # >>> return node raise IndexError("Index out of range: %s" % (i,)) def _create_new_root(self): new_shift = self._shift # Overflow root? if (self._count >> SHIFT) > (1 << self._shift): # >>> new_root = [self._root, self._new_path(self._shift, self._tail)] new_shift += SHIFT else: new_root = self._push_tail(self._shift, self._root, self._tail) return new_root, new_shift def append(self, val): if len(self._tail) < BRANCH_FACTOR: new_tail = list(self._tail) new_tail.append(val) return PythonPVector(self._count + 1, self._shift, self._root, new_tail) # Full tail, push into tree new_root, new_shift = self._create_new_root() return PythonPVector(self._count + 1, new_shift, new_root, [val]) def _new_path(self, level, node): if level == 0: return node return [self._new_path(level - SHIFT, node)] def _mutating_insert_tail(self): self._root, self._shift = self._create_new_root() self._tail = [] def _mutating_fill_tail(self, offset, sequence): max_delta_len = BRANCH_FACTOR - len(self._tail) delta = sequence[offset:offset + max_delta_len] self._tail.extend(delta) delta_len = len(delta) self._count += delta_len return offset + delta_len def _mutating_extend(self, sequence): offset = 0 sequence_len = len(sequence) while offset < sequence_len: offset = self._mutating_fill_tail(offset, sequence) if len(self._tail) == BRANCH_FACTOR: self._mutating_insert_tail() self._tail_offset = self._count - len(self._tail) def extend(self, obj): # Mutates the new vector directly for efficiency but that's only an # implementation detail, once it is returned it should be considered immutable l = obj.tolist() if isinstance(obj, PythonPVector) else list(obj) if l: new_vector = self.append(l[0]) new_vector._mutating_extend(l[1:]) return new_vector return self def _push_tail(self, level, parent, tail_node): """ if parent is leaf, insert node, else does it map to an existing child? -> node_to_insert = push node one more level else alloc new path return node_to_insert placed in copy of parent """ ret = list(parent) if level == SHIFT: ret.append(tail_node) return ret sub_index = ((self._count - 1) >> level) & BIT_MASK # >>> if len(parent) > sub_index: ret[sub_index] = self._push_tail(level - SHIFT, parent[sub_index], tail_node) return ret ret.append(self._new_path(level - SHIFT, tail_node)) return ret def index(self, value, *args, **kwargs): return self.tolist().index(value, *args, **kwargs) def count(self, value): return self.tolist().count(value) def delete(self, index, stop=None): l = self.tolist() del l[_index_or_slice(index, stop)] return _EMPTY_PVECTOR.extend(l) def remove(self, value): l = self.tolist() l.remove(value) return _EMPTY_PVECTOR.extend(l) class PVector(metaclass=ABCMeta): """ Persistent vector implementation. Meant as a replacement for the cases where you would normally use a Python list. Do not instantiate directly, instead use the factory functions :py:func:`v` and :py:func:`pvector` to create an instance. Heavily influenced by the persistent vector available in Clojure. Initially this was more or less just a port of the Java code for the Clojure vector. It has since been modified and to some extent optimized for usage in Python. The vector is organized as a trie, any mutating method will return a new vector that contains the changes. No updates are done to the original vector. Structural sharing between vectors are applied where possible to save space and to avoid making complete copies. This structure corresponds most closely to the built in list type and is intended as a replacement. Where the semantics are the same (more or less) the same function names have been used but for some cases it is not possible, for example assignments. The PVector implements the Sequence protocol and is Hashable. Inserts are amortized O(1). Random access is log32(n) where n is the size of the vector. The following are examples of some common operations on persistent vectors: >>> p = v(1, 2, 3) >>> p2 = p.append(4) >>> p3 = p2.extend([5, 6, 7]) >>> p pvector([1, 2, 3]) >>> p2 pvector([1, 2, 3, 4]) >>> p3 pvector([1, 2, 3, 4, 5, 6, 7]) >>> p3[5] 6 >>> p.set(1, 99) pvector([1, 99, 3]) >>> """ @abstractmethod def __len__(self): """ >>> len(v(1, 2, 3)) 3 """ @abstractmethod def __getitem__(self, index): """ Get value at index. Full slicing support. >>> v1 = v(5, 6, 7, 8) >>> v1[2] 7 >>> v1[1:3] pvector([6, 7]) """ @abstractmethod def __add__(self, other): """ >>> v1 = v(1, 2) >>> v2 = v(3, 4) >>> v1 + v2 pvector([1, 2, 3, 4]) """ @abstractmethod def __mul__(self, times): """ >>> v1 = v(1, 2) >>> 3 * v1 pvector([1, 2, 1, 2, 1, 2]) """ @abstractmethod def __hash__(self): """ >>> v1 = v(1, 2, 3) >>> v2 = v(1, 2, 3) >>> hash(v1) == hash(v2) True """ @abstractmethod def evolver(self): """ Create a new evolver for this pvector. The evolver acts as a mutable view of the vector with "transaction like" semantics. No part of the underlying vector i updated, it is still fully immutable. Furthermore multiple evolvers created from the same pvector do not interfere with each other. You may want to use an evolver instead of working directly with the pvector in the following cases: * Multiple updates are done to the same vector and the intermediate results are of no interest. In this case using an evolver may be a more efficient and easier to work with. * You need to pass a vector into a legacy function or a function that you have no control over which performs in place mutations of lists. In this case pass an evolver instance instead and then create a new pvector from the evolver once the function returns. The following example illustrates a typical workflow when working with evolvers. It also displays most of the API (which i kept small by design, you should not be tempted to use evolvers in excess ;-)). Create the evolver and perform various mutating updates to it: >>> v1 = v(1, 2, 3, 4, 5) >>> e = v1.evolver() >>> e[1] = 22 >>> _ = e.append(6) >>> _ = e.extend([7, 8, 9]) >>> e[8] += 1 >>> len(e) 9 The underlying pvector remains the same: >>> v1 pvector([1, 2, 3, 4, 5]) The changes are kept in the evolver. An updated pvector can be created using the persistent() function on the evolver. >>> v2 = e.persistent() >>> v2 pvector([1, 22, 3, 4, 5, 6, 7, 8, 10]) The new pvector will share data with the original pvector in the same way that would have been done if only using operations on the pvector. """ @abstractmethod def mset(self, *args): """ Return a new vector with elements in specified positions replaced by values (multi set). Elements on even positions in the argument list are interpreted as indexes while elements on odd positions are considered values. >>> v1 = v(1, 2, 3) >>> v1.mset(0, 11, 2, 33) pvector([11, 2, 33]) """ @abstractmethod def set(self, i, val): """ Return a new vector with element at position i replaced with val. The original vector remains unchanged. Setting a value one step beyond the end of the vector is equal to appending. Setting beyond that will result in an IndexError. >>> v1 = v(1, 2, 3) >>> v1.set(1, 4) pvector([1, 4, 3]) >>> v1.set(3, 4) pvector([1, 2, 3, 4]) >>> v1.set(-1, 4) pvector([1, 2, 4]) """ @abstractmethod def append(self, val): """ Return a new vector with val appended. >>> v1 = v(1, 2) >>> v1.append(3) pvector([1, 2, 3]) """ @abstractmethod def extend(self, obj): """ Return a new vector with all values in obj appended to it. Obj may be another PVector or any other Iterable. >>> v1 = v(1, 2, 3) >>> v1.extend([4, 5]) pvector([1, 2, 3, 4, 5]) """ @abstractmethod def index(self, value, *args, **kwargs): """ Return first index of value. Additional indexes may be supplied to limit the search to a sub range of the vector. >>> v1 = v(1, 2, 3, 4, 3) >>> v1.index(3) 2 >>> v1.index(3, 3, 5) 4 """ @abstractmethod def count(self, value): """ Return the number of times that value appears in the vector. >>> v1 = v(1, 4, 3, 4) >>> v1.count(4) 2 """ @abstractmethod def transform(self, *transformations): """ Transform arbitrarily complex combinations of PVectors and PMaps. A transformation consists of two parts. One match expression that specifies which elements to transform and one transformation function that performs the actual transformation. >>> from pyrsistent import freeze, ny >>> news_paper = freeze({'articles': [{'author': 'Sara', 'content': 'A short article'}, ... {'author': 'Steve', 'content': 'A slightly longer article'}], ... 'weather': {'temperature': '11C', 'wind': '5m/s'}}) >>> short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:25] + '...' if len(c) > 25 else c) >>> very_short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:15] + '...' if len(c) > 15 else c) >>> very_short_news.articles[0].content 'A short article' >>> very_short_news.articles[1].content 'A slightly long...' When nothing has been transformed the original data structure is kept >>> short_news is news_paper True >>> very_short_news is news_paper False >>> very_short_news.articles[0] is news_paper.articles[0] True """ @abstractmethod def delete(self, index, stop=None): """ Delete a portion of the vector by index or range. >>> v1 = v(1, 2, 3, 4, 5) >>> v1.delete(1) pvector([1, 3, 4, 5]) >>> v1.delete(1, 3) pvector([1, 4, 5]) """ @abstractmethod def remove(self, value): """ Remove the first occurrence of a value from the vector. >>> v1 = v(1, 2, 3, 2, 1) >>> v2 = v1.remove(1) >>> v2 pvector([2, 3, 2, 1]) >>> v2.remove(1) pvector([2, 3, 2]) """ _EMPTY_PVECTOR = PythonPVector(0, SHIFT, [], []) PVector.register(PythonPVector) Sequence.register(PVector) Hashable.register(PVector) def python_pvector(iterable=()): """ Create a new persistent vector containing the elements in iterable. >>> v1 = pvector([1, 2, 3]) >>> v1 pvector([1, 2, 3]) """ return _EMPTY_PVECTOR.extend(iterable) try: # Use the C extension as underlying trie implementation if it is available import os if os.environ.get('PYRSISTENT_NO_C_EXTENSION'): pvector = python_pvector else: from pvectorc import pvector PVector.register(type(pvector())) except ImportError: pvector = python_pvector def v(*elements): """ Create a new persistent vector containing all parameters to this function. >>> v1 = v(1, 2, 3) >>> v1 pvector([1, 2, 3]) """ return pvector(elements)
22,694
Python
30.875
135
0.553935
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_pset.py
from collections.abc import Set, Hashable import sys from pyrsistent._pmap import pmap class PSet(object): """ Persistent set implementation. Built on top of the persistent map. The set supports all operations in the Set protocol and is Hashable. Do not instantiate directly, instead use the factory functions :py:func:`s` or :py:func:`pset` to create an instance. Random access and insert is log32(n) where n is the size of the set. Some examples: >>> s = pset([1, 2, 3, 1]) >>> s2 = s.add(4) >>> s3 = s2.remove(2) >>> s pset([1, 2, 3]) >>> s2 pset([1, 2, 3, 4]) >>> s3 pset([1, 3, 4]) """ __slots__ = ('_map', '__weakref__') def __new__(cls, m): self = super(PSet, cls).__new__(cls) self._map = m return self def __contains__(self, element): return element in self._map def __iter__(self): return iter(self._map) def __len__(self): return len(self._map) def __repr__(self): if not self: return 'p' + str(set(self)) return 'pset([{0}])'.format(str(set(self))[1:-1]) def __str__(self): return self.__repr__() def __hash__(self): return hash(self._map) def __reduce__(self): # Pickling support return pset, (list(self),) @classmethod def _from_iterable(cls, it, pre_size=8): return PSet(pmap(dict((k, True) for k in it), pre_size=pre_size)) def add(self, element): """ Return a new PSet with element added >>> s1 = s(1, 2) >>> s1.add(3) pset([1, 2, 3]) """ return self.evolver().add(element).persistent() def update(self, iterable): """ Return a new PSet with elements in iterable added >>> s1 = s(1, 2) >>> s1.update([3, 4, 4]) pset([1, 2, 3, 4]) """ e = self.evolver() for element in iterable: e.add(element) return e.persistent() def remove(self, element): """ Return a new PSet with element removed. Raises KeyError if element is not present. >>> s1 = s(1, 2) >>> s1.remove(2) pset([1]) """ if element in self._map: return self.evolver().remove(element).persistent() raise KeyError("Element '%s' not present in PSet" % repr(element)) def discard(self, element): """ Return a new PSet with element removed. Returns itself if element is not present. """ if element in self._map: return self.evolver().remove(element).persistent() return self class _Evolver(object): __slots__ = ('_original_pset', '_pmap_evolver') def __init__(self, original_pset): self._original_pset = original_pset self._pmap_evolver = original_pset._map.evolver() def add(self, element): self._pmap_evolver[element] = True return self def remove(self, element): del self._pmap_evolver[element] return self def is_dirty(self): return self._pmap_evolver.is_dirty() def persistent(self): if not self.is_dirty(): return self._original_pset return PSet(self._pmap_evolver.persistent()) def __len__(self): return len(self._pmap_evolver) def copy(self): return self def evolver(self): """ Create a new evolver for this pset. For a discussion on evolvers in general see the documentation for the pvector evolver. Create the evolver and perform various mutating updates to it: >>> s1 = s(1, 2, 3) >>> e = s1.evolver() >>> _ = e.add(4) >>> len(e) 4 >>> _ = e.remove(1) The underlying pset remains the same: >>> s1 pset([1, 2, 3]) The changes are kept in the evolver. An updated pmap can be created using the persistent() function on the evolver. >>> s2 = e.persistent() >>> s2 pset([2, 3, 4]) The new pset will share data with the original pset in the same way that would have been done if only using operations on the pset. """ return PSet._Evolver(self) # All the operations and comparisons you would expect on a set. # # This is not very beautiful. If we avoid inheriting from PSet we can use the # __slots__ concepts (which requires a new style class) and hopefully save some memory. __le__ = Set.__le__ __lt__ = Set.__lt__ __gt__ = Set.__gt__ __ge__ = Set.__ge__ __eq__ = Set.__eq__ __ne__ = Set.__ne__ __and__ = Set.__and__ __or__ = Set.__or__ __sub__ = Set.__sub__ __xor__ = Set.__xor__ issubset = __le__ issuperset = __ge__ union = __or__ intersection = __and__ difference = __sub__ symmetric_difference = __xor__ isdisjoint = Set.isdisjoint Set.register(PSet) Hashable.register(PSet) _EMPTY_PSET = PSet(pmap()) def pset(iterable=(), pre_size=8): """ Creates a persistent set from iterable. Optionally takes a sizing parameter equivalent to that used for :py:func:`pmap`. >>> s1 = pset([1, 2, 3, 2]) >>> s1 pset([1, 2, 3]) """ if not iterable: return _EMPTY_PSET return PSet._from_iterable(iterable, pre_size=pre_size) def s(*elements): """ Create a persistent set. Takes an arbitrary number of arguments to insert into the new set. >>> s1 = s(1, 2, 3, 2) >>> s1 pset([1, 2, 3]) """ return pset(elements)
5,693
Python
23.973684
102
0.540664
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/typing.pyi
# flake8: noqa: E704 # from https://gist.github.com/WuTheFWasThat/091a17d4b5cab597dfd5d4c2d96faf09 # Stubs for pyrsistent (Python 3.6) # from typing import Any from typing import Callable from typing import Dict from typing import Generic from typing import Hashable from typing import Iterator from typing import Iterable from typing import List from typing import Mapping from typing import Optional from typing import Sequence from typing import AbstractSet from typing import Sized from typing import Set from typing import Tuple from typing import TypeVar from typing import Type from typing import Union from typing import overload T = TypeVar('T') KT = TypeVar('KT') VT = TypeVar('VT') class PMap(Mapping[KT, VT], Hashable): def __add__(self, other: PMap[KT, VT]) -> PMap[KT, VT]: ... def __getitem__(self, key: KT) -> VT: ... def __getattr__(self, key: str) -> VT: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[KT]: ... def __len__(self) -> int: ... def copy(self) -> PMap[KT, VT]: ... def discard(self, key: KT) -> PMap[KT, VT]: ... def evolver(self) -> PMapEvolver[KT, VT]: ... def iteritems(self) -> Iterable[Tuple[KT, VT]]: ... def iterkeys(self) -> Iterable[KT]: ... def itervalues(self) -> Iterable[VT]: ... def remove(self, key: KT) -> PMap[KT, VT]: ... def set(self, key: KT, val: VT) -> PMap[KT, VT]: ... def transform(self, *transformations: Any) -> PMap[KT, VT]: ... def update(self, *args: Mapping): ... def update_with(self, update_fn: Callable[[VT, VT], VT], *args: Mapping) -> Any: ... class PMapEvolver(Generic[KT, VT]): def __delitem__(self, key: KT) -> None: ... def __getitem__(self, key: KT) -> VT: ... def __len__(self) -> int: ... def __setitem__(self, key: KT, val: VT) -> None: ... def is_dirty(self) -> bool: ... def persistent(self) -> PMap[KT, VT]: ... def remove(self, key: KT) -> PMapEvolver[KT, VT]: ... def set(self, key: KT, val: VT) -> PMapEvolver[KT, VT]: ... class PVector(Sequence[T], Hashable): def __add__(self, other: PVector[T]) -> PVector[T]: ... @overload def __getitem__(self, index: int) -> T: ... @overload def __getitem__(self, index: slice) -> PVector[T]: ... def __hash__(self) -> int: ... def __len__(self) -> int: ... def __mul__(self, other: PVector[T]) -> PVector[T]: ... def append(self, val: T) -> PVector[T]: ... def delete(self, index: int, stop: Optional[int] = None) -> PVector[T]: ... def evolver(self) -> PVectorEvolver[T]: ... def extend(self, obj: Iterable[T]) -> PVector[T]: ... def tolist(self) -> List[T]: ... def mset(self, *args: Iterable[Union[T, int]]) -> PVector[T]: ... def remove(self, value: T) -> PVector[T]: ... # Not compatible with MutableSequence def set(self, i: int, val: T) -> PVector[T]: ... def transform(self, *transformations: Any) -> PVector[T]: ... class PVectorEvolver(Sequence[T], Sized): def __delitem__(self, i: Union[int, slice]) -> None: ... @overload def __getitem__(self, index: int) -> T: ... # Not actually supported @overload def __getitem__(self, index: slice) -> PVectorEvolver[T]: ... def __len__(self) -> int: ... def __setitem__(self, index: int, val: T) -> None: ... def append(self, val: T) -> PVectorEvolver[T]: ... def delete(self, value: T) -> PVectorEvolver[T]: ... def extend(self, obj: Iterable[T]) -> PVectorEvolver[T]: ... def is_dirty(self) -> bool: ... def persistent(self) -> PVector[T]: ... def set(self, i: int, val: T) -> PVectorEvolver[T]: ... class PSet(AbstractSet[T], Hashable): def __contains__(self, element: object) -> bool: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[T]: ... def __len__(self) -> int: ... def add(self, element: T) -> PSet[T]: ... def copy(self) -> PSet[T]: ... def difference(self, iterable: Iterable) -> PSet[T]: ... def discard(self, element: T) -> PSet[T]: ... def evolver(self) -> PSetEvolver[T]: ... def intersection(self, iterable: Iterable) -> PSet[T]: ... def issubset(self, iterable: Iterable) -> bool: ... def issuperset(self, iterable: Iterable) -> bool: ... def remove(self, element: T) -> PSet[T]: ... def symmetric_difference(self, iterable: Iterable[T]) -> PSet[T]: ... def union(self, iterable: Iterable[T]) -> PSet[T]: ... def update(self, iterable: Iterable[T]) -> PSet[T]: ... class PSetEvolver(Generic[T], Sized): def __len__(self) -> int: ... def add(self, element: T) -> PSetEvolver[T]: ... def is_dirty(self) -> bool: ... def persistent(self) -> PSet[T]: ... def remove(self, element: T) -> PSetEvolver[T]: ... class PBag(Generic[T], Sized, Hashable): def __add__(self, other: PBag[T]) -> PBag[T]: ... def __and__(self, other: PBag[T]) -> PBag[T]: ... def __contains__(self, elem: object) -> bool: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[T]: ... def __len__(self) -> int: ... def __or__(self, other: PBag[T]) -> PBag[T]: ... def __sub__(self, other: PBag[T]) -> PBag[T]: ... def add(self, elem: T) -> PBag[T]: ... def count(self, elem: T) -> int: ... def remove(self, elem: T) -> PBag[T]: ... def update(self, iterable: Iterable[T]) -> PBag[T]: ... class PDeque(Sequence[T], Hashable): @overload def __getitem__(self, index: int) -> T: ... @overload def __getitem__(self, index: slice) -> PDeque[T]: ... def __hash__(self) -> int: ... def __len__(self) -> int: ... def __lt__(self, other: PDeque[T]) -> bool: ... def append(self, elem: T) -> PDeque[T]: ... def appendleft(self, elem: T) -> PDeque[T]: ... def extend(self, iterable: Iterable[T]) -> PDeque[T]: ... def extendleft(self, iterable: Iterable[T]) -> PDeque[T]: ... @property def left(self) -> T: ... # The real return type is Integral according to what pyrsistent # checks at runtime but mypy doesn't deal in numeric.*: # https://github.com/python/mypy/issues/2636 @property def maxlen(self) -> int: ... def pop(self, count: int = 1) -> PDeque[T]: ... def popleft(self, count: int = 1) -> PDeque[T]: ... def remove(self, elem: T) -> PDeque[T]: ... def reverse(self) -> PDeque[T]: ... @property def right(self) -> T: ... def rotate(self, steps: int) -> PDeque[T]: ... class PList(Sequence[T], Hashable): @overload def __getitem__(self, index: int) -> T: ... @overload def __getitem__(self, index: slice) -> PList[T]: ... def __hash__(self) -> int: ... def __len__(self) -> int: ... def __lt__(self, other: PList[T]) -> bool: ... def __gt__(self, other: PList[T]) -> bool: ... def cons(self, elem: T) -> PList[T]: ... @property def first(self) -> T: ... def mcons(self, iterable: Iterable[T]) -> PList[T]: ... def remove(self, elem: T) -> PList[T]: ... @property def rest(self) -> PList[T]: ... def reverse(self) -> PList[T]: ... def split(self, index: int) -> Tuple[PList[T], PList[T]]: ... T_PClass = TypeVar('T_PClass', bound='PClass') class PClass(Hashable): def __new__(cls, **kwargs: Any): ... def set(self: T_PClass, *args: Any, **kwargs: Any) -> T_PClass: ... @classmethod def create( cls: Type[T_PClass], kwargs: Any, _factory_fields: Optional[Any] = ..., ignore_extra: bool = ..., ) -> T_PClass: ... def serialize(self, format: Optional[Any] = ...): ... def transform(self, *transformations: Any): ... def __eq__(self, other: object): ... def __ne__(self, other: object): ... def __hash__(self): ... def __reduce__(self): ... def evolver(self) -> PClassEvolver: ... def remove(self: T_PClass, name: Any) -> T_PClass: ... class PClassEvolver: def __init__(self, original: Any, initial_dict: Any) -> None: ... def __getitem__(self, item: Any): ... def set(self, key: Any, value: Any): ... def __setitem__(self, key: Any, value: Any) -> None: ... def remove(self, item: Any): ... def __delitem__(self, item: Any) -> None: ... def persistent(self) -> PClass: ... def __getattr__(self, item: Any): ... class CheckedPMap(PMap[KT, VT]): __key_type__: Type[KT] __value_type__: Type[VT] def __new__(cls, source: Mapping[KT, VT] = ..., size: int = ...) -> CheckedPMap: ... @classmethod def create(cls, source_data: Mapping[KT, VT], _factory_fields: Any = ...) -> CheckedPMap[KT, VT]: ... def serialize(self, format: Optional[Any] = ...) -> Dict[KT, VT]: ... class CheckedPVector(PVector[T]): __type__: Type[T] def __new__(self, initial: Iterable[T] = ...) -> CheckedPVector: ... @classmethod def create(cls, source_data: Iterable[T], _factory_fields: Any = ...) -> CheckedPVector[T]: ... def serialize(self, format: Optional[Any] = ...) -> List[T]: ... class CheckedPSet(PSet[T]): __type__: Type[T] def __new__(cls, initial: Iterable[T] = ...) -> CheckedPSet: ... @classmethod def create(cls, source_data: Iterable[T], _factory_fields: Any = ...) -> CheckedPSet[T]: ... def serialize(self, format: Optional[Any] = ...) -> Set[T]: ... class InvariantException(Exception): invariant_errors: Tuple[Any, ...] = ... # possibly nested tuple missing_fields: Tuple[str, ...] = ... def __init__( self, error_codes: Any = ..., missing_fields: Any = ..., *args: Any, **kwargs: Any ) -> None: ... class CheckedTypeError(TypeError): source_class: Type[Any] expected_types: Tuple[Any, ...] actual_type: Type[Any] actual_value: Any def __init__( self, source_class: Any, expected_types: Any, actual_type: Any, actual_value: Any, *args: Any, **kwargs: Any ) -> None: ... class CheckedKeyTypeError(CheckedTypeError): ... class CheckedValueTypeError(CheckedTypeError): ... class CheckedType: ... class PTypeError(TypeError): source_class: Type[Any] = ... field: str = ... expected_types: Tuple[Any, ...] = ... actual_type: Type[Any] = ... def __init__( self, source_class: Any, field: Any, expected_types: Any, actual_type: Any, *args: Any, **kwargs: Any ) -> None: ...
10,416
unknown
34.552901
105
0.562884
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_transformations.py
import re try: from inspect import Parameter, signature except ImportError: signature = None from inspect import getfullargspec _EMPTY_SENTINEL = object() def inc(x): """ Add one to the current value """ return x + 1 def dec(x): """ Subtract one from the current value """ return x - 1 def discard(evolver, key): """ Discard the element and returns a structure without the discarded elements """ try: del evolver[key] except KeyError: pass # Matchers def rex(expr): """ Regular expression matcher to use together with transform functions """ r = re.compile(expr) return lambda key: isinstance(key, str) and r.match(key) def ny(_): """ Matcher that matches any value """ return True # Support functions def _chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] def transform(structure, transformations): r = structure for path, command in _chunks(transformations, 2): r = _do_to_path(r, path, command) return r def _do_to_path(structure, path, command): if not path: return command(structure) if callable(command) else command kvs = _get_keys_and_values(structure, path[0]) return _update_structure(structure, kvs, path[1:], command) def _items(structure): try: return structure.items() except AttributeError: # Support wider range of structures by adding a transform_items() or similar? return list(enumerate(structure)) def _get(structure, key, default): try: if hasattr(structure, '__getitem__'): return structure[key] return getattr(structure, key) except (IndexError, KeyError): return default def _get_keys_and_values(structure, key_spec): if callable(key_spec): # Support predicates as callable objects in the path arity = _get_arity(key_spec) if arity == 1: # Unary predicates are called with the "key" of the path # - eg a key in a mapping, an index in a sequence. return [(k, v) for k, v in _items(structure) if key_spec(k)] elif arity == 2: # Binary predicates are called with the key and the corresponding # value. return [(k, v) for k, v in _items(structure) if key_spec(k, v)] else: # Other arities are an error. raise ValueError( "callable in transform path must take 1 or 2 arguments" ) # Non-callables are used as-is as a key. return [(key_spec, _get(structure, key_spec, _EMPTY_SENTINEL))] if signature is None: def _get_arity(f): argspec = getfullargspec(f) return len(argspec.args) - len(argspec.defaults or ()) else: def _get_arity(f): return sum( 1 for p in signature(f).parameters.values() if p.default is Parameter.empty and p.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD) ) def _update_structure(structure, kvs, path, command): from pyrsistent._pmap import pmap e = structure.evolver() if not path and command is discard: # Do this in reverse to avoid index problems with vectors. See #92. for k, v in reversed(kvs): discard(e, k) else: for k, v in kvs: is_empty = False if v is _EMPTY_SENTINEL: # Allow expansion of structure but make sure to cover the case # when an empty pmap is added as leaf node. See #154. is_empty = True v = pmap() result = _do_to_path(v, path, command) if result is not v or is_empty: e[k] = result return e.persistent()
3,800
Python
26.15
86
0.598421
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/__init__.pyi
# flake8: noqa: E704 # from https://gist.github.com/WuTheFWasThat/091a17d4b5cab597dfd5d4c2d96faf09 # Stubs for pyrsistent (Python 3.6) from typing import Any from typing import AnyStr from typing import Callable from typing import Iterable from typing import Iterator from typing import List from typing import Optional from typing import Mapping from typing import MutableMapping from typing import Sequence from typing import Set from typing import Union from typing import Tuple from typing import Type from typing import TypeVar from typing import overload # see commit 08519aa for explanation of the re-export from pyrsistent.typing import CheckedKeyTypeError as CheckedKeyTypeError from pyrsistent.typing import CheckedPMap as CheckedPMap from pyrsistent.typing import CheckedPSet as CheckedPSet from pyrsistent.typing import CheckedPVector as CheckedPVector from pyrsistent.typing import CheckedType as CheckedType from pyrsistent.typing import CheckedValueTypeError as CheckedValueTypeError from pyrsistent.typing import InvariantException as InvariantException from pyrsistent.typing import PClass as PClass from pyrsistent.typing import PBag as PBag from pyrsistent.typing import PDeque as PDeque from pyrsistent.typing import PList as PList from pyrsistent.typing import PMap as PMap from pyrsistent.typing import PMapEvolver as PMapEvolver from pyrsistent.typing import PSet as PSet from pyrsistent.typing import PSetEvolver as PSetEvolver from pyrsistent.typing import PTypeError as PTypeError from pyrsistent.typing import PVector as PVector from pyrsistent.typing import PVectorEvolver as PVectorEvolver T = TypeVar('T') KT = TypeVar('KT') VT = TypeVar('VT') def pmap(initial: Union[Mapping[KT, VT], Iterable[Tuple[KT, VT]]] = {}, pre_size: int = 0) -> PMap[KT, VT]: ... def m(**kwargs: VT) -> PMap[str, VT]: ... def pvector(iterable: Iterable[T] = ...) -> PVector[T]: ... def v(*iterable: T) -> PVector[T]: ... def pset(iterable: Iterable[T] = (), pre_size: int = 8) -> PSet[T]: ... def s(*iterable: T) -> PSet[T]: ... # see class_test.py for use cases Invariant = Tuple[bool, Optional[Union[str, Callable[[], str]]]] @overload def field( type: Union[Type[T], Sequence[Type[T]]] = ..., invariant: Callable[[Any], Union[Invariant, Iterable[Invariant]]] = lambda _: (True, None), initial: Any = object(), mandatory: bool = False, factory: Callable[[Any], T] = lambda x: x, serializer: Callable[[Any, T], Any] = lambda _, value: value, ) -> T: ... # The actual return value (_PField) is irrelevant after a PRecord has been instantiated, # see https://github.com/tobgu/pyrsistent/blob/master/pyrsistent/_precord.py#L10 @overload def field( type: Any = ..., invariant: Callable[[Any], Union[Invariant, Iterable[Invariant]]] = lambda _: (True, None), initial: Any = object(), mandatory: bool = False, factory: Callable[[Any], Any] = lambda x: x, serializer: Callable[[Any, Any], Any] = lambda _, value: value, ) -> Any: ... # Use precise types for the simplest use cases, but fall back to Any for # everything else. See record_test.py for the wide range of possible types for # item_type @overload def pset_field( item_type: Type[T], optional: bool = False, initial: Iterable[T] = ..., ) -> PSet[T]: ... @overload def pset_field( item_type: Any, optional: bool = False, initial: Any = (), ) -> PSet[Any]: ... @overload def pmap_field( key_type: Type[KT], value_type: Type[VT], optional: bool = False, invariant: Callable[[Any], Tuple[bool, Optional[str]]] = lambda _: (True, None), ) -> PMap[KT, VT]: ... @overload def pmap_field( key_type: Any, value_type: Any, optional: bool = False, invariant: Callable[[Any], Tuple[bool, Optional[str]]] = lambda _: (True, None), ) -> PMap[Any, Any]: ... @overload def pvector_field( item_type: Type[T], optional: bool = False, initial: Iterable[T] = ..., ) -> PVector[T]: ... @overload def pvector_field( item_type: Any, optional: bool = False, initial: Any = (), ) -> PVector[Any]: ... def pbag(elements: Iterable[T]) -> PBag[T]: ... def b(*elements: T) -> PBag[T]: ... def plist(iterable: Iterable[T] = (), reverse: bool = False) -> PList[T]: ... def l(*elements: T) -> PList[T]: ... def pdeque(iterable: Optional[Iterable[T]] = None, maxlen: Optional[int] = None) -> PDeque[T]: ... def dq(*iterable: T) -> PDeque[T]: ... @overload def optional(type: T) -> Tuple[T, Type[None]]: ... @overload def optional(*typs: Any) -> Tuple[Any, ...]: ... T_PRecord = TypeVar('T_PRecord', bound='PRecord') class PRecord(PMap[AnyStr, Any]): _precord_fields: Mapping _precord_initial_values: Mapping def __hash__(self) -> int: ... def __init__(self, **kwargs: Any) -> None: ... def __iter__(self) -> Iterator[Any]: ... def __len__(self) -> int: ... @classmethod def create( cls: Type[T_PRecord], kwargs: Mapping, _factory_fields: Optional[Iterable] = None, ignore_extra: bool = False, ) -> T_PRecord: ... # This is OK because T_PRecord is a concrete type def discard(self: T_PRecord, key: KT) -> T_PRecord: ... def remove(self: T_PRecord, key: KT) -> T_PRecord: ... def serialize(self, format: Optional[Any] = ...) -> MutableMapping: ... # From pyrsistent documentation: # This set function differs slightly from that in the PMap # class. First of all it accepts key-value pairs. Second it accepts multiple key-value # pairs to perform one, atomic, update of multiple fields. @overload def set(self, key: KT, val: VT) -> Any: ... @overload def set(self, **kwargs: VT) -> Any: ... def immutable( members: Union[str, Iterable[str]] = '', name: str = 'Immutable', verbose: bool = False, ) -> Tuple: ... # actually a namedtuple # ignore mypy warning "Overloaded function signatures 1 and 5 overlap with # incompatible return types" @overload def freeze(o: Mapping[KT, VT]) -> PMap[KT, VT]: ... # type: ignore @overload def freeze(o: List[T]) -> PVector[T]: ... # type: ignore @overload def freeze(o: Tuple[T, ...]) -> Tuple[T, ...]: ... @overload def freeze(o: Set[T]) -> PSet[T]: ... # type: ignore @overload def freeze(o: T) -> T: ... @overload def thaw(o: PMap[KT, VT]) -> MutableMapping[KT, VT]: ... # type: ignore @overload def thaw(o: PVector[T]) -> List[T]: ... # type: ignore @overload def thaw(o: Tuple[T, ...]) -> Tuple[T, ...]: ... # collections.abc.MutableSet is kind of garbage: # https://stackoverflow.com/questions/24977898/why-does-collections-mutableset-not-bestow-an-update-method @overload def thaw(o: PSet[T]) -> Set[T]: ... # type: ignore @overload def thaw(o: T) -> T: ... def mutant(fn: Callable) -> Callable: ... def inc(x: int) -> int: ... @overload def discard(evolver: PMapEvolver[KT, VT], key: KT) -> None: ... @overload def discard(evolver: PVectorEvolver[T], key: int) -> None: ... @overload def discard(evolver: PSetEvolver[T], key: T) -> None: ... def rex(expr: str) -> Callable[[Any], bool]: ... def ny(_: Any) -> bool: ... def get_in(keys: Iterable, coll: Mapping, default: Optional[Any] = None, no_default: bool = False) -> Any: ...
7,188
unknown
32.593458
111
0.668753
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/typing.py
"""Helpers for use with type annotation. Use the empty classes in this module when annotating the types of Pyrsistent objects, instead of using the actual collection class. For example, from pyrsistent import pvector from pyrsistent.typing import PVector myvector: PVector[str] = pvector(['a', 'b', 'c']) """ from __future__ import absolute_import try: from typing import Container from typing import Hashable from typing import Generic from typing import Iterable from typing import Mapping from typing import Sequence from typing import Sized from typing import TypeVar __all__ = [ 'CheckedPMap', 'CheckedPSet', 'CheckedPVector', 'PBag', 'PDeque', 'PList', 'PMap', 'PSet', 'PVector', ] T = TypeVar('T') KT = TypeVar('KT') VT = TypeVar('VT') class CheckedPMap(Mapping[KT, VT], Hashable): pass # PSet.add and PSet.discard have different type signatures than that of Set. class CheckedPSet(Generic[T], Hashable): pass class CheckedPVector(Sequence[T], Hashable): pass class PBag(Container[T], Iterable[T], Sized, Hashable): pass class PDeque(Sequence[T], Hashable): pass class PList(Sequence[T], Hashable): pass class PMap(Mapping[KT, VT], Hashable): pass # PSet.add and PSet.discard have different type signatures than that of Set. class PSet(Generic[T], Hashable): pass class PVector(Sequence[T], Hashable): pass class PVectorEvolver(Generic[T]): pass class PMapEvolver(Generic[KT, VT]): pass class PSetEvolver(Generic[T]): pass except ImportError: pass
1,767
Python
20.82716
80
0.627051
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_precord.py
from pyrsistent._checked_types import CheckedType, _restore_pickle, InvariantException, store_invariants from pyrsistent._field_common import ( set_fields, check_type, is_field_ignore_extra_complaint, PFIELD_NO_INITIAL, serialize, check_global_invariants ) from pyrsistent._pmap import PMap, pmap class _PRecordMeta(type): def __new__(mcs, name, bases, dct): set_fields(dct, bases, name='_precord_fields') store_invariants(dct, bases, '_precord_invariants', '__invariant__') dct['_precord_mandatory_fields'] = \ set(name for name, field in dct['_precord_fields'].items() if field.mandatory) dct['_precord_initial_values'] = \ dict((k, field.initial) for k, field in dct['_precord_fields'].items() if field.initial is not PFIELD_NO_INITIAL) dct['__slots__'] = () return super(_PRecordMeta, mcs).__new__(mcs, name, bases, dct) class PRecord(PMap, CheckedType, metaclass=_PRecordMeta): """ A PRecord is a PMap with a fixed set of specified fields. Records are declared as python classes inheriting from PRecord. Because it is a PMap it has full support for all Mapping methods such as iteration and element access using subscript notation. More documentation and examples of PRecord usage is available at https://github.com/tobgu/pyrsistent """ def __new__(cls, **kwargs): # Hack total! If these two special attributes exist that means we can create # ourselves. Otherwise we need to go through the Evolver to create the structures # for us. if '_precord_size' in kwargs and '_precord_buckets' in kwargs: return super(PRecord, cls).__new__(cls, kwargs['_precord_size'], kwargs['_precord_buckets']) factory_fields = kwargs.pop('_factory_fields', None) ignore_extra = kwargs.pop('_ignore_extra', False) initial_values = kwargs if cls._precord_initial_values: initial_values = dict((k, v() if callable(v) else v) for k, v in cls._precord_initial_values.items()) initial_values.update(kwargs) e = _PRecordEvolver(cls, pmap(pre_size=len(cls._precord_fields)), _factory_fields=factory_fields, _ignore_extra=ignore_extra) for k, v in initial_values.items(): e[k] = v return e.persistent() def set(self, *args, **kwargs): """ Set a field in the record. This set function differs slightly from that in the PMap class. First of all it accepts key-value pairs. Second it accepts multiple key-value pairs to perform one, atomic, update of multiple fields. """ # The PRecord set() can accept kwargs since all fields that have been declared are # valid python identifiers. Also allow multiple fields to be set in one operation. if args: return super(PRecord, self).set(args[0], args[1]) return self.update(kwargs) def evolver(self): """ Returns an evolver of this object. """ return _PRecordEvolver(self.__class__, self) def __repr__(self): return "{0}({1})".format(self.__class__.__name__, ', '.join('{0}={1}'.format(k, repr(v)) for k, v in self.items())) @classmethod def create(cls, kwargs, _factory_fields=None, ignore_extra=False): """ Factory method. Will create a new PRecord of the current type and assign the values specified in kwargs. :param ignore_extra: A boolean which when set to True will ignore any keys which appear in kwargs that are not in the set of fields on the PRecord. """ if isinstance(kwargs, cls): return kwargs if ignore_extra: kwargs = {k: kwargs[k] for k in cls._precord_fields if k in kwargs} return cls(_factory_fields=_factory_fields, _ignore_extra=ignore_extra, **kwargs) def __reduce__(self): # Pickling support return _restore_pickle, (self.__class__, dict(self),) def serialize(self, format=None): """ Serialize the current PRecord using custom serializer functions for fields where such have been supplied. """ return dict((k, serialize(self._precord_fields[k].serializer, format, v)) for k, v in self.items()) class _PRecordEvolver(PMap._Evolver): __slots__ = ('_destination_cls', '_invariant_error_codes', '_missing_fields', '_factory_fields', '_ignore_extra') def __init__(self, cls, original_pmap, _factory_fields=None, _ignore_extra=False): super(_PRecordEvolver, self).__init__(original_pmap) self._destination_cls = cls self._invariant_error_codes = [] self._missing_fields = [] self._factory_fields = _factory_fields self._ignore_extra = _ignore_extra def __setitem__(self, key, original_value): self.set(key, original_value) def set(self, key, original_value): field = self._destination_cls._precord_fields.get(key) if field: if self._factory_fields is None or field in self._factory_fields: try: if is_field_ignore_extra_complaint(PRecord, field, self._ignore_extra): value = field.factory(original_value, ignore_extra=self._ignore_extra) else: value = field.factory(original_value) except InvariantException as e: self._invariant_error_codes += e.invariant_errors self._missing_fields += e.missing_fields return self else: value = original_value check_type(self._destination_cls, field, key, value) is_ok, error_code = field.invariant(value) if not is_ok: self._invariant_error_codes.append(error_code) return super(_PRecordEvolver, self).set(key, value) else: raise AttributeError("'{0}' is not among the specified fields for {1}".format(key, self._destination_cls.__name__)) def persistent(self): cls = self._destination_cls is_dirty = self.is_dirty() pm = super(_PRecordEvolver, self).persistent() if is_dirty or not isinstance(pm, cls): result = cls(_precord_buckets=pm._buckets, _precord_size=pm._size) else: result = pm if cls._precord_mandatory_fields: self._missing_fields += tuple('{0}.{1}'.format(cls.__name__, f) for f in (cls._precord_mandatory_fields - set(result.keys()))) if self._invariant_error_codes or self._missing_fields: raise InvariantException(tuple(self._invariant_error_codes), tuple(self._missing_fields), 'Field invariant failed') check_global_invariants(result, cls._precord_invariants) return result
7,032
Python
40.863095
133
0.607651
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_pdeque.py
from collections.abc import Sequence, Hashable from itertools import islice, chain from numbers import Integral from pyrsistent._plist import plist class PDeque(object): """ Persistent double ended queue (deque). Allows quick appends and pops in both ends. Implemented using two persistent lists. A maximum length can be specified to create a bounded queue. Fully supports the Sequence and Hashable protocols including indexing and slicing but if you need fast random access go for the PVector instead. Do not instantiate directly, instead use the factory functions :py:func:`dq` or :py:func:`pdeque` to create an instance. Some examples: >>> x = pdeque([1, 2, 3]) >>> x.left 1 >>> x.right 3 >>> x[0] == x.left True >>> x[-1] == x.right True >>> x.pop() pdeque([1, 2]) >>> x.pop() == x[:-1] True >>> x.popleft() pdeque([2, 3]) >>> x.append(4) pdeque([1, 2, 3, 4]) >>> x.appendleft(4) pdeque([4, 1, 2, 3]) >>> y = pdeque([1, 2, 3], maxlen=3) >>> y.append(4) pdeque([2, 3, 4], maxlen=3) >>> y.appendleft(4) pdeque([4, 1, 2], maxlen=3) """ __slots__ = ('_left_list', '_right_list', '_length', '_maxlen', '__weakref__') def __new__(cls, left_list, right_list, length, maxlen=None): instance = super(PDeque, cls).__new__(cls) instance._left_list = left_list instance._right_list = right_list instance._length = length if maxlen is not None: if not isinstance(maxlen, Integral): raise TypeError('An integer is required as maxlen') if maxlen < 0: raise ValueError("maxlen must be non-negative") instance._maxlen = maxlen return instance @property def right(self): """ Rightmost element in dqueue. """ return PDeque._tip_from_lists(self._right_list, self._left_list) @property def left(self): """ Leftmost element in dqueue. """ return PDeque._tip_from_lists(self._left_list, self._right_list) @staticmethod def _tip_from_lists(primary_list, secondary_list): if primary_list: return primary_list.first if secondary_list: return secondary_list[-1] raise IndexError('No elements in empty deque') def __iter__(self): return chain(self._left_list, self._right_list.reverse()) def __repr__(self): return "pdeque({0}{1})".format(list(self), ', maxlen={0}'.format(self._maxlen) if self._maxlen is not None else '') __str__ = __repr__ @property def maxlen(self): """ Maximum length of the queue. """ return self._maxlen def pop(self, count=1): """ Return new deque with rightmost element removed. Popping the empty queue will return the empty queue. A optional count can be given to indicate the number of elements to pop. Popping with a negative index is the same as popleft. Executes in amortized O(k) where k is the number of elements to pop. >>> pdeque([1, 2]).pop() pdeque([1]) >>> pdeque([1, 2]).pop(2) pdeque([]) >>> pdeque([1, 2]).pop(-1) pdeque([2]) """ if count < 0: return self.popleft(-count) new_right_list, new_left_list = PDeque._pop_lists(self._right_list, self._left_list, count) return PDeque(new_left_list, new_right_list, max(self._length - count, 0), self._maxlen) def popleft(self, count=1): """ Return new deque with leftmost element removed. Otherwise functionally equivalent to pop(). >>> pdeque([1, 2]).popleft() pdeque([2]) """ if count < 0: return self.pop(-count) new_left_list, new_right_list = PDeque._pop_lists(self._left_list, self._right_list, count) return PDeque(new_left_list, new_right_list, max(self._length - count, 0), self._maxlen) @staticmethod def _pop_lists(primary_list, secondary_list, count): new_primary_list = primary_list new_secondary_list = secondary_list while count > 0 and (new_primary_list or new_secondary_list): count -= 1 if new_primary_list.rest: new_primary_list = new_primary_list.rest elif new_primary_list: new_primary_list = new_secondary_list.reverse() new_secondary_list = plist() else: new_primary_list = new_secondary_list.reverse().rest new_secondary_list = plist() return new_primary_list, new_secondary_list def _is_empty(self): return not self._left_list and not self._right_list def __lt__(self, other): if not isinstance(other, PDeque): return NotImplemented return tuple(self) < tuple(other) def __eq__(self, other): if not isinstance(other, PDeque): return NotImplemented if tuple(self) == tuple(other): # Sanity check of the length value since it is redundant (there for performance) assert len(self) == len(other) return True return False def __hash__(self): return hash(tuple(self)) def __len__(self): return self._length def append(self, elem): """ Return new deque with elem as the rightmost element. >>> pdeque([1, 2]).append(3) pdeque([1, 2, 3]) """ new_left_list, new_right_list, new_length = self._append(self._left_list, self._right_list, elem) return PDeque(new_left_list, new_right_list, new_length, self._maxlen) def appendleft(self, elem): """ Return new deque with elem as the leftmost element. >>> pdeque([1, 2]).appendleft(3) pdeque([3, 1, 2]) """ new_right_list, new_left_list, new_length = self._append(self._right_list, self._left_list, elem) return PDeque(new_left_list, new_right_list, new_length, self._maxlen) def _append(self, primary_list, secondary_list, elem): if self._maxlen is not None and self._length == self._maxlen: if self._maxlen == 0: return primary_list, secondary_list, 0 new_primary_list, new_secondary_list = PDeque._pop_lists(primary_list, secondary_list, 1) return new_primary_list, new_secondary_list.cons(elem), self._length return primary_list, secondary_list.cons(elem), self._length + 1 @staticmethod def _extend_list(the_list, iterable): count = 0 for elem in iterable: the_list = the_list.cons(elem) count += 1 return the_list, count def _extend(self, primary_list, secondary_list, iterable): new_primary_list, extend_count = PDeque._extend_list(primary_list, iterable) new_secondary_list = secondary_list current_len = self._length + extend_count if self._maxlen is not None and current_len > self._maxlen: pop_len = current_len - self._maxlen new_secondary_list, new_primary_list = PDeque._pop_lists(new_secondary_list, new_primary_list, pop_len) extend_count -= pop_len return new_primary_list, new_secondary_list, extend_count def extend(self, iterable): """ Return new deque with all elements of iterable appended to the right. >>> pdeque([1, 2]).extend([3, 4]) pdeque([1, 2, 3, 4]) """ new_right_list, new_left_list, extend_count = self._extend(self._right_list, self._left_list, iterable) return PDeque(new_left_list, new_right_list, self._length + extend_count, self._maxlen) def extendleft(self, iterable): """ Return new deque with all elements of iterable appended to the left. NB! The elements will be inserted in reverse order compared to the order in the iterable. >>> pdeque([1, 2]).extendleft([3, 4]) pdeque([4, 3, 1, 2]) """ new_left_list, new_right_list, extend_count = self._extend(self._left_list, self._right_list, iterable) return PDeque(new_left_list, new_right_list, self._length + extend_count, self._maxlen) def count(self, elem): """ Return the number of elements equal to elem present in the queue >>> pdeque([1, 2, 1]).count(1) 2 """ return self._left_list.count(elem) + self._right_list.count(elem) def remove(self, elem): """ Return new deque with first element from left equal to elem removed. If no such element is found a ValueError is raised. >>> pdeque([2, 1, 2]).remove(2) pdeque([1, 2]) """ try: return PDeque(self._left_list.remove(elem), self._right_list, self._length - 1) except ValueError: # Value not found in left list, try the right list try: # This is severely inefficient with a double reverse, should perhaps implement a remove_last()? return PDeque(self._left_list, self._right_list.reverse().remove(elem).reverse(), self._length - 1) except ValueError as e: raise ValueError('{0} not found in PDeque'.format(elem)) from e def reverse(self): """ Return reversed deque. >>> pdeque([1, 2, 3]).reverse() pdeque([3, 2, 1]) Also supports the standard python reverse function. >>> reversed(pdeque([1, 2, 3])) pdeque([3, 2, 1]) """ return PDeque(self._right_list, self._left_list, self._length) __reversed__ = reverse def rotate(self, steps): """ Return deque with elements rotated steps steps. >>> x = pdeque([1, 2, 3]) >>> x.rotate(1) pdeque([3, 1, 2]) >>> x.rotate(-2) pdeque([3, 1, 2]) """ popped_deque = self.pop(steps) if steps >= 0: return popped_deque.extendleft(islice(self.reverse(), steps)) return popped_deque.extend(islice(self, -steps)) def __reduce__(self): # Pickling support return pdeque, (list(self), self._maxlen) def __getitem__(self, index): if isinstance(index, slice): if index.step is not None and index.step != 1: # Too difficult, no structural sharing possible return pdeque(tuple(self)[index], maxlen=self._maxlen) result = self if index.start is not None: result = result.popleft(index.start % self._length) if index.stop is not None: result = result.pop(self._length - (index.stop % self._length)) return result if not isinstance(index, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(index).__name__) if index >= 0: return self.popleft(index).left shifted = len(self) + index if shifted < 0: raise IndexError( "pdeque index {0} out of range {1}".format(index, len(self)), ) return self.popleft(shifted).left index = Sequence.index Sequence.register(PDeque) Hashable.register(PDeque) def pdeque(iterable=(), maxlen=None): """ Return deque containing the elements of iterable. If maxlen is specified then len(iterable) - maxlen elements are discarded from the left to if len(iterable) > maxlen. >>> pdeque([1, 2, 3]) pdeque([1, 2, 3]) >>> pdeque([1, 2, 3, 4], maxlen=2) pdeque([3, 4], maxlen=2) """ t = tuple(iterable) if maxlen is not None: t = t[-maxlen:] length = len(t) pivot = int(length / 2) left = plist(t[:pivot]) right = plist(t[pivot:], reverse=True) return PDeque(left, right, length, maxlen) def dq(*elements): """ Return deque containing all arguments. >>> dq(1, 2, 3) pdeque([1, 2, 3]) """ return pdeque(elements)
12,203
Python
31.371353
115
0.574695
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/pyrsistent/_field_common.py
from pyrsistent._checked_types import ( CheckedPMap, CheckedPSet, CheckedPVector, CheckedType, InvariantException, _restore_pickle, get_type, maybe_parse_user_type, maybe_parse_many_user_types, ) from pyrsistent._checked_types import optional as optional_type from pyrsistent._checked_types import wrap_invariant import inspect def set_fields(dct, bases, name): dct[name] = dict(sum([list(b.__dict__.get(name, {}).items()) for b in bases], [])) for k, v in list(dct.items()): if isinstance(v, _PField): dct[name][k] = v del dct[k] def check_global_invariants(subject, invariants): error_codes = tuple(error_code for is_ok, error_code in (invariant(subject) for invariant in invariants) if not is_ok) if error_codes: raise InvariantException(error_codes, (), 'Global invariant failed') def serialize(serializer, format, value): if isinstance(value, CheckedType) and serializer is PFIELD_NO_SERIALIZER: return value.serialize(format) return serializer(format, value) def check_type(destination_cls, field, name, value): if field.type and not any(isinstance(value, get_type(t)) for t in field.type): actual_type = type(value) message = "Invalid type for field {0}.{1}, was {2}".format(destination_cls.__name__, name, actual_type.__name__) raise PTypeError(destination_cls, name, field.type, actual_type, message) def is_type_cls(type_cls, field_type): if type(field_type) is set: return True types = tuple(field_type) if len(types) == 0: return False return issubclass(get_type(types[0]), type_cls) def is_field_ignore_extra_complaint(type_cls, field, ignore_extra): # ignore_extra param has default False value, for speed purpose no need to propagate False if not ignore_extra: return False if not is_type_cls(type_cls, field.type): return False return 'ignore_extra' in inspect.signature(field.factory).parameters class _PField(object): __slots__ = ('type', 'invariant', 'initial', 'mandatory', '_factory', 'serializer') def __init__(self, type, invariant, initial, mandatory, factory, serializer): self.type = type self.invariant = invariant self.initial = initial self.mandatory = mandatory self._factory = factory self.serializer = serializer @property def factory(self): # If no factory is specified and the type is another CheckedType use the factory method of that CheckedType if self._factory is PFIELD_NO_FACTORY and len(self.type) == 1: typ = get_type(tuple(self.type)[0]) if issubclass(typ, CheckedType): return typ.create return self._factory PFIELD_NO_TYPE = () PFIELD_NO_INVARIANT = lambda _: (True, None) PFIELD_NO_FACTORY = lambda x: x PFIELD_NO_INITIAL = object() PFIELD_NO_SERIALIZER = lambda _, value: value def field(type=PFIELD_NO_TYPE, invariant=PFIELD_NO_INVARIANT, initial=PFIELD_NO_INITIAL, mandatory=False, factory=PFIELD_NO_FACTORY, serializer=PFIELD_NO_SERIALIZER): """ Field specification factory for :py:class:`PRecord`. :param type: a type or iterable with types that are allowed for this field :param invariant: a function specifying an invariant that must hold for the field :param initial: value of field if not specified when instantiating the record :param mandatory: boolean specifying if the field is mandatory or not :param factory: function called when field is set. :param serializer: function that returns a serialized version of the field """ # NB: We have to check this predicate separately from the predicates in # `maybe_parse_user_type` et al. because this one is related to supporting # the argspec for `field`, while those are related to supporting the valid # ways to specify types. # Multiple types must be passed in one of the following containers. Note # that a type that is a subclass of one of these containers, like a # `collections.namedtuple`, will work as expected, since we check # `isinstance` and not `issubclass`. if isinstance(type, (list, set, tuple)): types = set(maybe_parse_many_user_types(type)) else: types = set(maybe_parse_user_type(type)) invariant_function = wrap_invariant(invariant) if invariant != PFIELD_NO_INVARIANT and callable(invariant) else invariant field = _PField(type=types, invariant=invariant_function, initial=initial, mandatory=mandatory, factory=factory, serializer=serializer) _check_field_parameters(field) return field def _check_field_parameters(field): for t in field.type: if not isinstance(t, type) and not isinstance(t, str): raise TypeError('Type parameter expected, not {0}'.format(type(t))) if field.initial is not PFIELD_NO_INITIAL and \ not callable(field.initial) and \ field.type and not any(isinstance(field.initial, t) for t in field.type): raise TypeError('Initial has invalid type {0}'.format(type(field.initial))) if not callable(field.invariant): raise TypeError('Invariant must be callable') if not callable(field.factory): raise TypeError('Factory must be callable') if not callable(field.serializer): raise TypeError('Serializer must be callable') class PTypeError(TypeError): """ Raised when trying to assign a value with a type that doesn't match the declared type. Attributes: source_class -- The class of the record field -- Field name expected_types -- Types allowed for the field actual_type -- The non matching type """ def __init__(self, source_class, field, expected_types, actual_type, *args, **kwargs): super(PTypeError, self).__init__(*args, **kwargs) self.source_class = source_class self.field = field self.expected_types = expected_types self.actual_type = actual_type SEQ_FIELD_TYPE_SUFFIXES = { CheckedPVector: "PVector", CheckedPSet: "PSet", } # Global dictionary to hold auto-generated field types: used for unpickling _seq_field_types = {} def _restore_seq_field_pickle(checked_class, item_type, data): """Unpickling function for auto-generated PVec/PSet field types.""" type_ = _seq_field_types[checked_class, item_type] return _restore_pickle(type_, data) def _types_to_names(types): """Convert a tuple of types to a human-readable string.""" return "".join(get_type(typ).__name__.capitalize() for typ in types) def _make_seq_field_type(checked_class, item_type, item_invariant): """Create a subclass of the given checked class with the given item type.""" type_ = _seq_field_types.get((checked_class, item_type)) if type_ is not None: return type_ class TheType(checked_class): __type__ = item_type __invariant__ = item_invariant def __reduce__(self): return (_restore_seq_field_pickle, (checked_class, item_type, list(self))) suffix = SEQ_FIELD_TYPE_SUFFIXES[checked_class] TheType.__name__ = _types_to_names(TheType._checked_types) + suffix _seq_field_types[checked_class, item_type] = TheType return TheType def _sequence_field(checked_class, item_type, optional, initial, invariant=PFIELD_NO_INVARIANT, item_invariant=PFIELD_NO_INVARIANT): """ Create checked field for either ``PSet`` or ``PVector``. :param checked_class: ``CheckedPSet`` or ``CheckedPVector``. :param item_type: The required type for the items in the set. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory. :return: A ``field`` containing a checked class. """ TheType = _make_seq_field_type(checked_class, item_type, item_invariant) if optional: def factory(argument, _factory_fields=None, ignore_extra=False): if argument is None: return None else: return TheType.create(argument, _factory_fields=_factory_fields, ignore_extra=ignore_extra) else: factory = TheType.create return field(type=optional_type(TheType) if optional else TheType, factory=factory, mandatory=True, invariant=invariant, initial=factory(initial)) def pset_field(item_type, optional=False, initial=(), invariant=PFIELD_NO_INVARIANT, item_invariant=PFIELD_NO_INVARIANT): """ Create checked ``PSet`` field. :param item_type: The required type for the items in the set. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no value is given for the field. :return: A ``field`` containing a ``CheckedPSet`` of the given type. """ return _sequence_field(CheckedPSet, item_type, optional, initial, invariant=invariant, item_invariant=item_invariant) def pvector_field(item_type, optional=False, initial=(), invariant=PFIELD_NO_INVARIANT, item_invariant=PFIELD_NO_INVARIANT): """ Create checked ``PVector`` field. :param item_type: The required type for the items in the vector. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no value is given for the field. :return: A ``field`` containing a ``CheckedPVector`` of the given type. """ return _sequence_field(CheckedPVector, item_type, optional, initial, invariant=invariant, item_invariant=item_invariant) _valid = lambda item: (True, "") # Global dictionary to hold auto-generated field types: used for unpickling _pmap_field_types = {} def _restore_pmap_field_pickle(key_type, value_type, data): """Unpickling function for auto-generated PMap field types.""" type_ = _pmap_field_types[key_type, value_type] return _restore_pickle(type_, data) def _make_pmap_field_type(key_type, value_type): """Create a subclass of CheckedPMap with the given key and value types.""" type_ = _pmap_field_types.get((key_type, value_type)) if type_ is not None: return type_ class TheMap(CheckedPMap): __key_type__ = key_type __value_type__ = value_type def __reduce__(self): return (_restore_pmap_field_pickle, (self.__key_type__, self.__value_type__, dict(self))) TheMap.__name__ = "{0}To{1}PMap".format( _types_to_names(TheMap._checked_key_types), _types_to_names(TheMap._checked_value_types)) _pmap_field_types[key_type, value_type] = TheMap return TheMap def pmap_field(key_type, value_type, optional=False, invariant=PFIELD_NO_INVARIANT): """ Create a checked ``PMap`` field. :param key: The required type for the keys of the map. :param value: The required type for the values of the map. :param optional: If true, ``None`` can be used as a value for this field. :param invariant: Pass-through to ``field``. :return: A ``field`` containing a ``CheckedPMap``. """ TheMap = _make_pmap_field_type(key_type, value_type) if optional: def factory(argument): if argument is None: return None else: return TheMap.create(argument) else: factory = TheMap.create return field(mandatory=True, initial=TheMap(), type=optional_type(TheMap) if optional else TheMap, factory=factory, invariant=invariant)
11,963
Python
34.927928
125
0.65084
omniverse-code/kit/exts/omni.kit.property.usd_clipboard_test/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.1" 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 = "USD Property Clipboard Tests" description="Clipboard tests that relate to usd properties and need to show a window." # 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"] # 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.widget.stage" = {} "omni.kit.context_menu" = {} # Main python module this extension provides, it will be publicly available as "import omni.kit.property.usd". [[python.module]] name = "omni.kit.property.usd_clipboard_test" [[test]] timeout = 1200 args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/file/ignoreUnsavedOnExit=true", "--/persistent/app/stage/dragDropImport='reference'", "--/persistent/app/material/dragDropMaterialPath='absolute'", "--/persistent/app/omniverse/filepicker/options_menu/show_details=false", # "--no-window" - NOTE: using no-window causes exception in MousePressed cast function ] dependencies = [ "omni.hydra.pxr", "omni.usd", "omni.kit.window.content_browser", "omni.kit.window.stage", "omni.kit.property.material", "omni.kit.ui_test", "omni.kit.test_suite.helpers", "omni.kit.window.viewport", ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop "*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available ]
2,643
TOML
31.641975
122
0.710556
omniverse-code/kit/exts/omni.kit.property.usd_clipboard_test/omni/kit/property/usd_clipboard_test/tests/__init__.py
from .test_property_context_menu import *
42
Python
20.49999
41
0.785714
omniverse-code/kit/exts/omni.kit.property.usd_clipboard_test/omni/kit/property/usd_clipboard_test/tests/test_property_context_menu.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import os import sys import unittest import omni.kit.app import omni.kit.window.property.managed_frame from omni.kit.test.async_unittest import AsyncTestCase import omni.usd from omni.kit import ui_test from pxr import Gf from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows ) class PropertyContextMenu(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 64) await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda")) omni.kit.window.property.managed_frame.reset_collapsed_state() omni.kit.window.property.managed_frame.set_collapsed_state("Property/Raw USD Properties", False) # After running each test async def tearDown(self): await wait_stage_loading() omni.kit.window.property.managed_frame.reset_collapsed_state() # @unittest.skipIf(sys.platform.startswith("linux"), "Pyperclip fails on some TeamCity agents") async def test_property_context_menu(self): await ui_test.find("Content").focus() stage_window = ui_test.find("Stage") await stage_window.focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() await wait_stage_loading() # get prim attributes cube_attr = stage.GetPrimAtPath("/World/Cube").GetAttribute('xformOp:translate') cone_attr = stage.GetPrimAtPath("/World/Cone").GetAttribute('xformOp:translate') # verify transforms different self.assertEqual(cube_attr.Get(), Gf.Vec3d(119.899608, -1.138346, -118.761261)) self.assertEqual(cone_attr.Get(), Gf.Vec3d( 0.0, 0.0, 0.0)) # select cube await select_prims(["/World/Cube"]) await ui_test.human_delay() # scroll window to xformOp:translate ui_test.find("Property//Frame/**/Label[*].text=='xformOp:translate'").widget.scroll_here_y(0.5) await ui_test.human_delay() # right click on xformOp:translate await ui_test.find("Property//Frame/**/Label[*].text=='xformOp:translate'").click(right_click=True) await ui_test.human_delay() # context menu copy await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10)) # select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() # scroll window to xformOp:translate ui_test.find("Property//Frame/**/Label[*].text=='xformOp:translate'").widget.scroll_here_y(0.5) await ui_test.human_delay() # right click on xformOp:translate await ui_test.find("Property//Frame/**/Label[*].text=='xformOp:translate'").click(right_click=True) await ui_test.human_delay() # context menu paste await ui_test.select_context_menu("Paste", offset=ui_test.Vec2(10, 10)) # verify transforms same self.assertEqual(cube_attr.Get(), Gf.Vec3d(119.899608, -1.138346, -118.761261)) self.assertEqual(cone_attr.Get(), Gf.Vec3d(119.899608, -1.138346, -118.761261)) async def test_property_context_menu_paste(self): await ui_test.find("Content").focus() stage_window = ui_test.find("Stage") await stage_window.focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() await wait_stage_loading() # select cube await select_prims(["/World/Cube"]) await ui_test.human_delay(10) # scroll window to xformOp:translate ui_test.find("Property//Frame/**/Label[*].text=='xformOp:translate'").widget.scroll_here_y(0.5) await ui_test.human_delay() # verify code on clipbaord is NOT getting executed omni.kit.clipboard.copy("omni.kit.stage_templates.new_stage()") # right click on xformOp:translate await ui_test.find("Property//Frame/**/Label[*].text=='xformOp:translate'").click(right_click=True) await ui_test.human_delay() await ui_test.find("Property//Frame/**/Label[*].text=='xformOp:translate'").click() # if code was executed a new stage will have been created, so verify prims await ui_test.human_delay(250) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] prims.sort() self.assertEqual(prims, ['/World', '/World/Cone', '/World/Cube', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader', '/World/Sphere', '/World/defaultLight'])
5,196
Python
41.950413
341
0.666282
omniverse-code/kit/exts/omni.kit.property.usd_clipboard_test/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.1] - 2022-12-21 ### Added - Stabillity fix ## [1.0.0] - 2022-11-28 ### Added - Test added.
195
Markdown
15.333332
80
0.625641
omniverse-code/kit/exts/omni.kit.property.usd_clipboard_test/docs/README.md
# omni.kit.property.usd_clipboard_test ## Introduction This extension is used purely for holding tests for omni.kit.property.usd, that need to show a real window during automated tests. Mostly this is because the clipboard copy and paste code needs to have an actual window.
278
Markdown
45.499992
220
0.794964
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/setting_menu_container.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["SettingMenuContainer"] from omni.kit.viewport.menubar.core import ( IconMenuDelegate, SliderMenuDelegate, CheckboxMenuDelegate, SettingModel, SettingModelWithDefaultValue, ViewportMenuContainer, FloatArraySettingColorMenuItem, menu_is_tearable, ) from .menu_item.settings_renderer_menu_item import SettingsRendererMenuItem from .menu_item.settings_transform_manipulator import SettingsTransformManipulator from .style import UI_STYLE import carb import carb.settings import omni.ui as ui from omni.ui import color as cl from typing import Any, Dict, List, Union from functools import partial class ViewportSetting: def __init__(self, key: str, default: Any, set_default: bool = True, read_incoming: bool = False): settings = carb.settings.get_settings() if read_incoming: incoming_default = settings.get(key) if incoming_default is not None: default = incoming_default self.key = key self.default = default if set_default: settings.set_default(self.key, self.default) def reset(self, settings): settings.set(self.key, self.default) class SelectionColorSetting(ViewportSetting): OUTLINE = "/persistent/app/viewport/outline/color" INTERSECTION = "/persistent/app/viewport/outline/intersection/color" def __init__(self, default: Any): super().__init__(self.OUTLINE, default, False) self.index = 1020 def reset(self, settings): float_array = settings.get(self.key) float_array = float_array[0 : self.index] + self.default + float_array[self.index + len(self.default) :] carb.settings.get_settings().set(self.OUTLINE, float_array) carb.settings.get_settings().set(self.INTERSECTION, self.default) class VIEWPORT_SETTINGS: NAVIGATION_SPEED = ViewportSetting("/persistent/app/viewport/camMoveVelocity", 5.0) NAVIGATION_SPEED_MULTAMOUNT = ViewportSetting("/persistent/app/viewport/camVelocityScalerMultAmount", 1.1) SHOW_SPEED_ON_START = ViewportSetting("/persistent/app/viewport/camShowSpeedOnStart", True) ADAPTIVE_SPEED = ViewportSetting("/persistent/app/viewport/camVelocityCOINormalization", 0.0) GAMEPAD_CONTROL = ViewportSetting("/persistent/app/omniverse/gamepadCameraControl", True) CAMERA_STOP_ON_UP = ViewportSetting("/persistent/app/viewport/camStopOnMouseUp", True) CAM_UPDATE_CLAMPING = ViewportSetting("/ext/omni.kit.manipulator.camera/clampUpdates", 0.15, read_incoming=True) INERTIA_ENABLED = ViewportSetting("/persistent/app/viewport/camInertiaEnabled", False) INERTIA_ANOUNT = ViewportSetting("/persistent/app/viewport/camInertiaAmount", 0.55) ROTATION_SMOOTH_ENABLED = ViewportSetting("/persistent/app/viewport/camRotSmoothEnabled", True) ROTATION_SMOOTH_SCALE = ViewportSetting("/persistent/app/viewport/camRotSmoothScale", 20.0) ROTATION_SMOOTH_ALWAYS = ViewportSetting("/persistent/app/viewport/camRotSmoothAlways", False) GESTURE_ENABLED = ViewportSetting("/persistent/app/viewport/camGestureEnabled", False) GESTURE_TIME = ViewportSetting("/persistent/app/viewport/camGestureTime", 0.12) GESTURE_RADIUS = ViewportSetting("/persistent/app/viewport/camGestureRadius", 20) SELECTION_LINE_WIDTH = ViewportSetting("/persistent/app/viewport/outline/width", 2) GRID_LINE_WIDTH = ViewportSetting("/persistent/app/viewport/grid/lineWidth", 1) GRID_SCALE = ViewportSetting("/persistent/app/viewport/grid/scale", 100.0) GRID_FADE = ViewportSetting("/persistent/app/viewport/grid/lineFadeOutStartDistance", 10.0) GIZMO_LINE_WIDTH = ViewportSetting("/persistent/app/viewport/gizmo/lineWidth", 1.0) GIZMO_SCALE_ENABLED = ViewportSetting("/persistent/app/viewport/gizmo/constantScaleEnabled", True) GIZMO_SCALE = ViewportSetting("/persistent/app/viewport/gizmo/constantScale", 10.0) GIZMO_GLOBAL_SCALE = ViewportSetting("/persistent/app/viewport/gizmo/scale", 1.0) GIZMO_MIN_FADEOUT = ViewportSetting("/persistent/app/viewport/gizmo/minFadeOut", 1.0) GIZMO_MAX_FADEOUT = ViewportSetting("/persistent/app/viewport/gizmo/maxFadeOut", 50) UI_BACKGROUND_OPACITY = ViewportSetting("/persistent/app/viewport/ui/background/opacity", 1.0) UI_BRIGHTNESS = ViewportSetting("/persistent/app/viewport/ui/brightness", 0.84) OBJECT_CENTRIC = ViewportSetting("/persistent/app/viewport/objectCentricNavigation", 0) DOUBLE_CLICK_COI = ViewportSetting("/persistent/app/viewport/coiDoubleClick", False) BBOX_LINE_COLOR = ViewportSetting("/persistent/app/viewport/boundingBoxes/lineColor", [0.886, 0.447, 0.447]) GRID_LINE_COLOR = ViewportSetting("/persistent/app/viewport/grid/lineColor", [0.3, 0.3, 0.3]) OUTLINE_COLOR = SelectionColorSetting([1.0, 0.6, 0.0, 1.0]) LOOK_SPEED_HORIZ = ViewportSetting("/persistent/exts/omni.kit.manipulator.camera/lookSpeed/0", 180.0) LOOK_SPEED_VERT = ViewportSetting("/persistent/exts/omni.kit.manipulator.camera/lookSpeed/1", 90.0) TUMBLE_SPEED = ViewportSetting("/persistent/exts/omni.kit.manipulator.camera/tumbleSpeed", 360.0) ZOOM_SPEED = ViewportSetting("/persistent/exts/omni.kit.manipulator.camera/moveSpeed/2", 1.0) FLY_IGNORE_VIEW_DIRECTION = ViewportSetting("/persistent/exts/omni.kit.manipulator.camera/flyViewLock", False) class ViewportSettingModel(SettingModelWithDefaultValue): def __init__(self, viewport_setting: ViewportSetting, draggable: bool = False): super().__init__(viewport_setting.key, viewport_setting.default, draggable=draggable) CAM_VELOCITY_MIN = "/persistent/app/viewport/camVelocityMin" CAM_VELOCITY_MAX = "/persistent/app/viewport/camVelocityMax" CAM_VELOCITY_SCALER_MIN = "/persistent/app/viewport/camVelocityScalerMin" CAM_VELOCITY_SCALER_MAX = "/persistent/app/viewport/camVelocityScalerMax" SETTING_UI_BRIGHTNESS_MIN = "/app/viewport/ui/minBrightness" SETTING_UI_BRIGHTNESS_MAX = "/app/viewport/ui/maxBrightness" BRIGHTNESS_VALUE_RANGE_MIN = 0.25 BRIGHTNESS_VALUE_RANGE_MAX = 1.0 OUTLINE_COLOR_INDEX = 1020 class SelectionColorMenuItem(FloatArraySettingColorMenuItem): def __init__(self): setting = VIEWPORT_SETTINGS.OUTLINE_COLOR super().__init__( setting.key, setting.default, name="Selection Color", start_index=setting.index, has_reset=True ) def on_color_changed(self, colors: List[float]) -> None: # Set the default exterior color super().on_color_changed(colors) # Set the interior intersection color too carb.settings.get_settings().set(VIEWPORT_SETTINGS.OUTLINE_COLOR.INTERSECTION, colors) class BoundingColorMenuItem(FloatArraySettingColorMenuItem): def __init__(self): setting = VIEWPORT_SETTINGS.BBOX_LINE_COLOR super().__init__(setting.key, setting.default, name="Bounding Box Color", has_reset=True) class GridColorMenuItem(FloatArraySettingColorMenuItem): def __init__(self): setting = VIEWPORT_SETTINGS.GRID_LINE_COLOR super().__init__(setting.key, setting.default, name="Grid Color", has_reset=True) class MenuContext: def __init__(self): self.__renderer_menu_item: Union[SettingsRendererMenuItem, None] = None self.__settings = carb.settings.get_settings() self.__carb_subscriptions = [] @property def settings(self): return self.__settings @property def renderer_menu_item(self) -> Union[SettingsRendererMenuItem, None]: return self.__renderer_menu_item @renderer_menu_item.setter def renderer_menu_item(self, render_menu_item: Union[SettingsRendererMenuItem, None]) -> None: if self.__renderer_menu_item: self.__renderer_menu_item.destroy() self.__renderer_menu_item = render_menu_item def add_carb_subscription(self, carb_sub: carb.settings.SubscriptionId): self.__carb_subscriptions.append(carb_sub) def destroy(self): self.renderer_menu_item = None for sub in self.__carb_subscriptions: sub.unsubscribe() self.__carb_subscriptions = [] class SettingMenuContainer(ViewportMenuContainer): """The menu with the viewport settings""" def __init__(self): super().__init__( name="Settings", delegate=IconMenuDelegate("Settings"), visible_setting_path="/exts/omni.kit.viewport.menubar.settings/visible", order_setting_path="/exts/omni.kit.viewport.menubar.settings/order", style=UI_STYLE, ) self.__menu_context: Dict[str, MenuContext] = {} settings = carb.settings.get_settings() settings.set_default(CAM_VELOCITY_MIN, 0.01) settings.set_default(CAM_VELOCITY_MAX, 50) settings.set_default(CAM_VELOCITY_SCALER_MIN, 1) settings.set_default(CAM_VELOCITY_SCALER_MAX, 10) def destroy(self): for menu_ctx in self.__menu_context.values(): menu_ctx.destroy() self.__menu_context = {} super().destroy() def build_fn(self, factory: Dict): ui.Menu(self.name, delegate=self._delegate, on_build_fn=partial(self._build_menu, factory), style=self._style) def _build_menu(self, factory: Dict) -> None: viewport_api = factory.get("viewport_api") if not viewport_api: return viewport_api_id = viewport_api.id menu_ctx = self.__menu_context.get(viewport_api_id) if menu_ctx: menu_ctx.destroy() menu_ctx = MenuContext() self.__menu_context[viewport_api_id] = menu_ctx ui.Menu( "Navigation", on_build_fn=lambda: self.__build_navigation_menu_items(menu_ctx), tearable=menu_is_tearable("omni.kit.viewport.menubar.settings.Navigation"), ) ui.Menu( "Selection", on_build_fn=lambda: self.__build_selection_menu_items(menu_ctx), tearable=menu_is_tearable("omni.kit.viewport.menubar.settings.Selection"), ) ui.Menu( "Grid", on_build_fn=lambda: self.__build_grid_menu_items(menu_ctx), tearable=menu_is_tearable("omni.kit.viewport.menubar.settings.Grid"), ) ui.Menu( "Gizmos", on_build_fn=lambda: self.__build_gizmo_menu_items(menu_ctx), tearable=menu_is_tearable("omni.kit.viewport.menubar.settings.Gizmos"), ) menu_ctx.renderer_menu_item = SettingsRendererMenuItem( "Viewport", factory=factory, tearable=menu_is_tearable("omni.kit.viewport.menubar.settings.Viewport") ) ui.Menu( "Viewport UI", on_build_fn=lambda: self.__build_ui_menu_items(menu_ctx), tearable=menu_is_tearable("omni.kit.viewport.menubar.settings.ViewportUI"), ) SettingsTransformManipulator( "Manipulator Transform", factory=factory, tearable=menu_is_tearable("omni.kit.viewport.menubar.settings.ManipulatorTransform"), ) ui.Separator() ui.MenuItem( "Reset To Defaults", hide_on_click=False, triggered_fn=lambda vid=viewport_api_id: self.__reset_settings(vid), ) ui.Separator() ui.MenuItem("Preferences", hide_on_click=False, triggered_fn=self._show_viewport_preference) def __build_navigation_menu_items(self, menu_ctx: MenuContext) -> None: settings = carb.settings.get_settings() ui.MenuItem( "Navigation Speed", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.NAVIGATION_SPEED, draggable=True), min=settings.get(CAM_VELOCITY_MIN), max=settings.get(CAM_VELOCITY_MAX), tooltip="Set the Fly Mode navigation speed", has_reset=True, ), ) ui.MenuItem( "Navigation Speed Scalar", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.NAVIGATION_SPEED_MULTAMOUNT, draggable=True), min=settings.get(CAM_VELOCITY_SCALER_MIN), max=settings.get(CAM_VELOCITY_SCALER_MAX), tooltip="Change the Fly Mode navigation speed by this amount", has_reset=True, ), ) ui.MenuItem( "Lock Navigation Height", hide_on_click=False, delegate=CheckboxMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.FLY_IGNORE_VIEW_DIRECTION), tooltip="Whether forward/backward and up/down movements ignore camera-view direction (similar to left/right strafe)", has_reset=True, ) ) ui.MenuItem( "Gamepad Camera Control", hide_on_click=False, delegate=CheckboxMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.GAMEPAD_CONTROL), tooltip="Enable gamepad navigation for this Viewport", has_reset=True, ), ) ui.Separator() ui.MenuItem( "Object Centric Navigation", hide_on_click=False, delegate=CheckboxMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.OBJECT_CENTRIC), tooltip="Set camera's center of interest to center of object under mouse when camera manipulation begins", has_reset=True, ), ) ui.MenuItem( "Double Click Sets Interest", hide_on_click=False, delegate=CheckboxMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.DOUBLE_CLICK_COI), tooltip="Double click will set the center of interest to the object under mouse." + "\nEnabling this may make click-to-select less responsive.", has_reset=True, ) ) ui.Separator() self.__build_advanced_navigation_items(menu_ctx) ui.Separator() self.__build_navigation_speed_items(menu_ctx) self.__build_debug_settings(menu_ctx) def __build_navigation_speed_items(self, menu_ctx: MenuContext): ui.MenuItem( "Look Speed Horizontal", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.LOOK_SPEED_HORIZ, draggable=True), min=0, max=360, step=1, tooltip="Set the Look Mode navigation speed as degrees rotated over a drag across the Viepwort horizonatally.", has_reset=True, ), ) ui.MenuItem( "Look Speed Vertical", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.LOOK_SPEED_VERT, draggable=True), min=0, max=180, step=1, tooltip="Set the Look Mode navigation speed as degrees rotated over a drag across the Viepwort vertically.", has_reset=True, ), ) ui.MenuItem( "Tumble Speed", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.TUMBLE_SPEED, draggable=True), min=0, max=720, step=1, tooltip="Set the Tumble Mode navigation speed as degrees rotated over a drag across the Viepwort.", has_reset=True, ), ) ui.MenuItem( "Zoom Speed", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.ZOOM_SPEED, draggable=True), min=0, max=2, tooltip="Set the Zoom Mode navigation speed", has_reset=True, ), ) def __build_advanced_navigation_items(self, menu_ctx: MenuContext): settings = menu_ctx.settings inertia_enable_model = ViewportSettingModel(VIEWPORT_SETTINGS.INERTIA_ENABLED) ui.MenuItem( "Inertia Mode", hide_on_click=False, delegate=CheckboxMenuDelegate( model=inertia_enable_model, tooltip="Enable advanced settings to control camera inertia and gestures for mouse manipulation", has_reset=True, ), ) inertia_menu_item = ui.MenuItem( "Camera Inertia", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.INERTIA_ANOUNT, draggable=True), tooltip="Seconds the inertia is active for", min=0.0, max=4.0, has_reset=True, ), ) # Show an entry for enabling disabling inertia on all modes if this value is set inertia_modes = settings.get("/exts/omni.kit.manipulator.camera/inertiaModesEnabled") inertia_modes_menu_item = None if inertia_modes: # Odd setting to control inertai always, but its what View was using, so preserve as it is persistant legacy_all_interia_model = ViewportSettingModel(VIEWPORT_SETTINGS.ROTATION_SMOOTH_ALWAYS) inertia_modes_menu_item = ui.MenuItem( "Inertia For Other Movements", hide_on_click=False, delegate=CheckboxMenuDelegate( model=legacy_all_interia_model, tooltip="Apply inertia to other camera movements or only WASD navigation", has_reset=True, ), ) def _toggle_inertia_always(model: ui.AbstractValueModel): if model.as_bool: # Allow a user specified preference to enable ceratin modes only, otherwise default to all inertia_modes = settings.get("/app/viewport/inertiaModesEnabled") inertia_modes = inertia_modes or [1, 1, 1, 1] else: inertia_modes = [1, 0, 0, 0] settings.set("/exts/omni.kit.manipulator.camera/inertiaModesEnabled", inertia_modes) _toggle_inertia_always(legacy_all_interia_model) menu_ctx.add_carb_subscription( legacy_all_interia_model.subscribe_value_changed_fn(_toggle_inertia_always) ) def __on_inertial_changed(model: ui.AbstractValueModel): inertia_enabled = model.as_bool inertia_menu_item.visible = inertia_enabled if inertia_modes_menu_item: inertia_modes_menu_item.visible = inertia_enabled # Sync the state now __on_inertial_changed(inertia_enable_model) menu_ctx.add_carb_subscription( inertia_enable_model.subscribe_value_changed_fn(__on_inertial_changed) ) def __build_debug_settings(self, menu_ctx: MenuContext): settings = menu_ctx.settings _added_initial_separator = False def add_initial_separator(): nonlocal _added_initial_separator if not _added_initial_separator: _added_initial_separator = True ui.Separator() if settings.get("/exts/omni.kit.viewport.menubar.settings/show/camera/clamping"): add_initial_separator() ui.MenuItem( "Animation clamp", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.CAM_UPDATE_CLAMPING), tooltip="Clamp animation to this maximum number of seconds", min=0.0001, max=1.0, has_reset=True, ), ) def __build_selection_menu_items(self, menu_ctx: MenuContext): SelectionColorMenuItem() ui.MenuItem( "Selection Line Width", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.SELECTION_LINE_WIDTH, draggable=True), min=1, max=15, slider_class=ui.IntSlider, has_reset=True, ), ) BoundingColorMenuItem() def __build_grid_menu_items(self, menu_ctx: MenuContext): GridColorMenuItem() ui.MenuItem( "Grid Line Width", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.GRID_LINE_WIDTH, draggable=True), min=1, max=10, slider_class=ui.IntSlider, has_reset=True, ), ) ui.MenuItem( "Grid Size", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.GRID_SCALE, draggable=True), min=1.0, max=1000.0, has_reset=True, ), ) fadeout_model = ViewportSettingModel(VIEWPORT_SETTINGS.GRID_FADE, draggable=True) def __on_fadeout_changed(model: ui.AbstractValueModel): carb.settings.get_settings().set("/persistent/app/viewport/grid/lineFadeOutEndDistance", model.as_float * 4) ui.MenuItem( "Grid Fade", hide_on_click=False, delegate=SliderMenuDelegate(model=fadeout_model, min=0.5, max=50.0, has_reset=True), ) menu_ctx.add_carb_subscription( fadeout_model.subscribe_value_changed_fn(__on_fadeout_changed) ) def __build_ui_menu_items(self, menu_ctx: MenuContext): def __ui_background_opacity_changed(model: ui.AbstractValueModel) -> None: alpha = int(model.as_float * 255) name = "viewport_menubar_background" color = cl._find(name) color = (color & 0x00FFFFFF) + (alpha << 24) cl._store(name, color) ui_background_opacity_model = ViewportSettingModel(VIEWPORT_SETTINGS.UI_BACKGROUND_OPACITY, draggable=True) ui.MenuItem( "UI Background Opacity", hide_on_click=False, delegate=SliderMenuDelegate(model=ui_background_opacity_model, min=0.0, max=1.0, has_reset=True), ) __ui_background_opacity_changed(ui_background_opacity_model) settings = carb.settings.get_settings() min_brightness = settings.get(SETTING_UI_BRIGHTNESS_MIN) max_brightness = settings.get(SETTING_UI_BRIGHTNESS_MAX) def __ui_brightness_changed(model: ui.AbstractValueModel) -> None: def __gray_to_color(gray: int): return 0xFF000000 + (gray << 16) + (gray << 8) + gray value = (model.as_float - BRIGHTNESS_VALUE_RANGE_MIN) / ( BRIGHTNESS_VALUE_RANGE_MAX - BRIGHTNESS_VALUE_RANGE_MIN ) light_gray = int(value * 255) color = __gray_to_color(light_gray) cl._store("viewport_menubar_light", color) medium_gray = int(light_gray * 0.539) color = __gray_to_color(medium_gray) cl._store("viewport_menubar_medium", color) ui_brightness_model = ViewportSettingModel(VIEWPORT_SETTINGS.UI_BRIGHTNESS, draggable=True) ui.MenuItem( "UI Control Brightness", hide_on_click=False, delegate=SliderMenuDelegate(model=ui_brightness_model, min=min_brightness, max=max_brightness, has_reset=True), ) __ui_brightness_changed(ui_brightness_model) menu_ctx.add_carb_subscription( ui_background_opacity_model.subscribe_value_changed_fn(__ui_background_opacity_changed) ) menu_ctx.add_carb_subscription( ui_brightness_model.subscribe_value_changed_fn(__ui_brightness_changed) ) def __build_gizmo_menu_items(self, menu_ctx: MenuContext): ui.MenuItem( "Gizmo Line Width", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.GIZMO_LINE_WIDTH, draggable=True), min=1.0, max=25.0, has_reset=True, ), ) scale_enabled_model = ViewportSettingModel(VIEWPORT_SETTINGS.GIZMO_SCALE_ENABLED) ui.MenuItem( "Gizmo Constant Scale Enabled", hide_on_click=False, delegate=CheckboxMenuDelegate(model=scale_enabled_model, has_reset=True), ) constant_scale_menu_item = ui.MenuItem( "Gizmo Constant Scale", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.GIZMO_SCALE, draggable=True), min=0.5, max=100.0, has_reset=True, ), ) global_scale_menu_item = ui.MenuItem( "Gizmo Camera Scale" if scale_enabled_model.as_bool else "Gizmo Global Scale", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.GIZMO_GLOBAL_SCALE, draggable=True), min=0.01, max=4.0, has_reset=True, ), ) def __on_gizmo_enabled_changed(model: SettingModel): is_constant_scale = model.as_bool constant_scale_menu_item.visible = is_constant_scale global_scale_menu_item.text = "Gizmo Camera Scale" if is_constant_scale else "Gizmo Global Scale" __on_gizmo_enabled_changed(scale_enabled_model) menu_ctx.add_carb_subscription( scale_enabled_model.subscribe_value_changed_fn(__on_gizmo_enabled_changed) ) ui.MenuItem( "Gizmo Min FadeOut", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.GIZMO_MIN_FADEOUT, draggable=True), min=1.0, max=1000.0, has_reset=True, ), ) ui.MenuItem( "Gizmo Max FadeOut", hide_on_click=False, delegate=SliderMenuDelegate( model=ViewportSettingModel(VIEWPORT_SETTINGS.GIZMO_MAX_FADEOUT, draggable=True), min=1.0, max=1000.0, has_reset=True, ), ) def __reset_settings(self, viewport_api_id: str): settings = carb.settings.get_settings() for value in VIEWPORT_SETTINGS.__dict__.values(): if isinstance(value, ViewportSetting): value.reset(settings) # Only reset renderer settings of current viewport menu_ctx = self.__menu_context.get(viewport_api_id) renderer_menu_item = menu_ctx.renderer_menu_item if menu_ctx else None if renderer_menu_item: renderer_menu_item.reset() def _show_viewport_preference(self) -> None: try: import omni.kit.window.preferences as preferences import asyncio async def focus_async(): pref_window = ui.Workspace.get_window("Preferences") if pref_window: pref_window.focus() PAGE_TITLE = "Viewport" inst = preferences.get_instance() if not inst: carb.log_error("Preferences extension is not loaded yet") return pages = preferences.get_page_list() for page in pages: if page.get_title() == PAGE_TITLE: inst.select_page(page) # Show the Window inst.show_preferences_window() # Force the tab to be the active/focused tab (this currently needs to be done in async) asyncio.ensure_future(focus_async()) return page else: carb.log_error("Viewport Preferences page not found!") except ImportError: carb.log_error("omni.kit.window.preferences not enabled!")
28,966
Python
40.263533
133
0.617483
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/style.py
from omni.ui import color as cl from omni.ui import constant as fl from pathlib import Path CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("icons") UI_STYLE = { "Menu.Item.Icon::Settings": {"image_url": f"{ICON_PATH}/viewport_settings.svg"}, "ResolutionLink": {"background_color": 0, "margin": 0, "padding": 2}, "ResolutionLink.Image": {"image_url": f"{ICON_PATH}/link_dark.svg", "margin": 0}, "ResolutionLink.Image:checked": {"image_url": f"{ICON_PATH}/link.svg"}, "ComboBox::ratio": {"background_color": 0x0, "padding": 4, "margin": 0}, "Menu.Item.Button::save": {"padding": 0, "margin": 0, "background_color": 0}, "Menu.Item.Button.Image::save": {"image_url": f"{ICON_PATH}/save.svg", "color": cl.viewport_menubar_light}, "Menu.Item.Button.Image::save:checked": {"color": cl.shade(cl("#0697cd"))}, "Ratio.Background": {"background_color": 0xFF444444, "border_color": 0xFFA1701B, "border_width": 1}, "Resolution.Text": {"color": cl.input_hint}, "Resolution.Name": {"color": cl.viewport_menubar_light}, "Resolution.Del": {"image_url": f"{ICON_PATH}/delete.svg"}, } cl.save_background = cl.shade(cl("#1F2123")) cl.input_hint = cl.shade(cl('#5A5A5A')) SAVE_WINDOW_STYLE = { "Window": {"secondary_background_color": 0x0}, "Titlebar.Background": {"background_color": cl.save_background}, "Input.Hint": {"color": cl.input_hint}, "Image::close": {"image_url": f"{ICON_PATH}/close.svg"}, "Button": {"background_color": cl.save_background}, }
1,585
Python
45.647057
111
0.65489
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/extension.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportSettingsMenuBarExtension"] from .setting_menu_container import SettingMenuContainer import omni.ext class ViewportSettingsMenuBarExtension(omni.ext.IExt): """The Entry Point for the Viewport Settings in Viewport Menu Bar""" def on_startup(self, ext_id): self._settings_menu = SettingMenuContainer() def on_shutdown(self): self._settings_menu.destroy() self._settings_menu = None
873
Python
35.416665
76
0.761741
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/menu_item/settings_transform_manipulator.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["SettingsTransformManipulator"] from omni.kit.viewport.menubar.core import ( CheckboxMenuDelegate, ComboBoxMenuDelegate, SliderMenuDelegate, SettingComboBoxModel, ComboBoxItem, SettingModelWithDefaultValue, ResetHelper, ) import omni.ui as ui import carb.settings from typing import Any, Dict, Tuple, List, Optional, Union from functools import partial SETTING_SCALE = "/persistent/exts/omni.kit.manipulator.transform/manipulator/scaleMultiplier" SETTING_FREE_ROTATION_ENABLED = "/persistent/exts/omni.kit.manipulator.transform/manipulator/freeRotationEnabled" SETTING_FREE_ROTATION_TYPE = "/persistent/exts/omni.kit.manipulator.transform/manipulator/freeRotationType" SETTING_INTERSECTION_THICKNESS = "/persistent/exts/omni.kit.manipulator.transform/manipulator/intersectionThickness" FREE_ROTATION_TYPE_CLAMPED = "Clamped" FREE_ROTATION_TYPE_CONTINUOUS = "Continuous" MENU_WIDTH = 350 class _ManipulatorRotationTypeModel(SettingComboBoxModel, ResetHelper): def __init__(self): types = [FREE_ROTATION_TYPE_CLAMPED, FREE_ROTATION_TYPE_CONTINUOUS] super().__init__(SETTING_FREE_ROTATION_TYPE, types) def _on_current_item_changed(self, item: ComboBoxItem) -> None: super()._on_current_item_changed(item) self._update_reset_button() def get_default(self): return FREE_ROTATION_TYPE_CLAMPED def get_value(self): settings = carb.settings.get_settings() return settings.get(SETTING_FREE_ROTATION_TYPE) def restore_default(self) -> None: current_index = self.current_index if current_index: current = current_index.as_int items = self.get_item_children(None) # Early exit if the model is already correct if items[current].value == FREE_ROTATION_TYPE_CLAMPED: return # Iterate all items, and select the first match to the real value for index, item in enumerate(items): if item.value == FREE_ROTATION_TYPE_CLAMPED: current_index.set_value(index) return class SettingsTransformManipulator(ui.Menu): """The menu with the transform manipulator settings""" def __init__(self, text: str = "", factory: Dict = {}, **kwargs): settings = carb.settings.get_settings() settings.set_default_float(SETTING_SCALE, 1.4) settings.set_default_bool(SETTING_FREE_ROTATION_ENABLED, True) settings.set_default_string(SETTING_FREE_ROTATION_TYPE, FREE_ROTATION_TYPE_CLAMPED) settings.set_default_float(SETTING_INTERSECTION_THICKNESS, 10.0) super().__init__(text, on_build_fn=partial(self.build_fn, factory), **kwargs) def build_fn(self, factory: Dict): model = SettingModelWithDefaultValue(SETTING_SCALE, 1.4, draggable=True) ui.MenuItem( "Transform Manipulator Scale", hide_on_click=False, delegate=SliderMenuDelegate( model=model, width=MENU_WIDTH, min=0.0, max=25.0, has_reset=True, ), ) model = SettingModelWithDefaultValue(SETTING_FREE_ROTATION_ENABLED, True, draggable=True) ui.MenuItem( "Enable Free Rotation", hide_on_click=False, delegate=CheckboxMenuDelegate( model=model, width=MENU_WIDTH, has_reset=True, ), ) model = _ManipulatorRotationTypeModel() ui.MenuItem( "Free Rotation Type", hide_on_click=False, delegate=ComboBoxMenuDelegate( model=model, width=MENU_WIDTH, has_reset=True, ), ) model = SettingModelWithDefaultValue(SETTING_INTERSECTION_THICKNESS, 10.0, True) ui.MenuItem( "Manipulator Intersection Thickness", hide_on_click=False, delegate=SliderMenuDelegate( model=model, width=MENU_WIDTH, min=1.0, max=50.0, has_reset=True, ), )
4,657
Python
34.830769
116
0.640326
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/menu_item/settings_renderer_menu_item.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["SettingsRendererMenuItem"] from .custom_resolution.custom_resolution_menu_item import CustomResolutionMenuItem from .resolution_collection.model import ComboBoxResolutionModel from .resolution_collection.menu import ResolutionCollectionMenu from omni.kit.viewport.menubar.core import ( ViewportMenuItem, CheckboxMenuDelegate, ComboBoxMenuDelegate, ComboBoxModel, SettingComboBoxModel, ComboBoxItem, ResetHelper, RadioMenuCollection, ) import omni.ui as ui import omni.kit.app import carb from pxr import Sdf from typing import Any, Dict, Tuple, List, Optional, Union from functools import partial SETTING_APERTURE = "/app/hydra/aperture/conform" SETTING_RENDER_SCALE_LIST = "/app/renderer/resolution/multiplierList" def _resolve_viewport_setting(viewport_id: str, setting_name: str, isettings: carb.settings.ISettings, legacy_key: Union[str, None] = None): # Resolve a default Viewport setting from the most specific to the most general # /app/viewport/Viewport/Viewport0/setting => Startup value for this specific Viewport # /app/viewport/defaults/setting => Startup value targetting all Viewports # Next check if a non-persitent viewport-specific default exists via toml / start-up settings dflt_setting_key = f"/app/viewport/{viewport_id}/{setting_name}" pers_setting_key = "/persistent" + dflt_setting_key # 1. Get the persistant per-viewport value that is saved (may be non-existant) cur_value = isettings.get(pers_setting_key) # 2. Get the per-viewport default that the setting should restore to dflt_value = isettings.get(f"/app/viewport/{viewport_id}/{setting_name}") # 3. If there is no per-viewport default, try to restore to a value for all Viewports if dflt_value is None: dflt_value = isettings.get(f"/app/viewport/defaults/{setting_name}") # 4. If still no value to restore to, check for a legacy setting that represnts this if dflt_value is None: if legacy_key: dflt_value = isettings.get(legacy_key) elif setting_name == "resolution": width = isettings.get("/app/renderer/resolution/width") height = isettings.get("/app/renderer/resolution/height") if (width is not None) and (height is not None): # When either width or height is 0 or less, Viewport will be set to use UI size if (width > 0) and (height > 0): dflt_value = (width, height) if dflt_value is None: dflt_value = (0, 0) if cur_value is None: cur_value = dflt_value return ( (pers_setting_key, cur_value), (dflt_setting_key, dflt_value) ) class _ViewportResolutionSetter: """Simple class that forwards resolution menu item changes to the proper underlying object""" def __init__(self, factory_dict: dict, fill_viewport: bool): self.__factory_dict = factory_dict # Set the Viewport's fill_frame to False as we are controlling it fully viewport_api = self.viewport_api if viewport_api and viewport_api.fill_frame: viewport_api.fill_frame = False viewport_widget = self.viewport_widget if viewport_widget: viewport_widget.expand_viewport = fill_viewport @property def viewport_api(self): return self.__factory_dict.get("viewport_api") @property def viewport_widget(self): return self.__factory_dict.get("layer_provider").viewport_widget @property def fill_frame(self) -> bool: return self.viewport_widget.fill_frame @property def fill_viewport(self) -> bool: return self.viewport_widget.expand_viewport @fill_viewport.setter def fill_viewport(self, value: bool): self.viewport_widget.expand_viewport = value def set_resolution(self, resolution) -> None: self.viewport_widget.set_resolution(resolution) @property def full_resolution(self) -> Tuple[float, float]: return self.viewport_widget.full_resolution class _ComboBoxResolutionScaleModel(SettingComboBoxModel, ResetHelper): """The resolution scale model has all the resolution scales and sets the viewport resolution scale""" def __init__(self, viewport_api, resolution_scale_setting, settings): self.__viewport_api = viewport_api # Get the list of available multipliers or a default values = settings.get(SETTING_RENDER_SCALE_LIST) or [2.0, 1.0, 0.666666666666, 0.5, 0.333333333333, 0.25] # Check if the legacy per-app multiplier is set and use that if it is default = resolution_scale_setting[1][1] self.__default = default if default and default > 0 else 1.0 current_value = resolution_scale_setting[0][1] # Push current_value into resolution_scale if not set to it already if (current_value is not None) and (current_value > 0) and (current_value != self.__viewport_api.resolution_scale): self.__viewport_api.resolution_scale = current_value SettingComboBoxModel.__init__( self, # Set the key to set to to the persistent per-viewport key setting_path=resolution_scale_setting[0][0], texts=[str(int(value * 100)) + "%" for value in values], values=values, # This is passed to avoid defaulting the per-viewport persistent key to a value so that changes to the # setting when not adjusted/saved will pick up the new default current_value=self.__viewport_api.resolution_scale, ) ResetHelper.__init__(self) def _on_current_item_changed(self, item: ComboBoxItem) -> None: super()._on_current_item_changed(item) self.__viewport_api.resolution_scale = item.value self._update_reset_button() # for ResetHelper def get_default(self): return self.__default def restore_default(self) -> None: if self.__default is not None: current_index = self.current_index if current_index: current = current_index.as_int items = self.get_item_children(None) # Early exit if the model is already correct if items[current].value == self.__default: return # Iterate all items, and select the first match to the real value for index, item in enumerate(items): if item.value == self.__default: current_index.set_value(index) return def get_value(self): return self.__viewport_api.resolution_scale class _ComboBoxApertureFitModel(ComboBoxModel): """The aperture model""" def __init__(self, viewport_api, settings): self.__viewport_api = viewport_api values = [0, 1, 2, 3, 4] texts = ["Match Vertical", "Match Horizontal", "Fit", "Crop", "Stretch"] current_value = settings.get(SETTING_APERTURE) or 1 super().__init__(texts, values=values, current_value=current_value) def _on_current_item_changed(self, item: ComboBoxItem) -> None: # TODO: Add to Python bindings for UsdContext or HydraTexture # self.__viewport_api.set_aperture_conform_policy(item.value) pass class _FillViewportModel(ui.AbstractValueModel, ResetHelper): def __init__(self, resolution_setter, fill_viewport_settings, isettings: carb.settings.ISettings): self.__resolution_setter = resolution_setter # Get the default value that this item should reset/restore to self.__default = bool(fill_viewport_settings[1][1]) self.__saved_value = self.__default # This is the per-viewport persistent path this item will save to self.__setting_path = fill_viewport_settings[0][0] ui.AbstractValueModel.__init__(self) ResetHelper.__init__(self) self.__sub_model = self.subscribe_value_changed_fn(self.__on_value_changed) self.__sub_setting = isettings.subscribe_to_node_change_events(self.__setting_path, self.__on_setting_changed) def destroy(self): self.__sub_model = None if self.__sub_setting: carb.settings.get_settings().unsubscribe_to_change_events(self.__sub_setting) self.__sub_setting = None def get_value_as_bool(self) -> bool: return self.__resolution_setter.fill_viewport def set_value(self, value: bool, save_restore: bool = False): value = bool(value) if save_restore: if value: value = self.__saved_value else: self.__saved_value = self.get_value_as_bool() if value != self.get_value_as_bool(): self.__resolution_setter.fill_viewport = value self._value_changed() # for ResetHelper def get_default(self): return self.__default def restore_default(self) -> None: self.set_value(self.__default) def get_value(self): return self.get_value_as_bool() def __on_setting_changed(self, *args, **kwargs): if self.__sub_model: self.set_value(carb.settings.get_settings().get(self.__setting_path)) def __on_value_changed(self, model: ui.AbstractValueModel): # Use self.__sub_setting as a signal to process change in carb subscription settings = carb.settings.get_settings() model_sub, self.__sub_model = self.__sub_model, None try: value = model.as_bool if bool(settings.get(self.__setting_path)) != value: settings.set(self.__setting_path, value) self._update_reset_button() finally: # Make sure to put the subscription back self.__sub_model = model_sub class SettingsRendererMenuItem(ui.Menu): """The menu with the viewport settings""" def __init__(self, text: str = "", factory: Dict = {}, **kwargs): self.__resolution_model: Union[ComboBoxResolutionModel, None] = None self.__render_scale_model: Union[_ComboBoxResolutionScaleModel, None] = None self.__fill_viewport_model: Union[_FillViewportModel, None] = None self.__custom_menu_item: Union[CustomResolutionMenuItem, None] = None self.__viewport_api_id: Union[str, None] = None super().__init__(text, on_build_fn=partial(self.build_fn, factory), **kwargs) def build_fn(self, factory: Dict): # Create the model and the delegate here, not in __init__ to make the # objects unique per viewport. viewport_api = factory["viewport_api"] viewport_api_id = viewport_api.id isettings = carb.settings.get_settings() self.__viewport_api_id = viewport_api_id resolution_settings = _resolve_viewport_setting(viewport_api_id, "resolution", isettings) fill_viewport_settings = _resolve_viewport_setting(viewport_api_id, "fillViewport", isettings) resolution_scale_settings = _resolve_viewport_setting(viewport_api_id, "resolutionScale", isettings) resolution_delegate = _ViewportResolutionSetter(factory, fill_viewport_settings[0][1]) self.__resolution_model = ComboBoxResolutionModel(resolution_delegate, resolution_settings, isettings) ResolutionCollectionMenu("Render Resolution", self.__resolution_model) self.__custom_menu_item = CustomResolutionMenuItem(self.__resolution_model, resolution_delegate) self.__custom_menu_item.resolution = resolution_delegate.full_resolution self.__render_scale_model = _ComboBoxResolutionScaleModel(viewport_api, resolution_scale_settings, isettings) ui.MenuItem( "Render Scale", delegate=ComboBoxMenuDelegate(model=self.__render_scale_model, has_reset=True), hide_on_click=False ) # Requires Python bindings to set this through to the renderer # ui.MenuItem( # "Aperture Policy", # delegate=ComboBoxMenuDelegate(model=_ComboBoxApertureFitModel(viewport_api, settings)), # hide_on_click=False, # ) self.__fill_viewport_model = _FillViewportModel(resolution_delegate, fill_viewport_settings, isettings) self.__fill_viewport_item = ui.MenuItem( "Fill Viewport", delegate=CheckboxMenuDelegate(model=self.__fill_viewport_model, width=310, has_reset=True), hide_on_click=False, ) # Watch for an index change to disable / enable 'Fill Viewport' checkbox self.__sub_resolution_index = self.__resolution_model.current_index.subscribe_value_changed_fn( self.__on_resolution_index_changed ) # Viewport can be changed externally, watch for any resolution changes to sync back into our models self.__sub_render_settings = viewport_api.subscribe_to_render_settings_change( self.__on_render_settings_changed ) def __del__(self): self.destroy() def destroy(self): self.__sub_render_settings = None self.__sub_resolution_index = None if self.__resolution_model: self.__resolution_model.destroy() self.__resolution_model = None if self.__render_scale_model: self.__render_scale_model.destroy() self.__render_scale_model = None if self.__fill_viewport_model: self.__fill_viewport_model.destroy() self.__fill_viewport_model = None super().destroy() def reset(self) -> None: # When _default_resolution is None, them fill-frame is default on, off otherwise if self.__fill_viewport_model: self.__fill_viewport_model.restore_default() # Restore resolution scale based on setting if self.__render_scale_model: self.__render_scale_model.restore_default() # Restore resolution scale based on setting if self.__resolution_model: self.__resolution_model.restore_default() def __sync_model(self, combo_model: ComboBoxModel, value: Any, select_first: bool = False): current_index = combo_model.current_index # Special case for forcing "Viewport" selection to be checked if select_first: if current_index.as_int != 0: current_index.set_value(0) return items = combo_model.get_item_children(None) if items and items[current_index.as_int].value != value: # Iterate all items, and select the first match to the real value index_custom = -1 for index, item in enumerate(items): if item.value == value: current_index.set_value(index) return if item.model.as_string == "Custom": index_custom = index if index_custom != -1: current_index.set_value(index_custom) def __on_resolution_index_changed(self, index_model: ui.SimpleIntModel) -> None: # Enable or disable the 'Fill Viewport' option based on whether using Widget size for render resolution # XXX: Changing visibility causes the menu to resize, which isn't great index = index_model.as_int fill_enabled = index != 0 if index_model else False if fill_enabled != self.__fill_viewport_item.delegate.enabled: self.__fill_viewport_model.set_value(fill_enabled, True) self.__fill_viewport_item.delegate.enabled = fill_enabled # When fillViewport is turned off, try to restore to last resolution if not fill_enabled: resolution = carb.settings.get_settings().get(f"/persistent/app/viewport/{self.__viewport_api_id}/resolution") if resolution: self.__sync_model(self.__resolution_model, tuple(resolution)) items = self.__resolution_model.get_item_children(None) if index >= 0 and index < len(items): item = items[index] self.__custom_menu_item.resolution = item.value def __on_render_settings_changed(self, camera_path: Sdf.Path, resolution: Tuple[int, int], viewport_api): full_resolution = viewport_api.full_resolution if self.__custom_menu_item.resolution != full_resolution: # Update the custom_menu_item resolution entry boxes. self.__custom_menu_item.resolution = full_resolution # Sync the resolution to any existing settings (accounting for "Viewport" special case) self.__sync_model(self.__resolution_model, full_resolution, self.__resolution_model.fill_frame) # Sync the resolution scale menu item self.__sync_model(self.__render_scale_model, viewport_api.resolution_scale)
17,346
Python
42.47619
126
0.644414
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/menu_item/resolution_collection/model.py
import asyncio import carb.settings import omni.kit.app from omni.kit.viewport.menubar.core import ComboBoxItem, SettingComboBoxModel, ResetHelper from typing import Tuple, List, Optional SETTING_RESOLUTION_LIST = "/app/renderer/resolution/list" SETTING_CUSTOM_RESOLUTION_LIST = "/persistent/app/renderer/resolution/custom/list" NAME_RESOLUTIONS = { "Icon": (512, 512), "Square": (1024, 1024), "SD": (1280, 960), "HD720P": (1280, 720), "HD1080P": (1920, 1080), "2K": (2048, 1080), "1440P": (2560, 1440), "UHD": (3840, 2160), "Ultra Wide": (3440, 1440), "Super Ultra Wide": (3840, 1440), "5K Wide": (5120, 2880), } class ResolutionComboBoxItem(ComboBoxItem): def __init__(self, resolution: Tuple[int, int], name: Optional[str] = None, custom: bool = False ) -> None: self.resolution = resolution self.name = name if name else self.get_name_from_resolution(resolution) text = f"{resolution[0]}x{resolution[1]}" if self.is_valid_resolution() else self.name self.custom = custom super().__init__(text, resolution if resolution else "") def get_name_from_resolution(self, resolution: Tuple[int, int]) -> str: for name in NAME_RESOLUTIONS: if NAME_RESOLUTIONS[name] == resolution: return name return "" def is_valid_resolution(self): return self.resolution and self.resolution[0] > 0 and self.resolution[1] > 0 class ComboBoxResolutionModel(SettingComboBoxModel, ResetHelper): """The resolution model has all the resolutions and sets the viewport resolution""" def __init__(self, resolution_setter, resolution_setting, settings): # Parse the incoming resolution list via settings self.__resolution_setter = resolution_setter # Set the default restore to value based on the resolved default pref-key self.__default = resolution_setting[1][1] self.__default = tuple(self.__default) if self.__default else (0, 0) self.__custom_items: List[ResolutionComboBoxItem] = [] # XXX: For test-suite which passes None! full_resolution = resolution_setter.full_resolution if resolution_setter else (0, 0) values = None try: sttg_values = settings.get(SETTING_RESOLUTION_LIST) if sttg_values is not None: num_values = len(sttg_values) if num_values > 0 and num_values % 2 == 0: values = [(sttg_values[i*2 + 0], sttg_values[i*2 + 1]) for i in range(int(num_values / 2))] else: raise RuntimeError(f"Resolution list has invalid length of {num_values}") except Exception as e: import traceback carb.log_error(f"{e}") carb.log_error(f"{traceback.format_exc()}") if values is None: values = [(3840, 2160), (2560, 1440), (2048, 1080), (1920, 1080), (1280, 720), (1024, 1024), (512, 512)] SettingComboBoxModel.__init__( self, # Set the key to set to to the persistent per-viewport key setting_path=resolution_setting[0][0], # Filled in below texts=[], values=[], # Set the current value to the resolved persistent per-viewport value # This is passed to avoid defaulting the per-viewport persitent key to a value so that changes to the # setting when not adjusted/saved will pick up the new default current_value=full_resolution, ) ResetHelper.__init__(self) self._items.append(ResolutionComboBoxItem((0, 0), name="Viewport")) for value in values: self._items.append(ResolutionComboBoxItem(value)) # Separator self._items.append(ResolutionComboBoxItem(None)) self._items.append(ResolutionComboBoxItem((-1, -1), "Custom")) # Custom is the last one self.__index_custom = len(self._items) - 1 current = self._get_current_index_by_value(full_resolution) self.current_index.set_value(current) self.__update_setting = omni.kit.app.SettingChangeSubscription(SETTING_CUSTOM_RESOLUTION_LIST, self.__on_custom_change) self.__on_custom_change(None, carb.settings.ChangeEventType.CHANGED) def destroy(self): self.__update_setting = None self.__resolution_setter = None self.__custom_items = [] def _on_current_item_changed(self, item: ResolutionComboBoxItem) -> None: value = item.value if value[0] >= 0 and value[1] >= 0: super()._on_current_item_changed(item) if self.__resolution_setter: self.__resolution_setter.set_resolution(value) self._update_reset_button() def get_item_children(self, item) -> List[ResolutionComboBoxItem]: #return super().get_item_children(item) if item is None: items = [] items.extend(self._items) items.extend(self.__custom_items) return items else: return [] # for ResetHelper def get_default(self): return self.__default def restore_default(self) -> None: if self.__default is None: return current_index = self.current_index if current_index: current = current_index.as_int items = self.get_item_children(None) # Early exit if the model is already correct if items[current].value == self.__default: return # Iterate all items, and select the first match to the real value for index, item in enumerate(items): if item.value == self.__default: current_index.set_value(index) return current_index.set_value(3) def get_value(self) -> Optional[Tuple[int, int]]: if self.__resolution_setter: return self.__resolution_setter.full_resolution return None def is_custom(self, resolution: Tuple[int, int]) -> bool: for custom in self.__custom_items: if custom.value == resolution: return True return False @property def fill_frame(self) -> bool: return self.__resolution_setter.fill_frame if self.__resolution_setter else False def __on_custom_change(self, value, event_type) -> None: async def __refresh_custom(): # It is strange that sometimes it is triggered with not all fields updated. # Update a frame to make sure full information filled await omni.kit.app.get_app().next_update_async() self.__custom_items = [] custom_list = carb.settings.get_settings().get(SETTING_CUSTOM_RESOLUTION_LIST) or [] if custom_list: # Separator self.__custom_items.append(ResolutionComboBoxItem(None)) for custom in custom_list: name = custom.pop("name", "") width = custom.pop("width", -1) height = custom.pop("height", -1) if name and width > 0 and height > 0: self.__custom_items.append(ResolutionComboBoxItem((width, height), name=name, custom=True)) self._item_changed(None) if self.__resolution_setter: current = self._get_current_index_by_value(self.__resolution_setter.full_resolution, default=self.__index_custom) self.current_index.set_value(current) asyncio.ensure_future(__refresh_custom())
7,629
Python
39.157895
129
0.602307
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/menu_item/resolution_collection/menu.py
from .model import ResolutionComboBoxItem, ComboBoxResolutionModel import carb.settings import omni.ui as ui from omni.kit.viewport.menubar.core import RadioMenuCollection, ViewportMenuDelegate, AbstractWidgetMenuDelegate import math from typing import List, Union import weakref SETTING_CUSTOM_RESOLUTION_LIST = "/persistent/app/renderer/resolution/custom/list" DEFAULT_RATIOS = { "16:9": float(16)/9, "1:1": 1, "32:9": float(32)/9, "4:3": float(4)/3, "21:9": float(21)/9, } class ResolutionCollectionDelegate(AbstractWidgetMenuDelegate): def __init__(self, model: ComboBoxResolutionModel): # don't use content_clipping as submenu hovering becomes inconsistent super().__init__(model=model, has_reset=True, content_clipping=False) self.__resolution_label: Union[ui.Label, None] = None index_model = model.get_item_value_model(None, 0) self.__sub_index_change = index_model.subscribe_value_changed_fn( lambda m, this=weakref.proxy(self): this.__on_index_changed(m) ) def destroy(self): self.__sub_index_change = None def build_widget(self, item: ui.MenuHelper): ui.Spacer(width=4) ui.Label(item.text, width=0) ui.Spacer() self.__resolution_label = ui.Label(self.__get_current_resolution(), width=70) def __get_current_resolution(self): index = self._model.get_item_value_model(None, 0).as_int items: List[ResolutionComboBoxItem] = self._model.get_item_children(None) if index >= 0 and index < len(items): return items[index].name else: return "Unknown" def __on_index_changed(self, model: ui.SimpleIntModel) -> None: if self.__resolution_label: self.__resolution_label.text = self.__get_current_resolution() class ResolutionCollectionMenu(RadioMenuCollection): ITEM_HEIGHT = 20 def __init__(self, text: str, model: ComboBoxResolutionModel): super().__init__( text, model, delegate = ResolutionCollectionDelegate(model), ) self.__custom_menu_items = {} def build_menu_item(self, item: ResolutionComboBoxItem) -> ui.MenuItem: if item.resolution is None: return ui.Separator( delegate=ui.MenuDelegate( on_build_item=lambda _: ui.Line( height=0, alignment=ui.Alignment.V_CENTER, style_type_name_override="Menu.Separator" ) ) ) else: menu_item = ui.MenuItem( item.name, delegate = ViewportMenuDelegate(build_custom_widgets=lambda d, m, i=item: self.__build_resolution_menuitem_widgets(i)) ) if item.custom: self.__custom_menu_items[item.name] = menu_item return menu_item def __build_resolution_menuitem_widgets(self, item: ResolutionComboBoxItem): if item.is_valid_resolution(): ui.Spacer() ui.Spacer(width=20) ui.Label(item.model.as_string, width=80, style_type_name_override="Resolution.Text") with ui.HStack(width=60): ratio = float(item.resolution[0]) / item.resolution[1] width = self.ITEM_HEIGHT * ratio with ui.ZStack(width=width): ui.Rectangle(style_type_name_override="Ratio.Background") ui.Label(self.get_ratio_text(ratio), alignment=ui.Alignment.CENTER, style_type_name_override="Ratio.Text") ui.Spacer() if item.custom: with ui.VStack(content_clipping=1, width=0): ui.Image(width=20, style_type_name_override="Resolution.Del", mouse_pressed_fn=lambda x, y, b, f, i=item: self.__delete_resolution(i)) else: ui.Spacer(width=20) def get_ratio_text(self, ratio: float): found = [key for (key, value) in DEFAULT_RATIOS.items() if math.isclose(value, ratio, rel_tol=1e-2)] if found: return found[0] else: return f"{ratio: .2f}:1" def __delete_resolution(self, item: ResolutionComboBoxItem): settings = carb.settings.get_settings() custom_list = settings.get(SETTING_CUSTOM_RESOLUTION_LIST) or [] for custom in custom_list: name = custom["name"] if name == item.name: custom_list.remove(custom) settings.set(SETTING_CUSTOM_RESOLUTION_LIST, custom_list) if item.name in self.__custom_menu_items: self.__custom_menu_items[item.name].visible = False
4,698
Python
38.487395
154
0.603874
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/menu_item/custom_resolution/save_window.py
import omni.ui as ui from typing import Tuple, Callable from ...style import SAVE_WINDOW_STYLE class SaveWindow(ui.Window): """ Window to save custom resolution. """ PADDING = 8 def __init__(self, resolution: Tuple[int, int], on_save_fn: Callable[[str, Tuple[int, int]], bool]): self.name_model = ui.SimpleStringModel() self.__resolution = resolution self.__on_save_fn = on_save_fn flags = ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_MODAL super().__init__(f"###Resoluiton Save", width=400, height=180, flags=flags, auto_resize=False, padding_x=0, padding_y=0) self.frame.set_style(SAVE_WINDOW_STYLE) self.frame.set_build_fn(self.__build_ui) def __del__(self): self.__sub_begin_edit = None self.destroy() def __build_ui(self): with self.frame: with ui.VStack(height=0): self._build_titlebar() ui.Spacer(height=30) self._build_input() ui.Spacer(height=30) self._build_buttons() ui.Spacer(height=15) def _build_titlebar(self): with ui.ZStack(height=0): ui.Rectangle(style_tyle_name_override="Titlebar.Background") with ui.VStack(): ui.Spacer(height=self.PADDING) with ui.HStack(): ui.Spacer(width=self.PADDING) ui.Label("Save Custom Viewport Resolution", width=0, style_type_name_override="Titlebar.Title") ui.Spacer() ui.Image(width=20, height=20, mouse_released_fn=lambda x, y, b, f: self.__on_cancel(), name="close") ui.Spacer(width=self.PADDING) ui.Spacer(height=self.PADDING) def _build_input(self): with ui.HStack(): ui.Spacer() with ui.ZStack(width=160): name_input = ui.StringField(self.name_model) hint_label = ui.Label("Type Name", style_type_name_override="Input.Hint") ui.Spacer(width=20) ui.Label(f"{self.__resolution[0]} x {self.__resolution[1]}") ui.Spacer() name_input.focus_keyboard() def __hide_hint(): hint_label.visible = False self.__sub_begin_edit = self.name_model.subscribe_begin_edit_fn(lambda m: __hide_hint()) def _build_buttons(self): with ui.HStack(): ui.Spacer() ui.Button("Save", width=80, clicked_fn=self.__on_save) ui.Spacer(width=20) ui.Button("Cancel", width=80, clicked_fn=self.__on_cancel) ui.Spacer() def __on_save(self) -> None: if self.__on_save_fn(self.name_model.as_string, self.__resolution): self.visible = False def __on_cancel(self) -> None: self.visible = False
2,934
Python
35.6875
128
0.557941
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/menu_item/custom_resolution/custom_resolution_menu_item.py
import omni.ui as ui from typing import Tuple from .custom_resolution_delegate import CustomResolutionDelegate class CustomResolutionMenuItem(ui.MenuItem): """ Menu item to edit/save custom resolution. """ def __init__(self, res_model, res_setter): self.__delegate = CustomResolutionDelegate(res_model, res_setter) ui.MenuItem( "Custom Resolution", delegate=self.__delegate, hide_on_click=False, ) super().__init__("Custom Resolution") def destroy(self): self.__delegate.destroy() @property def resolution(self) -> Tuple[int, int]: return self.__delegate.resolution @resolution.setter def resolution(self, res: Tuple[int, int]) -> None: self.__delegate.resolution = res
803
Python
26.724137
73
0.633873
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/menu_item/custom_resolution/custom_resolution_delegate.py
from omni.kit.viewport.menubar.core import AbstractWidgetMenuDelegate import omni.ui as ui import omni.kit.app from .save_window import SaveWindow import carb.settings from typing import List, Optional, Callable, Tuple import weakref import math import asyncio SETTING_CUSTOM_RESOLUTION_LIST = "/persistent/app/renderer/resolution/custom/list" SETTING_MIN_RESOLUTION = "/exts/omni.kit.viewport.menubar.settings/min_resolution" class RatioItem(ui.AbstractItem): def __init__(self, text: str, value: float) -> None: super().__init__() self.model = ui.SimpleStringModel(text) self.value = value class RatioModel(ui.AbstractItemModel): """ The model used for ratio combobox """ def __init__(self): super().__init__() # List items self.__default_items = [ RatioItem("16:9", 16.0/9), RatioItem("4:3", 4.0/3), RatioItem("1:1", 1.0) ] self.__custom_item: Optional[RatioItem] = None # Current value self.current_index = ui.SimpleIntModel(-1) self._sub = self.current_index.subscribe_value_changed_fn( lambda _, this=weakref.proxy(self): this.__on_index_changed() ) def destroy(self): self._sub = None self.current_index = None @property def ratio(self) -> float: items = self.get_item_children(None) return items[self.current_index.as_int].value @ratio.setter def ratio(self, value: float) -> None: found = [index for (index, item) in enumerate(self.__default_items) if math.isclose(item.value, value, rel_tol=1e-2)] if found: self.__custom_item = None self.current_index.set_value(found[0]) self._item_changed(None) else: ratio_text = f"{value: .2f}:1" self.__custom_item = RatioItem(ratio_text, value) self.current_index.set_value(0) self._item_changed(None) def subscribe_ratio_changed_fn(self, on_ratio_changed_fn: Callable[[float], None]): def __on_sub_index_changed(this, callback): current_index = this.current_index.as_int items = this.get_item_children(None) callback(items[current_index].value) return self.current_index.subscribe_value_changed_fn( lambda _, this=weakref.proxy(self), callback=on_ratio_changed_fn: __on_sub_index_changed(this, callback) ) def get_item_children(self, item) -> List[RatioItem]: items = [] if self.__custom_item: items.append(self.__custom_item) items.extend(self.__default_items) return items def get_item_value_model(self, item, column_id): if item is None: return self.current_index return item.model def __on_index_changed(self): self._item_changed(None) class CustomResolutionDelegate(AbstractWidgetMenuDelegate): """ Delegate to edit/save custom resoltion. """ def __init__(self, resolution_model, resolution_setter): super().__init__(width=310, has_reset=False) self.__resolution_model = resolution_model self.__resolution_setter = resolution_setter self.__link_button: Optional[ui.Button] = None self.__save_button: Optional[ui.Button] = None self.__save_window: Optional[SaveWindow] = None self.__settings = carb.settings.get_settings() (self.__resolution_min_width, self.__resolution_min_height) = self.__settings.get(SETTING_MIN_RESOLUTION) or [64, 64] self.width_model = ui.SimpleIntModel(1920) self.__sub_width_begin_edit = self.width_model.subscribe_begin_edit_fn(lambda _: self.__on_begin_edit()) self.__sub_width_end_edit = self.width_model.subscribe_end_edit_fn(lambda _: self.__on_width_end_edit()) self.height_model = ui.SimpleIntModel(1080) self.__sub_height_begin_edit = self.height_model.subscribe_begin_edit_fn(lambda _: self.__on_begin_edit()) self.__sub_height_end_edit = self.height_model.subscribe_end_edit_fn(lambda _: self.__on_height_end_edit()) self.ratio_model = RatioModel() self.__sub_ratio_change = None self.__subscribe_ratio_change() def destroy(self): self.__sub_ratio_change = None self.__sub_width_begin_edit = None self.__sub_width_end_edit = None self.__sub_height_begin_edit = None self.__sub_height_end_edit = None @property def resolution(self) -> Tuple[int, int]: return (self.width_model.as_int, self.height_model.as_int) @resolution.setter def resolution(self, res: Tuple[int, int]) -> None: if res[0] == -1 and res[1] == -1: # "Custom" selected self.__update_save_image_state() elif res[0] > 0 and res[1] > 0: if self.width_model.as_int == res[0] and self.height_model.as_int == res[1]: return was_r_subscibed = self.__subscribe_ratio_change(enable=False) self.ratio_model.ratio = res[0] / res[1] self.width_model.set_value(res[0]) self.height_model.set_value(res[1]) self.__subscribe_ratio_change(enable=was_r_subscibed) self.__update_save_image_state() def build_widget(self, item: ui.MenuHelper): with ui.VStack(spacing=0): ui.Spacer(height=0, spacing=4) with ui.HStack(): ui.Spacer(width=8) ui.IntField(self.width_model, width=60, height=20) ui.Spacer(width=10) self.__link_button = ui.Button( width=35, image_height=20, image_width=24, checked=True, clicked_fn=self.__on_link_clicked, style_type_name_override="ResolutionLink", ) ui.Spacer(width=10) ui.IntField(self.height_model, width=60, height=20) ui.Spacer(width=10) ui.ComboBox(self.ratio_model, name="ratio") ui.Spacer(width=10) with ui.VStack(width=0, content_clipping=True): self.__save_button = ui.Button( style_type_name_override="Menu.Item.Button", name="save", width=20, height=20, image_width=20, image_height=20, clicked_fn=self.__save ) ui.Spacer(width=4) with ui.HStack(): ui.Spacer(width=8) ui.Label("Width", alignment=ui.Alignment.LEFT, width=60) ui.Spacer(width=54) ui.Label("Height", alignment=ui.Alignment.LEFT, width=60) ui.Spacer() def __on_width_changed(self, model): width = model.as_int if width < self.__resolution_min_width: self.__post_resolution_warning() model.set_value(self.__resolution_min_width) width = model.as_int if self.__link_button: if self.__link_button.checked: height = int(width/self.ratio_model.ratio) if height < self.__resolution_min_height: # Height is too small, change width to match the min height self.__post_resolution_warning() height = self.__resolution_min_height width = int(height * self.ratio_model.ratio) model.set_value(width) if height != self.height_model.as_int: self.height_model.set_value(height) else: self.ratio_model.ratio = float(width) / self.height_model.as_int self.__set_render_resolution(self.resolution) self.__update_save_image_state() def __on_height_changed(self, model): height = model.as_int if height < self.__resolution_min_height: self.__post_resolution_warning() model.set_value(self.__resolution_min_height) height = model.as_int if self.__link_button: if self.__link_button.checked: width = int(height * self.ratio_model.ratio) if width < self.__resolution_min_width: # Width is too small, change height to match min width self.__post_resolution_warning() width = self.__resolution_min_width height = int(width / self.ratio_model.ratio) model.set_value(height) if width != self.width_model.as_int: self.width_model.set_value(width) else: self.ratio_model.ratio = float(self.width_model.as_int) / height self.__set_render_resolution(self.resolution) self.__update_save_image_state() def __on_ratio_changed(self, ratio: float): height = int(self.width_model.as_int/self.ratio_model.ratio) if height != self.height_model.as_int: self.height_model.set_value(height) self.__set_render_resolution(self.resolution) self.__update_save_image_state() def __on_link_clicked(self): self.__link_button.checked = not self.__link_button.checked def __subscribe_ratio_change(self, enable: bool = True) -> bool: was_subscribed = self.__sub_ratio_change is not None if enable: if not was_subscribed: self.__sub_ratio_change = self.ratio_model.subscribe_ratio_changed_fn(self.__on_ratio_changed) elif was_subscribed: self.__sub_ratio_change = None return was_subscribed def __save(self): if self.__save_button.checked: if self.__save_window: self.__save_window = None self.__save_window = SaveWindow(self.resolution, self.__on_save_resolution) def __update_save_image_state(self): if not self.__save_button: return for item in self.__resolution_model.get_item_children(None): if self.resolution == item.value: self.__save_button.checked = False break else: self.__save_button.checked = True def __on_save_resolution(self, new_name: str, resolution: Tuple[int, int]) -> bool: custom_list = self.__settings.get(SETTING_CUSTOM_RESOLUTION_LIST) or [] for custom in custom_list: name = custom["name"] if name == new_name: carb.log_warn("f{new_name} already exists!") return False custom_list.append( { "name": new_name, "width": resolution[0], "height": resolution[1] } ) self.__settings.set(SETTING_CUSTOM_RESOLUTION_LIST, custom_list) self.__save_button.checked = False return True def __set_render_resolution(self, resolution: Tuple[int, int]): async def __delay_async(res: Tuple[int, int]): # Delay a frame to make sure current changes from UI are saved await omni.kit.app.get_app().next_update_async() self.__resolution_setter.set_resolution(res) asyncio.ensure_future(__delay_async(resolution)) def __on_begin_edit(self): self.__saved_width = self.width_model.as_int self.__saved_height = self.height_model.as_int def __on_width_end_edit(self): if self.width_model.as_int <= 0: self.width_model.set_value(self.__saved_width) self.__on_width_changed(self.width_model) def __on_height_end_edit(self): if self.height_model.as_int <= 0: self.height_model.set_value(self.__saved_height) self.__on_height_changed(self.height_model) def __post_resolution_warning(self): try: import omni.kit.notification_manager as nm nm.post_notification(f"Resolution cannot be lower than {self.__resolution_min_width}x{self.__resolution_min_height}", status=nm.NotificationStatus.WARNING) except ImportError: carb.log_warn(f"Resolution cannot be lower than {self.__resolution_min_width}x{self.__resolution_min_height}")
12,445
Python
38.891026
167
0.57268
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/tests/test_custom_resolution.py
import carb.settings import omni.kit.test from ..menu_item.resolution_collection.model import ComboBoxResolutionModel, ResolutionComboBoxItem SETTING_CUSTOM_RESOLUTION_LIST = "/persistent/app/renderer/resolution/custom/list" class TestCustomResolution(omni.kit.test.AsyncTestCase): async def setUp(self): self.__settings = carb.settings.get_settings() # Useles fake data that needs to go to ComboBoxResolutionModel resolution_setter = None resolution_settings = (("setting", (0,0)), ("setting", (0,0))) self.__model = ComboBoxResolutionModel(None, resolution_settings, self.__settings) super().setUp() async def tearDown(self): self.__settings.set(SETTING_CUSTOM_RESOLUTION_LIST, []) super().tearDown() async def test_custom_resolutions(self): items = self.__model.get_item_children(None) num_items = len(items) self.__settings.set(SETTING_CUSTOM_RESOLUTION_LIST, [{"name": "test", "width": 100, "height": 200}]) for _ in range(2): await omni.kit.app.get_app().next_update_async() items = self.__model.get_item_children(None) self.assertEqual(num_items + 2, len(items)) new_item: ResolutionComboBoxItem = items[-1] self.assertEqual(new_item.name, "test") self.assertEqual(new_item.resolution, (100, 200)) self.assertTrue(new_item.custom) self.__settings.set(SETTING_CUSTOM_RESOLUTION_LIST, []) for _ in range(2): await omni.kit.app.get_app().next_update_async() items = self.__model.get_item_children(None) self.assertEqual(num_items, len(items))
1,666
Python
40.674999
108
0.657263
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/tests/__init__.py
from .test_ui import * from .test_custom_resolution import *
61
Python
19.66666
37
0.754098
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/tests/test_ui.py
import omni.kit.test from re import I from omni.ui.tests.test_base import OmniUiTest import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 import omni.usd import omni.kit.app from omni.kit.test.teamcity import is_running_in_teamcity from pathlib import Path import carb.input import asyncio import unittest import sys CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 600, 600 class TestSettingMenuWindow(OmniUiTest): async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await omni.kit.app.get_app().next_update_async() async def test_navigation(self): await self.__show_subitem("menubar_setting_navigation.png", 86) async def test_selection(self): await self.__show_subitem("menubar_setting_selection.png", 106) async def test_grid(self): await self.__show_subitem("menubar_setting_grid.png", 126) async def test_gizmo(self): await self.__show_subitem("menubar_setting_gizmo.png", 146) @unittest.skipIf( (sys.platform == "linux" and is_running_in_teamcity()), "OM-64377: Delegate for RadioMenuCollection does not work in Linux", ) async def test_viewport(self): await self.__show_subitem("menubar_setting_viewport.png", 166) async def test_viewport_ui(self): await self.__show_subitem("menubar_setting_viewport_ui.png", 186) async def test_viewport_manipulate(self): await self.__show_subitem("menubar_setting_viewport_manipulator.png", 206) async def test_reset_item(self): settings = carb.settings.get_settings() cam_vel = settings.get("/persistent/app/viewport/camMoveVelocity") in_enabled = settings.get("/persistent/app/viewport/camInertiaEnabled") settings.set("/persistent/app/viewport/camMoveVelocity", cam_vel * 2) settings.set("/persistent/app/viewport/camInertiaEnabled", not in_enabled) try: await self.__do_ui_test(ui_test.emulate_mouse_click, 225) self.assertEqual(settings.get("/persistent/app/viewport/camMoveVelocity"), cam_vel) self.assertEqual(settings.get("/persistent/app/viewport/camInertiaEnabled"), in_enabled) finally: settings.set("/persistent/app/viewport/camMoveVelocity", cam_vel) settings.set("/persistent/app/viewport/camInertiaEnabled", in_enabled) async def __show_subitem(self, golden_img_name: str, y: int) -> None: async def gloden_compare(): await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.__do_ui_test(gloden_compare, y) async def __do_ui_test(self, test_operation, y: int, frame_wait: int = 3) -> None: # Enable mouse input app = omni.kit.app.get_app() app_window = omni.appwindow.get_default_app_window() for device in [carb.input.DeviceType.MOUSE]: app_window.set_input_blocking_state(device, None) try: await ui_test.emulate_mouse_move(Vec2(20, 46), human_delay_speed=4) await ui_test.emulate_mouse_click() await ui_test.emulate_mouse_move(Vec2(20, y)) for _ in range(frame_wait): await app.next_update_async() await test_operation() finally: for _ in range(frame_wait): await app.next_update_async() await ui_test.emulate_mouse_move(Vec2(300, 26)) await ui_test.emulate_mouse_click() for _ in range(frame_wait): await app.next_update_async()
3,830
Python
36.930693
106
0.661358
omniverse-code/kit/exts/omni.kit.window.status_bar/config/extension.toml
[package] version = "0.1.5" title = "Status Bar" changelog = "docs/CHANGELOG.md" [dependencies] "omni.usd" = {} "omni.ui" = {} "omni.kit.mainwindow" = { optional=true } [[native.plugin]] path = "bin/*.plugin" recursive = false # That will make tests auto-discoverable by test_runner: [[python.module]] name = "omni.kit.window.status_bar.tests" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.capture", "omni.ui", ]
538
TOML
16.966666
56
0.644981
omniverse-code/kit/exts/omni.kit.window.status_bar/omni/kit/window/status_bar/tests/test_status_bar.py
## Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from omni.ui.tests.test_base import OmniUiTest import carb import asyncio class TestStatusBar(OmniUiTest): # Before running each test async def setUp(self): self.name_progress = carb.events.type_from_string("omni.kit.window.status_bar@progress") self.name_activity = carb.events.type_from_string("omni.kit.window.status_bar@activity") self.message_bus = omni.kit.app.get_app().get_message_bus_event_stream() self.message_bus.push(self.name_activity, payload={"text": ""}) self.message_bus.push(self.name_progress, payload={"progress": "-1"}) # After running each test async def tearDown(self): pass async def test_general(self): await self.create_test_area(256, 64) async def log(): # Delayed log because self.finalize_test logs things carb.log_warn("StatusBar test") asyncio.ensure_future(log()) await self.finalize_test() async def test_activity(self): await self.create_test_area(512, 64) async def log(): # Delayed log because self.finalize_test logs things carb.log_warn("StatusBar test") # Test activity name with spaces URL-encoded self.message_bus.push(self.name_activity, payload={"text": "MFC%20For%20NvidiaAnimated.usd"}) self.message_bus.push(self.name_progress, payload={"progress": "0.2"}) asyncio.ensure_future(log()) await self.finalize_test()
1,941
Python
36.346153
101
0.686244
omniverse-code/kit/exts/omni.kit.primitive.mesh/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.8" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] category = "Internal" # The title and description fields are primarly for displaying extension info in UI title = "Kit Mesh Primitives Generator" description="Generators for basic mesh geometry." # Keywords for the extension keywords = ["kit", "mesh primitive"] # URL of the extension source repository. repository = "" # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" [dependencies] "omni.kit.commands" = {} "omni.usd" = {} "omni.ui" = {optional = true} "omni.kit.menu.utils" = {optional = true} "omni.kit.usd.layers" = {} "omni.kit.actions.core" = {} [[python.module]] name = "omni.kit.primitive.mesh" [[test]] timeout=300 args = [ "--/app/file/ignoreUnsavedOnExit=true", "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.hydra.pxr", "omni.kit.commands", "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.test", "omni.ui", "omni.kit.menu.utils" ]
1,473
TOML
24.413793
93
0.691785
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/extension.py
__all__ = ["PrimitiveMeshExtension"] import omni from .mesh_actions import register_actions, deregister_actions from pxr import Usd class PrimitiveMeshExtension(omni.ext.IExt): def __init__(self): super().__init__() def on_startup(self, ext_id): self._ext_name = omni.ext.get_extension_name(ext_id) self._mesh_generator = None try: from .generator import MeshGenerator self._mesh_generator = MeshGenerator() self._mesh_generator.register_menu() except ImportError: pass register_actions(self._ext_name, PrimitiveMeshExtension, lambda: self._mesh_generator) def on_shutdown(self): deregister_actions(self._ext_name) if self._mesh_generator: self._mesh_generator.destroy()
814
Python
27.103447
94
0.635135
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/__init__.py
from .evaluators import get_geometry_mesh_prim_list, AbstractShapeEvaluator from .command import CreateMeshPrimCommand, CreateMeshPrimWithDefaultXformCommand from .extension import PrimitiveMeshExtension
204
Python
50.249987
81
0.887255
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/mesh_actions.py
import omni.usd import omni.kit.commands import omni.kit.actions.core from .evaluators import get_geometry_mesh_prim_list def register_actions(extension_id, cls, get_self_fn): def create_mesh_prim(prim_type): usd_context = omni.usd.get_context() with omni.kit.usd.layers.active_authoring_layer_context(usd_context): omni.kit.commands.execute("CreateMeshPrimWithDefaultXform", prim_type=prim_type, above_ground=True) # actions for prim in get_geometry_mesh_prim_list(): omni.kit.actions.core.get_action_registry().register_action( extension_id, f"create_mesh_prim_{prim.lower()}", lambda p=prim: create_mesh_prim(p), display_name=f"Create Mesh Prim {prim}", description=f"Create Mesh Prim {prim}", tag="Create Mesh Prim", ) if get_self_fn() is not None: omni.kit.actions.core.get_action_registry().register_action( extension_id, "show_setting_window", get_self_fn().show_setting_window, display_name="Show Settings Window", description="Show Settings Window", tag="Show Settings Window", ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
1,391
Python
34.692307
111
0.646298
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/generator.py
import carb.settings import omni import omni.kit from omni import ui from .evaluators import _get_all_evaluators, get_geometry_mesh_prim_list from omni.kit.menu.utils import MenuItemDescription, remove_menu_items, add_menu_items class MeshGenerator: def __init__(self): self._settings = carb.settings.get_settings() self._window = None self._mesh_setting_ui = {} self._current_setting_index = 0 self._mesh_menu_list = [] def destroy(self): self._window = None remove_menu_items(self._mesh_menu_list, "Create") def register_menu(self): sub_menu = [] for prim in get_geometry_mesh_prim_list(): sub_menu.append(MenuItemDescription(name=prim, onclick_action=("omni.kit.primitive.mesh", f"create_mesh_prim_{prim.lower()}"))) sub_menu.append(MenuItemDescription()) sub_menu.append(MenuItemDescription(name="Settings", onclick_action=("omni.kit.primitive.mesh", "show_setting_window"))) self._mesh_menu_list = [ MenuItemDescription(name="Mesh", glyph="menu_prim.svg", sub_menu=sub_menu) ] add_menu_items(self._mesh_menu_list, "Create") def on_primitive_type_selected(self, model, item): names = get_geometry_mesh_prim_list() old_mesh_name = names[self._current_setting_index] if old_mesh_name in self._mesh_setting_ui: self._mesh_setting_ui[old_mesh_name].visible = False idx = model.get_item_value_model().as_int mesh_name = names[idx] if mesh_name in self._mesh_setting_ui: self._mesh_setting_ui[old_mesh_name].visible = False self._mesh_setting_ui[mesh_name].visible = True self._current_setting_index = idx def show_setting_window(self): flags = ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR if not self._window: self._window = ui.Window( "Mesh Generation Settings", ui.DockPreference.DISABLED, width=400, height=260, flags=flags, padding_x=0, padding_y=0, ) with self._window.frame: with ui.VStack(height=0): ui.Spacer(width=0, height=20) with ui.HStack(height=0): ui.Spacer(width=20, height=0) ui.Label("Primitive Type", name="text", height=0) model = ui.ComboBox(0, *get_geometry_mesh_prim_list(), name="primitive_type").model model.add_item_changed_fn(self.on_primitive_type_selected) ui.Spacer(width=20, height=0) ui.Spacer(width=0, height=10) ui.Separator(height=0, name="text") ui.Spacer(width=0, height=10) with ui.ZStack(height=0): mesh_names = get_geometry_mesh_prim_list() for i in range(len(mesh_names)): mesh_name = mesh_names[i] stack = ui.VStack(spacing=0) self._mesh_setting_ui[mesh_name] = stack with stack: ui.Spacer(height=20) evaluator_class = _get_all_evaluators()[mesh_name] evaluator_class.build_setting_ui() ui.Spacer(height=5) if i != 0: stack.visible = False ui.Spacer(width=0, height=20) with ui.HStack(height=0): ui.Spacer() ui.Button( "Create", alignment=ui.Alignment.H_CENTER, name="create", width=120, height=0, mouse_pressed_fn=lambda *args: self._create_shape(), ) ui.Button( "Reset Settings", alignment=ui.Alignment.H_CENTER, name="reset", width=120, height=0, mouse_pressed_fn=lambda *args: self._reset_settings(), ) ui.Spacer() self._current_setting_index = 0 self._window.visible = True def _create_shape(self): names = get_geometry_mesh_prim_list() mesh_type = names[self._current_setting_index] usd_context = omni.usd.get_context() with omni.kit.usd.layers.active_authoring_layer_context(usd_context): omni.kit.commands.execute("CreateMeshPrimWithDefaultXform", prim_type=mesh_type, above_ground=True) def _reset_settings(self): names = get_geometry_mesh_prim_list() mesh_type = names[self._current_setting_index] evaluator_class = _get_all_evaluators()[mesh_type] evaluator_class.reset_setting()
5,205
Python
39.992126
139
0.510086
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/command.py
__all__ = ["CreateMeshPrimWithDefaultXformCommand", "CreateMeshPrimCommand"] import omni import carb.settings from pxr import UsdGeom, Usd, Vt, Kind, Sdf, Gf from .evaluators import _get_all_evaluators PERSISTENT_SETTINGS_PREFIX = "/persistent" class CreateMeshPrimWithDefaultXformCommand(omni.kit.commands.Command): def __init__(self, prim_type: str, **kwargs): """ Creates primitive. Args: prim_type (str): It supports Plane/Sphere/Cone/Cylinder/Disk/Torus/Cube. kwargs: object_origin (Gf.Vec3f): Position of mesh center in stage units. u_patches (int): The number of patches to tessellate U direction. v_patches (int): The number of patches to tessellate V direction. w_patches (int): The number of patches to tessellate W direction. It only works for Cone/Cylinder/Cube. half_scale (float): Half size of mesh in centimeters. Default is None, which means it's controlled by settings. u_verts_scale (int): Tessellation Level of U. It's a multiplier of u_patches. v_verts_scale (int): Tessellation Level of V. It's a multiplier of v_patches. w_verts_scale (int): Tessellation Level of W. It's a multiplier of w_patches. It only works for Cone/Cylinder/Cube. For Cone/Cylinder, it's to tessellate the caps. For Cube, it's to tessellate along z-axis. above_ground (bool): It will offset the center of mesh above the ground plane if it's True, False otherwise. It's False by default. This param only works when param object_origin is not given. Otherwise, it will be ignored. """ self._prim_type = prim_type[0:1].upper() + prim_type[1:].lower() self._usd_context = omni.usd.get_context(kwargs.get("context_name", "")) self._selection = self._usd_context.get_selection() self._stage = self._usd_context.get_stage() self._settings = carb.settings.get_settings() self._default_path = kwargs.get("prim_path", None) self._select_new_prim = kwargs.get("select_new_prim", True) self._prepend_default_prim = kwargs.get("prepend_default_prim", True) self._above_round = kwargs.get("above_ground", False) self._attributes = {**kwargs} # Supported mesh types should have an associated evaluator class self._evaluator_class = _get_all_evaluators()[prim_type] assert isinstance(self._evaluator_class, type) def do(self): self._prim_path = None if self._default_path: path = omni.usd.get_stage_next_free_path(self._stage, self._default_path, self._prepend_default_prim) else: path = omni.usd.get_stage_next_free_path(self._stage, "/" + self._prim_type, self._prepend_default_prim) mesh = UsdGeom.Mesh.Define(self._stage, path) prim = mesh.GetPrim() defaultXformOpType = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType") defaultRotationOrder = self._settings.get( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder" ) defaultXformOpOrder = self._settings.get( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder" ) defaultXformPrecision = self._settings.get( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision" ) vec3_type = Sdf.ValueTypeNames.Double3 if defaultXformPrecision == "Double" else Sdf.ValueTypeNames.Float3 quat_type = Sdf.ValueTypeNames.Quatd if defaultXformPrecision == "Double" else Sdf.ValueTypeNames.Quatf up_axis = UsdGeom.GetStageUpAxis(self._stage) self._attributes["up_axis"] = up_axis half_scale = self._attributes.get("half_scale", None) if half_scale is None or half_scale <= 0.0: half_scale = self._evaluator_class.get_default_half_scale() object_origin = self._attributes.get("object_origin", None) if object_origin is None and self._above_round: # To move the mesh above the ground. if self._prim_type != "Disk" and self._prim_type != "Plane": if self._prim_type != "Torus": offset = half_scale else: # The tube of torus is half of the half_scale. offset = half_scale / 2.0 # Scale it to make sure it matches stage units. units = UsdGeom.GetStageMetersPerUnit(mesh.GetPrim().GetStage()) if Gf.IsClose(units, 0.0, 1e-6): units = 0.01 scale = 0.01 / units offset = offset * scale if up_axis == "Y": object_origin = Gf.Vec3f(0.0, offset, 0.0) else: object_origin = Gf.Vec3f(0.0, 0.0, offset) else: object_origin = Gf.Vec3f(0.0) elif isinstance(object_origin, list): object_origin = Gf.Vec3f(*object_origin) else: object_origin = Gf.Vec3f(0.0) default_translate = Gf.Vec3d(object_origin) if defaultXformPrecision == "Double" else object_origin default_euler = Gf.Vec3d(0.0, 0.0, 0.0) if defaultXformPrecision == "Double" else Gf.Vec3f(0.0, 0.0, 0.0) default_scale = Gf.Vec3d(1.0, 1.0, 1.0) if defaultXformPrecision == "Double" else Gf.Vec3f(1.0, 1.0, 1.0) default_orient = ( Gf.Quatd(1.0, Gf.Vec3d(0.0, 0.0, 0.0)) if defaultXformPrecision == "Double" else Gf.Quatf(1.0, Gf.Vec3f(0.0, 0.0, 0.0)) ) mat4_type = Sdf.ValueTypeNames.Matrix4d # there is no Matrix4f in SdfValueTypeNames if defaultXformOpType == "Scale, Rotate, Translate": attr_translate = prim.CreateAttribute("xformOp:translate", vec3_type, False) attr_translate.Set(default_translate) attr_rotate_name = "xformOp:rotate" + defaultRotationOrder attr_rotate = prim.CreateAttribute(attr_rotate_name, vec3_type, False) attr_rotate.Set(default_euler) attr_scale = prim.CreateAttribute("xformOp:scale", vec3_type, False) attr_scale.Set(default_scale) attr_order = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.TokenArray, False) attr_order.Set(["xformOp:translate", attr_rotate_name, "xformOp:scale"]) if defaultXformOpType == "Scale, Orient, Translate": attr_translate = prim.CreateAttribute("xformOp:translate", vec3_type, False) attr_translate.Set(default_translate) attr_rotate = prim.CreateAttribute("xformOp:orient", quat_type, False) attr_rotate.Set(default_orient) attr_scale = prim.CreateAttribute("xformOp:scale", vec3_type, False) attr_scale.Set(default_scale) attr_order = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.TokenArray, False) attr_order.Set(["xformOp:translate", "xformOp:orient", "xformOp:scale"]) if defaultXformOpType == "Transform": attr_matrix = prim.CreateAttribute("xformOp:transform", mat4_type, False) attr_matrix.Set(Gf.Matrix4d(1.0)) attr_order = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.TokenArray, False) attr_order.Set(["xformOp:transform"]) self._prim_path = path if self._select_new_prim: self._selection.set_prim_path_selected(path, True, False, True, True) self._define_mesh(mesh) return self._prim_path def undo(self): if self._prim_path: self._stage.RemovePrim(self._prim_path) def _define_mesh(self, mesh): evaluator = self._evaluator_class(self._attributes) points = [] normals = [] sts = [] point_indices = [] face_vertex_counts = [] points, normals, sts, point_indices, face_vertex_counts = evaluator.eval(**self._attributes) units = UsdGeom.GetStageMetersPerUnit(mesh.GetPrim().GetStage()) if Gf.IsClose(units, 0.0, 1e-6): units = 0.01 # Scale points to make sure it's already in centimeters scale = 0.01 / units points = [point * scale for point in points] mesh.GetPointsAttr().Set(Vt.Vec3fArray(points)) mesh.GetNormalsAttr().Set(Vt.Vec3fArray(normals)) mesh.GetFaceVertexIndicesAttr().Set(point_indices) mesh.GetFaceVertexCountsAttr().Set(face_vertex_counts) mesh.SetNormalsInterpolation("faceVarying") prim = mesh.GetPrim() # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 sts_primvar = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray) sts_primvar.SetInterpolation("faceVarying") sts_primvar.Set(Vt.Vec2fArray(sts)) mesh.CreateSubdivisionSchemeAttr("none") attr = prim.GetAttribute(UsdGeom.Tokens.extent) if attr: bounds = UsdGeom.Boundable.ComputeExtentFromPlugins(UsdGeom.Boundable(prim), Usd.TimeCode.Default()) if bounds: attr.Set(bounds) # set the new prim as the active selection if self._select_new_prim: self._selection.set_selected_prim_paths([prim.GetPath().pathString], False) # For back compatibility. class CreateMeshPrimCommand(CreateMeshPrimWithDefaultXformCommand): def __init__(self, prim_type: str, **kwargs): super().__init__(prim_type, **kwargs) omni.kit.commands.register(CreateMeshPrimCommand) omni.kit.commands.register(CreateMeshPrimWithDefaultXformCommand)
9,980
Python
44.995391
123
0.62505
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/cone.py
import math from .utils import ( get_int_setting, build_int_slider, modify_winding_order, transform_point, inverse_u, inverse_v, generate_disk ) from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf from typing import List, Tuple class ConeEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/cone/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/cone/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/cone/v_scale" SETTING_W_SCALE = "/persistent/app/mesh_generator/shapes/cone/w_scale" def __init__(self, attributes: dict): super().__init__(attributes) self.radius = 1.0 self.height = 2.0 # The sequence must be kept in the same as generate_circle_points # in the u direction to share points with the cap. def _eval(self, up_axis, u, v) -> Tuple[Gf.Vec3f, Gf.Vec3f]: theta = u * 2.0 * math.pi x = (1 - v) * math.cos(theta) h = v * self.height - 1 if up_axis == "Y": z = (1 - v) * math.sin(theta) point = Gf.Vec3f(x, h, z) dpdu = Gf.Vec3f(-2.0 * math.pi * z, 0.0, 2.0 * math.pi * x) dpdv = Gf.Vec3f(-x / (1 - v), self.height, -z / (1 - v)) normal = dpdv ^ dpdu normal = normal.GetNormalized() else: y = (1 - v) * math.sin(theta) point = Gf.Vec3f(x, y, h) dpdu = Gf.Vec3f(-2.0 * math.pi * y, 2.0 * math.pi * x, 0) dpdv = Gf.Vec3f(-x / (1 - v), -y / (1 - v), self.height) normal = dpdu ^ dpdv normal = normal.GetNormalized() return point, normal def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(ConeEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(ConeEvaluator.SETTING_V_SCALE, 3) num_w_verts_scale = kwargs.get("w_verts_scale", None) if num_w_verts_scale is None or num_w_verts_scale <= 0: num_w_verts_scale = get_int_setting(ConeEvaluator.SETTING_W_SCALE, 1) num_u_verts_scale = max(num_u_verts_scale, 1) num_v_verts_scale = max(num_v_verts_scale, 1) num_w_verts_scale = max(num_w_verts_scale, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) u_patches = kwargs.get("u_patches", 64) v_patches = kwargs.get("v_patches", 1) w_patches = kwargs.get("w_patches", 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale w_patches = w_patches * num_w_verts_scale u_patches = max(int(u_patches), 3) v_patches = max(int(v_patches), 1) w_patches = max(int(w_patches), 1) accuracy = 0.00001 u_delta = 1.0 / u_patches v_delta = (1.0 - accuracy) / v_patches num_u_verts = u_patches num_v_verts = v_patches + 1 points: List[Gf.Vec3f] = [] point_normals: List[Gf.Vec3f] = [] normals: List[Gf.Vec3f] = [] sts: List[Gf.Vec2f] = [] face_indices: List[int] = [] face_vertex_counts: List[int] = [] for j in range(num_v_verts): for i in range(num_u_verts): u = i * u_delta v = j * v_delta point, normal = self._eval(up_axis, u, v) point = transform_point(point, origin, half_scale) points.append(point) point_normals.append(normal) def calc_index(i, j): i = i if i < num_u_verts else 0 base_index = j * num_u_verts point_index = base_index + i return point_index def get_uv(i, j): u = 1 - i * u_delta if i < num_u_verts else 0.0 v = j * v_delta if j != num_v_verts - 1 else 1.0 return Gf.Vec2f(u, v) for j in range(v_patches): for i in range(u_patches): vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) uv00 = get_uv(i, j) uv10 = get_uv(i + 1, j) uv11 = get_uv(i + 1, j + 1) uv01 = get_uv(i, j + 1) # Right-hand order if up_axis == "Y": sts.extend([uv00, uv01, uv11, uv10]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normals.extend( [ point_normals[vindex00], point_normals[vindex01], point_normals[vindex11], point_normals[vindex10], ] ) else: sts.extend([inverse_u(uv00), inverse_u(uv10), inverse_u(uv11), inverse_u(uv01)]) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) normals.extend( [ point_normals[vindex00], point_normals[vindex10], point_normals[vindex11], point_normals[vindex01], ] ) face_vertex_counts.append(4) # Add hat if up_axis == "Y": bottom_center_point = Gf.Vec3f(0, -1, 0) top_center_point = Gf.Vec3f(0, 1 - accuracy, 0) else: bottom_center_point = Gf.Vec3f(0, 0, -1) top_center_point = Gf.Vec3f(0, 0, 1 - accuracy) def add_hat(center_point, rim_points_start_index, w_patches, invert_wind_order=False): bt_points, _, bt_sts, bt_face_indices, bt_face_vertex_counts = generate_disk( center_point, u_patches, w_patches, origin, half_scale, up_axis ) # Total points before adding hat total_points = len(points) # Skips shared points points.extend(bt_points[num_u_verts:]) if invert_wind_order: modify_winding_order(bt_face_vertex_counts, bt_sts) for st in bt_sts: sts.append(inverse_v(st)) else: sts.extend(bt_sts) face_vertex_counts.extend(bt_face_vertex_counts) normals.extend([center_point] * len(bt_face_indices)) # Remapping cap points for i, index in enumerate(bt_face_indices): if index >= num_u_verts: bt_face_indices[i] += total_points - num_u_verts else: bt_face_indices[i] += rim_points_start_index if invert_wind_order: modify_winding_order(bt_face_vertex_counts, bt_face_indices) face_indices.extend(bt_face_indices) # Add top hat to close shape top_hat_start_index = len(points) - num_u_verts add_hat(top_center_point, top_hat_start_index, 1) # Add bottom hat to close shape add_hat(bottom_center_point, 0, w_patches, True) return points, normals, sts, face_indices, face_vertex_counts @staticmethod def build_setting_ui(): from omni import ui ConeEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", ConeEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) ConeEvaluator._u_scale_slider = build_int_slider( "U Verts Scale", ConeEvaluator.SETTING_U_SCALE, 1, 1, 10, "Tessellation Level in Horizontal Direction" ) ui.Spacer(height=5) ConeEvaluator._v_scale_slider = build_int_slider( "V Verts Scale", ConeEvaluator.SETTING_V_SCALE, 1, 1, 10, "Tessellation Level in Vertical Direction" ) ui.Spacer(height=5) ConeEvaluator._w_scale_slider = build_int_slider( "W Verts Scale", ConeEvaluator.SETTING_W_SCALE, 1, 1, 10, "Tessellation Level of Bottom Cap" ) @staticmethod def reset_setting(): ConeEvaluator._half_scale_slider.set_value(ConeEvaluator.get_default_half_scale()) ConeEvaluator._u_scale_slider.set_value(1) ConeEvaluator._v_scale_slider.set_value(1) ConeEvaluator._w_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(ConeEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
9,127
Python
38.008547
112
0.5315
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/__init__.py
__all__ = ["get_geometry_mesh_prim_list", "AbstractShapeEvaluator"] import re from .abstract_shape_evaluator import AbstractShapeEvaluator from .cone import ConeEvaluator from .disk import DiskEvaluator from .cube import CubeEvaluator from .cylinder import CylinderEvaluator from .sphere import SphereEvaluator from .torus import TorusEvaluator from .plane import PlaneEvaluator _all_evaluators = {} def _get_all_evaluators(): global _all_evaluators if not _all_evaluators: evaluator_classes = list(filter(lambda x: re.search(r".+Evaluator$", x), globals().keys())) evaluator_classes.remove(AbstractShapeEvaluator.__name__) for evaluator in evaluator_classes: name = re.sub(r"(.*)Evaluator$", r"\1", evaluator) _all_evaluators[name] = globals()[f"{name}Evaluator"] return _all_evaluators def get_geometry_mesh_prim_list(): names = list(_get_all_evaluators().keys()) names.sort() return names
973
Python
27.647058
99
0.706064
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/abstract_shape_evaluator.py
from typing import List, Tuple from pxr import Gf class AbstractShapeEvaluator: # pragma: no cover def __init__(self, attributes: dict): self._attributes = attributes def eval(self, **kwargs) -> Tuple[ List[Gf.Vec3f], List[Gf.Vec3f], List[Gf.Vec2f], List[int], List[int] ]: """It must be implemented to return tuple [points, normals, uvs, face_indices, face_vertex_counts], where: * points and normals are array of Gf.Vec3f. * uvs are array of Gf.Vec2f that represents uv coordinates. * face_indexes are array of int that represents face indices. * face_vertex_counts are array of int that represents vertex count per face. * Normals and uvs must be face varying. """ raise NotImplementedError("Eval must be implemented for this shape.") @staticmethod def build_setting_ui(): pass @staticmethod def reset_setting(): pass @staticmethod def get_default_half_scale(): return 50
1,039
Python
28.714285
84
0.636189
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/utils.py
import math import carb.settings from pxr import Gf from typing import List, Tuple from numbers import Number def _save_settings(model, setting): value = model.get_value_as_int() carb.settings.get_settings().set(setting, value) def build_int_slider(name, setting, default_value, min_value, max_value, tooltip=None): from omni import ui layout = ui.HStack(height=0) with layout: ui.Spacer(width=20, height=0) ui.Label(name, height=0, name="text") model = ui.IntSlider(name="text", min=min_value, max=max_value, height=0, aligment=ui.Alignment.LEFT).model value = get_int_setting(setting, default_value) model.set_value(value) ui.Spacer(width=20, height=0) model.add_value_changed_fn(lambda m: _save_settings(m, setting)) if tooltip: layout.set_tooltip(tooltip) return model def inverse_u(uv) -> Gf.Vec2f: return Gf.Vec2f(1 - uv[0], uv[1]) def inverse_v(uv) -> Gf.Vec2f: return Gf.Vec2f(uv[0], 1 - uv[1]) def inverse_uv(uv) -> Gf.Vec2f: return Gf.Vec2f(1 - uv[0], 1 - uv[1]) def transform_point(point: Gf.Vec3f, origin: Gf.Vec3f, half_scale: float) -> Gf.Vec3f: return half_scale * point + origin def generate_circle_points( up_axis, num_points, delta, center_point=Gf.Vec3f(0.0) ) -> Tuple[List[Gf.Vec3f], List[Gf.Vec2f]]: points: List[Gf.Vec3f] = [] point_sts: List[Gf.Vec2f] = [] for i in range(num_points): theta = i * delta * math.pi * 2 if up_axis == "Y": point = Gf.Vec3f(math.cos(theta), 0.0, math.sin(theta)) st = Gf.Vec2f(1.0 - point[0] / 2.0, (1.0 + point[2]) / 2.0) else: point = Gf.Vec3f(math.cos(theta), math.sin(theta), 0.0) st = Gf.Vec2f((1.0 - point[0]) / 2.0, (1.0 + point[1]) / 2.0) point_sts.append(st) points.append(point + center_point) return points, point_sts def get_int_setting(key, default_value): settings = carb.settings.get_settings() settings.set_default(key, default_value) value = settings.get_as_int(key) return value def generate_disk( center_point: Gf.Vec3f, u_patches: int, v_patches: int, origin: Gf.Vec3f, half_scale: float, up_axis="Y" ) -> Tuple[List[Gf.Vec3f], List[Gf.Vec3f], List[Gf.Vec2f], List[int], List[int]]: u_delta = 1.0 / u_patches v_delta = 1.0 / v_patches num_u_verts = u_patches num_v_verts = v_patches + 1 points: List[Gf.Vec3f] = [] normals: List[Gf.Vec3f] = [] sts: List[Gf.Vec2f] = [] face_indices: List[int] = [] face_vertex_counts: List[int] = [] center_point = transform_point(center_point, origin, half_scale) circle_points, _ = generate_circle_points(up_axis, u_patches, 1.0 / u_patches) for i in range(num_v_verts - 1): v = v_delta * i for j in range(num_u_verts): point = transform_point(circle_points[j], (0, 0, 0), half_scale * (1 - v)) points.append(point + center_point) # Center point points.append(center_point) def calc_index(i, j): ii = i if i < num_u_verts else 0 base_index = j * num_u_verts if j == num_v_verts - 1: return base_index else: return base_index + ii def get_uv(i, j): vindex = calc_index(i, j) # Ensure all axis to be [-1, 1] point = (points[vindex] - origin) / half_scale if up_axis == "Y": st = (Gf.Vec2f(-point[0], -point[2]) + Gf.Vec2f(1, 1)) / 2 else: st = (Gf.Vec2f(point[0], point[1]) + Gf.Vec2f(1)) / 2 return st # Generating quads or triangles of the center for j in range(v_patches): for i in range(u_patches): vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) uv00 = get_uv(i, j) uv10 = get_uv(i + 1, j) uv11 = get_uv(i + 1, j + 1) uv01 = get_uv(i, j + 1) # Right-hand order if up_axis == "Y": if vindex11 == vindex01: sts.extend([inverse_u(uv00), inverse_u(uv01), inverse_u(uv10)]) face_indices.extend((vindex00, vindex01, vindex10)) else: sts.extend([inverse_u(uv00), inverse_u(uv01), inverse_u(uv11), inverse_u(uv10)]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normal = Gf.Vec3f(0.0, 1.0, 0.0) else: if vindex11 == vindex01: sts.extend([uv00, uv10, uv01]) face_indices.extend((vindex00, vindex10, vindex01)) else: sts.extend([uv00, uv10, uv11, uv01]) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) normal = Gf.Vec3f(0.0, 0.0, 1.0) if vindex11 == vindex01: face_vertex_counts.append(3) normals.extend([normal] * 3) else: face_vertex_counts.append(4) normals.extend([normal] * 4) return points, normals, sts, face_indices, face_vertex_counts def generate_plane(origin, half_scale, u_patches, v_patches, up_axis): if isinstance(half_scale, Number): [w, h, d] = half_scale, half_scale, half_scale else: [w, h, d] = half_scale [x, y, z] = origin[0], origin[1], origin[2] num_u_verts = u_patches + 1 num_v_verts = v_patches + 1 points = [] normals = [] sts = [] face_indices = [] face_vertex_counts = [] u_delta = 1.0 / u_patches v_delta = 1.0 / v_patches if up_axis == "Y": w_delta = 2.0 * w * u_delta h_delta = 2.0 * d * v_delta bottom_left = Gf.Vec3f(x - w, y, z - d) for i in range(num_v_verts): for j in range(num_u_verts): point = bottom_left + Gf.Vec3f(j * w_delta, 0.0, i * h_delta) points.append(point) elif up_axis == "Z": w_delta = 2.0 * w / u_patches h_delta = 2.0 * h / v_patches bottom_left = Gf.Vec3f(x - w, y - h, z) for i in range(num_v_verts): for j in range(num_u_verts): point = bottom_left + Gf.Vec3f(j * w_delta, i * h_delta, 0.0) points.append(point) else: # X up w_delta = 2.0 * h / u_patches h_delta = 2.0 * d / v_patches bottom_left = Gf.Vec3f(x, y - h, z - d) for i in range(num_v_verts): for j in range(num_u_verts): point = bottom_left + Gf.Vec3f(0, j * w_delta, i * h_delta) points.append(point) def calc_index(i, j): ii = i if i < num_u_verts else 0 jj = j if j < num_v_verts else 0 return jj * num_u_verts + ii def get_uv(i, j): u = i * u_delta if i < num_u_verts else 1.0 if up_axis == "Y": v = 1 - j * v_delta if j < num_v_verts else 0.0 else: v = j * v_delta if j < num_v_verts else 1.0 return Gf.Vec2f(u, v) # Generating quads for j in range(v_patches): for i in range(u_patches): vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) uv00 = get_uv(i, j) uv10 = get_uv(i + 1, j) uv11 = get_uv(i + 1, j + 1) uv01 = get_uv(i, j + 1) # Right-hand order if up_axis == "Y": sts.extend([uv00, uv01, uv11, uv10]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normal = Gf.Vec3f(0.0, 1.0, 0.0) elif up_axis == "Z": sts.extend([uv00, uv10, uv11, uv01]) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) normal = Gf.Vec3f(0.0, 0.0, 1.0) else: # X sts.extend([uv00, uv01, uv11, uv10]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normal = Gf.Vec3f(0.0, 1.0, 0.0) face_vertex_counts.append(4) normals.extend([normal] * 4) return points, normals, sts, face_indices, face_vertex_counts def modify_winding_order(face_counts, face_indices): total = 0 for count in face_counts: if count >= 3: start = total + 1 end = total + count face_indices[start:end] = face_indices[start:end][::-1] total += count
8,670
Python
32.608527
115
0.529873
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/plane.py
from .utils import get_int_setting, build_int_slider, inverse_u, generate_plane from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf class PlaneEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/plane/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/plane/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/plane/v_scale" def __init__(self, attributes: dict): super().__init__(attributes) def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(PlaneEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(PlaneEvaluator.SETTING_V_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) half_scale = [half_scale, half_scale, half_scale] u_patches = kwargs.get("u_patches", 1) v_patches = kwargs.get("v_patches", 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale u_patches = max(int(u_patches), 1) v_patches = max(int(v_patches), 1) return generate_plane(origin, half_scale, u_patches, v_patches, up_axis) @staticmethod def build_setting_ui(): from omni import ui PlaneEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", PlaneEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) PlaneEvaluator._u_scale_slider = build_int_slider("U Verts Scale", PlaneEvaluator.SETTING_U_SCALE, 1, 1, 10) ui.Spacer(height=5) PlaneEvaluator._v_scale_slider = build_int_slider("V Verts Scale", PlaneEvaluator.SETTING_V_SCALE, 1, 1, 10) @staticmethod def reset_setting(): PlaneEvaluator._half_scale_slider.set_value(PlaneEvaluator.get_default_half_scale()) PlaneEvaluator._u_scale_slider.set_value(1) PlaneEvaluator._v_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(PlaneEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
2,585
Python
39.406249
116
0.649903
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/cylinder.py
from .utils import ( get_int_setting, build_int_slider, modify_winding_order, generate_circle_points, transform_point, inverse_u, inverse_v, generate_disk ) from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf from typing import List class CylinderEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/cylinder/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/cylinder/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/cylinder/v_scale" SETTING_W_SCALE = "/persistent/app/mesh_generator/shapes/cylinder/w_scale" def __init__(self, attributes: dict): super().__init__(attributes) def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(CylinderEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(CylinderEvaluator.SETTING_V_SCALE, 1) num_w_verts_scale = kwargs.get("w_verts_scale", None) if num_w_verts_scale is None or num_w_verts_scale <= 0: num_w_verts_scale = get_int_setting(CylinderEvaluator.SETTING_W_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) u_patches = kwargs.get("u_patches", 32) v_patches = kwargs.get("v_patches", 1) w_patches = kwargs.get("w_patches", 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale w_patches = w_patches * num_w_verts_scale u_patches = max(int(u_patches), 3) v_patches = max(int(v_patches), 1) w_patches = max(int(w_patches), 1) u_delta = 1.0 / (u_patches if u_patches != 0 else 1) v_delta = 1.0 / (v_patches if v_patches != 0 else 1) # open meshes need an extra vert on the end to create the last patch # closed meshes reuse the vert at index 0 to close their final patch num_u_verts = u_patches num_v_verts = v_patches + 1 points: List[Gf.Vec3f] = [] normals: List[Gf.Vec3f] = [] sts: List[Gf.Vec2f] = [] face_indices: List[int] = [] face_vertex_counts: List[int] = [] # generate circle points circle_points, _ = generate_circle_points(up_axis, num_u_verts, u_delta) for j in range(num_v_verts): for i in range(num_u_verts): v = j * v_delta point = circle_points[i] if up_axis == "Y": point[1] = 2.0 * (v - 0.5) else: point[2] = 2.0 * (v - 0.5) point = transform_point(point, origin, half_scale) points.append(point) def calc_index(i, j): ii = i if i < num_u_verts else 0 jj = j if j < num_v_verts else 0 return jj * num_u_verts + ii def get_uv(i, j): u = 1 - i * u_delta if i < num_u_verts else 0.0 v = j * v_delta if j < num_v_verts else 1.0 return Gf.Vec2f(u, v) for j in range(v_patches): for i in range(u_patches): vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) uv00 = get_uv(i, j) uv10 = get_uv(i + 1, j) uv11 = get_uv(i + 1, j + 1) uv01 = get_uv(i, j + 1) p00 = points[vindex00] p10 = points[vindex10] p11 = points[vindex11] p01 = points[vindex01] # Right-hand order if up_axis == "Y": sts.extend([uv00, uv01, uv11, uv10]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normals.append(Gf.Vec3f(p00[0], 0, p00[2])) normals.append(Gf.Vec3f(p01[0], 0, p01[2])) normals.append(Gf.Vec3f(p11[0], 0, p11[2])) normals.append(Gf.Vec3f(p10[0], 0, p10[2])) else: sts.extend([inverse_u(uv00), inverse_u(uv10), inverse_u(uv11), inverse_u(uv01)]) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) normals.append(Gf.Vec3f(p00[0], p00[1], 0)) normals.append(Gf.Vec3f(p10[0], p10[1], 0)) normals.append(Gf.Vec3f(p11[0], p11[1], 0)) normals.append(Gf.Vec3f(p01[0], p01[1], 0)) face_vertex_counts.append(4) # Add hat if up_axis == "Y": bottom_center_point = Gf.Vec3f(0, -1, 0) top_center_point = Gf.Vec3f(0, 1, 0) else: bottom_center_point = Gf.Vec3f(0, 0, -1) top_center_point = Gf.Vec3f(0, 0, 1) def add_hat(center_point, rim_points_start_index, w_patches, invert_wind_order=False): bt_points, _, bt_sts, bt_face_indices, bt_face_vertex_counts = generate_disk( center_point, u_patches, w_patches, origin, half_scale, up_axis ) total_points = len(points) # Skips shared points points.extend(bt_points[num_u_verts:]) if invert_wind_order: modify_winding_order(bt_face_vertex_counts, bt_sts) for st in bt_sts: sts.append(inverse_v(st)) else: sts.extend(bt_sts) face_vertex_counts.extend(bt_face_vertex_counts) normals.extend([center_point] * len(bt_face_indices)) # Remapping cap points for i, index in enumerate(bt_face_indices): if index >= num_u_verts: bt_face_indices[i] += total_points - num_u_verts else: bt_face_indices[i] += rim_points_start_index if invert_wind_order: modify_winding_order(bt_face_vertex_counts, bt_face_indices) face_indices.extend(bt_face_indices) top_hat_start_index = len(points) - num_u_verts # Add bottom hat to close shape add_hat(bottom_center_point, 0, w_patches, True) # Add top hat to close shape add_hat(top_center_point, top_hat_start_index, w_patches) return points, normals, sts, face_indices, face_vertex_counts @staticmethod def build_setting_ui(): from omni import ui CylinderEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", CylinderEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) CylinderEvaluator._u_scale_slider = build_int_slider( "U Verts Scale", CylinderEvaluator.SETTING_U_SCALE, 1, 1, 10, "Tessellation Level in Horizontal Direction" ) ui.Spacer(height=5) CylinderEvaluator._v_scale_slider = build_int_slider( "V Verts Scale", CylinderEvaluator.SETTING_V_SCALE, 1, 1, 10, "Tessellation Level in Vertical Direction" ) ui.Spacer(height=5) CylinderEvaluator._w_scale_slider = build_int_slider( "W Verts Scale", CylinderEvaluator.SETTING_W_SCALE, 1, 1, 10, "Tessellation Level of Bottom and Top Caps" ) @staticmethod def reset_setting(): CylinderEvaluator._half_scale_slider.set_value(CylinderEvaluator.get_default_half_scale()) CylinderEvaluator._u_scale_slider.set_value(1) CylinderEvaluator._v_scale_slider.set_value(1) CylinderEvaluator._w_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(CylinderEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
8,285
Python
40.019802
100
0.555462
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/sphere.py
import math from .utils import get_int_setting, build_int_slider from .utils import transform_point from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf class SphereEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/shpere/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/sphere/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/sphere/v_scale" def __init__(self, attributes: dict): super().__init__(attributes) def _eval(self, u, v, up_axis): theta = u * 2.0 * math.pi phi = (v - 0.5) * math.pi cos_phi = math.cos(phi) if up_axis == "Y": x = cos_phi * math.cos(theta) y = math.sin(phi) z = cos_phi * math.sin(theta) else: x = cos_phi * math.cos(theta) y = cos_phi * math.sin(theta) z = math.sin(phi) return Gf.Vec3f(x, y, z) def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(SphereEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(SphereEvaluator.SETTING_V_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) u_patches = kwargs.get("u_patches", 32) v_patches = kwargs.get("v_patches", 16) num_u_verts_scale = max(num_u_verts_scale, 1) num_v_verts_scale = max(num_v_verts_scale, 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale u_patches = max(int(u_patches), 3) v_patches = max(int(v_patches), 2) u_delta = 1.0 / u_patches v_delta = 1.0 / v_patches num_u_verts = u_patches num_v_verts = v_patches + 1 points = [] normals = [] sts = [] face_indices = [] face_vertex_counts = [] if up_axis == "Y": bottom_point = Gf.Vec3f(0.0, -1.0, 0.0) else: bottom_point = Gf.Vec3f(0.0, 0.0, -1.0) point = transform_point(bottom_point, origin, half_scale) points.append(point) for j in range(1, num_v_verts - 1): v = j * v_delta for i in range(num_u_verts): u = i * u_delta point = self._eval(u, v, up_axis) point = transform_point(point, origin, half_scale) points.append(Gf.Vec3f(point)) if up_axis == "Y": top_point = Gf.Vec3f(0.0, 1.0, 0.0) else: top_point = Gf.Vec3f(0.0, 0.0, 1.0) point = transform_point(top_point, origin, half_scale) points.append(point) def calc_index(i, j): if j == 0: return 0 elif j == num_v_verts - 1: return len(points) - 1 else: i = i if i < num_u_verts else 0 return (j - 1) * num_u_verts + i + 1 def get_uv(i, j): if up_axis == "Y": u = 1 - i * u_delta v = j * v_delta else: u = i * u_delta v = j * v_delta return Gf.Vec2f(u, v) # Generate body for j in range(v_patches): for i in range(u_patches): # Index 0 is the bottom hat point vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) st00 = get_uv(i, j) st10 = get_uv(i + 1, j) st11 = get_uv(i + 1, j + 1) st01 = get_uv(i, j + 1) p0 = points[vindex00] p1 = points[vindex10] p2 = points[vindex11] p3 = points[vindex01] # Use face varying uv if up_axis == "Y": if vindex11 == vindex01: sts.extend([st00, st01, st10]) face_indices.extend((vindex00, vindex01, vindex10)) face_vertex_counts.append(3) normals.extend([p0, p3, p1]) elif vindex00 == vindex10: sts.extend([st00, st01, st11]) face_indices.extend((vindex00, vindex01, vindex11)) face_vertex_counts.append(3) normals.extend([p0, p3, p2]) else: sts.extend([st00, st01, st11, st10]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) face_vertex_counts.append(4) normals.extend([p0, p3, p2, p1]) else: if vindex11 == vindex01: sts.extend([st00, st10, st01]) face_indices.extend((vindex00, vindex10, vindex01)) face_vertex_counts.append(3) normals.extend([p0, p1, p3]) elif vindex00 == vindex10: sts.extend([st00, st11, st01]) face_indices.extend((vindex00, vindex11, vindex01)) face_vertex_counts.append(3) normals.extend([p0, p2, p3]) else: sts.extend([st00, st10, st11, st01]) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) face_vertex_counts.append(4) normals.extend([p0, p1, p2, p3]) return points, normals, sts, face_indices, face_vertex_counts @staticmethod def build_setting_ui(): from omni import ui SphereEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", SphereEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) SphereEvaluator._u_scale_slider = build_int_slider( "U Verts Scale", SphereEvaluator.SETTING_U_SCALE, 1, 1, 10 ) ui.Spacer(height=5) SphereEvaluator._v_scale_slider = build_int_slider( "V Verts Scale", SphereEvaluator.SETTING_V_SCALE, 1, 1, 10 ) @staticmethod def reset_setting(): SphereEvaluator._half_scale_slider.set_value(SphereEvaluator.get_default_half_scale()) SphereEvaluator._u_scale_slider.set_value(1) SphereEvaluator._v_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(SphereEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
7,142
Python
36.397906
96
0.506301
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/cube.py
from .utils import get_int_setting, build_int_slider, generate_plane, modify_winding_order from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf class CubeEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/cube/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/cube/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/cube/v_scale" SETTING_W_SCALE = "/persistent/app/mesh_generator/shapes/cube/w_scale" def __init__(self, attributes: dict): super().__init__(attributes) def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(CubeEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(CubeEvaluator.SETTING_V_SCALE, 1) num_w_verts_scale = kwargs.get("w_verts_scale", None) if num_w_verts_scale is None or num_w_verts_scale <= 0: num_w_verts_scale = get_int_setting(CubeEvaluator.SETTING_W_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) u_patches = kwargs.get("u_patches", 1) v_patches = kwargs.get("v_patches", 1) w_patches = kwargs.get("w_patches", 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale w_patches = w_patches * num_w_verts_scale u_patches = max(int(u_patches), 1) v_patches = max(int(v_patches), 1) w_patches = max(int(w_patches), 1) [x, y, z] = origin ( xy_plane_points, xy_plane_normals, xy_plane_sts, xy_plane_face_indices, xy_plane_face_vertex_counts ) = generate_plane(Gf.Vec3f(x, y, z + half_scale), half_scale, u_patches, v_patches, "Z") ( xz_plane_points, xz_plane_normals, xz_plane_sts, xz_plane_face_indices, xz_plane_face_vertex_counts ) = generate_plane(Gf.Vec3f(x, y - half_scale, z), half_scale, u_patches, w_patches, "Y") ( yz_plane_points, yz_plane_normals, yz_plane_sts, yz_plane_face_indices, yz_plane_face_vertex_counts ) = generate_plane(Gf.Vec3f(x - half_scale, y, z), half_scale, v_patches, w_patches, "X") points = [] normals = [] sts = [] face_indices = [] face_vertex_counts = [] # XY planes points.extend(xy_plane_points) normals.extend([Gf.Vec3f(0, 0, 1)] * len(xy_plane_normals)) sts.extend(xy_plane_sts) face_indices.extend(xy_plane_face_indices) face_vertex_counts.extend(xy_plane_face_vertex_counts) total_indices = len(points) plane_points = [point + Gf.Vec3f(0, 0, -2.0 * half_scale) for point in xy_plane_points] points.extend(plane_points) normals.extend([Gf.Vec3f(0, 0, -1)] * len(xy_plane_normals)) modify_winding_order(xy_plane_face_vertex_counts, xy_plane_sts) plane_sts = [Gf.Vec2f(1 - st[0], st[1]) for st in xy_plane_sts] sts.extend(plane_sts) plane_face_indices = [index + total_indices for index in xy_plane_face_indices] modify_winding_order(xy_plane_face_vertex_counts, plane_face_indices) face_indices.extend(plane_face_indices) face_vertex_counts.extend(xy_plane_face_vertex_counts) # xz planes total_indices = len(points) plane_points = [point + Gf.Vec3f(0, 2.0 * half_scale, 0) for point in xz_plane_points] points.extend(plane_points) normals.extend([Gf.Vec3f(0, 1, 0)] * len(xz_plane_normals)) sts.extend(xz_plane_sts) plane_face_indices = [index + total_indices for index in xz_plane_face_indices] face_indices.extend(plane_face_indices) face_vertex_counts.extend(xz_plane_face_vertex_counts) total_indices = len(points) points.extend(xz_plane_points) normals.extend([Gf.Vec3f(0, -1, 0)] * len(xz_plane_normals)) modify_winding_order(xz_plane_face_vertex_counts, xz_plane_sts) plane_sts = [Gf.Vec2f(st[0], 1 - st[1]) for st in xz_plane_sts] sts.extend(plane_sts) plane_face_indices = [index + total_indices for index in xz_plane_face_indices] modify_winding_order(xz_plane_face_vertex_counts, plane_face_indices) face_indices.extend(plane_face_indices) face_vertex_counts.extend(xz_plane_face_vertex_counts) # yz planes total_indices = len(points) points.extend(yz_plane_points) normals.extend([Gf.Vec3f(-1, 0, 0)] * len(yz_plane_normals)) plane_sts = [Gf.Vec2f(st[1], st[0]) for st in yz_plane_sts] sts.extend(plane_sts) plane_face_indices = [index + total_indices for index in yz_plane_face_indices] face_indices.extend(plane_face_indices) face_vertex_counts.extend(yz_plane_face_vertex_counts) total_indices = len(points) plane_points = [point + Gf.Vec3f(2.0 * half_scale, 0, 0) for point in yz_plane_points] points.extend(plane_points) normals.extend([Gf.Vec3f(1, 0, 0)] * len(yz_plane_normals)) modify_winding_order(yz_plane_face_vertex_counts, yz_plane_sts) plane_sts = [Gf.Vec2f(1 - st[1], st[0]) for st in yz_plane_sts] sts.extend(plane_sts) plane_face_indices = [index + total_indices for index in yz_plane_face_indices] modify_winding_order(yz_plane_face_vertex_counts, plane_face_indices) face_indices.extend(plane_face_indices) face_vertex_counts.extend(yz_plane_face_vertex_counts) # Welds the edges of cube keep = [True] * len(points) index_remap = [-1] * len(points) keep_points = [] for i in range(0, len(points)): if not keep[i]: continue keep_points.append(points[i]) index_remap[i] = len(keep_points) - 1 for j in range(i + 1, len(points)): if Gf.IsClose(points[j], points[i], 1e-6): keep[j] = False index_remap[j] = len(keep_points) - 1 for i in range(len(face_indices)): face_indices[i] = index_remap[face_indices[i]] return keep_points, normals, sts, face_indices, face_vertex_counts @staticmethod def build_setting_ui(): from omni import ui CubeEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", CubeEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) CubeEvaluator._u_scale_slider = build_int_slider( "U Verts Scale", CubeEvaluator.SETTING_U_SCALE, 1, 1, 10, "Tessellation Level along X Axis" ) ui.Spacer(height=5) CubeEvaluator._v_scale_slider = build_int_slider( "V Verts Scale", CubeEvaluator.SETTING_V_SCALE, 1, 1, 10, "Tessellation Level along Y Axis" ) ui.Spacer(height=5) CubeEvaluator._w_scale_slider = build_int_slider( "W Verts Scale", CubeEvaluator.SETTING_W_SCALE, 1, 1, 10, "Tessellation Level along Z Axis" ) @staticmethod def reset_setting(): CubeEvaluator._half_scale_slider.set_value(CubeEvaluator.get_default_half_scale()) CubeEvaluator._u_scale_slider.set_value(1) CubeEvaluator._v_scale_slider.set_value(1) CubeEvaluator._w_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(CubeEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
7,997
Python
41.770053
97
0.614731
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/disk.py
from .utils import get_int_setting, build_int_slider from .utils import generate_disk from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf class DiskEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/disk/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/disk/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/disk/v_scale" def __init__(self, attributes: dict): super().__init__(attributes) def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(DiskEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(DiskEvaluator.SETTING_V_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) # Disk will be approximated by quads composed from inner circle # to outer circle. The parameter `u_patches` means the segments # of circle. And v_patches means the number of segments (circles) # in radius direction. u_patches = kwargs.get("u_patches", 32) v_patches = kwargs.get("v_patches", 1) num_u_verts_scale = max(num_u_verts_scale, 1) num_v_verts_scale = max(num_v_verts_scale, 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale u_patches = max(int(u_patches), 3) v_patches = max(int(v_patches), 1) center_point = Gf.Vec3f(0.0) return generate_disk(center_point, u_patches, v_patches, origin, half_scale, up_axis) @staticmethod def build_setting_ui(): from omni import ui DiskEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", DiskEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) DiskEvaluator._u_scale_slider = build_int_slider("U Verts Scale", DiskEvaluator.SETTING_U_SCALE, 1, 1, 10) ui.Spacer(height=5) DiskEvaluator._v_scale_slider = build_int_slider("V Verts Scale", DiskEvaluator.SETTING_V_SCALE, 1, 1, 10) @staticmethod def reset_setting(): DiskEvaluator._half_scale_slider.set_value(DiskEvaluator.get_default_half_scale()) DiskEvaluator._u_scale_slider.set_value(1) DiskEvaluator._v_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(DiskEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
2,917
Python
39.527777
114
0.649983
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/torus.py
import math from .utils import get_int_setting, build_int_slider from .utils import transform_point from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf class TorusEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/torus/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/torus/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/torus/v_scale" def __init__(self, attributes: dict): super().__init__(attributes) self.hole_radius = 1.0 self.tube_radius = 0.5 def _eval(self, up_axis, u, v): theta = u * 2.0 * math.pi phi = v * 2.0 * math.pi - 0.5 * math.pi rad_cos_phi = self.tube_radius * math.cos(phi) cos_theta = math.cos(theta) sin_phi = math.sin(phi) sin_theta = math.sin(theta) x = (self.hole_radius + rad_cos_phi) * cos_theta nx = self.hole_radius * cos_theta if up_axis == "Y": y = self.tube_radius * sin_phi z = (self.hole_radius + rad_cos_phi) * sin_theta ny = 0 nz = self.hole_radius * sin_theta else: y = (self.hole_radius + rad_cos_phi) * sin_theta z = self.tube_radius * sin_phi ny = self.hole_radius * sin_theta nz = 0 point = Gf.Vec3f(x, y, z) # construct the normal by creating a vector from the center point of the tube to the surface normal = Gf.Vec3f(x - nx, y - ny, z - nz) normal = normal.GetNormalized() return point, normal def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(TorusEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(TorusEvaluator.SETTING_V_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) u_patches = kwargs.get("u_patches", 32) v_patches = kwargs.get("v_patches", 32) num_u_verts_scale = max(num_u_verts_scale, 1) num_v_verts_scale = max(num_v_verts_scale, 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale u_patches = max(int(u_patches), 3) v_patches = max(int(v_patches), 3) u_delta = 1.0 / u_patches v_delta = 1.0 / v_patches num_u_verts = u_patches num_v_verts = v_patches points = [] point_normals = [] sts = [] face_indices = [] face_vertex_counts = [] for j in range(num_v_verts): v = j * v_delta for i in range(num_u_verts): u = i * u_delta point, point_normal = self._eval(up_axis, u, v) point = transform_point(point, origin, half_scale) points.append(point) point_normals.append(point_normal) def calc_index(i, j): ii = i if i < num_u_verts else 0 jj = j if j < num_v_verts else 0 return jj * num_u_verts + ii def get_uv(i, j): if up_axis == "Y": u = 1 - i * u_delta if i < num_u_verts else 0.0 else: u = i * u_delta if i < num_u_verts else 1.0 v = j * v_delta if j < num_v_verts else 1.0 return Gf.Vec2f(u, v) # Last patch from last vert to first vert to close shape normals = [] for j in range(v_patches): for i in range(u_patches): vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) # Use face varying uv face_vertex_counts.append(4) if up_axis == "Y": sts.append(get_uv(i, j)) sts.append(get_uv(i, j + 1)) sts.append(get_uv(i + 1, j + 1)) sts.append(get_uv(i + 1, j)) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normals.extend( [ point_normals[vindex00], point_normals[vindex01], point_normals[vindex11], point_normals[vindex10], ] ) else: sts.append(get_uv(i, j)) sts.append(get_uv(i + 1, j)) sts.append(get_uv(i + 1, j + 1)) sts.append(get_uv(i, j + 1)) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) normals.extend( [ point_normals[vindex00], point_normals[vindex10], point_normals[vindex11], point_normals[vindex01], ] ) return points, normals, sts, face_indices, face_vertex_counts @staticmethod def build_setting_ui(): from omni import ui TorusEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", TorusEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) TorusEvaluator._u_scale_slider = build_int_slider("U Verts Scale", TorusEvaluator.SETTING_U_SCALE, 1, 1, 10) ui.Spacer(height=5) TorusEvaluator._v_scale_slider = build_int_slider("V Verts Scale", TorusEvaluator.SETTING_V_SCALE, 1, 1, 10) @staticmethod def reset_setting(): TorusEvaluator._half_scale_slider.set_value(TorusEvaluator.get_default_half_scale()) TorusEvaluator._u_scale_slider.set_value(1) TorusEvaluator._v_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(TorusEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
6,485
Python
36.275862
116
0.523516
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/tests/__init__.py
from .test_mesh_prims import *
31
Python
14.999993
30
0.741935
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/tests/test_mesh_prims.py
import omni.kit.test import omni.usd import omni.kit.app import omni.kit.primitive.mesh import omni.kit.commands import omni.kit.actions.core from pathlib import Path from pxr import Gf, Kind, Sdf, Usd, UsdGeom, UsdShade EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests") # NOTE: those tests belong to omni.kit.primitive.mesh extension. class TestMeshPrims(omni.kit.test.AsyncTestCase): async def test_tessellation_params(self): test_data = { "Cube": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1, "w_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 1}, }, { "params": {"half_scale": 400, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "w_verts_scale": 1, "u_patches": 2, "v_patches": 2, "w_patches": 2 }, }, ], "Cone": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1, "w_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 1}, }, { "params": {"half_scale": 400, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "w_verts_scale": 1, "u_patches": 2, "v_patches": 2, "w_patches": 2 }, }, ], "Cylinder": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1, "w_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 1}, }, { "params": {"half_scale": 400, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "w_verts_scale": 1, "u_patches": 2, "v_patches": 2, "w_patches": 2 }, }, ], "Disk": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "u_patches": 2, "v_patches": 2 }, }, ], "Plane": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "u_patches": 2, "v_patches": 2 }, }, ], "Sphere": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "u_patches": 2, "v_patches": 2 }, }, ], "Torus": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "u_patches": 2, "v_patches": 2 }, }, ], } golden_file = TEST_DATA_PATH.joinpath("golden.usd") golden_stage = Usd.Stage.Open(str(golden_file)) self.assertTrue(golden_stage) await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() for prim_type, test_cases in test_data.items(): for test_case in test_cases: params = test_case["params"] result, path = omni.kit.commands.execute( "CreateMeshPrim", prim_type=prim_type, above_ground=True, **params ) self.assertTrue(result) mesh_prim = stage.GetPrimAtPath(path) self.assertTrue(mesh_prim) golden_prim = golden_stage.GetPrimAtPath(path) self.assertTrue(golden_prim) property_names = mesh_prim.GetPropertyNames() golden_property_names = golden_prim.GetPropertyNames() self.assertEqual(property_names, golden_property_names) path = Sdf.Path(path) for property_name in property_names: property_path = path.AppendProperty(property_name) prop = mesh_prim.GetPropertyAtPath(property_path) golden_prop = golden_prim.GetPropertyAtPath(property_path) # Skips relationship if hasattr(prop, "GetTypeName"): self.assertTrue(prop.GetTypeName(), golden_prop.GetTypeName()) self.assertEqual(prop.Get(), golden_prop.Get()) async def test_mesh_prims(self): """Test all mesh generator prims.""" for y_axis in [True, False]: await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() axis = UsdGeom.Tokens.y if y_axis else UsdGeom.Tokens.z UsdGeom.SetStageUpAxis(stage, axis) for prim_type in omni.kit.primitive.mesh.get_geometry_mesh_prim_list(): result, path = omni.kit.commands.execute("CreateMeshPrim", prim_type=prim_type, above_ground=True) self.assertTrue(result) def check_exist(): prim = stage.GetPrimAtPath(path) attr = prim.GetAttribute(UsdGeom.Tokens.extent) self.assertTrue(attr and attr.Get()) self.assertTrue(prim) self.assertTrue(prim.IsA(UsdGeom.Mesh)) self.assertTrue(prim.IsA(UsdGeom.Xformable)) mesh_prim = UsdGeom.Mesh(prim) points = mesh_prim.GetPointsAttr().Get() face_indices = mesh_prim.GetFaceVertexIndicesAttr().Get() normals = mesh_prim.GetNormalsAttr().Get() face_counts = mesh_prim.GetFaceVertexCountsAttr().Get() total = 0 for face_count in face_counts: total += face_count unique_indices = set(face_indices) self.assertTrue(len(points) == len(unique_indices)) self.assertTrue(total == len(normals)) self.assertTrue(total == len(face_indices)) def check_does_not_exist(): self.assertFalse(stage.GetPrimAtPath(path)) check_exist() omni.kit.undo.undo() check_does_not_exist() omni.kit.undo.redo() check_exist() omni.kit.undo.undo() check_does_not_exist() async def test_meshes_creation_from_menu(self): import omni.kit.ui_test as ui_test await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() for prim_type in omni.kit.primitive.mesh.get_geometry_mesh_prim_list(): await ui_test.menu_click(f"Create/Mesh/{prim_type.capitalize()}") path = f"/{prim_type}" def check_exist(): prim = stage.GetPrimAtPath(path) self.assertTrue(prim) def check_does_not_exist(): self.assertFalse(stage.GetPrimAtPath(path)) check_exist() omni.kit.undo.undo() check_does_not_exist() omni.kit.undo.redo() check_exist() omni.kit.undo.undo() check_does_not_exist() async def test_mesh_settings(self): import omni.kit.ui_test as ui_test await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() await ui_test.menu_click("Create/Mesh/Settings") window = ui_test.find("Mesh Generation Settings") self.assertTrue(window) await window.focus() primitive_type_combobox = window.find("**/ComboBox[*].name=='primitive_type'") self.assertTrue(primitive_type_combobox) create_button = window.find("**/Button[*].name=='create'") self.assertTrue(create_button) model = primitive_type_combobox.model value_model = model.get_item_value_model() for i, prim_type in enumerate(omni.kit.primitive.mesh.get_geometry_mesh_prim_list()): value_model.set_value(i) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await create_button.click() path = f"/{prim_type}" self.assertTrue(stage.GetPrimAtPath(path)) async def test_actions(self): await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() for prim_type in omni.kit.primitive.mesh.get_geometry_mesh_prim_list(): omni.kit.actions.core.execute_action( "omni.kit.primitive.mesh", f"create_mesh_prim_{prim_type.lower()}" ) path = f"/{prim_type}" def check_exist(): prim = stage.GetPrimAtPath(path) self.assertTrue(prim) def check_does_not_exist(): self.assertFalse(stage.GetPrimAtPath(path)) check_exist() omni.kit.undo.undo() check_does_not_exist() omni.kit.undo.redo() check_exist() omni.kit.undo.undo() check_does_not_exist()
11,354
Python
38.702797
115
0.468822
omniverse-code/kit/exts/omni.kit.primitive.mesh/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.8] - 2022-11-25 ### Changes - Improve mesh primitives for physx needs. - Make sure cone and cylinder are watertight. - Fix normal issues at the tip of Cone. - Add more tessellation settings for caps of cone and cylinder. - Add more tessellation settings for cube to tesselate cube with axis. ## [1.0.7] - 2022-11-22 ### Changes - Fix to avoid crash at shutdown when loading optional slice ## [1.0.6] - 2022-11-22 ### Changes - Make UI dpendency optional ## [1.0.5] - 2022-11-12 ### Changes - Export extent attr for mesh. ## [1.0.4] - 2022-11-11 ### Changes - Clean up dependencies. ## [1.0.3] - 2022-10-25 ### Changes - Added prepend_default_prim parameters to CreateMeshPrimWithDefaultXformCommand ## [1.0.2] - 2022-08-12 ### Changes - Added select_new_prim & prim_path parameters to CreateMeshPrimWithDefaultXformCommand ## [1.0.1] - 2022-06-08 ### Changes - Updated menus to use actions. ## [1.0.0] - 2020-09-09 ### Changes - Supports cube, cone, cylinder, disk, plane, sphere, torus generation. - Supports subdivision of meshes.
1,143
Markdown
24.999999
87
0.702537
omniverse-code/kit/exts/omni.kit.primitive.mesh/docs/index.rst
omni.kit.primitive.mesh: omni.kit.mesh_generator ################################################# Python Extension Mesh Generator
132
reStructuredText
25.599995
49
0.515152
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/animation.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['AnimationEventStream'] import carb import omni.kit.app import traceback from typing import Any, Callable class AnimationEventStream: __g_instance = None @staticmethod def get_instance(): if AnimationEventStream.__g_instance is None: AnimationEventStream.__g_instance = [AnimationEventStream(), 1] else: AnimationEventStream.__g_instance[1] = AnimationEventStream.__g_instance[1] + 1 return AnimationEventStream.__g_instance[0] def __init__(self): self.__event_sub = None self.__callbacks = {} def __del__(self): self.destroy() def destroy(self): if AnimationEventStream.__g_instance and AnimationEventStream.__g_instance[0] == self: AnimationEventStream.__g_instance[1] = AnimationEventStream.__g_instance[1] - 1 if AnimationEventStream.__g_instance[1] > 0: return AnimationEventStream.__g_instance = None self.__event_sub = None self.__callbacks = {} def __on_event(self, e: carb.events.IEvent): dt = e.payload['dt'] for _, callbacks in self.__callbacks.items(): for cb_fn in callbacks: try: cb_fn(dt) except Exception: carb.log_error(traceback.format_exc()) def __init(self): if self.__event_sub: return self.__event_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop( self.__on_event, name="omni.kit.manipulator.camera.AnimationEventStream", order=omni.kit.app.UPDATE_ORDER_PYTHON_ASYNC_FUTURE_END_UPDATE ) def add_animation(self, animation_fn: Callable, key: Any, remove_others: bool = True): if remove_others: self.__callbacks[key] = [animation_fn] else: prev_fns = self.__callbacks.get(key) or [] if prev_fns: prev_fns.append(animation_fn) else: self.__callbacks[key] = [animation_fn] self.__init() def remove_animation(self, key: Any, animation_fn: Callable = None): if animation_fn: prev_fns = self.__callbacks.get(key) if prev_fns: try: prev_fns.remove(animation_fn) except ValueError: pass else: prev_fns = None if not prev_fns: try: del self.__callbacks[key] except KeyError: pass if not self.__callbacks: self.__event_sub = None
3,114
Python
31.447916
103
0.582531
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/viewport_camera_manipulator.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .model import CameraManipulatorModel, _flatten_matrix, _optional_bool, _optional_int from .usd_camera_manipulator import ( UsdCameraManipulator, KIT_COI_ATTRIBUTE, KIT_LOOKTHROUGH_ATTRIBUTE, KIT_CAMERA_LOCK_ATTRIBUTE, _compute_local_transform ) from omni.ui import scene as sc from pxr import Usd, UsdGeom, Sdf, Gf import carb import math __all__ = ['ViewportCameraManipulator'] # More advanced implementation for a Viewport that can use picked objects and -look through- arbitrary scene items # def _check_for_camera_forwarding(imageable: UsdGeom.Imageable): # Look for the relationship setup via LookAtCommand prim = imageable.GetPrim() look_through = prim.GetRelationship(KIT_LOOKTHROUGH_ATTRIBUTE).GetForwardedTargets() if look_through: stage = prim.GetStage() # Loop over all targets (should really be only one) and see if we can get a valid UsdGeom.Imageable for target in look_through: target_prim = stage.GetPrimAtPath(target) if not target_prim: continue target_imageable = UsdGeom.Imageable(target_prim) if target_imageable: return target_imageable carb.log_warn(f'{prim.GetPath()} was set up for look-thorugh, but no valid prim was found for targets: {look_through}') return imageable def _setup_center_of_interest(model: sc.AbstractManipulatorModel, prim: Usd.Prim, time: Usd.TimeCode, object_centric: int = 0, viewport_api=None, mouse=None): def get_center_of_interest(): coi_attr = prim.GetAttribute(KIT_COI_ATTRIBUTE) if not coi_attr or not coi_attr.IsAuthored(): # Use UsdGeomCamera.focusDistance is present distance = 0 fcs_dist = prim.GetAttribute('focusDistance') if fcs_dist and fcs_dist.IsAuthored(): distance = fcs_dist.Get(time) # distance 0 is invalid, so create the atribute based on length from origin if not fcs_dist or distance == 0: origin = Gf.Matrix4d(*model.get_as_floats('initial_transform')).Transform((0, 0, 0)) distance = origin.GetLength() coi_attr = prim.CreateAttribute(KIT_COI_ATTRIBUTE, Sdf.ValueTypeNames.Vector3d, True, Sdf.VariabilityUniform) coi_attr.Set(Gf.Vec3d(0, 0, -distance)) # Make sure COI isn't ridiculously low coi_val = coi_attr.Get() length = coi_val.GetLength() if length < 0.000001 or not math.isfinite(length): coi_val = Gf.Vec3d(0, 0, -100) return coi_val def query_completed(path, pos, *args): # Reset center-of-interest if there's an obect and world-space position if path and pos: # Convert carb value to Gf.Vec3d pos = Gf.Vec3d(pos.x, pos.y, pos.z) # Object centric 1 will use the object-center, so replace pos with the UsdGeom.Imageable's (0, 0, 0) coord if object_centric == 1: picked_prim = prim.GetStage().GetPrimAtPath(path) imageable = UsdGeom.Imageable(picked_prim) if picked_prim else None if imageable: pos = imageable.ComputeLocalToWorldTransform(time).Transform(Gf.Vec3d(0, 0, 0)) if math.isfinite(pos[0]) and math.isfinite(pos[1]) and math.isfinite(pos[2]): inv_xform = Gf.Matrix4d(*model.get_as_floats('transform')).GetInverse() coi = inv_xform.Transform(pos) model.set_floats('center_of_interest_picked', [pos[0], pos[1], pos[2]]) # Also need to trigger a recomputation of ndc_speed based on our new center of interest coi_item = model.get_item('center_of_interest') model.set_floats(coi_item, [coi[0], coi[1], coi[2]]) model._item_changed(coi_item) # Re-enable all movement that we previouly disabled model.set_ints('disable_pan', [disable_pan]) model.set_ints('disable_tumble', [disable_tumble]) model.set_ints('disable_look', [disable_look]) model.set_ints('disable_zoom', [disable_zoom]) coi = get_center_of_interest() model.set_floats('center_of_interest', [coi[0], coi[1], coi[2]]) if object_centric != 0: # Map the NDC co-ordinates to a viewport's texture-space mouse, viewport_api = viewport_api.map_ndc_to_texture_pixel(mouse) if (mouse is None) or (viewport_api is None): object_centric = 0 if object_centric == 0: model.set_floats('center_of_interest_picked', []) return # Block all movement until the query completes disable_pan = _optional_bool(model, 'disable_pan') disable_tumble = _optional_bool(model, 'disable_tumble') disable_look = _optional_bool(model, 'disable_look') disable_zoom = _optional_bool(model, 'disable_zoom') model.set_ints('disable_pan', [1]) model.set_ints('disable_tumble', [1]) model.set_ints('disable_look', [1]) model.set_ints('disable_zoom', [1]) # Start the query viewport_api.request_query(mouse, query_completed) class ViewportCameraManipulator(UsdCameraManipulator): def __init__(self, viewport_api, bindings: dict = None, *args, **kwargs): super().__init__(bindings, viewport_api.usd_context_name) self.__viewport_api = viewport_api # def view_changed(*args): # return # from .gesturebase import set_frame_delivered # set_frame_delivered(True) # self.__vc_change = viewport_api.subscribe_to_frame_change(view_changed) def _on_began(self, model: CameraManipulatorModel, mouse): # We need a viewport and a stage to start. If either are missing disable any further processing. viewport_api = self.__viewport_api stage = viewport_api.stage if viewport_api else None settings = carb.settings.get_settings() # Store the viewport_id in the model for use later if necessary model.set_ints('viewport_id', [viewport_api.id if viewport_api else 0]) if not stage: # TODO: Could we forward this to adjust the viewport_api->omni.scene.ui ? model.set_ints('disable_tumble', [1]) model.set_ints('disable_look', [1]) model.set_ints('disable_pan', [1]) model.set_ints('disable_zoom', [1]) model.set_ints('disable_fly', [1]) return cam_path = viewport_api.camera_path if hasattr(model, '_set_animation_key'): model._set_animation_key(cam_path) time = viewport_api.time cam_prim = stage.GetPrimAtPath(cam_path) cam_imageable = UsdGeom.Imageable(cam_prim) camera = UsdGeom.Camera(cam_prim) if cam_imageable else None if not cam_imageable or not cam_imageable.GetPrim().IsValid(): raise RuntimeError('ViewportCameraManipulator with an invalid UsdGeom.Imageable or Usd.Prim') # Push the viewport's projection into the model projection = _flatten_matrix(viewport_api.projection) model.set_floats('projection', projection) # Check if we should actaully keep camera at identity and forward our movements to another object target_imageable = _check_for_camera_forwarding(cam_imageable) local_xform, parent_xform = _compute_local_transform(target_imageable, time) model.set_floats('initial_transform', _flatten_matrix(local_xform)) model.set_floats('transform', _flatten_matrix(local_xform)) # Setup the model if the camera is orthographic (where for Usd we must edit apertures) # We do this before center-of-interest query to get disabled-state pushed into the model if camera: orthographic = int(camera.GetProjectionAttr().Get(time) == 'orthographic') if orthographic: model.set_floats('initial_aperture', [camera.GetHorizontalApertureAttr().Get(time), camera.GetVerticalApertureAttr().Get(time)]) else: orthographic = int(projection[15] == 1 if projection else False) model.set_floats('initial_aperture', []) up_axis = UsdGeom.GetStageUpAxis(stage) if up_axis == UsdGeom.Tokens.x: up_axis = Gf.Vec3d(1, 0, 0) elif up_axis == UsdGeom.Tokens.y: up_axis = Gf.Vec3d(0, 1, 0) elif up_axis == UsdGeom.Tokens.z: up_axis = Gf.Vec3d(0, 0, 1) if not bool(settings.get("exts/omni.kit.manipulator.camera/forceStageUp")): up_axis = parent_xform.TransformDir(up_axis).GetNormalized() model.set_floats('up_axis', [up_axis[0], up_axis[1], up_axis[2]]) # Disable undo for implict cameras. This might be better handled with custom meta-data / attribute long term disable_undo = cam_path.pathString in ['/OmniverseKit_Persp', '/OmniverseKit_Front', '/OmniverseKit_Right', '/OmniverseKit_Top'] model.set_ints('disable_undo', [int(disable_undo)]) # Test whether this camera is locked cam_lock = cam_prim.GetAttribute(KIT_CAMERA_LOCK_ATTRIBUTE) if cam_lock and cam_lock.Get(): model.set_ints('disable_tumble', [1]) model.set_ints('disable_look', [1]) model.set_ints('disable_pan', [1]) model.set_ints('disable_zoom', [1]) model.set_ints('disable_fly', [1]) else: model.set_ints('orthographic', [orthographic]) model.set_ints('disable_tumble', [orthographic]) model.set_ints('disable_look', [orthographic]) model.set_ints('disable_pan', [0]) model.set_ints('disable_zoom', [0]) model.set_ints('disable_fly', [0]) # Extract the camera's center of interest, from a property or world-space query # model.set_ints('object_centric_movement', [1]) object_centric = settings.get('/exts/omni.kit.manipulator.camera/objectCentric/type') or 0 object_centric = _optional_int(self.model, 'object_centric_movement', object_centric) _setup_center_of_interest(model, target_imageable.GetPrim(), time, object_centric, viewport_api, mouse) # Setup the model for command execution on key-framed data had_transform_at_key = False if not time.IsDefault(): xformable = UsdGeom.Xformable(target_imageable) if xformable: for xformOp in xformable.GetOrderedXformOps(): had_transform_at_key = time in xformOp.GetTimeSamples() if had_transform_at_key: break model.set_ints('had_transform_at_key', [had_transform_at_key]) # Set the pan/zoom speed equivalent to the world space travel of the mouse model.set_floats('world_speed', [1, 1, 1]) # Make a full drag across the viewport equal to a 180 tumble uv_space = viewport_api.map_ndc_to_texture((1, 1))[0] model.set_floats('rotation_speed', [((v * 2.0) - 1.0) for v in uv_space] + [1]) # Tell the USD manipulator the context and prim to operate on self._set_context(viewport_api.usd_context_name, target_imageable.GetPath()) def destroy(self): self.__vc_change = None self.__viewport_api = None super().destroy() import omni.kit.app import time class ZoomEvents: __instances = set() @staticmethod def get_instance(viewport_api): instance = None for inst in ZoomEvents.__instances: if inst.__viewport_api == viewport_api: instance = inst break if instance is None: instance = ZoomEvents(viewport_api) ZoomEvents.__instances.add(instance) else: instance.__mark_time() return instance def __init__(self, viewport_api): self.__viewport_api = viewport_api self.__mouse = [0, 0] self.__manipulator = ViewportCameraManipulator(viewport_api, bindings={'ZoomGesture': 'LeftButton'}) self.__manipulator.on_build() self.__zoom_gesture = self.__manipulator._screen.gestures[0] self.__zoom_gesture._disable_flight() self.__zoom_gesture.on_began(self.__mouse) # 1030 if hasattr(omni.kit.app, 'UPDATE_ORDER_PYTHON_ASYNC_FUTURE_END_UPDATE'): update_order = omni.kit.app.UPDATE_ORDER_PYTHON_ASYNC_FUTURE_END_UPDATE else: update_order = 50 self.__event_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop( self.__on_event, name="omni.kit.manipulator.camera.ZoomEvents", order=update_order ) def update(self, x, y): self.__mark_time() coi = Gf.Vec3d(*self.__manipulator.model.get_as_floats('center_of_interest')) scale = math.log10(max(10, coi.GetLength())) / 40 self.__mouse = (self.__mouse[0] + x * scale, self.__mouse[1] + y * scale) self.__zoom_gesture.on_changed(self.__mouse) self.__mark_time() def __mark_time(self): self.__last_time = time.time() def __time_since_last(self): return time.time() - self.__last_time def __on_event(self, e: carb.events.IEvent): delta = self.__time_since_last() if delta > 0.1: self.destroy() def destroy(self): self.__event_sub = None self.__zoom_gesture.on_ended() self.__manipulator.destroy() try: ZoomEvents.__instances.remove(self) except KeyError: pass # Helper function to do single a zoom-operation, from a scroll-wheel for example def _zoom_operation(x, y, viewport_api): if not viewport_api: return None instance = ZoomEvents.get_instance(viewport_api) instance.update(x, y) return True
14,470
Python
43.118902
136
0.622391
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/__init__.py
# Expose these for easier import via from omni.kit.manipulator.camera import XXX from .manipulator import SceneViewCameraManipulator, CameraManipulatorBase, adjust_center_of_interest from .usd_camera_manipulator import UsdCameraManipulator from .viewport_camera_manipulator import ViewportCameraManipulator
308
Python
50.499992
101
0.863636
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/flight_mode.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['FlightModeKeyboard', 'get_keyboard_input'] from .model import CameraManipulatorModel, _accumulate_values, _optional_floats from omni.ui import scene as sc import omni.appwindow from pxr import Gf import carb import carb.input class FlightModeValues: def __init__(self): self.__xyz_values = ( [0, 0, 0], [0, 0, 0], [0, 0, 0], ) def update(self, i0, i1, value) -> bool: self.__xyz_values[i0][i1] = value total = 0 for values in self.__xyz_values: values[2] = values[1] - values[0] total += values[2] != 0 return total != 0 @property def value(self): return ( self.__xyz_values[0][2], self.__xyz_values[1][2], self.__xyz_values[2][2] ) class FlightModeKeyboard: __g_char_map = None @staticmethod def get_char_map(): if not FlightModeKeyboard.__g_char_map: key_char_map = { 'w': (2, 0), 's': (2, 1), 'a': (0, 0), 'd': (0, 1), 'q': (1, 0), 'e': (1, 1), } carb_key_map = {eval(f'carb.input.KeyboardInput.{ascii_val.upper()}'): index for ascii_val, index in key_char_map.items()} FlightModeKeyboard.__g_char_map = carb_key_map for k, v in FlightModeKeyboard.__g_char_map.items(): yield k, v def __init__(self): self.__input = None self.__model = None self.__stop_events = False self.__keyboard_sub = None self.__initial_speed = None self.__current_adjusted_speed = 1 def init(self, model, iinput, mouse, mouse_button, app_window) -> None: self.__model = model if self.__input is None: self.__input = iinput self.__keyboard = app_window.get_keyboard() self.__keyboard_sub = iinput.subscribe_to_keyboard_events(self.__keyboard, self.__on_key) self.__mouse = mouse # XXX: This isn't working # self.__mouse_sub = iinput.subscribe_to_mouse_events(mouse, self.__on_mouse) # So just query the state on key-down self.__mouse_button = mouse_button self.__key_index = {k: v for k, v in FlightModeKeyboard.get_char_map()} self.__values = FlightModeValues() # Setup for modifier keys adjusting speed self.__settings = carb.settings.get_settings() # Shift or Control can modify flight speed, get the current state self.__setup_speed_modifiers() # Need to update all input key states on start for key, index in self.__key_index.items(): # Read the key and update the value. Update has to occur whether key is down or not as numeric field # might have text focus; causing carbonite not to deliver __on_key messages key_val = self.__input.get_keyboard_value(self.__keyboard, key) self.__values.update(*index, 1 if key_val else 0) # Record whether a previous invocation had started external events prev_stop = self.__stop_events # Test if any interesting key-pair result in a value key_down = any(self.__values.value) # If a key is no longer down, it may have not gotten to __on_key subscription if a numeric entry id focused # In that case there is no more key down so kill any external trigger if prev_stop and not key_down: prev_stop = False self.__model._stop_external_events() self.__stop_events = key_down or prev_stop self.__model.set_floats('fly', self.__values.value) if self.__stop_events: self.__model._start_external_events(True) def _cancel(self) -> bool: return self.__input.get_mouse_value(self.__mouse, self.__mouse_button) == 0 if self.__input else True @property def active(self) -> bool: """Returns if Flight mode is active or not""" return bool(self.__stop_events) def __adjust_speed_modifiers(self, cur_speed_mod: float, prev_speed_mod: float): # Get the current state from initial_speed = self.__settings.get('/persistent/app/viewport/camMoveVelocity') or 1 # Undo any previos speed modification based on key state if prev_speed_mod and prev_speed_mod != 1: initial_speed /= prev_speed_mod # Store the unadjusted values for restoration later (camMoveVelocity may change underneath modifiers) self.__initial_speed = initial_speed # Set the new speed if it is different cur_speed = initial_speed * cur_speed_mod self.__settings.set('/persistent/app/viewport/camMoveVelocity', cur_speed) def __setup_speed_modifiers(self): # Default to legacy value of modifying speed by doubling / halving self.__speed_modifier_amount = self.__settings.get('/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount') if not self.__speed_modifier_amount: return # Store the current_adjusted_speed as inital_speed prev_speed_mod = self.__current_adjusted_speed cur_speed_mod = prev_speed_mod # Scan the input keys that modify speed and adjust current_adjusted_speed if self.__input.get_keyboard_value(self.__keyboard, carb.input.KeyboardInput.LEFT_SHIFT): cur_speed_mod *= self.__speed_modifier_amount if self.__input.get_keyboard_value(self.__keyboard, carb.input.KeyboardInput.LEFT_CONTROL): if self.__speed_modifier_amount != 0: cur_speed_mod /= self.__speed_modifier_amount # Store new speed into proper place if prev_speed_mod != cur_speed_mod: self.__current_adjusted_speed = cur_speed_mod self.__adjust_speed_modifiers(cur_speed_mod, prev_speed_mod) def __process_speed_modifier(self, key: carb.input.KeyboardEventType, is_down: bool): if not self.__speed_modifier_amount: return def speed_adjustment(increase: bool): return self.__speed_modifier_amount if increase else (1 / self.__speed_modifier_amount) prev_speed_mod = self.__current_adjusted_speed cur_speed_mod = prev_speed_mod if key == carb.input.KeyboardInput.LEFT_SHIFT: cur_speed_mod *= speed_adjustment(is_down) if key == carb.input.KeyboardInput.LEFT_CONTROL: cur_speed_mod *= speed_adjustment(not is_down) if prev_speed_mod != cur_speed_mod: self.__current_adjusted_speed = cur_speed_mod self.__adjust_speed_modifiers(cur_speed_mod, prev_speed_mod) return True return False def __on_key(self, e) -> bool: index, value, speed_changed = None, None, False event_type = e.type KeyboardEventType = carb.input.KeyboardEventType if event_type == KeyboardEventType.KEY_PRESS or event_type == KeyboardEventType.KEY_REPEAT: index, value = self.__key_index.get(e.input), 1 if event_type == KeyboardEventType.KEY_PRESS: speed_changed = self.__process_speed_modifier(e.input, True) elif event_type == KeyboardEventType.KEY_RELEASE: index, value = self.__key_index.get(e.input), 0 speed_changed = self.__process_speed_modifier(e.input, False) # If not a navigation key, pass it on to another handler (unless it was a speed-moficiation key). if not index: return not speed_changed canceled = self._cancel() if canceled: value = 0 has_data = self.__values.update(*index, value) if hasattr(self.__model, '_start_external_events'): if has_data: self.__stop_events = True self.__model._start_external_events(True) elif self.__stop_events: self.__stop_events = False self.__model._stop_external_events(True) self.__model.set_floats('fly', self.__values.value) # self.__model._item_changed(None) if canceled: self.destroy() return False def end(self): self.destroy() return None def __del__(self): self.destroy() def destroy(self) -> None: if self.__initial_speed is not None: self.__settings.set('/persistent/app/viewport/camMoveVelocity', self.__initial_speed) self.__initial_speed = None self.__current_adjusted_speed = 1 if self.__model: self.__model.set_floats('fly', None) if self.__stop_events: self.__model._stop_external_events() if self.__keyboard_sub: self.__input.unsubscribe_to_keyboard_events(self.__keyboard, self.__keyboard_sub) self.__keyboard_sub = None self.__keyboard = None # if self.__mouse_sub: # self.__input.unsubscribe_to_mouse_events(self.__mouse, self.__mouse_sub) # self.__mouse_sub = None self.__mouse = None self.__input = None self.__values = None self.__key_index = None def get_keyboard_input(model, walk_through: FlightModeKeyboard = None, end_with_mouse_ended: bool = False, mouse_button=carb.input.MouseInput.RIGHT_BUTTON): iinput = carb.input.acquire_input_interface() app_window = omni.appwindow.get_default_app_window() mouse = app_window.get_mouse() mouse_value = iinput.get_mouse_value(mouse, mouse_button) if mouse_value: if walk_through is None: walk_through = FlightModeKeyboard() walk_through.init(model, iinput, mouse, mouse_button, app_window) elif walk_through and end_with_mouse_ended: walk_through.destroy() walk_through = None return walk_through
10,350
Python
39.913043
156
0.604444
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/math.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['TransformAccumulator'] from pxr import Gf class TransformAccumulator: def __init__(self, initial_xform: Gf.Matrix4d): self.__inverse_xform = initial_xform.GetInverse() if initial_xform else None def get_rotation_axis(self, up_axis: Gf.Vec3d): if up_axis: return self.__inverse_xform.TransformDir(up_axis) else: return self.__inverse_xform.TransformDir(Gf.Vec3d(0, 1, 0)) def get_translation(self, amount: Gf.Vec3d): return Gf.Matrix4d().SetTranslate(amount) def get_tumble(self, degrees: Gf.Vec3d, center_of_interest: Gf.Vec3d, up_axis: Gf.Vec3d): # Rotate around proper scene axis rotate_axis = self.get_rotation_axis(up_axis) # Move to center_of_interest, rotate and move back # No need for identity, all SetXXX methods will do that for us translate = Gf.Matrix4d().SetTranslate(-center_of_interest) # X-Y in ui/mouse are swapped so x-move is rotate around Y, and Y-move is rotate around X rotate_x = Gf.Matrix4d().SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), degrees[1])) rotate_y = Gf.Matrix4d().SetRotate(Gf.Rotation(rotate_axis, degrees[0])) return translate * rotate_x * rotate_y * translate.GetInverse() def get_look(self, degrees: Gf.Vec3d, up_axis: Gf.Vec3d): # Rotate around proper scene axis rotate_axis = self.get_rotation_axis(up_axis) # X-Y in ui/mouse are swapped so x-move is rotate around Y, and Y-move is rotate around X rotate_x = Gf.Matrix4d().SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), degrees[1])) rotate_y = Gf.Matrix4d().SetRotate(Gf.Rotation(rotate_axis, degrees[0])) return rotate_x * rotate_y
2,166
Python
44.145832
97
0.686057
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/usd_camera_manipulator.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .manipulator import CameraManipulatorBase, adjust_center_of_interest from .model import _optional_bool, _flatten_matrix from omni.kit import commands, undo import omni.usd from pxr import Usd, UsdGeom, Sdf, Tf, Gf import carb.profiler import carb.settings import math from typing import List __all__ = ['UsdCameraManipulator'] KIT_COI_ATTRIBUTE = 'omni:kit:centerOfInterest' KIT_LOOKTHROUGH_ATTRIBUTE = 'omni:kit:viewport:lookThrough:target' KIT_CAMERA_LOCK_ATTRIBUTE = 'omni:kit:cameraLock' def _get_context_stage(usd_context_name: str): return omni.usd.get_context(usd_context_name).get_stage() def _compute_local_transform(imageable: UsdGeom.Imageable, time: Usd.TimeCode): # xformable = UsdGeom.Xformable(imageable) # if xformable: # return xformable.GetLocalTransformation(time) world_xform = imageable.ComputeLocalToWorldTransform(time) parent_xform = imageable.ComputeParentToWorldTransform(time) parent_ixform = parent_xform.GetInverse() return (world_xform * parent_ixform), parent_ixform class SRTDecomposer: def __init__(self, prim: Usd.Prim, time: Usd.TimeCode = None): if time is None: time = Usd.TimeCode.Default() xform_srt = omni.usd.get_local_transform_SRT(prim, time) xform_srt = (Gf.Vec3d(xform_srt[0]), Gf.Vec3d(xform_srt[1]), Gf.Vec3i(xform_srt[2]), Gf.Vec3d(xform_srt[3])) self.__start_scale, self.__start_rotation_euler, self.__start_rotation_order, self.__start_translation = xform_srt self.__current_scale, self.__current_rotation_euler, self.__current_rotation_order, self.__current_translation = xform_srt @staticmethod def __repeat(t: float, length: float) -> float: return t - (math.floor(t / length) * length) @staticmethod def __generate_compatible_euler_angles(euler: Gf.Vec3d, rotation_order: Gf.Vec3i) -> List[Gf.Vec3d]: equal_eulers = [euler] mid_order = rotation_order[1] equal = Gf.Vec3d() for i in range(3): if i == mid_order: equal[i] = 180 - euler[i] else: equal[i] = euler[i] + 180 equal_eulers.append(equal) for i in range(3): equal[i] -= 360 equal_eulers.append(equal) return equal_eulers @staticmethod def __find_best_euler_angles(old_rot_vec: Gf.Vec3d, new_rot_vec: Gf.Vec3d, rotation_order: Gf.Vec3i) -> Gf.Vec3d: equal_eulers = SRTDecomposer.__generate_compatible_euler_angles(new_rot_vec, rotation_order) nearest_euler = None for euler in equal_eulers: for i in range(3): euler[i] = SRTDecomposer.__repeat(euler[i] - old_rot_vec[i] + 180.0, 360.0) + old_rot_vec[i] - 180.0 if nearest_euler is None: nearest_euler = euler else: distance_1 = (nearest_euler - old_rot_vec).GetLength() distance_2 = (euler - old_rot_vec).GetLength() if distance_2 < distance_1: nearest_euler = euler return nearest_euler def update(self, xform: Gf.Matrix4d): # Extract new translation self.__current_translation = xform.ExtractTranslation() # Extract new euler rotation ro = self.__start_rotation_order old_s_mtx = Gf.Matrix4d().SetScale(self.__start_scale) old_t_mtx = Gf.Matrix4d().SetTranslate(self.__start_translation) rot_new = (old_s_mtx.GetInverse() * xform * old_t_mtx.GetInverse()).ExtractRotation() axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]]) index_order = Gf.Vec3i() for i in range(3): index_order[ro[i]] = 2 - i new_rot_vec = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]]) new_rot_vec = self.__find_best_euler_angles(self.__start_rotation_euler, new_rot_vec, self.__start_rotation_order) self.__current_rotation_euler = new_rot_vec # Because this is a camera manipulation, we purposefully ignore scale and rotation order changes # They remain constant across the interaction. return self @property def translation(self): return self.__current_translation @property def rotation(self): return self.__current_rotation_euler @property def start_translation(self): return self.__start_translation @property def start_rotation(self): self.__start_rotation_euler class ExternalUsdCameraChange(): def __init__(self, time: Usd.TimeCode): self.__tf_listener = None self.__usd_context_name, self.__prim_path = None, None self.__updates_paused = False self.__kill_external_animation = None self.__time = time def __del__(self): self.destroy() def update(self, model, usd_context_name: str, prim_path: Sdf.Path): self.__kill_external_animation = getattr(model, '_kill_external_animation', None) if self.__kill_external_animation is None: return self.__prim_path = prim_path if usd_context_name != self.__usd_context_name: self.__usd_context_name = usd_context_name if self.__tf_listener: self.__tf_listener.Revoke() self.__tf_listener = None if not self.__tf_listener: try: stage = _get_context_stage(self.__usd_context_name) if stage: self.__tf_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.__object_changed, stage) except ImportError: pass def destroy(self): if self.__tf_listener: self.__tf_listener.Revoke() self.__tf_listener = None self.__usd_context_name, self.__prim_path = None, None self.__kill_external_animation = None @carb.profiler.profile def __object_changed(self, notice, sender): if self.__updates_paused: return if not sender or sender != _get_context_stage(self.__usd_context_name): return for p in notice.GetChangedInfoOnlyPaths(): if (p.IsPropertyPath() and p.GetPrimPath() == self.__prim_path and UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name)): xformable = UsdGeom.Xformable(sender.GetPrimAtPath(self.__prim_path)) xform = _flatten_matrix(xformable.GetLocalTransformation(self.__time)) if xformable else None self.__kill_external_animation(True, xform) break def pause_tracking(self): self.__updates_paused = True def start_tracking(self): self.__updates_paused = False # Base Usd implementation that will set model back to Usd data via kit-commands class UsdCameraManipulator(CameraManipulatorBase): def __init__(self, bindings: dict = None, usd_context_name: str = '', prim_path: Sdf.Path = None, *args, **kwargs): self.__usd_context_name, self.__prim_path = None, None self.__external_change_tracker = None super().__init__(bindings, *args, **kwargs) self._set_context(usd_context_name, prim_path) def _set_context(self, usd_context_name: str, prim_path: Sdf.Path): self.__usd_context_name = usd_context_name self.__prim_path = prim_path self.__srt_decompose = None if prim_path and carb.settings.get_settings().get('/persistent/app/camera/controllerUseSRT'): stage = _get_context_stage(self.__usd_context_name) if stage: prim = stage.GetPrimAtPath(prim_path) if prim: model = self.model time = model.get_as_floats('time') if model else None time = Usd.TimeCode(time[0]) if time else Usd.TimeCode.Default() self.__srt_decompose = SRTDecomposer(prim) def _on_began(self, model, *args, **kwargs): super()._on_began(model, *args, **kwargs) stage = _get_context_stage(self.__usd_context_name) if not stage: # TODO: Could we forward this to adjust the viewport_api->omni.scene.ui ? model.set_ints('disable_tumble', [1]) model.set_ints('disable_look', [1]) model.set_ints('disable_pan', [1]) model.set_ints('disable_zoom', [1]) model.set_ints('disable_fly', [1]) return cam_prim = stage.GetPrimAtPath(self.__prim_path) cam_imageable = UsdGeom.Imageable(cam_prim) if bool(cam_prim) else None if not cam_imageable or not cam_imageable.GetPrim().IsValid(): raise RuntimeError('ViewportCameraManipulator with an invalid UsdGeom.Imageable or Usd.Prim') # Check if we should actaully keep camera at identity and forward our movements to another object local_xform, parent_xform = _compute_local_transform(cam_imageable, Usd.TimeCode.Default()) model.set_floats('initial_transform', _flatten_matrix(local_xform)) model.set_floats('transform', _flatten_matrix(local_xform)) up_axis = UsdGeom.GetStageUpAxis(stage) if up_axis == UsdGeom.Tokens.x: up_axis = Gf.Vec3d(1, 0, 0) elif up_axis == UsdGeom.Tokens.y: up_axis = Gf.Vec3d(0, 1, 0) elif up_axis == UsdGeom.Tokens.z: up_axis = Gf.Vec3d(0, 0, 1) if not bool(carb.settings.get_settings().get("exts/omni.kit.manipulator.camera/forceStageUp")): up_axis = parent_xform.TransformDir(up_axis).GetNormalized() model.set_floats('up_axis', [up_axis[0], up_axis[1], up_axis[2]]) @carb.profiler.profile def __vp1_cooperation(self, prim_path, time, usd_context_name: str, center_of_interest_end): try: from omni.kit import viewport_legacy vp1_iface = viewport_legacy.get_viewport_interface() final_transform, coi_world, pos_world, cam_path = None, None, None, None for vp1_handle in vp1_iface.get_instance_list(): vp1_window = vp1_iface.get_viewport_window(vp1_handle) if not vp1_window or (vp1_window.get_usd_context_name() != usd_context_name): continue if not final_transform: # Save the path's string represnetation cam_path = prim_path.pathString # We need to calculate world-space transform for VP-1, important for nested camera's # TODO: UsdBBoxCache.ComputeWorldBound in compute_path_world_transform doesn't seem to work for non-geometry: # final_transform = omni.usd.get_context(usd_context_name).compute_path_world_transform(cam_path) # final_transform = Gf.Matrix4d(*final_transform) final_transform = UsdGeom.Imageable(prim_path).ComputeLocalToWorldTransform(time) # center_of_interest_end is adjusted and returned for VP-2 center_of_interest_end = Gf.Vec3d(0, 0, -center_of_interest_end.GetLength()) # Pass world center-of-interest to VP-1 set_camera_target coi_world = final_transform.Transform(center_of_interest_end) # Pass world position to VP-1 set_camera_position pos_world = final_transform.Transform(Gf.Vec3d(0, 0, 0)) # False for first call to set target only, True for second to trigger radius re-calculation # This isn't particuarly efficient; but 'has to be' for now due to some Viewport-1 internals vp1_window.set_camera_target(cam_path, coi_world[0], coi_world[1], coi_world[2], False) vp1_window.set_camera_position(cam_path, pos_world[0], pos_world[1], pos_world[2], True) except Exception: pass return center_of_interest_end @carb.profiler.profile def on_model_updated(self, item): # Handle case of inertia being applied though a new stage-open usd_context_name = self.__usd_context_name if usd_context_name is None or _get_context_stage(usd_context_name) is None: return model = self.model prim_path = self.__prim_path time = model.get_as_floats('time') time = Usd.TimeCode(time[0]) if time else Usd.TimeCode.Default() undoable = False def run_command(cmd_name, **kwargs): carb.profiler.begin(1, cmd_name) if undoable: commands.execute(cmd_name, **kwargs) else: commands.create(cmd_name, **kwargs).do() carb.profiler.end(1) try: if item == model.get_item('transform'): if self.__external_change_tracker: self.__external_change_tracker.update(model, usd_context_name, prim_path) self.__external_change_tracker.pause_tracking() # We are undoable on the final event if undo hasn't been disabled on the model undoable = _optional_bool(self.model, 'interaction_ended') and not _optional_bool(self.model, 'disable_undo') if undoable: undo.begin_group() final_transform = Gf.Matrix4d(*model.get_as_floats('transform')) initial_transform = model.get_as_floats('initial_transform') initial_transform = Gf.Matrix4d(*initial_transform) if initial_transform else initial_transform had_transform_at_key = _optional_bool(self.model, 'had_transform_at_key') if self.__srt_decompose: srt_deompose = self.__srt_decompose.update(final_transform) run_command( 'TransformPrimSRTCommand', path=prim_path, new_translation=srt_deompose.translation, new_rotation_euler=srt_deompose.rotation, # new_scale=srt_deompose.scale, # new_rotation_order=srt_deompose.rotation_order, old_translation=srt_deompose.start_translation, old_rotation_euler=srt_deompose.start_rotation, # old_rotation_order=srt_deompose.start_rotation_order, # old_scale=srt_deompose.start_scale, time_code=time, had_transform_at_key=had_transform_at_key, usd_context_name=usd_context_name ) else: run_command( 'TransformPrimCommand', path=prim_path, new_transform_matrix=final_transform, old_transform_matrix=initial_transform, time_code=time, had_transform_at_key=had_transform_at_key, usd_context_name=usd_context_name ) center_of_interest_start, center_of_interest_end = adjust_center_of_interest(model, initial_transform, final_transform) if center_of_interest_start and center_of_interest_end: # See if we need to adjust center-of-interest to cooperate with Viewport-1, which can only do a 1 dimensional version center_of_interest_end = self.__vp1_cooperation(prim_path, time, usd_context_name, center_of_interest_end) run_command( 'ChangePropertyCommand', prop_path=prim_path.AppendProperty(KIT_COI_ATTRIBUTE), value=center_of_interest_end, prev=center_of_interest_start, usd_context_name=usd_context_name ) elif item == model.get_item('current_aperture'): # We are undoable on the final event if undo hasn't been disabled on the model undoable = _optional_bool(self.model, 'interaction_ended') and not _optional_bool(self.model, 'disable_undo') if undoable: undo.begin_group() initial_aperture = model.get_as_floats('initial_aperture') current_aperture = model.get_as_floats('current_aperture') prop_names = ('horizontalAperture', 'verticalAperture') for initial_value, current_value, prop_name in zip(initial_aperture, current_aperture, prop_names): run_command( 'ChangePropertyCommand', prop_path=prim_path.AppendProperty(prop_name), value=current_value, prev=initial_value, timecode=time, usd_context_name=usd_context_name ) elif item == model.get_item('interaction_animating'): interaction_animating = model.get_as_ints(item) if interaction_animating and interaction_animating[0]: if not self.__external_change_tracker: self.__external_change_tracker = ExternalUsdCameraChange(time) self.__external_change_tracker.update(model, usd_context_name, prim_path) self.__external_change_tracker.pause_tracking() elif self.__external_change_tracker: self.__external_change_tracker.destroy() self.__external_change_tracker = None finally: if undoable: undo.end_group() if self.__external_change_tracker: self.__external_change_tracker.start_tracking()
18,397
Python
44.539604
137
0.594717
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/model.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['CameraManipulatorModel'] from omni.ui import scene as sc from pxr import Gf from typing import Any, Callable, List, Sequence, Union from .math import TransformAccumulator from .animation import AnimationEventStream import time import carb.profiler import carb.settings ALMOST_ZERO = 1.e-4 def _flatten_matrix(matrix: Gf.Matrix4d): return [matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3], matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3], matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]] def _optional_floats(model: sc.AbstractManipulatorModel, item: str, default_value: Sequence[float] = None): item = model.get_item(item) if item: values = model.get_as_floats(item) if values: return values return default_value def _optional_float(model: sc.AbstractManipulatorModel, item: str, default_value: float = 0): item = model.get_item(item) if item: values = model.get_as_floats(item) if values: return values[0] return default_value def _optional_int(model: sc.AbstractManipulatorModel, item: str, default_value: int = 0): item = model.get_item(item) if item: values = model.get_as_ints(item) if values: return values[0] return default_value def _optional_bool(model: sc.AbstractManipulatorModel, item: str, default_value: bool = False): return _optional_int(model, item, default_value) def _accumulate_values(model: sc.AbstractManipulatorModel, name: str, x: float, y: float, z: float): item = model.get_item(name) if item: values = model.get_as_floats(item) model.set_floats(item, [values[0] + x, values[1] + y, values[2] + z] if values else [x, y, z]) return item def _scalar_or_vector(value: Sequence[float]): acceleration_len = len(value) if acceleration_len == 1: return Gf.Vec3d(value[0], value[0], value[0]) if acceleration_len == 2: return Gf.Vec3d(value[0], value[1], 1) return Gf.Vec3d(value[0], value[1], value[2]) class ModelState: def __reduce_value(self, vec: Gf.Vec3d): if vec and (vec[0] == 0 and vec[1] == 0 and vec[2] == 0): return None return vec def __expand_value(self, vec: Gf.Vec3d, alpha: float): if vec: vec = tuple(v * alpha for v in vec) if vec[0] != 0 or vec[1] != 0 or vec[2] != 0: return vec return None def __init__(self, tumble: Gf.Vec3d = None, look: Gf.Vec3d = None, move: Gf.Vec3d = None, fly: Gf.Vec3d = None): self.__tumble = self.__reduce_value(tumble) self.__look = self.__reduce_value(look) self.__move = self.__reduce_value(move) self.__fly = self.__reduce_value(fly) def any_values(self): return self.__tumble or self.__look or self.__move or self.__fly def apply_alpha(self, alpha: float): return (self.__expand_value(self.__tumble, alpha), self.__expand_value(self.__look, alpha), self.__expand_value(self.__move, alpha), self.__expand_value(self.__fly, alpha)) @property def tumble(self): return self.__tumble @property def look(self): return self.__look @property def move(self): return self.__move @property def fly(self): return self.__fly class Velocity: def __init__(self, acceleration: Sequence[float], dampening: Sequence[float] = (10,), clamp_dt: float = 0.15): self.__velocity = Gf.Vec3d(0, 0, 0) self.__acceleration_rate = _scalar_or_vector(acceleration) self.__dampening = _scalar_or_vector(dampening) self.__clamp_dt = clamp_dt def apply(self, value: Gf.Vec3d, dt: float, alpha: float = 1): ### XXX: We're not locked to anything and event can come in spuriously ### So clamp the max delta-time to a value (if this is to high, it can introduces lag) if (dt > 0) and (dt > self.__clamp_dt): dt = self.__clamp_dt if value: acceleration = Gf.CompMult(value, self.__acceleration_rate) * alpha self.__velocity += acceleration * dt damp_factor = tuple(max(min(v * dt, 0.75), 0) for v in self.__dampening) self.__velocity += Gf.CompMult(-self.__velocity, Gf.Vec3d(*damp_factor)) if Gf.Dot(self.__velocity, self.__velocity) < ALMOST_ZERO: self.__velocity = Gf.Vec3d(0, 0, 0) return self.__velocity * dt @staticmethod def create(model: sc.AbstractManipulatorModel, mode: str, clamp_dt: float = 0.15): acceleration = _optional_floats(model, f'{mode}_acceleration') if acceleration is None: return None dampening = _optional_floats(model, f'{mode}_dampening') return Velocity(acceleration, dampening or (10, 10, 10), clamp_dt) class Decay: def __init__(self): pass def apply(self, value: Gf.Vec3d, dt: float, alpha: float = 1): return value * alpha if value else None class CameraManipulatorModel(sc.AbstractManipulatorModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__settings = carb.settings.get_settings() self.__items = { # 'view': (sc.AbstractManipulatorItem(), 16), 'projection': (sc.AbstractManipulatorItem(), 16), 'transform': (sc.AbstractManipulatorItem(), 16), 'orthographic': (sc.AbstractManipulatorItem(), 1), 'center_of_interest': (sc.AbstractManipulatorItem(), 3), # Accumulated movement 'move': (sc.AbstractManipulatorItem(), 3), 'tumble': (sc.AbstractManipulatorItem(), 3), 'look': (sc.AbstractManipulatorItem(), 3), 'fly': (sc.AbstractManipulatorItem(), 3), # Optional speed for world (pan, truck) and rotation (tumble, look) operation # Can be set individually for x, y, z or as a scalar 'world_speed': (sc.AbstractManipulatorItem(), (3, 1)), 'move_speed': (sc.AbstractManipulatorItem(), (3, 1)), 'rotation_speed': (sc.AbstractManipulatorItem(), (3, 1)), 'tumble_speed': (sc.AbstractManipulatorItem(), (3, 1)), 'look_speed': (sc.AbstractManipulatorItem(), (3, 1)), 'fly_speed': (sc.AbstractManipulatorItem(), (3, 1)), # Inertia enabled, and amoint of second to apply it for 'inertia_enabled': (sc.AbstractManipulatorItem(), 1), 'inertia_seconds': (sc.AbstractManipulatorItem(), 1), # Power of ineratia decay (for an ease-out) 0 and 1 are linear 'inertia_decay': (sc.AbstractManipulatorItem(), 1), # Acceleration and dampening values 'tumble_acceleration': (sc.AbstractManipulatorItem(), (3, 1)), 'look_acceleration': (sc.AbstractManipulatorItem(), (3, 1)), 'move_acceleration': (sc.AbstractManipulatorItem(), (3, 1)), 'fly_acceleration': (sc.AbstractManipulatorItem(), (3, 1)), 'tumble_dampening': (sc.AbstractManipulatorItem(), (3, 1)), 'look_dampening': (sc.AbstractManipulatorItem(), (3, 1)), 'move_dampening': (sc.AbstractManipulatorItem(), (3, 1)), 'fly_dampening': (sc.AbstractManipulatorItem(), (3, 1)), 'fly_mode_lock_view': (sc.AbstractManipulatorItem(), 1), # Decimal precision of rotation operations 'rotation_precision': (sc.AbstractManipulatorItem(), 1), # Mapping of units from input to world 'ndc_scale': (sc.AbstractManipulatorItem(), 3), # Optional int-as-bool items 'disable_pan': (sc.AbstractManipulatorItem(), 1), 'disable_tumble': (sc.AbstractManipulatorItem(), 1), 'disable_look': (sc.AbstractManipulatorItem(), 1), 'disable_zoom': (sc.AbstractManipulatorItem(), 1), 'disable_fly': (sc.AbstractManipulatorItem(), 1), 'disable_undo': (sc.AbstractManipulatorItem(), 1), 'object_centric_movement': (sc.AbstractManipulatorItem(), 1), 'viewport_id': (sc.AbstractManipulatorItem(), 1), # USD specific concepts 'up_axis': (sc.AbstractManipulatorItem(), 3), 'current_aperture': (sc.AbstractManipulatorItem(), 2), 'initial_aperture': (sc.AbstractManipulatorItem(), 2), 'had_transform_at_key': (sc.AbstractManipulatorItem(), 1), 'time': (sc.AbstractManipulatorItem(), 1), # Internal signal for final application of the changes, use disable_undo for user-control 'interaction_ended': (sc.AbstractManipulatorItem(), 1), # Signal that undo should be applied 'interaction_active': (sc.AbstractManipulatorItem(), 1), # Signal that a gesture is manipualting camera 'interaction_animating': (sc.AbstractManipulatorItem(), 1), # Signal that an animation is manipulating camera 'center_of_interest_start': (sc.AbstractManipulatorItem(), 3), 'center_of_interest_picked': (sc.AbstractManipulatorItem(), 3), 'adjust_center_of_interest': (sc.AbstractManipulatorItem(), 1), 'initial_transform': (sc.AbstractManipulatorItem(), 16), } self.__values = {item: [] for item, _ in self.__items.values()} self.__values[self.__items.get('look_speed')[0]] = [1, 0.5] self.__values[self.__items.get('fly_speed')[0]] = [1] self.__values[self.__items.get('inertia_seconds')[0]] = [0.5] self.__values[self.__items.get('inertia_enabled')[0]] = [0] # self.__values[self.__items.get('interaction_active')[0]] = [0] # self.__values[self.__items.get('interaction_animating')[0]] = [0] self.__settings_changed_subs = [] def read_inertia_setting(mode: str, setting_scale: float): global_speed_key = f'/persistent/exts/omni.kit.manipulator.camera/{mode}Speed' subscribe = self.__settings.subscribe_to_tree_change_events self.__settings_changed_subs.append( subscribe(global_speed_key, lambda *args, **kwargs: self.__speed_setting_changed(*args, **kwargs, mode=mode, setting_scale=setting_scale)), ) self.__speed_setting_changed(None, None, carb.settings.ChangeEventType.CHANGED, mode, setting_scale) accel = self.__settings.get(f'/exts/omni.kit.manipulator.camera/{mode}Acceleration') damp = self.__settings.get(f'/exts/omni.kit.manipulator.camera/{mode}Dampening') if accel is None or damp is None: if accel is None and damp is not None: pass elif damp is None and accel is not None: pass return self.__values[self.__items.get(f'{mode}_acceleration')[0]] = [accel] self.__values[self.__items.get(f'{mode}_dampening')[0]] = [damp] read_inertia_setting('fly', 1) read_inertia_setting('look', 180) read_inertia_setting('move', 1) read_inertia_setting('tumble', 360) self.__settings_changed_subs.append( self.__settings.subscribe_to_node_change_events('/persistent/exts/omni.kit.manipulator.camera/flyViewLock', self.__fly_mode_lock_view_changed) ) self.__fly_mode_lock_view_changed(None, carb.settings.ChangeEventType.CHANGED) self.__animation_key = id(self) self.__flight_inertia_active = False self.__last_applied = None # Faster access for key-values looked up during animation self.__move = self.__items.get('move')[0] self.__tumble = self.__items.get('tumble')[0] self.__look = self.__items.get('look')[0] self.__fly = self.__items.get('fly')[0] self.__transform = self.__items.get('transform')[0] self.__projection = self.__items.get('projection')[0] self.__center_of_interest = self.__items.get('center_of_interest')[0] self.__adjust_center_of_interest = self.__items.get('adjust_center_of_interest')[0] self.__inertia_enabled = self.__items.get('inertia_enabled')[0] self.__inertia_seconds = self.__items.get('inertia_seconds')[0] self.__tumble_velocity = None self.__look_velocity = None self.__move_velocity = None self.__fly_velocity = None self.__intertia_state = None self.__anim_stream = None self.__anim_stopped = 0 self.__mode = None def __speed_setting_changed(self, tree_item: carb.dictionary.Item, changed_item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType, mode: str, setting_scale: float = 1): if tree_item is None: speed = self.__settings.get(f'/persistent/exts/omni.kit.manipulator.camera/{mode}Speed') else: speed = tree_item.get_dict() if speed: if (not isinstance(speed, tuple)) and (not isinstance(speed, list)): speed = [speed] self.__values[self.__items.get(f'{mode}_speed')[0]] = [float(x) / setting_scale for x in speed] def __fly_mode_lock_view_changed(self, changed_item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): model_key = self.__items.get('fly_mode_lock_view')[0] setting_key = '/persistent/exts/omni.kit.manipulator.camera/flyViewLock' self.__values[model_key] = [self.__settings.get(setting_key)] def __del__(self): self.destroy() def destroy(self): self.__destroy_animation() if self.__settings and self.__settings_changed_subs: for subscription in self.__settings_changed_subs: self.__settings.unsubscribe_to_change_events(subscription) self.__settings_changed_subs = None self.__settings = None def __destroy_animation(self): if self.__anim_stream: self.__anim_stream.destroy() self.__anim_stream = None self.__mark_animating(0) def __validate_arguments(self, name: Union[str, sc.AbstractManipulatorItem], values: Sequence[Union[int, float]] = None) -> sc.AbstractManipulatorItem: if isinstance(name, sc.AbstractManipulatorItem): return name item, expected_len = self.__items.get(name, (None, None)) if item is None: raise KeyError(f"CameraManipulatorModel doesn't understand values of {name}") if values and (len(values) != expected_len): if (not isinstance(expected_len, tuple)) or (not len(values) in expected_len): raise ValueError(f"CameraManipulatorModel {name} takes {expected_len} values, got {len(values)}") return item def get_item(self, name: str) -> sc.AbstractManipulatorItem(): return self.__items.get(name, (None, None))[0] def set_ints(self, item: Union[str, sc.AbstractManipulatorItem], values: Sequence[int]): item = self.__validate_arguments(item, values) self.__values[item] = values def set_floats(self, item: Union[str, sc.AbstractManipulatorItem], values: Sequence[int]): item = self.__validate_arguments(item, values) self.__values[item] = values def get_as_ints(self, item: Union[str, sc.AbstractManipulatorItem]) -> List[int]: item = self.__validate_arguments(item) return self.__values[item] def get_as_floats(self, item: Union[str, sc.AbstractManipulatorItem]) -> List[float]: item = self.__validate_arguments(item) return self.__values[item] @carb.profiler.profile def _item_changed(self, item: Union[str, sc.AbstractManipulatorItem], delta_time: float = None, alpha: float = None): # item == None is the signal to push all model values into a final matrix at 'transform' if item is not None: if not isinstance(item, sc.AbstractManipulatorItem): item = self.__items.get(item) item = item[0] if item else None # Either of these adjust the pixel-to-world mapping if item == self.__center_of_interest or item == self.__projection: self.calculate_pixel_to_world(Gf.Vec3d(self.get_as_floats(self.__center_of_interest))) super()._item_changed(item) return if self.__anim_stream and delta_time is None: # If this is the end of an interaction (mouse up), return and let animation/inertia continue as is. if _optional_int(self, 'interaction_ended', 0) or (self.__intertia_state is None): return # If inertia is active, look values should be passed through; so as camera is drifting the look-rotation # is still applied. If there is no look applied, then inertia is killed for any other movement. look = self.get_as_floats(self.__look) if self.__flight_inertia_active else None if look: # Destroy the look-velocity correction; otherwise look wil lag as camera drifts through inertia self.__look_velocity = None else: self._kill_external_animation(False) return tumble, look, move, fly = None, None, None, None if item is None or item == self.__tumble: tumble = self.get_as_floats(self.__tumble) if tumble: tumble = Gf.Vec3d(*tumble) self.set_floats(self.__tumble, None) if item is None or item == self.__look: look = self.get_as_floats(self.__look) if look: look = Gf.Vec3d(*look) self.set_floats(self.__look, None) if item is None or item == self.__move: move = self.get_as_floats(self.__move) if move: move = Gf.Vec3d(*move) self.set_floats(self.__move, None) if item is None or item == self.__fly: fly = self.get_as_floats(self.__fly) if fly: fly = Gf.Vec3d(*fly) fly_speed = _optional_floats(self, 'fly_speed') if fly_speed: if len(fly_speed) == 1: fly_speed = Gf.Vec3d(fly_speed[0], fly_speed[0], fly_speed[0]) else: fly_speed = Gf.Vec3d(*fly_speed) # Flight speed is multiplied by 5 for VP-1 compatability fly = Gf.CompMult(fly, fly_speed * 5) self.__last_applied = ModelState(tumble, look, move, fly) if (delta_time is not None) or self.__last_applied.any_values(): self._apply_state(self.__last_applied, delta_time, alpha) else: super()._item_changed(item) def calculate_pixel_to_world(self, pos): projection = Gf.Matrix4d(*self.get_as_floats(self.__projection)) top_left, bot_right = self._calculate_pixel_to_world(pos, projection, projection.GetInverse()) x = top_left[0] - bot_right[0] y = top_left[1] - bot_right[1] # For NDC-z we don't want to use the clip range which could be huge # So avergae the X-Y scales instead self.set_floats('ndc_scale', [x, y, (x + y) * 0.5]) def _calculate_pixel_to_world(self, pos, projection, inv_projection): ndc = projection.Transform(pos) top_left = inv_projection.Transform(Gf.Vec3d(-1, -1, ndc[2])) bot_right = inv_projection.Transform(Gf.Vec3d(1, 1, ndc[2])) return (top_left, bot_right) def _set_animation_key(self, key: str): self.__animation_key = key def _start_external_events(self, flight_mode: bool = False): # If flight mode is already doing inertia, do nothing. # This is for the case where right-click for WASD navigation end with a mouse up and global inertia is enabled. if self.__flight_inertia_active and not flight_mode: return False # Quick check that inertia is enabled for any mode other than flight if not flight_mode: inertia_modes = self.__settings.get('/exts/omni.kit.manipulator.camera/inertiaModesEnabled') len_inertia_enabled = len(inertia_modes) if inertia_modes else 0 if len_inertia_enabled == 0: return if len_inertia_enabled == 1: self.__inertia_modes = [inertia_modes[0], 0, 0, 0] elif len_inertia_enabled == 2: self.__inertia_modes = [inertia_modes[0], inertia_modes[1], 0, 0] elif len_inertia_enabled == 3: self.__inertia_modes = [inertia_modes[0], inertia_modes[1], inertia_modes[2], 0] else: self.__inertia_modes = inertia_modes else: self.__inertia_modes = [1, 0, 1, 0] # Setup the animation state self.__anim_stopped = 0 self.__intertia_state = None self.__flight_inertia_active = flight_mode # Pull more infor from inertai settings fro what is to be created create_tumble = self.__inertia_modes[1] create_look = flight_mode or self.__inertia_modes[2] create_move = self.__inertia_modes[3] create_fly = flight_mode if self.__anim_stream: # Handle case where key was down, then lifted, then pushed again by recreating look_velocity / flight correction. create_tumble = create_tumble and not self.__tumble_velocity create_look = create_look and not self.__look_velocity create_move = create_move and not self.__move_velocity create_fly = False clamp_dt = self.__settings.get('/ext/omni.kit.manipulator.camera/clampUpdates') or 0.15 if create_look: self.__look_velocity = Velocity.create(self, 'look', clamp_dt) if create_tumble: self.__tumble_velocity = Velocity.create(self, 'tumble', clamp_dt) if create_move: self.__move_velocity = Velocity.create(self, 'move', clamp_dt) if create_fly: self.__fly_velocity = Velocity.create(self, 'fly', clamp_dt) # If any velocities are valid, then setup an animation to apply it. if self.__tumble_velocity or self.__look_velocity or self.__move_velocity or self.__fly_velocity: # Only set up the animation in flight-mode, let _stop_external_events set it up otherwise if flight_mode and not self.__anim_stream: self.__anim_stream = AnimationEventStream.get_instance() self.__anim_stream.add_animation(self._apply_state_tick, self.__animation_key) return True if self.__anim_stream: anim_stream, self.__anim_stream = self.__anim_stream, None anim_stream.destroy() return False def _stop_external_events(self, flight_mode: bool = False): # Setup animation for inertia in non-flight mode if not flight_mode and not self.__anim_stream: tumble, look, move = None, None, None if self.__last_applied and (self.__tumble_velocity or self.__look_velocity or self.__move_velocity or self.__fly_velocity): if self.__tumble_velocity and self.__inertia_modes[1]: tumble = self.__last_applied.tumble if self.__look_velocity and self.__inertia_modes[2]: look = self.__last_applied.look if self.__move_velocity and self.__inertia_modes[3]: move = self.__last_applied.move if tumble or look or move: self.__last_applied = ModelState(tumble, look, move, self.__last_applied.fly) self.__anim_stream = AnimationEventStream.get_instance() self.__anim_stream.add_animation(self._apply_state_tick, self.__animation_key) else: self.__tumble_velocity = None self.__look_velocity = None self.__move_velocity = None self.__fly_velocity = None self.__intertia_state = None return self.__anim_stopped = time.time() self.__intertia_state = self.__last_applied self.__mark_animating(1) def __mark_animating(self, interaction_animating: int): item, _ = self.__items.get('interaction_animating', (None, None)) self.set_ints(item, [interaction_animating]) super()._item_changed(item) def _apply_state_time(self, dt: float, apply_fn: Callable): alpha = 1 if self.__anim_stopped: now = time.time() inertia_enabled = _optional_int(self, 'inertia_enabled', 0) inertia_seconds = _optional_float(self, 'inertia_seconds', 0) if inertia_enabled and inertia_seconds > 0: alpha = 1.0 - ((now - self.__anim_stopped) / inertia_seconds) if alpha > ALMOST_ZERO: decay = self.__settings.get('/exts/omni.kit.manipulator.camera/inertiaDecay') decay = _optional_int(self, 'inertia_decay', decay) alpha = pow(alpha, decay) if decay else 1 else: alpha = 0 else: alpha = 0 if alpha == 0: if self.__anim_stream: anim_stream, self.__anim_stream = self.__anim_stream, None anim_stream.destroy() self.set_ints('interaction_ended', [1]) apply_fn(dt * alpha, 1) if alpha == 0: self.set_ints('interaction_ended', [0]) self.__mark_animating(0) self.__tumble_velocity = None self.__look_velocity = None self.__move_velocity = None self.__fly_velocity = None self.__intertia_state = None self.__flight_inertia_active = False return False return True def _apply_state_tick(self, dt: float = None): keep_anim = True istate = self.__intertia_state if istate: if self.__flight_inertia_active: # See _item_changed, but during an inertia move, look should still be applied (but without any velocity) look = self.get_as_floats(self.__look) if look: self.set_floats(self.__look, None) state = ModelState(None, look, None, istate.fly) else: tumble = (self.get_as_floats(self.__tumble) or istate.tumble) if self.__inertia_modes[1] else None look = (self.get_as_floats(self.__look) or istate.look) if self.__inertia_modes[2] else None move = (self.get_as_floats(self.__move) or istate.move) if self.__inertia_modes[3] else None state = ModelState(tumble, look, move) keep_anim = self._apply_state_time(dt, lambda dt, alpha: self._apply_state(state, dt, alpha)) else: keep_anim = self._apply_state_time(dt, lambda dt, alpha: self._item_changed(None, dt, alpha)) if not keep_anim and self.__anim_stream: self.__destroy_animation() def _kill_external_animation(self, kill_stream: bool = True, initial_transform = None): if kill_stream: self.__destroy_animation() # self._stop_external_events() self.__tumble_velocity = None self.__look_velocity = None self.__move_velocity = None self.__fly_velocity = None self.__intertia_state = None self.__flight_inertia_active = False # Reset internal transform if provided if initial_transform: self.set_floats('transform', initial_transform) self.set_floats('initial_transform', initial_transform) @carb.profiler.profile def _apply_state(self, state: ModelState, dt: float = None, alpha: float = None): up_axis = _optional_floats(self, 'up_axis') rotation_precision = _optional_int(self, 'rotation_precision', 5) last_transform = Gf.Matrix4d(*self.get_as_floats(self.__transform)) xforms = TransformAccumulator(last_transform) center_of_interest = None tumble = state.tumble if self.__tumble_velocity: tumble = self.__tumble_velocity.apply(tumble, dt, alpha) if tumble: center_of_interest = Gf.Vec3d(*self.get_as_floats(self.__center_of_interest)) tumble = Gf.Vec3d(round(tumble[0], rotation_precision), round(tumble[1], rotation_precision), round(tumble[2], rotation_precision)) final_xf = xforms.get_tumble(tumble, center_of_interest, up_axis) else: final_xf = Gf.Matrix4d(1) look = state.look if self.__look_velocity: look = self.__look_velocity.apply(look, dt, alpha) if look: look = Gf.Vec3d(round(look[0], rotation_precision), round(look[1], rotation_precision), round(look[2], rotation_precision)) final_xf = final_xf * xforms.get_look(look, up_axis) move = state.move if self.__move_velocity: move = self.__move_velocity.apply(move, dt, alpha) if move: final_xf = xforms.get_translation(move) * final_xf adjust_coi = move[2] != 0 else: adjust_coi = False fly = None if _optional_int(self, 'disable_fly', 0) else state.fly if self.__fly_velocity: fly = self.__fly_velocity.apply(fly, dt, alpha) if fly: if _optional_bool(self, 'fly_mode_lock_view', False): decomp_rot = last_transform.ExtractRotation().Decompose(Gf.Vec3d.ZAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis()) rot_z = Gf.Rotation(Gf.Vec3d.ZAxis(), decomp_rot[0]) rot_y = Gf.Rotation(Gf.Vec3d.YAxis(), decomp_rot[1]) rot_x = Gf.Rotation(Gf.Vec3d.XAxis(), decomp_rot[2]) last_transform_tr = Gf.Matrix4d().SetTranslate(last_transform.ExtractTranslation()) last_transform_rt_0 = Gf.Matrix4d().SetRotate(rot_x) last_transform_rt_1 = Gf.Matrix4d().SetRotate(rot_y * rot_z) if up_axis[2]: fly[1], fly[2] = -fly[2], fly[1] elif Gf.Dot(Gf.Vec3d.ZAxis(), last_transform.TransformDir((0, 0, 1))) < 0: fly[1], fly[2] = -fly[1], -fly[2] flight_xf = xforms.get_translation(fly) last_transform = last_transform_rt_0 * flight_xf * last_transform_rt_1 * last_transform_tr else: final_xf = xforms.get_translation(fly) * final_xf transform = final_xf * last_transform # If zooming out in Z, adjust the center-of-interest and pixel-to-world in 'ndc_scale' self.set_ints(self.__adjust_center_of_interest, [adjust_coi]) if adjust_coi: center_of_interest = center_of_interest or Gf.Vec3d(*self.get_as_floats(self.__center_of_interest)) coi = Gf.Matrix4d(*self.get_as_floats('initial_transform')).Transform(center_of_interest) coi = transform.GetInverse().Transform(coi) self.calculate_pixel_to_world(coi) self.set_floats(self.__transform, _flatten_matrix(transform)) super()._item_changed(self.__transform) def _broadcast_mode(self, mode: str): if mode == self.__mode: return viewport_id = _optional_int(self, 'viewport_id', None) if viewport_id is None: return # Send a signal that contains the viewport_id and mode (carb requires a homogenous array, so as strings) self.__settings.set("/exts/omni.kit.manipulator.camera/viewportMode", [str(viewport_id), mode]) self.__mode = mode
32,559
Python
45.781609
143
0.589729
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/manipulator.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['CameraManipulatorBase', 'adjust_center_of_interest'] from omni.ui import scene as sc from .gestures import build_gestures from .model import CameraManipulatorModel, _optional_bool, _flatten_matrix from pxr import Gf # Common math to adjust the center-of-interest def adjust_center_of_interest(model: CameraManipulatorModel, initial_transform: Gf.Matrix4d, final_transform: Gf.Matrix4d): # Adjust the center-of-interest if requested. # For object-centric movement we always adjust it if an object was hit object_centric = _optional_bool(model, 'object_centric_movement') coi_picked = model.get_as_floats('center_of_interest_picked') if object_centric else False adjust_center_of_interest = (object_centric and coi_picked) or _optional_bool(model, 'adjust_center_of_interest') if not adjust_center_of_interest: return None, None # When adjusting the center of interest we'll operate on a direction and length (in camera-space) # Which helps to not introduce -drift- as we jump through the different spaces to update it. # Final camera position world_cam_pos = final_transform.Transform(Gf.Vec3d(0, 0, 0)) # center_of_interest_start is in camera-space center_of_interest_start = Gf.Vec3d(*model.get_as_floats('center_of_interest_start')) # Save the direction center_of_interest_dir = center_of_interest_start.GetNormalized() if coi_picked: # Keep original center-of-interest direction, but adjust its length to the picked position world_coi = Gf.Vec3d(coi_picked[0], coi_picked[1], coi_picked[2]) # TODO: Setting to keep subsequent movement focused on screen-center or move it to the object. if False: # Save the center-of-interest to the hit-point by adjusting direction center_of_interest_dir = final_transform.GetInverse().Transform(world_coi).GetNormalized() else: # Move center-of-interest to world space at initial transform world_coi = initial_transform.Transform(center_of_interest_start) # Now get the length between final camera-position and the world-space-coi, # and apply that to the direction. center_of_interest_end = center_of_interest_dir * (world_cam_pos - world_coi).GetLength() return center_of_interest_start, center_of_interest_end # Base class, resposible for building up the gestures class CameraManipulatorBase(sc.Manipulator): def __init__(self, bindings: dict = None, model: sc.AbstractManipulatorModel = None, *args, **kwargs): super().__init__(*args, **kwargs) self._screen = None # Provide some defaults self.model = model or CameraManipulatorModel() self.bindings = bindings # Provide a slot for a user to fill in with a GestureManager but don't use anything by default self.manager = None self.gestures = [] self.__transform = None self.__gamepad = None def _on_began(self, model: CameraManipulatorModel, *args, **kwargs): pass def on_build(self): # Need to hold a reference to this or the sc.Screen would be destroyed when out of scope self.__transform = sc.Transform() with self.__transform: self._screen = sc.Screen(gestures=self.gestures or build_gestures(self.model, self.bindings, self.manager, self._on_began)) def destroy(self): if self.__gamepad: self.__gamepad.destroy() self.__gamepad = None if self.__transform: self.__transform.clear() self.__transform = None self._screen = None if hasattr(self.model, 'destroy'): self.model.destroy() @property def gamepad_enabled(self) -> bool: return self.__gamepad is not None @gamepad_enabled.setter def gamepad_enabled(self, value: bool): if value: if not self.__gamepad: from .gamepad import GamePadController self.__gamepad = GamePadController(self) elif self.__gamepad: self.__gamepad.destroy() self.__gamepad = None # We have all the imoorts already, so provide a simple omni.ui.scene camera manipulator that one can use. # Takes an omni.ui.scene view and center-of-interest and applies model changes to that view class SceneViewCameraManipulator(CameraManipulatorBase): def __init__(self, center_of_interest, *args, **kwargs): super().__init__(*args, **kwargs) self.__center_of_interest = center_of_interest def _on_began(self, model: CameraManipulatorModel, mouse): model.set_floats('center_of_interest', [self.__center_of_interest[0], self.__center_of_interest[1], self.__center_of_interest[2]]) if _optional_bool(model, 'orthographic'): model.set_ints('disable_tumble', [1]) model.set_ints('disable_look', [1]) def on_model_updated(self, item): model = self.model if item == model.get_item('transform'): final_transform = Gf.Matrix4d(*model.get_as_floats(item)) initial_transform = Gf.Matrix4d(*model.get_as_floats('initial_transform')) # Adjust our center-of-interest coi_start, coi_end = adjust_center_of_interest(model, initial_transform, final_transform) if coi_end: self.__center_of_interest = coi_end # omni.ui.scene.SceneView.CameraModel expects 'view', but we operate on 'transform' # The following will push our transform changes into the SceneView.model.view sv_model = self.scene_view.model view = sv_model.get_item('view') sv_model.set_floats(view, _flatten_matrix(final_transform.GetInverse())) sv_model._item_changed(view)
6,222
Python
46.503816
138
0.674381
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/gesturebase.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['CameraGestureBase'] from omni.ui import scene as sc from .model import _accumulate_values, _optional_bool, _optional_floats, _flatten_matrix from .flight_mode import get_keyboard_input import carb.settings from pxr import Gf import time from typing import Callable, Sequence # Base class for camera transform manipulation/gesture # class CameraGestureBase(sc.DragGesture): def __init__(self, model: sc.AbstractManipulatorModel, configure_model: Callable = None, name: str = None, *args, **kwargs): super().__init__(*args, **kwargs) self.name = name if name else self.__class__.__name__ self.model = model # XXX: Need a manipulator on_began method self.__configure_model = configure_model self.__prev_mouse = None self.__prev_mouse_time = None self.__keyboard = None self.__fly_active = None def destroy(self): self.model = None self._disable_flight() super().destroy() @property def center_of_interest(self): return Gf.Vec3d(self.model.get_as_floats('center_of_interest')) @property def initial_transform(self): return Gf.Matrix4d(*self.model.get_as_floats('initial_transform')) @property def last_transform(self): return Gf.Matrix4d(*self.model.get_as_floats('transform')) @property def projection(self): return Gf.Matrix4d(*self.model.get_as_floats('projection')) @property def orthographic(self): return _optional_bool(self.model, 'orthographic') @property def disable_pan(self): return _optional_bool(self.model, 'disable_pan') @property def disable_tumble(self): return _optional_bool(self.model, 'disable_tumble') @property def disable_look(self): return _optional_bool(self.model, 'disable_look') @property def disable_zoom(self): return _optional_bool(self.model, 'disable_zoom') @property def intertia(self): inertia = _optional_bool(self.model, 'inertia_enabled') if not inertia: return 0 inertia = _optional_floats(self.model, 'inertia_seconds') return inertia[0] if inertia else 0 @property def up_axis(self): # Assume Y-up if not specified return _optional_bool(self.model, 'up_axis', 1) @staticmethod def __conform_speed(values): if values: vlen = len(values) if vlen == 1: return (values[0], values[0], values[0]) if vlen == 2: return (values[0], values[1], 0) return values return (1, 1, 1) def get_rotation_speed(self, secondary): model = self.model rotation_speed = self.__conform_speed(_optional_floats(model, 'rotation_speed')) secondary_speed = self.__conform_speed(_optional_floats(model, secondary)) return (rotation_speed[0] * secondary_speed[0], rotation_speed[1] * secondary_speed[1], rotation_speed[2] * secondary_speed[2]) @property def tumble_speed(self): return self.get_rotation_speed('tumble_speed') @property def look_speed(self): return self.get_rotation_speed('look_speed') @property def move_speed(self): return self.__conform_speed(_optional_floats(self.model, 'move_speed')) @property def world_speed(self): model = self.model ndc_scale = self.__conform_speed(_optional_floats(model, 'ndc_scale')) world_speed = self.__conform_speed(_optional_floats(model, 'world_speed')) return Gf.CompMult(world_speed, ndc_scale) def _disable_flight(self): if self.__keyboard: self.__keyboard.destroy() def _setup_keyboard(self, model, exit_mode: bool) -> bool: """Setup keyboard and return whether the manipualtor mode (fly) was broadcast to consumers""" self.__keyboard = get_keyboard_input(model, self.__keyboard) if self.__keyboard: # If the keyboard is active, broadcast that fly mode has been entered if self.__keyboard.active: self.__fly_active = True model._broadcast_mode("fly") return True # Check if fly mode was exited if self.__fly_active: exit_mode = self.name.replace('Gesture', '').lower() if exit_mode else "" model._broadcast_mode(exit_mode) return True return False # omni.ui.scene Gesture interface # We absract on top of this due to asynchronous picking, in that we # don't want a gesture to begin until the object/world-space query has completed # This 'delay' could be a setting, but will wind up 'snapping' from the transition # from a Camera's centerOfInterest to the new world-space position def on_began(self, mouse: Sequence[float] = None): model = self.model # Setup flight mode and possibly broadcast that mode to any consumers was_brodcast = self._setup_keyboard(model, False) # If fly mode was not broadcast, then brodcast this gesture's mode if not was_brodcast: # LookGesture => look manip_mode = self.name.replace('Gesture', '').lower() model._broadcast_mode(manip_mode) mouse = mouse if mouse else self.sender.gesture_payload.mouse if self.__configure_model: self.__configure_model(model, mouse) self.__prev_mouse = mouse xf = model.get_as_floats('transform') if xf: # Save an imutable copy of transform for undoable end-event model.set_floats('initial_transform', xf.copy()) coi = model.get_as_floats('center_of_interest') if coi: # Save an imutable copy of center_of_interest for end adjustment if desired (avoiding space conversions) model.set_floats('center_of_interest_start', coi.copy()) model._item_changed('center_of_interest') model.set_ints('interaction_active', [1]) def on_changed(self, mouse: Sequence[float] = None): self._setup_keyboard(self.model, True) self.__last_change = time.time() cur_mouse = mouse if mouse else self.sender.gesture_payload.mouse mouse_moved = (cur_mouse[0] - self.__prev_mouse[0], cur_mouse[1] - self.__prev_mouse[1]) # if (mouse_moved[0] != 0) or (mouse_moved[1] != 0): self.__prev_mouse = cur_mouse self.on_mouse_move(mouse_moved) def on_ended(self): model = self.model final_position = True # Brodcast that the camera manipulationmode is now none model._broadcast_mode("") if self.__keyboard: self.__keyboard = self.__keyboard.end() final_position = self.__keyboard is None self.__prev_mouse = None self.__prev_mouse_time = None if final_position: if model._start_external_events(False): model._stop_external_events(False) self.__apply_as_undoable() model.set_ints('adjust_center_of_interest', []) model.set_floats('current_aperture', []) model.set_ints('interaction_active', [0]) # model.set_floats('center_of_interest_start', []) # model.set_floats('center_of_interest_picked', []) def dirty_items(self, model: sc.AbstractManipulatorModel): model = self.model cur_item = model.get_item('transform') if model.get_as_floats('initial_transform') != model.get_as_floats(cur_item): return [cur_item] def __apply_as_undoable(self): model = self.model dirty_items = self.dirty_items(model) if dirty_items: model.set_ints('interaction_ended', [1]) try: for item in dirty_items: model._item_changed(item) except: raise finally: model.set_ints('interaction_ended', [0]) def _accumulate_values(self, key: str, x: float, y: float, z: float): item = _accumulate_values(self.model, key, x, y, z) if item: self.model._item_changed(None if self.__keyboard else item)
8,715
Python
35.316667
128
0.616753
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/gamepad.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .model import _accumulate_values import omni.kit.app from omni.ui import scene as sc import carb import asyncio from typing import Dict, List, Sequence, Set # Setting per action mode (i.e): # /exts/omni.kit.manipulator.camera/gamePad/fly/deadZone # /exts/omni.kit.manipulator.camera/gamePad/look/deadZone ACTION_MODE_SETTING_KEYS = {"scale", "deadZone"} ACTION_MODE_SETTING_ROOT = "/exts/omni.kit.manipulator.camera/gamePad" # Setting per action trigger (i.e): # /exts/omni.kit.manipulator.camera/gamePad/button/a/scale ACTION_TRIGGER_SETTING_KEYS = {"scale"} __all__ = ['GamePadController'] class ValueMapper: def __init__(self, mode: str, trigger: str, index: int, sub_index: int): self.__mode: str = mode self.__trigger: str = trigger self.__index: int = index self.__sub_index = sub_index @property def mode(self) -> str: return self.__mode @property def trigger(self) -> str: return self.__trigger @property def index(self) -> int: return self.__index @property def sub_index(self) -> int: return self.__sub_index class ModeSettings: def __init__(self, action_mode: str, settings: carb.settings.ISettings): self.__scale: float = 1.0 self.__dead_zone: float = 1e-04 self.__action_mode = action_mode self.__setting_subs: Sequence[carb.settings.SubscriptionId] = [] for setting_key in ACTION_MODE_SETTING_KEYS: sp = self.__get_setting_path(setting_key) self.__setting_subs.append( settings.subscribe_to_node_change_events(sp, lambda *args, k=setting_key: self.__setting_changed(*args, setting_key=k)) ) self.__setting_changed(None, carb.settings.ChangeEventType.CHANGED, setting_key=setting_key) def __del__(self): self.destroy() def __get_setting_path(self, setting_key: str): return f"{ACTION_MODE_SETTING_ROOT}/{self.__action_mode}/{setting_key}" def __setting_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType, setting_key: str): if event_type == carb.settings.ChangeEventType.CHANGED: setting_path = self.__get_setting_path(setting_key) if setting_key == "scale": self.__scale = carb.settings.get_settings().get(setting_path) if self.__scale is None: self.__scale = 1.0 elif setting_key == "deadZone": # Use absolute value, no negative dead-zones and clamp to 1.0 dead_zone = carb.settings.get_settings().get(setting_path) self.__dead_zone = min(abs(dead_zone) or 1e-04, 1.0) if (dead_zone is not None) else 0.0 def destroy(self, settings: carb.settings.ISettings = None): settings = settings or carb.settings.get_settings() for setting_sub in self.__setting_subs: settings.unsubscribe_to_change_events(setting_sub) self.__setting_subs = tuple() def get_value(self, value: float, axis_idx: int) -> float: # Legacy implementation, which scales input value into new range fitted by dead_zone value = (value - self.__dead_zone) / (1.0 - self.__dead_zone) value = max(0, min(1, value)) scale = self.__scale return value * scale # Somewhat simpler version that doesn't scale input by dead-zone if abs(value) > self.__dead_zone: return value * scale return 0 def _limit_camera_velocity(value: float, settings: carb.settings.ISettings, context_name: str): cam_limit = settings.get('/exts/omni.kit.viewport.window/cameraSpeedLimit') if context_name in cam_limit: vel_min = settings.get('/persistent/app/viewport/camVelocityMin') if vel_min is not None: value = max(vel_min, value) vel_max = settings.get('/persistent/app/viewport/camVelocityMax') if vel_max is not None: value = min(vel_max, value) return value def _adjust_flight_speed(xyz_value: Sequence[float]): y = xyz_value[1] if y == 0.0: return import math settings = carb.settings.get_settings() value = settings.get('/persistent/app/viewport/camMoveVelocity') or 1 scaler = settings.get('/persistent/app/viewport/camVelocityScalerMultAmount') or 1.1 scaler = 1.0 + (max(scaler, 1.0 + 1e-8) - 1.0) * abs(y) if y < 0: value = value / scaler elif y > 0: value = value * scaler if math.isfinite(value) and (value > 1e-8): value = _limit_camera_velocity(value, settings, 'gamepad') settings.set('/persistent/app/viewport/camMoveVelocity', value) class GamePadController: def __init__(self, manipulator: sc.Manipulator): self.__manipulator: sc.Manipulator = manipulator self.__gp_event_sub: Dict[carb.input.Gamepad, int] = {} self.__compressed_events: Dict[int, float] = {} self.__action_modes: Dict[str, List[float]] = {} self.__app_event_sub: carb.events.ISubscription = None self.__mode_settings: Dict[str, ModeSettings] = {} self.__value_actions: Dict[carb.input.GamepadInput, ValueMapper] = {} self.__setting_subs: Sequence[carb.settings.SubscriptionId] = [] # Some button presses need synthetic events because unlike keyboard input, carb gamepad doesn't repeat. # event 1 left presssed: value = 0.5 # event 2 right pressed: value = 0.5 # these should cancel, but there is no notification of left event until it changes from 0.5 # This is all handled in __gamepad_event trigger_synth = {carb.input.GamepadInput.RIGHT_TRIGGER, carb.input.GamepadInput.LEFT_TRIGGER} shoulder_synth = {carb.input.GamepadInput.RIGHT_SHOULDER, carb.input.GamepadInput.LEFT_SHOULDER} self.__synthetic_state_init = { carb.input.GamepadInput.RIGHT_TRIGGER: trigger_synth, carb.input.GamepadInput.LEFT_TRIGGER: trigger_synth, carb.input.GamepadInput.RIGHT_SHOULDER: shoulder_synth, carb.input.GamepadInput.LEFT_SHOULDER: shoulder_synth, } self.__synthetic_state = self.__synthetic_state_init.copy() self.__init_gamepad_action(None, carb.settings.ChangeEventType.CHANGED) self.__gp_connect_sub = self._iinput.subscribe_to_gamepad_connection_events(self.__gamepad_connection) def __init_gamepad_action(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type != carb.settings.ChangeEventType.CHANGED: return self.__value_actions: Dict[carb.input.GamepadInput, ValueMapper] = {} settings = carb.settings.get_settings() create_subs = not bool(self.__setting_subs) gamepad_action_paths = [] gamepad_input_names = ["rightStick", "leftStick", "dPad", "trigger", "shoulder", "button/a", "button/b", "button/x", "button/y"] for gamepad_input in gamepad_input_names: action_setting_path = f"{ACTION_MODE_SETTING_ROOT}/{gamepad_input}/action" gamepad_action_paths.append(action_setting_path) if create_subs: self.__setting_subs.append( settings.subscribe_to_node_change_events(action_setting_path, self.__init_gamepad_action) ) # TODO: Maybe need more configuable/robust action mapping def action_mapping_4(action_mode: str): action_modes = action_mode.split(".") if len(action_modes) != 1: carb.log_error(f"Action mapping '{action_mode}' for quad input is invalid, using '{action_modes[0]}'") action_mode = action_modes[0] if action_mode == "look": return action_mode, (0, 1), (0, 1, 0, 1) return action_mode, (0, 2), (1, 0, 1, 0) def action_mapping_2(action_mode: str): action_modes = action_mode.split(".") if len(action_modes) != 2: action_modes = (action_modes[0], "x") carb.log_error(f"Action mapping '{action_mode}' for dual input is invalid, using '{action_modes[0]}.x'") axis = {'x': 0, 'y': 1, 'z': 2}.get(action_modes[1], 0) return action_modes[0], axis, (0, 1) def action_mapping_1(action_mode: str): action_modes = action_mode.split(".") if len(action_modes) != 2: action_modes = (action_modes[0], "x") carb.log_error(f"Action mapping '{action_mode}' for dual input is invalid, using '{action_modes[0]}.x'") axis = {'x': 0, 'y': 1, 'z': 2}.get(action_modes[1], 0) return action_modes[0], axis, 0 # Go through the list of named events and setup the action based on it's value right_stick_action = settings.get(gamepad_action_paths[0]) if right_stick_action: right_stick_action, axis, sub_idx = action_mapping_4(right_stick_action) self.__value_actions[carb.input.GamepadInput.RIGHT_STICK_LEFT] = ValueMapper(right_stick_action, gamepad_input_names[0], axis[0], sub_idx[0]) self.__value_actions[carb.input.GamepadInput.RIGHT_STICK_RIGHT] = ValueMapper(right_stick_action, gamepad_input_names[0], axis[0], sub_idx[1]) self.__value_actions[carb.input.GamepadInput.RIGHT_STICK_UP] = ValueMapper(right_stick_action, gamepad_input_names[0], axis[1], sub_idx[2]) self.__value_actions[carb.input.GamepadInput.RIGHT_STICK_DOWN] = ValueMapper(right_stick_action, gamepad_input_names[0], axis[1], sub_idx[3]) left_stick_action = settings.get(gamepad_action_paths[1]) if left_stick_action: left_stick_action, axis, sub_idx = action_mapping_4(left_stick_action) self.__value_actions[carb.input.GamepadInput.LEFT_STICK_LEFT] = ValueMapper(left_stick_action, gamepad_input_names[1], axis[0], sub_idx[0]) self.__value_actions[carb.input.GamepadInput.LEFT_STICK_RIGHT] = ValueMapper(left_stick_action, gamepad_input_names[1], axis[0], sub_idx[1]) self.__value_actions[carb.input.GamepadInput.LEFT_STICK_UP] = ValueMapper(left_stick_action, gamepad_input_names[1], axis[1], sub_idx[2]) self.__value_actions[carb.input.GamepadInput.LEFT_STICK_DOWN] = ValueMapper(left_stick_action, gamepad_input_names[1], axis[1], sub_idx[3]) dpad_action = settings.get(gamepad_action_paths[2]) if dpad_action: dpad_action, axis, sub_idx = action_mapping_4(dpad_action) self.__value_actions[carb.input.GamepadInput.DPAD_LEFT] = ValueMapper(dpad_action, gamepad_input_names[2], axis[0], sub_idx[0]) self.__value_actions[carb.input.GamepadInput.DPAD_RIGHT] = ValueMapper(dpad_action, gamepad_input_names[2], axis[0], sub_idx[1]) self.__value_actions[carb.input.GamepadInput.DPAD_UP] = ValueMapper(dpad_action, gamepad_input_names[2], axis[1], sub_idx[2]) self.__value_actions[carb.input.GamepadInput.DPAD_DOWN] = ValueMapper(dpad_action, gamepad_input_names[2], axis[1], sub_idx[3]) trigger_action = settings.get(gamepad_action_paths[3]) if trigger_action: trigger_action, axis, sub_idx = action_mapping_2(trigger_action) self.__value_actions[carb.input.GamepadInput.RIGHT_TRIGGER] = ValueMapper(trigger_action, gamepad_input_names[3], axis, sub_idx[0]) self.__value_actions[carb.input.GamepadInput.LEFT_TRIGGER] = ValueMapper(trigger_action, gamepad_input_names[3], axis, sub_idx[1]) shoulder_action = settings.get(gamepad_action_paths[4]) if shoulder_action: shoulder_action, axis, sub_idx = action_mapping_2(shoulder_action) self.__value_actions[carb.input.GamepadInput.RIGHT_SHOULDER] = ValueMapper(shoulder_action, gamepad_input_names[4], axis, sub_idx[0]) self.__value_actions[carb.input.GamepadInput.LEFT_SHOULDER] = ValueMapper(shoulder_action, gamepad_input_names[4], axis, sub_idx[1]) button_action = settings.get(gamepad_action_paths[5]) if button_action: button_action, axis, sub_idx = action_mapping_1(button_action) self.__value_actions[carb.input.GamepadInput.A] = ValueMapper(button_action, gamepad_input_names[5], axis, sub_idx) button_action = settings.get(gamepad_action_paths[6]) if button_action: button_action, axis, sub_idx = action_mapping_1(button_action) self.__value_actions[carb.input.GamepadInput.B] = ValueMapper(button_action, gamepad_input_names[6], axis, sub_idx) button_action = settings.get(gamepad_action_paths[7]) if button_action: button_action, axis, sub_idx = action_mapping_1(button_action) self.__value_actions[carb.input.GamepadInput.X] = ValueMapper(button_action, gamepad_input_names[7], axis, sub_idx) button_action = settings.get(gamepad_action_paths[8]) if button_action: button_action, axis, sub_idx = action_mapping_1(button_action) self.__value_actions[carb.input.GamepadInput.Y] = ValueMapper(button_action, gamepad_input_names[8], axis, sub_idx) for value_mapper in self.__value_actions.values(): action_mode = value_mapper.mode if self.__mode_settings.get(action_mode) is None: self.__mode_settings[action_mode] = ModeSettings(action_mode, settings) action_trigger = value_mapper.trigger if self.__mode_settings.get(action_trigger) is None: self.__mode_settings[action_trigger] = ModeSettings(action_trigger, settings) def __del__(self): self.destroy() @property def _iinput(self): return carb.input.acquire_input_interface() async def __apply_events(self): # Grab the events to apply and reset the state to empty events, self.__compressed_events = self.__compressed_events, {} # Reset the synthetic state self.__synthetic_state = self.__synthetic_state_init.copy() if not events: return manipulator = self.__manipulator if not manipulator: return model = manipulator.model manipulator._on_began(model, None) # Map the action to +/- values per x, y, z components action_modes: Dict[str, Dict[int, List[float]]] = {} for input, value in events.items(): action = self.__value_actions.get(input) if not action: continue # Must exists, KeyError otherwise mode_seting = self.__mode_settings[action.mode] trigger_setting = self.__mode_settings[action.trigger] # Get the dict for this action storing +/- values per x, y, z pos_neg_value_dict = action_modes.get(action.mode) or {} # Get the +/- values for the x, y, z component pos_neg_values = pos_neg_value_dict.get(action.index) or [0, 0] # Scale the value by the action's scaling factor value = mode_seting.get_value(value, action.index) # Scale the value by the trigger's scaling factor value = trigger_setting.get_value(value, action.index) # Store the +/- value into the proper slot '+' into 0, '-' into 1 pos_neg_values[action.sub_index] += value # Store back into the dict mapping x, y, z to +/- values pos_neg_value_dict[action.index] = pos_neg_values # Store back into the dict storing the +/- values per x, y, z into the action action_modes[action.mode] = pos_neg_value_dict # Collapse the +/- values per individual action and x, y, z into a single total for action_mode, pos_neg_value_dict in action_modes.items(): # Some components may not have been touched but need to preserve last value xyz_value = self.__action_modes.get(action_mode) or [0, 0, 0] for xyz_index, pos_neg_value in pos_neg_value_dict.items(): xyz_value[xyz_index] = pos_neg_value[0] - pos_neg_value[1] # Apply model speed to anything but fly (that is handled by model itself) if action_mode != "fly": model_speed = model.get_item(f"{action_mode}_speed") if model_speed is not None: model_speed = model.get_as_floats(model_speed) if model_speed is not None: for i in range(len(model_speed)): xyz_value[i] *= model_speed[i] # Store the final values self.__action_modes[action_mode] = xyz_value # Prune any actions that now do nothing (has 0 for x, y, and z) self.__action_modes = { action_mode: xyz_value for action_mode, xyz_value in self.__action_modes.items() if (xyz_value[0] or xyz_value[1] or xyz_value[2]) } has_data: bool = bool(self.__action_modes) if has_data: self.__apply_gamepad_state() if hasattr(model, '_start_external_events'): if has_data: self.___start_external_events(model) else: self.__stop_external_events(model) def ___start_external_events(self, model): if self.__app_event_sub: return _broadcast_mode = getattr(model, '_broadcast_mode', None) if _broadcast_mode: _broadcast_mode("gamepad") self.__app_event_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop( self.__apply_gamepad_state, name=f"omni.kit.manipulator.camera.GamePadController.{id(self)}", # order=omni.kit.app.UPDATE_ORDER_PYTHON_ASYNC_FUTURE_END_UPDATE ) model._start_external_events(True) def __stop_external_events(self, model): if self.__app_event_sub: _broadcast_mode = getattr(model, '_broadcast_mode', None) if _broadcast_mode: _broadcast_mode("") self.__app_event_sub = None self.__action_modes = {} model._stop_external_events(True) def __apply_gamepad_state(self, *args, **kwargs): manipulator = self.__manipulator model = manipulator.model # manipulator._on_began(model, None) for action_mode, xyz_value in self.__action_modes.items(): if action_mode == "fly": model.set_floats("fly", xyz_value) continue elif action_mode == "speed": _adjust_flight_speed(xyz_value) continue item = _accumulate_values(model, action_mode, xyz_value[0], xyz_value[1], xyz_value[2]) if item: model._item_changed(item) def __gamepad_event(self, event: carb.input.GamepadEvent): event_input = event.input self.__compressed_events[event_input] = event.value # Gamepad does not get repeat events, so on certain button presses there needs to be a 'synthetic' event # that represents the inverse-key (left/right) based on its last/current state. synth_state = self.__synthetic_state.get(event.input) if synth_state: for synth_input in synth_state: del self.__synthetic_state[synth_input] if synth_input != event_input: self.__compressed_events[synth_input] = self._iinput.get_gamepad_value(event.gamepad, synth_input) asyncio.ensure_future(self.__apply_events()) def __gamepad_connection(self, event: carb.input.GamepadConnectionEvent): e_type = event.type e_gamepad = event.gamepad if e_type == carb.input.GamepadConnectionEventType.DISCONNECTED: e_gamepad_sub = self.__gp_event_sub.get(e_gamepad) if e_gamepad_sub: self._iinput.unsubscribe_to_gamepad_events(e_gamepad, e_gamepad_sub) del self.__gp_event_sub[e_gamepad] pass elif e_type == carb.input.GamepadConnectionEventType.CONNECTED: if self.__gp_event_sub.get(e_gamepad): carb.log_error("Gamepad connected event, but already subscribed") return gp_event_sub = self._iinput.subscribe_to_gamepad_events(e_gamepad, self.__gamepad_event) if gp_event_sub: self.__gp_event_sub[e_gamepad] = gp_event_sub def destroy(self): iinput = self._iinput settings = carb.settings.get_settings() # Remove gamepad connected subscriptions if self.__gp_connect_sub: iinput.unsubscribe_to_gamepad_connection_events(self.__gp_connect_sub) self.__gp_connect_sub = None # Remove gamepad event subscriptions for gamepad, gamepad_sub in self.__gp_event_sub.items(): iinput.unsubscribe_to_gamepad_events(gamepad, gamepad_sub) self.__gp_event_sub = {} # Remove any pending state on the model model = self.__manipulator.model if self.__manipulator else None if model: self.__stop_external_events(model) self.__manipulator = None # Remove any settings subscriptions for setting_sub in self.__setting_subs: settings.unsubscribe_to_change_events(setting_sub) self.__setting_subs = [] # Destroy any mode/action specific settings for action_mode, mode_settings in self.__mode_settings.items(): mode_settings.destroy(settings) self.__mode_settings = {}
22,082
Python
47.427631
154
0.623675
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/gestures.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['build_gestures', 'PanGesture', 'TumbleGesture', 'LookGesture', 'ZoomGesture'] from omni.ui import scene as sc from .gesturebase import CameraGestureBase from pxr import Gf import carb from typing import Callable kDefaultKeyBindings = { 'PanGesture': 'Any MiddleButton', 'TumbleGesture': 'Alt LeftButton', 'ZoomGesture': 'Alt RightButton', 'LookGesture': 'RightButton' } def build_gestures(model: sc.AbstractManipulatorModel, bindings: dict = None, manager: sc.GestureManager = None, configure_model: Callable = None): def _parse_binding(binding_str: str): keys = binding_str.split(' ') button = { 'LeftButton': 0, 'RightButton': 1, 'MiddleButton': 2 }.get(keys.pop()) modifiers = 0 for mod_str in keys: mod_bit = { 'Shift': carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT, 'Ctrl': carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, 'Alt': carb.input.KEYBOARD_MODIFIER_FLAG_ALT, 'Super': carb.input.KEYBOARD_MODIFIER_FLAG_SUPER, 'Any': 0xffffffff, }.get(mod_str) if not mod_bit: raise RuntimeError(f'Unparseable binding: {binding_str}') modifiers = modifiers | mod_bit return (button, modifiers) if not bindings: bindings = kDefaultKeyBindings gestures = [] for gesture, binding in bindings.items(): instantiator = globals().get(gesture) if not instantiator: carb.log_warn(f'Gesture "{gesture}" was not found for key-binding: "{binding}"') continue button, modifers = _parse_binding(binding) gestures.append(instantiator(model, configure_model, mouse_button=button, modifiers=modifers, manager=manager)) return gestures class PanGesture(CameraGestureBase): def on_mouse_move(self, mouse_moved): if self.disable_pan: return world_speed = self.world_speed move_speed = self.move_speed self._accumulate_values('move', mouse_moved[0] * 0.5 * world_speed[0] * move_speed[0], mouse_moved[1] * 0.5 * world_speed[1] * move_speed[1], 0) class TumbleGesture(CameraGestureBase): def on_mouse_move(self, mouse_moved): if self.disable_tumble: return # Mouse moved is [-1,1], so make a full drag scross the viewport a 180 tumble speed = self.tumble_speed self._accumulate_values('tumble', mouse_moved[0] * speed[0] * -90, mouse_moved[1] * speed[1] * 90, 0) class LookGesture(CameraGestureBase): def on_mouse_move(self, mouse_moved): if self.disable_look: return # Mouse moved is [-1,1], so make a full drag scross the viewport a 180 look speed = self.look_speed self._accumulate_values('look', mouse_moved[0] * speed[0] * -90, mouse_moved[1] * speed[1] * 90, 0) class OrthoZoomAperture(): def __init__(self, model: sc.AbstractManipulatorModel, apertures): self.__values = apertures.copy() def apply(self, model: sc.AbstractManipulatorModel, distance: float): # TODO ortho-speed for i in range(2): self.__values[i] -= distance * 2 model.set_floats('current_aperture', self.__values) model._item_changed(model.get_item('current_aperture')) def dirty_items(self, model: sc.AbstractManipulatorModel): cur_ap = model.get_item('current_aperture') if model.get_as_floats('initial_aperture') != model.get_as_floats(cur_ap): return [cur_ap] class OrthoZoomProjection(): def __init__(self, model: sc.AbstractManipulatorModel, projection): self.__projection = projection.copy() def apply(self, model: sc.AbstractManipulatorModel, distance: float): # TODO ortho-speed distance /= 3.0 rml = (2.0 / self.__projection[0]) tmb = (2.0 / self.__projection[5]) aspect = tmb / rml rpl = rml * -self.__projection[12] tpb = tmb * self.__projection[13] rml -= distance tmb -= distance * aspect rpl += distance tpb += distance self.__projection[0] = 2.0 / rml self.__projection[5] = 2.0 / tmb #self.__projection[12] = -rpl / rml #self.__projection[13] = tpb / tmb model.set_floats('projection', self.__projection) # Trigger recomputation of ndc_speed model._item_changed(model.get_item('projection')) def dirty_items(self, model: sc.AbstractManipulatorModel): proj = model.get_item('projection') return [proj] if model.get_as_floats('projection') != model.get_as_floats(proj): return [proj] class ZoomGesture(CameraGestureBase): def dirty_items(self, model: sc.AbstractManipulatorModel): return super().dirty_items(model) if not self.__orth_zoom else self.__orth_zoom.dirty_items(model) def __setup_ortho_zoom(self): apertures = self.model.get_as_floats('initial_aperture') if apertures: self.__orth_zoom = OrthoZoomAperture(self.model, apertures) return True projection = self.model.get_as_floats('projection') if projection: self.__orth_zoom = OrthoZoomProjection(self.model, projection) return True carb.log_warn("Orthographic zoom needs a projection or aperture") return False def on_began(self, *args, **kwargs): super().on_began(*args, **kwargs) # Setup an orthographic movement (aperture adjustment) if needed self.__orth_zoom = False if self.orthographic: self.__setup_ortho_zoom() # self.model.set_ints('adjust_center_of_interest', [1]) # Zoom into center of view or mouse interest self.__direction = Gf.Vec3d(self.center_of_interest.GetNormalized()) if False else None def on_mouse_move(self, mouse_moved): if self.disable_zoom: return # Compute length/radius from gesture start distance = (mouse_moved[0] + mouse_moved[1]) * self.world_speed.GetLength() * 1.41421356 distance *= self.move_speed[2] if self.__orth_zoom: self.__orth_zoom.apply(self.model, distance) return # Zoom into view-enter or current mouse/world interest direction = self.__direction if self.__direction else Gf.Vec3d(self.center_of_interest.GetNormalized()) amount = direction * distance self._accumulate_values('move', amount[0], amount[1], amount[2])
7,324
Python
36.372449
119
0.604178
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/tests/test_manipulator_camera.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['TestManipulatorCamera', 'TestFlightMode'] 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 from pxr import Gf from omni.kit.manipulator.camera.manipulator import CameraManipulatorBase, SceneViewCameraManipulator, adjust_center_of_interest import omni.kit.ui_test as ui_test from carb.input import MouseEventType, KeyboardEventType, KeyboardInput CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.manipulator.camera}/data")) TEST_WIDTH, TEST_HEIGHT = 500, 500 TEST_UI_CENTER = ui_test.Vec2(TEST_WIDTH / 2, TEST_HEIGHT / 2) def _flatten_matrix(matrix: Gf.Matrix4d): return [matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3], matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3], matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]] class SimpleGrid(): def __init__(self, lineCount: float = 100, lineStep: float = 10, thicknes: float = 1, color: ui.color = ui.color(0.25)): self.__transform = ui.scene.Transform() with self.__transform: for i in range(lineCount * 2 + 1): ui.scene.Line( ((i - lineCount) * lineStep, 0, -lineCount * lineStep), ((i - lineCount) * lineStep, 0, lineCount * lineStep), color=color, thickness=thicknes, ) ui.scene.Line( (-lineCount * lineStep, 0, (i - lineCount) * lineStep), (lineCount * lineStep, 0, (i - lineCount) * lineStep), color=color, thickness=thicknes, ) class SimpleOrigin(): def __init__(self, length: float = 5, thickness: float = 4): origin = (0, 0, 0) with ui.scene.Transform(): ui.scene.Line(origin, (length, 0, 0), color=ui.color.red, thickness=thickness) ui.scene.Line(origin, (0, length, 0), color=ui.color.green, thickness=thickness) ui.scene.Line(origin, (0, 0, length), color=ui.color.blue, thickness=thickness) # Create a few scenes with different camera-maniupulators (a general ui.scene manip and one that allows ortho-tumble ) class SimpleScene: def __init__(self, ortho: bool = False, custom: bool = False, *args, **kwargs): self.__scene_view = ui.scene.SceneView(*args, **kwargs) if ortho: view = [-1, 0, 0, 0, 0, 0, 0.9999999999999998, 0, 0, 0.9999999999999998, 0, 0, 0, 0, -1000, 1] projection = [0.008, 0, 0, 0, 0, 0.008, 0, 0, 0, 0, -2.000002000002e-06, 0, 0, 0, -1.000002000002, 1] else: view = [0.7071067811865476, -0.40557978767263897, 0.5792279653395693, 0, -2.775557561562892e-17, 0.8191520442889919, 0.5735764363510462, 0, -0.7071067811865477, -0.4055797876726389, 0.5792279653395692, 0, 6.838973831690966e-14, -3.996234471857009, -866.0161835150924, 1.0000000000000002] projection = [4.7602203407949375, 0, 0, 0, 0, 8.483787309173106, 0, 0, 0, 0, -1.000002000002, -1, 0, 0, -2.000002000002, 0] view = Gf.Matrix4d(*view) center_of_interest = [0, 0, -view.Transform((0, 0, 0)).GetLength()] with self.__scene_view.scene: self.items = [SimpleGrid(), ui.scene.Arc(100, axis=1, wireframe=True), SimpleOrigin()] with ui.scene.Transform(transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1000, 0, 1000, 1]): self.items.append(ui.scene.Arc(100, axis=1, wireframe=True, color=ui.color.green)) with ui.scene.Transform(transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -260, 0, 260, 1]): self.items.append(ui.scene.Arc(100, axis=1, wireframe=True, color=ui.color.blue)) if custom: self.items.append(CameraManipulatorBase()) else: self.items.append(SceneViewCameraManipulator(center_of_interest)) # Push the start values into the CameraManipulator self.setup_camera_model(self.items[-1].model, view, projection, center_of_interest, ortho) def setup_camera_model(self, cam_model, view, projection, center_of_interest, ortho): cam_model.set_floats('transform', _flatten_matrix(view.GetInverse())) cam_model.set_floats('projection', projection) cam_model.set_floats('center_of_interest', [0, 0, -view.Transform((0, 0, 0)).GetLength()]) if ortho: cam_model.set_ints('orthographic', [ortho]) # Setup up the subscription to the CameraModel so changes here get pushed to SceneView self.model_changed_sub = cam_model.subscribe_item_changed_fn(self.model_changed) # And push the view and projection into the SceneView.model cam_model._item_changed(cam_model.get_item('transform')) cam_model._item_changed(cam_model.get_item('projection')) def model_changed(self, model, item): if item == model.get_item('transform'): transform = Gf.Matrix4d(*model.get_as_floats(item)) # Signal that this this is the final change block, adjust our center-of-interest then interaction_ended = model.get_as_ints('interaction_ended') if interaction_ended and interaction_ended[0]: transform = Gf.Matrix4d(*model.get_as_floats(item)) # Adjust the center-of-interest if requested (zoom out in perspective does this) initial_transform = Gf.Matrix4d(*model.get_as_floats('initial_transform')) coi_start, coi_end = adjust_center_of_interest(model, initial_transform, transform) if coi_end: model.set_floats('center_of_interest', [coi_end[0], coi_end[1], coi_end[2]]) # Push the start values into the SceneView self.__scene_view.model.set_floats('view', _flatten_matrix(transform.GetInverse())) elif item == model.get_item('projection'): self.__scene_view.model.set_floats('projection', model.get_as_floats('projection')) @property def scene(self): return self.__scene_view.scene @property def model(self): return self.__scene_view.model async def wait_human_delay(delay=1): await ui_test.human_delay(delay) class TestManipulatorCamera(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 create_test_view(self, name: str, ortho: bool = False, custom: bool = False): window = await self.create_test_window(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) with window.frame: scene_view = SimpleScene(ortho, custom) return (window, scene_view) async def _test_perspective_camera(self): objects = await self.create_test_view('Perspective') await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_perspective_camera.png') async def _test_orthographic_camera(self): objects = await self.create_test_view('Orthographic', True) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_orthographic_camera.png') async def _test_custom_camera(self): objects = await self.create_test_view('Custom Orthographic', True, True) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_custom_camera.png') async def _test_mouse_across_screen(self, mouse_down, mouse_up): objects = await self.create_test_view('WASD Movement') mouse_begin = ui_test.Vec2(0, TEST_UI_CENTER.y) mouse_end = ui_test.Vec2(TEST_WIDTH , TEST_UI_CENTER.y) await ui_test.input.emulate_mouse(MouseEventType.MOVE, mouse_begin) await wait_human_delay() try: await ui_test.input.emulate_mouse(mouse_down, mouse_begin) await ui_test.input.emulate_mouse_slow_move(mouse_begin, mouse_end) await wait_human_delay() finally: await ui_test.input.emulate_mouse(mouse_up, mouse_end) await wait_human_delay() return objects async def test_pan_across_screen(self): """Test pan across X is a full move across NDC by default""" objects = await self._test_mouse_across_screen(MouseEventType.MIDDLE_BUTTON_DOWN, MouseEventType.MIDDLE_BUTTON_UP) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_pan_across_screen.png') async def test_look_across_screen(self): """Test look rotation across X is 180 degrees by default""" objects = await self._test_mouse_across_screen(MouseEventType.RIGHT_BUTTON_DOWN, MouseEventType.RIGHT_BUTTON_UP) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_look_across_screen.png') class TestFlightMode(OmniUiTest): async def create_test_view(self, name: str, custom=False, ortho: bool = False): window = await self.create_test_window(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) with window.frame: simple_scene = SimpleScene() return (window, simple_scene) def get_translation(self, model): matrix = model.view return (matrix[12], matrix[13], matrix[14]) async def do_key_press(self, key: KeyboardInput, operation = None): try: await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_PRESS, key) await wait_human_delay() if operation: operation() finally: await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_RELEASE, key) await wait_human_delay() async def test_movement(self): """Test flight movement via WASD keyboard.""" window, simple_scene = await self.create_test_view('WASD Movement') model = simple_scene.model await ui_test.input.emulate_mouse(MouseEventType.MOVE, TEST_UI_CENTER) await wait_human_delay() start_pos = self.get_translation(model) try: await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_CENTER) await wait_human_delay() await self.do_key_press(KeyboardInput.W) after_w = self.get_translation(model) # W should have moved Z forward self.assertAlmostEqual(after_w[0], start_pos[0], places=5) self.assertAlmostEqual(after_w[1], start_pos[1], places=5) self.assertTrue(after_w[2] > start_pos[2]) await self.do_key_press(KeyboardInput.A) after_wa = self.get_translation(model) # A should have moved X left self.assertTrue(after_wa[0] > after_w[0]) self.assertAlmostEqual(after_wa[1], after_w[1], places=5) self.assertAlmostEqual(after_wa[2], after_w[2], places=5) await self.do_key_press(KeyboardInput.S) after_was = self.get_translation(model) # S should have moved Z back self.assertAlmostEqual(after_was[0], after_wa[0], places=5) self.assertAlmostEqual(after_was[1], after_wa[1], places=5) self.assertTrue(after_was[2] < after_wa[2]) await self.do_key_press(KeyboardInput.D) after_wasd = self.get_translation(model) # D should have moved X right self.assertTrue(after_wasd[0] < after_was[0]) self.assertAlmostEqual(after_wasd[1], after_was[1], places=5) self.assertAlmostEqual(after_wasd[2], after_was[2], places=5) # Test disabling flight-mode in the model would stop keyboard from doing anything before_wasd = self.get_translation(model) simple_scene.items[-1].model.set_ints('disable_fly', [1]) await self.do_key_press(KeyboardInput.W) await self.do_key_press(KeyboardInput.A) await self.do_key_press(KeyboardInput.S) await self.do_key_press(KeyboardInput.D) await wait_human_delay() after_wasd = self.get_translation(model) simple_scene.items[-1].model.set_ints('disable_fly', [0]) self.assertTrue(Gf.IsClose(before_wasd, after_wasd, 1e-5)) finally: await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_UP) await wait_human_delay() async def _test_speed_modifier(self, value_a, value_b): vel_key = '/persistent/app/viewport/camMoveVelocity' mod_amount_key = '/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount' settings = carb.settings.get_settings() window, simple_scene = await self.create_test_view('WASD Movement') model = simple_scene.model settings.set(vel_key, 5) await ui_test.input.emulate_mouse(MouseEventType.MOVE, TEST_UI_CENTER) await wait_human_delay() def compare_velocity(velocity): vel_value = settings.get(vel_key) self.assertEqual(vel_value, velocity) try: compare_velocity(5) await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_CENTER) # By default Shift should double speed await self.do_key_press(KeyboardInput.LEFT_SHIFT, lambda: compare_velocity(value_a)) # By default Shift should halve speed await self.do_key_press(KeyboardInput.LEFT_CONTROL, lambda: compare_velocity(value_b)) await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_UP) await wait_human_delay() compare_velocity(5) finally: settings.set(vel_key, 5) settings.set(mod_amount_key, 2) await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_UP) await wait_human_delay() async def test_speed_modifier_a(self): """Test default flight speed adjustement: 2x""" await self._test_speed_modifier(10, 2.5) async def test_speed_modifier_b(self): """Test custom flight speed adjustement: 4x""" carb.settings.get_settings().set('/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount', 4) await self._test_speed_modifier(20, 1.25) async def test_speed_modifier_c(self): """Test custom flight speed adjustement: 0x""" # Test when set to 0 carb.settings.get_settings().set('/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount', 0) await self._test_speed_modifier(5, 5)
15,278
Python
45.440729
299
0.63994
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/tests/test_manipulator_usd.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ['TestManipulatorUSDCamera'] from omni.kit.manipulator.camera.usd_camera_manipulator import UsdCameraManipulator from omni.kit.manipulator.camera.model import CameraManipulatorModel, _flatten_matrix import omni.usd import omni.kit.test import carb.settings from pxr import Gf, Sdf, UsdGeom from pathlib import Path from typing import List, Sequence import sys import unittest TESTS_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.manipulator.camera}/data")).absolute().resolve() USD_FILES = TESTS_PATH.joinpath("tests", "usd") class TestManipulatorUSDCamera(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await omni.usd.get_context().new_stage_async() self.stage = omni.usd.get_context().get_stage() super().setUp() # After running each test async def tearDown(self): super().tearDown() def __reset_initial_xf(self, usd_manip, initial_transform_item, prim): # Reset the initial transform to the current transform matrix = omni.usd.get_world_transform_matrix(prim) usd_manip.model.set_floats(initial_transform_item, _flatten_matrix(matrix)) # This synthesizes the start of a new event usd_manip._set_context('', prim.GetPath()) def __setup_usdmanip_tumble_test(self, prim_path: Sdf.Path): usd_manip = UsdCameraManipulator(prim_path=prim_path) usd_manip.model = CameraManipulatorModel() usd_manip._on_began(usd_manip.model) cam_prim = self.stage.GetPrimAtPath(prim_path) self.assertTrue(bool(cam_prim)) initial_transform_item = usd_manip.model.get_item('initial_transform') tumble_item = usd_manip.model.get_item('tumble') transform_item = usd_manip.model.get_item('transform') self.__reset_initial_xf(usd_manip, initial_transform_item, cam_prim) usd_manip.model.set_floats(transform_item, _flatten_matrix(Gf.Matrix4d(1))) usd_manip.on_model_updated(transform_item) return (usd_manip, cam_prim, initial_transform_item, tumble_item) async def __test_tumble_camera(self, prim_path: Sdf.Path, rotations: List[Sequence[float]], epsilon: float = 1.0e-5): (usd_manip, cam_prim, initial_transform_item, tumble_item) = self.__setup_usdmanip_tumble_test(prim_path) rotateYXZ = cam_prim.GetAttribute('xformOp:rotateYXZ') self.assertIsNotNone(rotateYXZ) cur_rot = Gf.Vec3d(rotateYXZ.Get()) self.assertTrue(Gf.IsClose(cur_rot, Gf.Vec3d(0, 0, 0), epsilon)) is_linux = sys.platform.startswith('linux') for index, rotation in enumerate(rotations): usd_manip.model.set_floats(tumble_item, [-90, 0, 0]) usd_manip.model._item_changed(tumble_item) self.__reset_initial_xf(usd_manip, initial_transform_item, cam_prim) cur_rot = Gf.Vec3d(rotateYXZ.Get()) is_equal = Gf.IsClose(cur_rot, Gf.Vec3d(rotation), epsilon) if is_equal: continue # Linux and Windows are returning different results for some rotations that are essentially equivalent is_equal = True for current, expected in zip(cur_rot, rotation): if not Gf.IsClose(current, expected, epsilon): expected = abs(expected) is_equal = (expected == 180) or (expected == 360) if not is_equal: break self.assertTrue(is_equal, msg=f"Rotation values differ: current: {cur_rot}, expected: {rotation}") async def __test_camera_YXZ_edit(self, rotations: List[Sequence[float]]): camera = UsdGeom.Camera.Define(self.stage, '/Camera') cam_prim = camera.GetPrim() cam_prim.CreateAttribute('omni:kit:centerOfInterest', Sdf.ValueTypeNames.Vector3d, True, Sdf.VariabilityUniform).Set(Gf.Vec3d(0, 0, -10)) await self.__test_tumble_camera(cam_prim.GetPath(), rotations) async def test_camera_rotate(self): '''Test rotation values in USD (with controllerUseSRT set to False)''' await self.__test_camera_YXZ_edit([ (0, -90, 0), (0, 180, 0), (0, 90, 0), (0, 0, 0) ]) async def test_camera_rotate_SRT(self): '''Test rotation accumulation in USD with controllerUseSRT set to True''' settings = carb.settings.get_settings() try: settings.set('/persistent/app/camera/controllerUseSRT', True) await self.__test_camera_YXZ_edit([ (0, -90, 0), (0, -180, 0), (0, -270, 0), (0, -360, 0) ]) finally: settings.destroy_item('/persistent/app/camera/controllerUseSRT') async def test_camera_yup_in_zup(self): '''Test Viewport rotation of a camera from a y-up layer, referenced in a z-up stage''' await omni.usd.get_context().open_stage_async(str(USD_FILES.joinpath('yup_in_zup.usda'))) self.stage = omni.usd.get_context().get_stage() await self.__test_tumble_camera(Sdf.Path('/World/yup_ref/Camera'), [ (0, -90, 0), (0, 180, 0), (0, 90, 0), (0, 0, 0) ] ) async def test_camera_zup_in_yup(self): '''Test Viewport rotation of a camera from a z-up layer, referenced in a y-up stage''' await omni.usd.get_context().open_stage_async(str(USD_FILES.joinpath('zup_in_yup.usda'))) self.stage = omni.usd.get_context().get_stage() await self.__test_tumble_camera(Sdf.Path('/World/zup_ref/Camera'), [ (0, 0, -90), (0, 0, 180), (0, 0, 90), (0, 0, 0) ] )
6,352
Python
38.216049
121
0.615712
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/tests/test_viewport_manipulator.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ['TestViewportCamera'] import omni.kit.app import omni.kit.ui_test as ui_test from carb.input import MouseEventType, KeyboardEventType, KeyboardInput from pxr import Gf, Sdf, UsdGeom TEST_GUTTER = 10 TEST_WIDTH, TEST_HEIGHT = 500, 500 TEST_UI_CENTER = ui_test.Vec2(TEST_WIDTH / 2, TEST_HEIGHT / 2) TEST_UI_LEFT = ui_test.Vec2(TEST_GUTTER, TEST_UI_CENTER.y) TEST_UI_RIGHT = ui_test.Vec2(TEST_WIDTH - TEST_GUTTER, TEST_UI_CENTER.y) TEST_UI_TOP = ui_test.Vec2(TEST_UI_CENTER.x, TEST_GUTTER) TEST_UI_BOTTOM = ui_test.Vec2(TEST_UI_CENTER.x, TEST_HEIGHT - TEST_GUTTER) class TestViewportCamera(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): from omni.kit.viewport.utility import get_active_viewport self.viewport = get_active_viewport() await self.viewport.usd_context.new_stage_async() self.stage = self.viewport.stage self.camera = UsdGeom.Xformable(self.stage.GetPrimAtPath(self.viewport.camera_path)) # Disable locking to render results, as there are no render-results self.viewport.lock_to_render_result = False super().setUp() await self.wait_n_updates() # After running each test async def tearDown(self): super().tearDown() async def wait_n_updates(self, n_frames: int = 3): app = omni.kit.app.get_app() for _ in range(n_frames): await app.next_update_async() async def __do_mouse_interaction(self, mouse_down: MouseEventType, start: ui_test.Vec2, end: ui_test.Vec2, mouse_up: MouseEventType, modifier: KeyboardInput | None = None): if modifier: await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_PRESS, modifier) await ui_test.human_delay() else: await self.wait_n_updates(10) await ui_test.input.emulate_mouse(MouseEventType.MOVE, start) await ui_test.input.emulate_mouse(mouse_down, start) await ui_test.input.emulate_mouse_slow_move(start, end) await ui_test.input.emulate_mouse(mouse_up, end) if modifier: await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_RELEASE, modifier) await ui_test.human_delay() else: await self.wait_n_updates() def assertIsClose(self, a, b): self.assertTrue(Gf.IsClose(a, b, 0.1)) def assertRotationIsClose(self, a, b): self.assertTrue(Gf.IsClose(a.GetReal(), b.GetReal(), 0.1)) self.assertTrue(Gf.IsClose(a.GetImaginary(), b.GetImaginary(), 0.1)) @property def camera_position(self): return self.camera.GetLocalTransformation(self.viewport.time).ExtractTranslation() @property def camera_rotation(self): return self.camera.GetLocalTransformation(self.viewport.time).ExtractRotation().GetQuaternion() async def test_viewport_scroll(self, is_locked: bool = False): """Test scrollwheel with a Viewport""" test_pos = [ Gf.Vec3d(500, 500, 500), Gf.Vec3d(1007.76, 1007.76, 1007.76), Gf.Vec3d(555.97, 555.97, 555.97), ] if is_locked: test_pos = [test_pos[0]] * len(test_pos) await ui_test.input.emulate_mouse_move_and_click(TEST_UI_CENTER) self.assertIsClose(self.camera_position, test_pos[0]) await ui_test.input.emulate_mouse_scroll(ui_test.Vec2(0, -2500)) await self.wait_n_updates(100) self.assertIsClose(self.camera_position, test_pos[1]) await ui_test.input.emulate_mouse_scroll(ui_test.Vec2(0, 1000)) await self.wait_n_updates(100) self.assertIsClose(self.camera_position, test_pos[2]) async def test_viewport_pan(self, is_locked: bool = False): """Test panning across a Viewport""" test_pos = [ Gf.Vec3d(500, 500, 500), Gf.Vec3d(1189.86, 500, -189.86), Gf.Vec3d(699.14, 101.7, 699.14), ] if is_locked: test_pos = [test_pos[0]] * len(test_pos) self.assertIsClose(self.camera_position, test_pos[0]) await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN, TEST_UI_RIGHT, TEST_UI_LEFT, MouseEventType.MIDDLE_BUTTON_UP) self.assertIsClose(self.camera_position, test_pos[1]) await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN, TEST_UI_LEFT, TEST_UI_RIGHT, MouseEventType.MIDDLE_BUTTON_UP) self.assertIsClose(self.camera_position, test_pos[0]) await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_TOP, MouseEventType.MIDDLE_BUTTON_UP) self.assertIsClose(self.camera_position, test_pos[2]) await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_BOTTOM, MouseEventType.MIDDLE_BUTTON_UP) self.assertIsClose(self.camera_position, test_pos[0]) async def test_viewport_look(self, is_locked: bool = False): """Test panning across a Viewport""" test_rot = [ Gf.Quaternion(0.88, Gf.Vec3d(-0.27, 0.36, 0.11)), Gf.Quaternion(-0.33, Gf.Vec3d(0.10, 0.89, 0.28)), Gf.Quaternion(0.86, Gf.Vec3d(0.33, 0.35, -0.13)), ] if is_locked: test_rot = [test_rot[0]] * len(test_rot) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_RIGHT, TEST_UI_LEFT, MouseEventType.RIGHT_BUTTON_UP) self.assertRotationIsClose(self.camera_rotation, test_rot[1]) await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_LEFT, TEST_UI_RIGHT, MouseEventType.RIGHT_BUTTON_UP) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_TOP, MouseEventType.RIGHT_BUTTON_UP) self.assertRotationIsClose(self.camera_rotation, test_rot[2]) await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_BOTTOM, MouseEventType.RIGHT_BUTTON_UP) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) async def __test_viewport_orbit_modifer_not_working(self, is_locked: bool = False): """Test orbit across a Viewport""" test_rot = [ Gf.Quaternion(0.88, Gf.Vec3d(-0.27, 0.36, 0.11)), Gf.Quaternion(-0.33, Gf.Vec3d(0.10, 0.89, 0.28)), Gf.Quaternion(0.86, Gf.Vec3d(0.33, 0.35, -0.13)), ] if is_locked: test_rot = [test_rot[0]] * len(test_rot) await ui_test.input.emulate_mouse_move_and_click(TEST_UI_CENTER) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN, TEST_UI_RIGHT, TEST_UI_LEFT, MouseEventType.LEFT_BUTTON_UP, KeyboardInput.LEFT_ALT) self.assertRotationIsClose(self.camera_rotation, test_rot[1]) await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN, TEST_UI_LEFT, TEST_UI_RIGHT, MouseEventType.LEFT_BUTTON_UP, KeyboardInput.LEFT_ALT) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_TOP, MouseEventType.LEFT_BUTTON_UP, KeyboardInput.LEFT_ALT) self.assertRotationIsClose(self.camera_rotation, test_rot[2]) await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_BOTTOM, MouseEventType.LEFT_BUTTON_UP, KeyboardInput.LEFT_ALT) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) async def test_viewport_lock(self): """Test the lock attribute blocks navigation""" self.camera.GetPrim().CreateAttribute("omni:kit:cameraLock", Sdf.ValueTypeNames.Bool, True).Set(True) await self.test_viewport_pan(is_locked=True) await self.test_viewport_look(is_locked=True) await self.test_viewport_scroll(is_locked=True)
9,868
Python
44.270642
109
0.582286
omniverse-code/kit/exts/omni.kit.window.tests/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.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 = "Kit Tests Window" description="Window to list/run all found python tests." # URL of the extension source repository. repository = "" # One of categories for UI. category = "Internal" # Keywords for the extension keywords = ["kit"] # https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" [dependencies] "omni.ui" = {} "omni.kit.test" = {} "omni.kit.commands" = {} [[python.module]] name = "omni.kit.window.tests" [[test]] args = ["--/exts/omni.kit.window.tests/openWindow=1"] stdoutFailPatterns.exclude = [] waiver = "Old UI, hard to test" # This window works well, but really needs an update on omni.ui. That will enable using ui_test to test. [settings] # Open window by default exts."omni.kit.window.tests".openWindow = false
1,028
TOML
24.09756
136
0.719844
omniverse-code/kit/exts/omni.kit.window.tests/omni/kit/window/_test_runner_window.py
"""Implementation of the manager of the Test Runner window. Exports only TestRunnerWindow: The object managing the window, a singleton. Instatiate it to create the window. Limitations: - When tests are running and extensions are disabled then enabled as part of it any tests owned by the disabled extensions are removed and not restored. Toolbar Interactions - what happens when each control on the toolbar is used: Run Selected: Gather the list of all selected tests and run them one at a time until completion (disabled when no tests exist) Select All: Add all tests to the selection list (disabled when all tests are currently selected) Deselect All: Remove all tests from the selection list (disabled when no tests are currently selected) Filter: Text that full tests names must match before being displayed Load Tests...: Reload the set of available tests from one of the plug-in options Properties: Display the settings in a separate window Note that all tests displayed must come from an enabled extension. To add tests on currently disabled extensions you would just enable the extension and the test list will be repopulated from the new set of enabled extensions. Similarly if you disable an extension its tests will be removed from the list. Individual Test Interactions - what happens when each per-test control is used: Checkbox: Adds or removes the test from the selection list Run: Run the one test and modify its icon to indicate test state Soak: Run the one test 1,000 times and modify its icon to indicate test state Open: Open the source file of the test script for the test (Final icon is updated to depict the state of the test - not run, running, successful, failed) TODO: Fix the text file processing to show potential missing extensions TODO: Add in editing of the user settings in the window # -------------------------------------------------------------------------------------------------------------- # def _edit_filter_settings(self): # # Emit the UI commands required to edit the filters defined in the user settings # from carb.settings import get_settings # include_tests = get_settings().get("/exts/omni.kit.test/includeTests") # exclude_tests = get_settings().get("/exts/omni.kit.test/excludeTests") """ from __future__ import annotations import asyncio from contextlib import suppress from enum import auto, Enum import fnmatch from functools import partial import logging from pathlib import Path import sys import unittest import carb import carb.settings import omni.ext import omni.kit.test import omni.kit.commands import omni.kit.app import omni.kit.ui from omni.kit.test import TestRunStatus from omni.kit.test import TestPopulator from omni.kit.test import TestPopulateAll from omni.kit.test import TestPopulateDisabled from omni.kit.test import DEFAULT_POPULATOR_NAME from omni.kit.window.properties import TestingPropertiesWindow import omni.ui as ui __all__ = ["TestRunnerWindow"] # Size constants _BUTTON_HEIGHT = 24 # ============================================================================================================== # Local logger for dumping debug information about the test runner window operation. # By default it is off but it can be enabled in the extension setup. _LOG = logging.getLogger("test_runner_window") # ============================================================================================================== class _TestUiEntry: """UI Data for a single test in the test runner""" def __init__(self, test: unittest.TestCase, file_path: str): """Initialize the entry with the given test""" self.test: unittest.TestCase = test # Test this entry manages self.checkbox: ui.Checkbox = None # Selection checkbox for this test self.sub_checked: ui.Subscription = None # Subscription to the checkbox change self.label_stack: ui.HStack = None # Container stack for the test module and name self.run_button: ui.Button = None # Button for running the test self.soak_button: ui.Button = None # Button for running the test 1000 times self.open_button: ui.Button = None # Button for opening the file containing the test self.file_path: Path = file_path # Path to the file containing the test self.status: TestRunStatus = TestRunStatus.UNKNOWN # Current test status self.status_label: ui.Label = None # Icon label indicating the test status def destroy(self): """Destroy the test entry; mostly to avoid leaking caused by dangling callbacks""" with suppress(AttributeError): self.sub_checked = None self.checkbox = None with suppress(AttributeError): self.run_button.set_clicked_fn(None) self.run_button = None with suppress(AttributeError): self.soak_button.set_clicked_fn(None) self.soak_button = None with suppress(AttributeError): self.open_button.set_clicked_fn(None) self.open_button = None def __del__(self): """Ensure the destroy is always called - it's safe to call it multiple times""" self.destroy() # ============================================================================================================== class _Buttons(Enum): """Index for all of the buttons created in the toolbar""" RUN = auto() # Run all selected tests SELECT_ALL = auto() # Select every listed test DESELECT_ALL = auto() # Deselect every listed test PROPERTIES = auto() # Open the properties window LOAD_MENU = auto() # Open the menu for loading a test list # ============================================================================================================== class _TestUiPopulator: """Base class for the objects used to populate the initial list of tests, before filtering.""" def __init__(self, populator: TestPopulator): """Set up the populator with the important information it needs for getting tests from some location Args: name: Name of the populator, which can be used for a menu description: Verbose description of the populator, which can be used for the tooltip of the menu item doing_what: Parameter to the descriptive waiting sentence "Rebuilding after {doing_what}..." source: Source type this populator implements """ self.populator = populator self._cached_tests: list[_TestUiEntry] = [] # -------------------------------------------------------------------------------------------------------------- @property def name(self) -> str: """The name of the populator""" return self.populator.name @property def description(self) -> str: """The description of the populator""" return self.populator.description @property def tests(self) -> list[_TestUiEntry]: """The list of test UI entries gleaned from the raw test list supplied by the populator implementation""" if not self._cached_tests: _LOG.info("Translating %d unit tests into a _TestUiEntry list", len(self.populator.tests)) self._cached_tests = {} for test in self.populator.tests: try: file_path = sys.modules[test.__module__].__file__ except KeyError: # if the module is not enabled the test does not belong in the list continue entry = _TestUiEntry(test, file_path) self._cached_tests[test.id()] = entry return self._cached_tests # -------------------------------------------------------------------------------------------------------------- def clear(self): """Remove the cache so that it can be rebuilt on demand, usually if the contents might have changed""" self._cached_tests = {} # -------------------------------------------------------------------------------------------------------------- def destroy(self): """Opportunity to clean up any allocated resources""" self._cached_tests = {} self.populator.destroy() # -------------------------------------------------------------------------------------------------------------- def get_tests(self, call_when_done: callable): """Main method for retrieving the list of tests that the populator provides. When the tests are available invoke the callback with the test list. call_when_done(_TestUiPopulator, canceled: bool) """ def __create_cache(canceled: bool = False): call_when_done(self, canceled) if not self._cached_tests: self.populator.get_tests(__create_cache) else: call_when_done(self) # ============================================================================================================== class TestRunnerWindow: """Managers the window containing the test runner Members: _buttons: Dictionary of _Buttons:ui.Button for all of the toolbar buttons _change_sub: Subscription to the extension list change event _count: Temporary variable to count number of iterations during test soak _filter_begin_edit_sub: Subscription to the start of editing the filter text field _filter_end_edit_sub: Subscription to the end of editing the filter text field _filter_hint: Label widget holding the overlay text for the filter text field _filter_regex: Expression on which to filter the list of source tests _filter: StringField widget holding the filter text _is_running_tests: Are the selected tests currently running? _load_menu: UI Widget containing the menu used for loading the test list _properties_window: The temporary dialog that displays the test running properties set by the user _refresh_task: Async task to refresh the test status values as they are completed _status_label: Text to show in the label in the toolbar that shows test counts _test_frame: UI Widget encompassing the frame containing the list of tests to run _test_list_source_rc: RadioCollection containing the test source choices _test_populators: Dictionary of name:_TestUiPopulator used to populate the full list of tests in the window _tests: Dictionary of (ID, Checkbox) corresponding to all visible tests _tests_selected: Number of tests in the dictionary currently selected. This is maintained on the fly to avoid an O(N^2) update problem when monitoring checkbox changes and updating the SelectAll buttons _toolbar_frame: UI Widget encompassing the set of tools at the top of the window _ui_status_label: UI Widget containing the label displaying test runner status _window: UI Widget of the toolbar window """ # Location of the window in the larger UI element path space WINDOW_NAME = "Test Runner" MENU_PATH = f"Window/{WINDOW_NAME}" _POPULATORS = [TestPopulateAll(), TestPopulateDisabled()] WINDOW_MANAGER = None # -------------------------------------------------------------------------------------------------------------- # API for adding and removing custom populators of the test list @classmethod def add_populator(cls, new_populator: TestPopulator): """Adds the new populator to the available list, raising ValueError if there already is one with that name""" if new_populator in cls._POPULATORS: raise ValueError(f"Tried to add the same populator twice '{new_populator.name}'") cls._POPULATORS.append(new_populator) # Updating the window allows dynamic adding and removal of populator types if cls.WINDOW_MANAGER is not None: cls.WINDOW_MANAGER._test_populators[new_populator.name] = _TestUiPopulator(new_populator) # noqa: PLW0212 cls.WINDOW_MANAGER._toolbar_frame.rebuild() # noqa: PLW0212 @classmethod def remove_populator(cls, populator_to_remove: str): """Removes the populator with the given name, raising KeyError if it does not exist""" to_remove = None for populator in cls._POPULATORS: if populator.name == populator_to_remove: to_remove = populator break if to_remove is None: raise KeyError(f"Trying to remove populator named {populator_to_remove} before adding it") # Updating the window allows dynamic adding and removal of populator types if cls.WINDOW_MANAGER is not None: del cls.WINDOW_MANAGER._test_populators[populator_to_remove] # pylint: disable=protected-access cls.WINDOW_MANAGER._toolbar_frame.rebuild() # pylint: disable=protected-access cls._POPULATORS.remove(to_remove) def __init__(self, start_open: bool): """Set up the window and open it if the setting to always open it is enabled""" TestRunnerWindow.WINDOW_MANAGER = self self._buttons: dict[_Buttons, ui.Button] = {} self._change_sub: carb.Subscription = None self._count: int = 0 self._filter_begin_edit_sub: carb.Subscription = None self._filter_end_edit_sub: carb.Subscription = None self._filter_hint: ui.Label = None self._filter_regex: str = "" self._filter: ui.StringField = None self._is_running_tests: bool = False self._load_menu: ui.Menu = None self._test_file_path: Path = None self._properties_window: TestingPropertiesWindow = None self._refresh_task: asyncio.Task = None self._test_frame: ui.ScrollingFrame = None self._status_label: str = "Checking for tests..." self._test_list_source_rc: ui.RadioCollection = None self._tests: dict[str, ui.CheckBox] = {} self._tests_selected: int = 0 self._test_populators = { populator.name: _TestUiPopulator(populator) for populator in self._POPULATORS } self._test_populator: TestPopulator = None self._toolbar_frame: ui.Frame = None self._ui_status_label: ui.Label = None _LOG.info("Initializing the main window") manager = omni.kit.app.get_app().get_extension_manager() self._change_sub = manager.get_change_event_stream().create_subscription_to_pop( self.on_extensions_changed, name="test_runner extensions change event" ) self._window = ui.Window( self.WINDOW_NAME, menu_path=self.MENU_PATH, width=1200, height=800, dockPreference=ui.DockPreference.RIGHT_TOP, visibility_changed_fn=self._visibility_changed, width_changed_fn=self._width_changed, ) with self._window.frame: with ui.VStack(): self._toolbar_frame = ui.Frame(height=_BUTTON_HEIGHT + 4) self._toolbar_frame.set_build_fn(self._build_toolbar_frame) with self._toolbar_frame: self._build_toolbar_frame() self._test_frame = ui.ScrollingFrame( vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, ) self._test_frame.set_build_fn(self._build_test_frame) # Populate the initial test list self._populate_test_entries(self._test_populators[DEFAULT_POPULATOR_NAME]) self._window.visible = start_open # -------------------------------------------------------------------------------------------------------------- def destroy(self): """Detach all subscriptions and destroy the window elements to avoid dangling callbacks and UI elements""" _LOG.info("Destroying the main window {") self.WINDOW_MANAGER = None if self._window is not None: self._window.visible = False # Remove the callbacks first for _button_id, button in self._buttons.items(): button.set_clicked_fn(None) self._buttons = {} for populator in self._test_populators.values(): populator.destroy() self._test_populators = None # Remove the widget elements before removing the window itself self._clean_refresh_task() self._change_sub = None self._count = 0 self._filter = None self._filter_begin_edit_sub = None self._filter_end_edit_sub = None self._filter_hint = None self._filter_regex = "" self._load_menu = None self._ui_status_label = None self._status_label = None self._test_list_source_rc = None self._test_populator = None self._tests = {} self._tests_selected = 0 if self._properties_window is not None: self._properties_window.destroy() del self._properties_window self._properties_window = None if self._toolbar_frame is not None: self._toolbar_frame.set_build_fn(None) del self._toolbar_frame self._toolbar_frame = None if self._test_frame is not None: self._test_frame.set_build_fn(None) del self._test_frame self._test_frame = None if self._window is not None: self._window.set_visibility_changed_fn(None) self._window.set_width_changed_fn(None) self._window.frame.set_build_fn(None) del self._window self._window = None # -------------------------------------------------------------------------------------------------------------- @property def visible(self) -> bool: return self._window.visible if self._window is not None else False @visible.setter def visible(self, visible: bool): if self._window is not None: self._window.visible = visible elif visible: raise ValueError("Tried to change visibility after window was destroyed") def _visibility_changed(self, visible: bool): """Update the menu with the visibility state""" _LOG.info("Window visibility changed to %s", visible) editor_menu = omni.kit.ui.EditorMenu() editor_menu.set_value(self.MENU_PATH, visible) # -------------------------------------------------------------------------------------------------------------- def _width_changed(self, new_width: float): """Update the sizing of the test frame when the window size changes""" _LOG.info("Window width changed to %f", new_width) if self._test_frame is not None: self._resize_test_frame(new_width) # -------------------------------------------------------------------------------------------------------------- def on_extensions_changed(self, *_): """Callback executed when the known extensions may have changed.""" # Protect calls to _LOG since if it's this extension being disabled it may not exist if self._is_running_tests: if _LOG is not None: _LOG.info("Extension changes ignored while tests are running as it could be part of the tests") else: if _LOG is not None: _LOG.info("Extensions were changed, tests are rebuilding") for populator in self._test_populators.values(): populator.clear() self._refresh_after_tests_complete(load_tests=True, cause="extensions changed") # -------------------------------------------------------------------------------------------------------------- def _refresh_after_tests_complete(self, load_tests: bool, cause: str, new_populator: TestPopulator = None): """Refresh the window information after the tests finish running. If load_tests is True then reconstruct all of the tests from the current test source selected. If cause is not empty then place a temporary message in the test pane to indicate a rebuild is happening. If a new_populator is specified then it will replace the existing one if its population step succeeds, otherwise the original will remain. """ async def _delayed_refresh(): try: # Busy wait until the tests are done running slept = 0.0 while self._is_running_tests: _LOG.debug("....sleep(%f)", slept) slept += 0.2 await asyncio.sleep(0.2) # Refresh the test information _LOG.info("Delayed refresh triggered with load_tests=%s", load_tests) if cause: self._ui_status_label.text = f"Rebuilding after {cause}..." await omni.kit.app.get_app().next_update_async() if load_tests: _LOG.info("...repopulating the test list") self._populate_test_entries(new_populator) else: _LOG.info("...rebuilding the test frame") with self._test_frame: self._build_test_frame() except asyncio.CancelledError: pass except Exception as error: # pylint: disable=broad-except carb.log_warn(f"Failed to refresh content of window.tests. Error: '{error}' {type(error)}.") self._clean_refresh_task() self._refresh_task = asyncio.ensure_future(_delayed_refresh()) # -------------------------------------------------------------------------------------------------------------- def _update_toolbar_status(self): """Update the state of the elements in the toolbar, avoiding a full rebuild when values change""" filtered_tests = self._filtered_tests() _LOG.info("Refreshing the toolbar status for %d tests", len(filtered_tests)) any_on = self._tests_selected > 0 any_off = self._tests_selected < len(filtered_tests) _LOG.info(" RUN=%s, SELECT_ALL=%s, DESELECT_ALL=%s", any_on, any_off, any_on) self._buttons[_Buttons.RUN].enabled = any_on self._buttons[_Buttons.SELECT_ALL].enabled = any_off self._buttons[_Buttons.DESELECT_ALL].enabled = any_on _LOG.info("Reset status to '%s'", self._status_label) self._ui_status_label.text = self._status_label # -------------------------------------------------------------------------------------------------------------- def _build_toolbar_frame(self): """Emit the UI commands required to build the toolbar that appears at the top of the window""" _LOG.info("Rebuilding the toolbar frame") # Defining the toolbar callbacks at the top of this method because they are so small def on_run(*_): _LOG.info("Hit the Run button") tests = [entry.test for entry in self._tests.values() if entry.checkbox.model.as_bool] self._run_tests(tests) def on_select_all(*_): _LOG.info("Hit the Select All button") filtered_tests = self._filtered_tests() for entry in filtered_tests.values(): entry.checkbox.model.set_value(True) self._tests_selected = len(filtered_tests) self._update_toolbar_status() def on_deselect_all(*_): _LOG.info("Hit the Deselect All button") filtered_tests = self._filtered_tests() for entry in filtered_tests.values(): entry.checkbox.model.set_value(False) self._tests_selected = 0 self._update_toolbar_status() def _on_filter_begin_edit(model: ui.AbstractValueModel): self._filter_hint.visible = False def _on_filter_end_edit(model: ui.AbstractValueModel): if len(model.get_value_as_string()) == 0: self._filter_hint.visible = True self._filter_regex = "" else: self._filter_regex = f"*{model.get_value_as_string()}*" _LOG.info("Reset filter to '%s'", self._filter_regex) self._refresh_after_tests_complete(load_tests=False, cause="filter changed") def on_properties(*_): _LOG.info("Hit the Properties button") if self._properties_window is None: self._properties_window = TestingPropertiesWindow() self._properties_window.show() # + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + with ui.HStack(height=_BUTTON_HEIGHT + 4, style={"Button.Label:disabled": {"color": 0xFF606060}}): self._buttons[_Buttons.RUN] = ui.Button( "Run Selected", clicked_fn=on_run, width=ui.Percent(10), style={"border_radius": 5.0}) self._buttons[_Buttons.SELECT_ALL] = ui.Button( "Select All", clicked_fn=on_select_all, width=ui.Percent(10), style={"border_radius": 5.0}) self._buttons[_Buttons.DESELECT_ALL] = ui.Button( "Deselect All", clicked_fn=on_deselect_all, width=ui.Percent(10), style={"border_radius": 5.0}) with ui.ZStack(width=ui.Percent(20)): ui.Spacer(width=ui.Pixel(10)) # Trick required to give the string field a greyed out "hint" as to what should be typed in it self._filter = ui.StringField(height=_BUTTON_HEIGHT) self._filter_hint = ui.Label( " Filter (*, ?)", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F} ) if self._filter_regex: self._filter.model.set_value(self._filter_regex[1:-1]) self._filter_hint.visible = False self._filter_begin_edit_sub = self._filter.model.subscribe_begin_edit_fn(_on_filter_begin_edit) self._filter_end_edit_sub = self._filter.model.subscribe_value_changed_fn(_on_filter_end_edit) with ui.HStack(height=0, width=ui.Percent(20)): ui.Spacer(width=ui.Pixel(3)) def __on_flag_set(populator): _LOG.info("Invoking load menu with %s", populator) self._load_menu = None self._refresh_after_tests_complete( load_tests=True, cause=f"selecting populator '{populator.name}'", new_populator=populator ) def __show_load_menu(mouse_x: int, mouse_y: int, mouse_button: int, modifier: int): _LOG.info("Invoked load menu at %d,%d - B%d/%d", mouse_x, mouse_y, mouse_button, modifier) widget = self._buttons[_Buttons.LOAD_MENU] self._load_menu = ui.Menu() with self._load_menu: for populator_name in sorted(self._test_populators.keys()): populator = self._test_populators[populator_name] ui.MenuItem( populator.name, triggered_fn=partial(__on_flag_set, populator), checkable=True, checked=( self._test_populator is not None and (populator.name == self._test_populator.name) ), ) self._load_menu.show_at( (int)(widget.screen_position_x), (int)(widget.screen_position_y + widget.computed_content_height) ) self._buttons[_Buttons.LOAD_MENU] = ui.Button( "Load Tests From...", height=_BUTTON_HEIGHT + 4, width=0, mouse_released_fn=__show_load_menu, style={"border_radius": 5.0}, ) with ui.HStack(width=ui.Percent(10)): self._buttons[_Buttons.PROPERTIES] = ui.Button( "Properties", clicked_fn=on_properties, style={"border_radius": 5.0}, ) ui.Spacer(width=ui.Pixel(10)) with ui.HStack(height=_BUTTON_HEIGHT + 4, width=ui.Percent(15)): self._ui_status_label = ui.Label("Initializing tests...") # -------------------------------------------------------------------------------------------------------------- def _space_for_test_labels(self, full_width: float) -> float: """Returns the number of pixels available for the test labels in the test frame, for manual resizing""" label_space = full_width - 20 - 45 - 50 - 50 - 30 - 5 * 3 # Arbitrary "minimum readable" limit if label_space < 200: _LOG.info("Label space went below the threshold of 200 to %f, clipping it to 200", label_space) label_space = 200 return label_space # -------------------------------------------------------------------------------------------------------------- def _resize_test_frame(self, new_size: float): """Reset the manually computed size for all of the elements in the test frame. Avoids full rebuild.""" label_space = self._space_for_test_labels(new_size) _LOG.info("Resizing test frame with %d pixels of %d for labels", label_space, new_size) for _test_id, entry in self._tests.items(): if entry.label_stack is None: continue entry.label_stack.width = ui.Pixel(int(label_space)) # -------------------------------------------------------------------------------------------------------------- def _filtered_tests(self) -> dict[str, ui.CheckBox]: return { test_id: entry for test_id, entry in self._tests.items() if (not self._filter_regex) or fnmatch.fnmatch(test_id.lower(), self._filter_regex.lower()) } # -------------------------------------------------------------------------------------------------------------- def _build_test_frame(self): """Emit the UI commands required to populate the test frame with the list of visible tests""" _LOG.info("Rebuilding the test frame with %d tests", len(self._tests)) # Compute the space available for the test names by taking the total frame width and subtracting the size # used by the checkbox, run button, soak button, open button, and status icon, plus spacing between them label_space = self._space_for_test_labels(self._window.frame.computed_width) with ui.VStack(): ui.Spacer(height=ui.Pixel(10)) filtered_tests = self._filtered_tests() for test_id, entry in filtered_tests.items(): # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Test-specific callbacks def on_checked(check_model: ui.AbstractValueModel): filtered_tests = self._filtered_tests() if check_model.as_bool: self._tests_selected += 1 if self._tests_selected in (1, len(filtered_tests)): self._update_toolbar_status() else: self._tests_selected -= 1 if self._tests_selected in (0, len(filtered_tests) - 1): self._update_toolbar_status() def on_run_test(*_, test: unittest.TestCase = entry.test): self._run_tests([test]) def on_soak_test(*_, test: unittest.TestCase = entry.test): self._run_tests([test], repeats=1000) def on_open(*_, path: str = entry.file_path): import webbrowser webbrowser.open(path) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Test row entry.hstack = ui.HStack(spacing=2, height=0, width=ui.Percent(100)) with entry.hstack: entry.checkbox = ui.CheckBox( value=False, on_changed_fn=on_checked, style={"margin_height": 2}, width=20, ) entry.sub_checked = entry.checkbox.model.subscribe_value_changed_fn(on_checked) test_class, test_method = test_id.rsplit(".", 1) entry.label_stack = ui.HStack(width=label_space) with entry.label_stack: entry.label1 = ui.Label( test_class, tooltip=entry.file_path, elided_text=True, alignment=ui.Alignment.LEFT_TOP, width=ui.Fraction(2), ) entry.label2 = ui.Label( test_method, tooltip=test_method, elided_text=True, alignment=ui.Alignment.LEFT_TOP, width=ui.Fraction(1), ) entry.run_button = ui.Button("Run", clicked_fn=on_run_test, width=45) entry.soak_button = ui.Button("Soak", clicked_fn=on_soak_test, width=50) entry.open_button = ui.Button("Open", clicked_fn=on_open, width=50) entry.status_label = ui.Label("", width=30) entry.status = TestRunStatus.UNKNOWN self._refresh_test_status(test_id) tests_available = len(self._tests) tests_used = len(filtered_tests) if self._test_populator is not None: self._status_label = f"Showing {tests_used} of {tests_available} test(s) from {self._test_populator.name}" else: self._status_label = f"Showing {tests_used} of {tests_available} test(s) with no populator" self._update_toolbar_status() # -------------------------------------------------------------------------------------------------------------- def _refresh_test_status(self, test_id: str): _LOG.debug("Refresh status of test %s to %s", test_id, self._tests[test_id].status) status = self._tests[test_id].status status_to_svg = { TestRunStatus.UNKNOWN: "${glyphs}/question.svg", TestRunStatus.RUNNING: "${glyphs}/spinner.svg", TestRunStatus.FAILED: "${glyphs}/exclamation.svg", TestRunStatus.PASSED: "${glyphs}/check_solid.svg", } status_to_color = { TestRunStatus.UNKNOWN: 0xFFFFFFFF, TestRunStatus.RUNNING: 0xFFFF7D7D, TestRunStatus.PASSED: 0xFF00FF00, TestRunStatus.FAILED: 0xFF0000FF, } code = ui.get_custom_glyph_code(status_to_svg.get(status, "")) label = self._tests[test_id].status_label label.text = f"{code}" label.set_style({"color": status_to_color[status]}) # -------------------------------------------------------------------------------------------------------------- def _set_test_status(self, test_id: str, status: TestRunStatus): _LOG.info("Setting status of test '%s' to %s", test_id, status) try: self._tests[test_id].status = status self._refresh_test_status(test_id) except KeyError: _LOG.warning("...could not find test %s in the list", test_id) # -------------------------------------------------------------------------------------------------------------- def _set_is_running(self, running: bool): _LOG.info("Change running state to %s", running) self._is_running_tests = running self._buttons[_Buttons.RUN].enabled = not running if running: self._ui_status_label.text = "Running Tests..." else: self._ui_status_label.text = "" # ------------------------------------------------------------------------------------------------------------- def _populate_test_entries(self, new_populator: TestPopulator = None): """Repopulate the test entry information based on the current filtered source test list. If a new_populator is specified then set the current one to it if the population succeeded, otherwise retain the original. """ async def __populate(): _LOG.info("Retrieving the tests from the populator") def __repopulate(populator: _TestUiPopulator, canceled: bool = False): if canceled: _LOG.info("...test retrieval was canceled") self._test_frame.enabled = True else: self._tests_selected = 0 self._tests = populator.tests if new_populator is not None: self._test_populator = new_populator _LOG.info("...triggering the test frame rebuild after repopulation") self._test_frame.enabled = True self._test_frame.rebuild() self._test_frame.enabled = False if new_populator is not None: new_populator.get_tests(__repopulate) elif self._test_populator is not None: self._test_populator.get_tests(__repopulate) asyncio.ensure_future(__populate()) # -------------------------------------------------------------------------------------------------------------- def _run_tests(self, tests, repeats=0, ignore_running=False): """Find all of the selected tests and execute them all asynchronously""" _LOG.info("Running the tests with a repeat of %d", repeats) if self._is_running_tests and not ignore_running: _LOG.info("...skipping, already running the tests") return def on_finish(runner): if self._count > 0: self._count -= 1 print(f"\n\n\n\n{'-'*40} Iteration {self._count} {'-'*40}\n\n") self._run_tests(tests, self._count, ignore_running=True) return self._set_is_running(False) def on_status_report(test_id, status, **_): self._set_test_status(test_id, status) self._count = repeats self._set_is_running(True) for t in tests: self._set_test_status(t.id(), TestRunStatus.UNKNOWN) omni.kit.test.run_tests(tests, on_finish, on_status_report) # -------------------------------------------------------------------------------------------------------------- def _clean_refresh_task(self): """Clean up the refresh task, canceling it if it is in progress first""" with suppress(asyncio.CancelledError, AttributeError): self._refresh_task.cancel() self._refresh_task = None
39,484
Python
48.854798
119
0.54731
omniverse-code/kit/exts/omni.kit.window.tests/omni/kit/window/tests.py
"""Implementation of the extension containing the Test Runner window.""" import logging import sys import carb import omni.ext from omni.kit.ui import EditorMenu # Cannot do relative imports here due to the way the omni.kit.window import space is duplicated in multiple extensions from omni.kit.window._test_runner_window import _LOG from omni.kit.window._test_runner_window import TestRunnerWindow # ============================================================================================================== class Extension(omni.ext.IExt): """The extension manager that handles the life span of the test runner window""" def __init__(self): self._test_runner_window = None self._menu_item = None super().__init__() def _show_window(self, menu: str, value: bool): if self._test_runner_window is None: self._test_runner_window = TestRunnerWindow(value) else: self._test_runner_window.visible = value def on_startup(self): _LOG.disabled = True # Set to False to dump out debugging information for the extension if not _LOG.disabled: _handler = logging.StreamHandler(sys.stdout) _handler.setFormatter(logging.Formatter("TestRunner: %(levelname)s: %(message)s")) _LOG.addHandler(_handler) _LOG.setLevel(logging.INFO) _LOG.info("Starting up the test runner extension") open_window = carb.settings.get_settings().get("/exts/omni.kit.window.tests/openWindow") self._menu_item = EditorMenu.add_item(TestRunnerWindow.MENU_PATH, self._show_window, toggle=True, value=open_window) if open_window: self._show_window(TestRunnerWindow.MENU_PATH, True) def on_shutdown(self): """Cleanup the constructed elements""" _LOG.info("Shutting down the test runner extension") if self._test_runner_window is not None: _LOG.info("Destroying the test runner window") self._test_runner_window.visible = False self._test_runner_window.destroy() self._test_runner_window = None EditorMenu.remove_item(TestRunnerWindow.MENU_PATH) handler_list = _LOG.handlers for handler in handler_list: _LOG.removeHandler(handler) self._menu_item = None
2,333
Python
41.436363
124
0.63009
omniverse-code/kit/exts/omni.kit.window.tests/omni/kit/window/properties.py
import carb import carb.settings import omni.kit.app import omni.ui as ui HUMAN_DELAY_SETTING = "/exts/omni.kit.ui_test/humanDelay" class TestingPropertiesWindow: def __init__(self): self._window = ui.Window("Testing Properties", width=400, height=200, flags=ui.WINDOW_FLAGS_NO_DOCKING) self._window.visible = False def destroy(self): self._window = None def show(self): if not self._window.visible: self._window.visible = True self.refresh() def refresh(self): with self._window.frame: with ui.VStack(height=0): settings = carb.settings.get_settings() ui.Spacer(height=10) ui.Label("Test Settings:", style={"color": 0xFFB7F222, "font_size": 16}) ui.Spacer(height=5) for key in ["/exts/omni.kit.test/includeTests", "/exts/omni.kit.test/excludeTests"]: value = settings.get(key) ui.Label(f"{key}: {value}") ui.Spacer(height=5) # Setting specific to UI tests manager = omni.kit.app.get_app().get_extension_manager() if manager.is_extension_enabled("omni.kit.ui_test"): ui.Spacer(height=10) ui.Label("UI Test (omni.kit.ui_test) Settings:", style={"color": 0xFFB7F222, "font_size": 16}) ui.Spacer(height=5) with ui.HStack(height=0): ui.Label("UI Test Delay (s)") delay_widget = ui.FloatDrag(min=0, max=1000000) delay_widget.model.set_value(settings.get_as_float(HUMAN_DELAY_SETTING)) delay_widget.model.add_value_changed_fn( lambda m: settings.set(HUMAN_DELAY_SETTING, m.get_value_as_float()) )
1,912
Python
35.094339
114
0.538703
omniverse-code/kit/exts/omni.kit.exec.core/omni/kit/exec/core/unstable/__init__.py
"""Python Module Initialization for omni.kit.exec.core""" from ._omni_kit_exec_core_unstable import * from .scripts.extension import _PublicExtension
151
Python
29.399994
57
0.781457
omniverse-code/kit/exts/omni.kit.exec.core/omni/kit/exec/core/unstable/_omni_kit_exec_core_unstable.pyi
from __future__ import annotations import omni.kit.exec.core.unstable._omni_kit_exec_core_unstable import typing __all__ = [ "dump_graph_topology" ] def dump_graph_topology(fileName: str) -> None: """ Write the default execution controller's corresponding execution graph topology out as a GraphViz file. """
328
unknown
22.499998
107
0.713415
omniverse-code/kit/exts/omni.kit.widget.prompt/config/extension.toml
[package] title = "Prompt dialog for omni.ui widgets" category = "Internal" description = "Prompt dialog for use with omni.ui widgets" version = "1.0.5" authors = ["NVIDIA"] repository = "" keywords = ["widget"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.ui" = {} [[python.module]] name = "omni.kit.widget.prompt" [[test]] args = [ "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.commands", "omni.kit.selection", "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.ui_test" ] stdoutFailPatterns.include = [] stdoutFailPatterns.exclude = []
757
TOML
20.055555
58
0.667107
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/extension.py
import omni.ext from .prompt import PromptManager class PromptExtension(omni.ext.IExt): def on_startup(self): PromptManager.on_startup() def on_shutdown(self): PromptManager.on_shutdown()
225
Python
16.384614
37
0.671111
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/prompt.py
from typing import Callable, List import carb import carb.input import omni import uuid class PromptButtonInfo: def __init__(self, name: str, on_button_clicked_fn: Callable[[], None] = None): self._name = name self._on_button_clicked_fn = on_button_clicked_fn @property def name(self): return self._name @property def on_button_clicked_fn(self): return self._on_button_clicked_fn class PromptManager: _prompts = set([]) @staticmethod def on_startup(): pass @staticmethod def on_shutdown(): all_prompts = PromptManager._prompts PromptManager._prompts = set([]) for prompt in all_prompts: prompt.destroy() @staticmethod def query_prompt_by_title(title: str): for prompt in PromptManager._prompts: if prompt._title == title: return prompt return None @staticmethod def add_prompt(prompt): if prompt not in PromptManager._prompts: PromptManager._prompts.add(prompt) @staticmethod def remove_prompt(prompt): if prompt in PromptManager._prompts: PromptManager._prompts.remove(prompt) @staticmethod def post_simple_prompt( title: str, message: str, ok_button_info: PromptButtonInfo = PromptButtonInfo("OK", None), cancel_button_info: PromptButtonInfo = None, middle_button_info: PromptButtonInfo = None, middle_2_button_info: PromptButtonInfo = None, on_window_closed_fn: Callable[[], None] = None, modal=True, shortcut_keys=True, standalone=True, no_title_bar=False, width=None, height=None, callback_addons: List = [], ): """When standalone is true, it will hide all other managed prompts in this manager.""" def unwrap_button_info(button_info: PromptButtonInfo): if button_info: return button_info.name, button_info.on_button_clicked_fn else: return None, None ok_button_text, ok_button_fn = unwrap_button_info(ok_button_info) cancel_button_text, cancel_button_fn = unwrap_button_info(cancel_button_info) middle_button_text, middle_button_fn = unwrap_button_info(middle_button_info) middle_2_button_text, middle_2_button_fn = unwrap_button_info(middle_2_button_info) if standalone: prompts = PromptManager._prompts PromptManager._prompts = set([]) for prompt in prompts: prompt.destroy() prompt = Prompt( title, message, ok_button_text=ok_button_text, cancel_button_text=cancel_button_text, middle_button_text=middle_button_text, middle_2_button_text=middle_2_button_text, ok_button_fn=ok_button_fn, cancel_button_fn=cancel_button_fn, middle_button_fn=middle_button_fn, middle_2_button_fn=middle_2_button_fn, modal=modal, on_closed_fn=on_window_closed_fn, shortcut_keys=shortcut_keys, no_title_bar=no_title_bar, width=width, height=height, callback_addons=callback_addons ) prompt.show() return prompt class Prompt: """Pop up a prompt window that asks the user a simple question with up to four buttons for answers. Callbacks are executed for each button press, as well as when the window is closed manually. """ def __init__( self, title, text, ok_button_text="OK", cancel_button_text=None, middle_button_text=None, middle_2_button_text=None, ok_button_fn=None, cancel_button_fn=None, middle_button_fn=None, middle_2_button_fn=None, modal=False, on_closed_fn=None, shortcut_keys=True, no_title_bar=False, width=None, height=None, callback_addons: List = [] ): """Initialize the callbacks and window information Args: title: Text appearing in the titlebar of the window text: Text of the question being posed to the user ok_button_text: Text for the first button cancel_button_text: Text for the last button middle_button_text: Text for the middle button middle_button_2_text: Text for the second middle button ok_button_fn: Function executed when the first button is pressed cancel_button_fn: Function executed when the last button is pressed middle_button_fn: Function executed when the middle button is pressed middle_2_button_fn: Function executed when the second middle button is pressed modal: True if the window is modal, shutting down other UI until an answer is received on_closed_fn: Function executed when the window is closed without hitting a button shortcut_keys: If it can be confirmed or hidden with shortcut keys like Enter or ESC. no_title_bar: If it needs to show title bar. width: The specified width. By default, it will use the computed width. height: The specified height. By default, it will use the computed height. callback_addons: Addon widgets which is appended in the prompt window. By default, it is empty """ self._title = title self._text = text self._cancel_button_text = cancel_button_text self._cancel_button_fn = cancel_button_fn self._ok_button_fn = ok_button_fn self._ok_button_text = ok_button_text self._middle_button_text = middle_button_text self._middle_button_fn = middle_button_fn self._middle_2_button_text = middle_2_button_text self._middle_2_button_fn = middle_2_button_fn self._modal = modal self._on_closed_fn = on_closed_fn self._button_clicked = False self._shortcut_keys = shortcut_keys self._no_title_bar = no_title_bar self._width = width self._height = height self._callback_addons = callback_addons self._key_functions = { int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn, int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn } self._buttons = [] self._build_ui() def __del__(self): self.destroy() def destroy(self): for button in self._buttons: button.set_clicked_fn(None) self._buttons.clear() self.hide() if self._window: self._window.set_visibility_changed_fn(None) self._window = None def __enter__(self): """Called on entering a 'with' loop""" self.show() return self def __exit__(self, type, value, trace): """Called on exiting a 'with' loop""" self.hide() @property def visible(self): return self.is_visible() @visible.setter def visible(self, value): if value: self.show() else: self.hide() def show(self): """Make the prompt window visible""" if not self._window: self._build_ui() self._window.visible = True self._button_clicked = False PromptManager.add_prompt(self) def hide(self): """Make the prompt window invisible""" if self._window: self._window.visible = False PromptManager.remove_prompt(self) def is_visible(self): """Returns True if the prompt is currently visible""" return self._window and self._window.visible def set_text(self, text): """Set a new question label""" self._text_label.text = text def set_confirm_fn(self, on_ok_button_clicked): """Define a new callback for when the first (okay) button is clicked""" self._ok_button_fn = on_ok_button_clicked def set_cancel_fn(self, on_cancel_button_clicked): """Define a new callback for when the third (cancel) button is clicked""" self._cancel_button_fn = on_cancel_button_clicked def set_middle_button_fn(self, on_middle_button_clicked): """Define a new callback for when the second (middle) button is clicked""" self._middle_button_fn = on_middle_button_clicked def set_middle_2_button_fn(self, on_middle_2_button_clicked): self._middle_2_button_fn = on_middle_2_button_clicked def set_on_closed_fn(self, on_on_closed): """Define a new callback for when the window is closed without pressing a button""" self._on_closed_fn = on_on_closed def _on_visibility_changed(self, new_visibility: bool): """Callback executed when visibility of the window closes""" if not new_visibility: if not self._button_clicked and self._on_closed_fn is not None: self._on_closed_fn() self.hide() def _on_ok_button_fn(self): """Callback executed when the first (okay) button is pressed""" self._button_clicked = True self.hide() if self._ok_button_fn: self._ok_button_fn() def _on_cancel_button_fn(self): """Callback executed when the third (cancel) button is pressed""" self._button_clicked = True self.hide() if self._cancel_button_fn: self._cancel_button_fn() def _on_middle_button_fn(self): """Callback executed when the second (middle) button is pressed""" self._button_clicked = True self.hide() if self._middle_button_fn: self._middle_button_fn() def _on_closed_fn(self): """Callback executed when the window is closed without pressing a button""" self._button_clicked = True self.hide() if self._on_closed_fn: self._on_closed_fn() def _on_middle_2_button_fn(self): self._button_clicked = True self.hide() if self._middle_2_button_fn: self._middle_2_button_fn() def _on_key_pressed_fn(self, key, mod, pressed): if not pressed or not self._shortcut_keys: return func = self._key_functions.get(key) if func: func() def _build_ui(self): """Construct the window based on the current parameters""" num_buttons = 0 if self._ok_button_text: num_buttons += 1 if self._cancel_button_text: num_buttons += 1 if self._middle_button_text: num_buttons += 1 if self._middle_2_button_text: num_buttons += 1 button_width = 120 spacer_width = 60 if self._width: window_width = self._width else: window_width = button_width * num_buttons + spacer_width * 2 if window_width < 400: window_width = 400 if self._height: window_height = self._height else: window_height = 0 if self._title: window_id = self._title else: # Generates unique id for this window to make sure all prompts are unique. window_id = f"##{str(uuid.uuid1())}" self._window = omni.ui.Window( window_id, visible=False, height=window_height, width=window_width, dockPreference=omni.ui.DockPreference.DISABLED, visibility_changed_fn=self._on_visibility_changed, ) self._window.flags = ( omni.ui.WINDOW_FLAGS_NO_COLLAPSE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_RESIZE | omni.ui.WINDOW_FLAGS_NO_MOVE ) self._window.set_key_pressed_fn(self._on_key_pressed_fn) if self._no_title_bar: self._window.flags = self._window.flags | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR if self._modal: self._window.flags = self._window.flags | omni.ui.WINDOW_FLAGS_MODAL num_buttons = 0 if self._ok_button_text: num_buttons += 1 if self._cancel_button_text: num_buttons += 1 if self._middle_button_text: num_buttons += 1 if self._middle_2_button_text: num_buttons += 1 button_width = 120 with self._window.frame: with omni.ui.VStack(height=0): omni.ui.Spacer(width=0, height=10) with omni.ui.HStack(height=0): omni.ui.Spacer(width=40) self._text_label = omni.ui.Label( self._text, word_wrap=True, width=self._window.width - 80, height=0, name="prompt_text" ) omni.ui.Spacer(width=40) omni.ui.Spacer(width=0, height=10) with omni.ui.HStack(height=0): omni.ui.Spacer(height=0) if self._ok_button_text: ok_button = omni.ui.Button(self._ok_button_text, name="confirm_button", width=button_width, height=0) ok_button.set_clicked_fn(self._on_ok_button_fn) self._buttons.append(ok_button) if self._middle_button_text: middle_button = omni.ui.Button(self._middle_button_text, name="middle_button", width=button_width, height=0) middle_button.set_clicked_fn(self._on_middle_button_fn) self._buttons.append(middle_button) if self._middle_2_button_text: middle_2_button = omni.ui.Button(self._middle_2_button_text, name="middle_2_button", width=button_width, height=0) middle_2_button.set_clicked_fn(self._on_middle_2_button_fn) self._buttons.append(middle_2_button) if self._cancel_button_text: cancel_button = omni.ui.Button(self._cancel_button_text, name="cancel_button", width=button_width, height=0) cancel_button.set_clicked_fn(self._on_cancel_button_fn) self._buttons.append(cancel_button) omni.ui.Spacer(height=0) omni.ui.Spacer(width=0, height=10) for callback in self._callback_addons: if callback and callable(callback): callback()
14,437
Python
35.004987
138
0.584748
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/tests/test_prompt.py
import omni.kit.test import omni.kit.ui_test as ui_test from functools import partial from omni.kit.widget.prompt import Prompt, PromptManager, PromptButtonInfo class TestPrompt(omni.kit.test.AsyncTestCase): async def setUp(self): PromptManager.on_shutdown() async def _wait(self, frames=5): for i in range(frames): await omni.kit.app.get_app().next_update_async() async def test_show_prompt_and_button_clicks(self): value = "" def f(text): nonlocal value value = text button_names = ["left", "right", "middle", "middle_2"] prompt = Prompt( "title", "information text", *button_names, ok_button_fn=partial(f, button_names[0]), cancel_button_fn=partial(f, button_names[1]), middle_button_fn=partial(f, button_names[2]), middle_2_button_fn=partial(f, button_names[3]) ) for button_name in button_names: prompt.show() self.assertTrue(prompt.visible) await ui_test.find("title").focus() label = ui_test.find("title//Frame/**/Label[*].text=='information text'") self.assertTrue(label) button = ui_test.find(f"title//Frame/**/Button[*].text=='{button_name}'") self.assertTrue(button) await button.click() self.assertEqual(value, button_name) self.assertFalse(prompt.visible) self.assertFalse(prompt.is_visible()) prompt.destroy() async def test_set_buttons_fn(self): value = "" def f(text): nonlocal value value = text button_names = ["left", "right", "middle", "middle_2"] prompt = Prompt("title", "test", *button_names) prompt.set_confirm_fn(partial(f, button_names[0])) prompt.set_cancel_fn(partial(f, button_names[1])) prompt.set_middle_button_fn(partial(f, button_names[2])) prompt.set_middle_2_button_fn(partial(f, button_names[3])) prompt.set_on_closed_fn(partial(f, "closed")) for button_name in button_names: prompt.show() self.assertTrue(prompt.visible) await ui_test.find("title").focus() label = ui_test.find("title//Frame/**/Label[*].text=='test'") self.assertTrue(label) button = ui_test.find(f"title//Frame/**/Button[*].text=='{button_name}'") self.assertTrue(button) await button.click() self.assertEqual(value, button_name) self.assertFalse(prompt.visible) self.assertFalse(prompt.is_visible()) prompt.show() prompt.hide() self.assertEqual(value, "closed") prompt.destroy() async def test_hide_prompt(self): value = "" def f(text): nonlocal value value = text prompt = Prompt("title", "hide dialog", on_closed_fn=partial(f, "closed")) prompt.show() self.assertTrue(prompt.visible) prompt.hide() self.assertEqual(value, "closed") self.assertFalse(prompt.visible) prompt.show() self.assertTrue(prompt.visible) prompt.visible = False self.assertFalse(prompt.visible) async def test_set_text(self): prompt = Prompt("test", "test") prompt.show() prompt.set_text("set text") await ui_test.find("test").focus() label = ui_test.find("test//Frame/**/Label[*].text=='set text'") self.assertTrue(label) async def test_prompt_manager(self): value = "" def f(text): nonlocal value value = text n = ["1left", "1right", "1middle", "1middle_2"] prompt = PromptManager.post_simple_prompt( "title", "test", ok_button_info=PromptButtonInfo(n[0], partial(f, n[0])), cancel_button_info=PromptButtonInfo(n[1], partial(f, n[1])), middle_button_info=PromptButtonInfo(n[2], partial(f, n[2])), middle_2_button_info=PromptButtonInfo(n[3], partial(f, n[3])), on_window_closed_fn=partial(f, "closed") ) for button_name in n: prompt.show() self.assertTrue(prompt.visible) await ui_test.find("title").focus() label = ui_test.find("title//Frame/**/Label[*].text=='test'") self.assertTrue(label) button = ui_test.find(f"title//Frame/**/Button[*].text=='{button_name}'") self.assertTrue(button) await button.click() self.assertEqual(value, button_name) self.assertFalse(prompt.visible) self.assertFalse(prompt.is_visible()) prompt.show() prompt.hide() self.assertEqual(value, "closed") prompt.destroy()
4,873
Python
34.838235
104
0.567823
omniverse-code/kit/exts/omni.kit.widget.prompt/docs/CHANGELOG.md
# Changelog Omniverse Kit Prompt Dialog ## [1.0.5] - 2023-01-19 ### Fixed - Generates unique id when title is not provided for prompt. ## [1.0.4] - 2022-12-07 ### Fixed - Missing import (OM-75466). ## [1.0.3] - 2022-11-21 ### Changed - Adjust button size. ## [1.0.2] - 2022-06-15 ### Changed - Add prompt manager to simplify prompt notifications. ## [1.0.1] - 2022-03-01 ### Changed - Add unittests. ## [1.0.0] - 2021-02-24 ### Added - Prompt Dialog
457
Markdown
15.357142
60
0.630197
omniverse-code/kit/exts/omni.kit.viewport.utility/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.14" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Viewport Utility" description="Utility functions to access [active] Viewport information" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "viewport", "utility"] # 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.rst" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" category = "Viewport" [dependencies] "omni.kit.viewport.window" = { optional = true } # Viewport-Next "omni.kit.window.viewport" = { optional = true } # Viewport-Legacy "omni.ui" = { optional = true } # Required for Viewport-Legacy adapter # Main python module this extension provides, it will be publicly available as "import omni.kit.viewport.registry". [[python.module]] name = "omni.kit.viewport.utility" [settings] # exts."omni.kit.viewport.registry".xxx = "" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/pxr/rendermode=HdStormRendererPlugin", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/window/hideUi=true", "--/app/renderer/resolution/width=500", "--/app/renderer/resolution/height=500", "--/app/window/width=500", "--/app/window/height=500", "--/app/viewport/forceHideFps=true", "--no-window" ] dependencies = [ "omni.ui", "omni.kit.mainwindow", "omni.kit.test_helpers_gfx", "omni.kit.ui_test", "omni.kit.manipulator.selection", "omni.hydra.pxr", "omni.kit.window.viewport", "omni.kit.context_menu" ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop ] [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
2,499
TOML
30.25
115
0.697079
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/__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. # __all__ = [ 'frame_viewport_prims', 'frame_viewport_selection', 'get_viewport_from_window_name', 'get_active_viewport', 'get_active_viewport_window' 'get_active_viewport_and_window', 'get_viewport_window_camera_path', 'get_viewport_window_camera_string', 'get_active_viewport_camera_path', 'get_active_viewport_camera_string', 'get_num_viewports', 'capture_viewport_to_file', 'capture_viewport_to_buffer', 'post_viewport_message', 'toggle_global_visibility', 'create_drop_helper', 'disable_selection', 'get_ground_plane_info' ] import asyncio import carb from pxr import Gf, Sdf from typing import Callable, List, Optional, Tuple _g_is_viewport_next = None def _is_viewport_next(self): global _g_is_viewport_next if _g_is_viewport_next is None: vp_window_name = carb.settings.get_settings().get('/exts/omni.kit.viewport.window/startup/windowName') _g_is_viewport_next = vp_window_name and (vp_window_name == 'Viewport') return _g_is_viewport_next def _get_default_viewport_window_name(window_name: str = None): if window_name: return window_name return carb.settings.get_settings().get('/exts/omni.kit.viewport.window/startup/windowName') or 'Viewport' def get_viewport_from_window_name(window_name: str = None): '''Return the first Viewport that is held inside a specific Window name.''' window_name = _get_default_viewport_window_name(window_name) try: from omni.kit.viewport.window import get_viewport_window_instances # Get every ViewportWindow, regardless of UsdContext it is attached to for window in get_viewport_window_instances(None): if window.title == window_name: return window.viewport_api except ImportError: pass try: import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() viewport_handle = vp_iface.get_instance(window_name) if viewport_handle: vp_window = vp_iface.get_viewport_window(viewport_handle) if vp_window: from .legacy_viewport_api import LegacyViewportAPI return LegacyViewportAPI(vp_iface.get_viewport_window_name(viewport_handle)) except ImportError: pass return None def get_active_viewport_and_window(usd_context_name: str = '', wrap_legacy: bool = True, window_name: str = None): '''Return the active Viewport for a given UsdContext and the name of the Window it is inside of.''' default_window_name = _get_default_viewport_window_name(window_name) try: from omni.kit.viewport.window import get_viewport_window_instances, ViewportWindow # If no windowname provided, see if the ViewportWindow already knows what is active if window_name is None: active_window = ViewportWindow.active_window if active_window: # Have an active Window, need to make sure UsdContext name matches (or passed None to avoid the match) viewport_api = active_window.viewport_api if (usd_context_name is None) or (usd_context_name == viewport_api.usd_context_name): return (viewport_api, active_window) active_window = None # Get all ViewportWindows attached the UsdContext with this name for window in get_viewport_window_instances(usd_context_name): # If matching by name, check that first ignoring whether focused or not (multiple Windows cannot have same name) window_title = window.title if window_name and window_name != window_title: continue # If this Window is focused, then return it if window.focused: active_window = window break # Save the first encountered Window as he fallback 'default' Window if window_title == default_window_name: active_window = window elif active_window is None: active_window = window if active_window: return (active_window.viewport_api, active_window) except ImportError: pass try: import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() instance_list = vp_iface.get_instance_list() if instance_list: first_context_match = None for viewport_handle in vp_iface.get_instance_list(): vp_window = vp_iface.get_viewport_window(viewport_handle) if not vp_window: continue # If matching by name, check that first ignoring whether focused or not (multiple Windows cannot have same name) window_title = vp_iface.get_viewport_window_name(viewport_handle) if window_name and window_name != vp_iface.get_viewport_window_name(viewport_handle): continue # Filter by UsdContext name, where None means any UsdContext if (usd_context_name is not None) and (usd_context_name != vp_window.get_usd_context_name()): continue if vp_window.is_focused(): first_context_match = viewport_handle break elif window_title == default_window_name: first_context_match = viewport_handle elif first_context_match is None: first_context_match = viewport_handle # If there was a match on UsdContext name (but not focused), return the first one if first_context_match is not None: vp_window = vp_iface.get_viewport_window(first_context_match) if vp_window: from .legacy_viewport_api import LegacyViewportAPI window_name = vp_iface.get_viewport_window_name(first_context_match) viewport_api = LegacyViewportAPI(vp_iface.get_viewport_window_name(first_context_match)) if wrap_legacy: from .legacy_viewport_window import LegacyViewportWindow vp_window = LegacyViewportWindow(window_name, viewport_api) return (viewport_api, vp_window) except ImportError: pass return (None, None) def get_active_viewport_window(window_name: str = None, wrap_legacy: bool = True, usd_context_name: str = ''): '''Return the active Viewport for a given UsdContext.''' return get_active_viewport_and_window(usd_context_name, wrap_legacy, window_name)[1] def get_active_viewport(usd_context_name: str = ''): '''Return the active Viewport for a given UsdContext.''' return get_active_viewport_and_window(usd_context_name, False)[0] def get_viewport_window_camera_path(window_name: str = None) -> Sdf.Path: '''Return a Sdf.Path to the camera used by the active Viewport in a named Window.''' viewport_api = get_viewport_from_window_name(window_name) return viewport_api.camera_path if viewport_api else None def get_viewport_window_camera_string(window_name: str = None) -> str: '''Return a string path to the camera used by the active Viewport in a named Window.''' viewport_api = get_viewport_from_window_name(window_name) return viewport_api.camera_path.pathString if viewport_api else None def get_active_viewport_camera_path(usd_context_name: str = '') -> Sdf.Path: '''Return a Sdf.Path to the camera used by the active Viewport for a specific UsdContext.''' viewport_api = get_active_viewport(usd_context_name) return viewport_api.camera_path if viewport_api else None def get_active_viewport_camera_string(usd_context_name: str = '') -> str: '''Return a string path to the camera used by the active Viewport for a specific UsdContext.''' viewport_api = get_active_viewport(usd_context_name) return viewport_api.camera_path.pathString if viewport_api else None def get_available_aovs_for_viewport(viewport_api): if hasattr(viewport_api, 'legacy_window'): viewport_handle = viewport_api.frame_info.get('viewport_handle') asyncio.ensure_future(viewport_api.usd_context.next_frame_async(viewport_handle)) return viewport_api.legacy_window.get_aov_list() carb.log_error('Available AOVs not implemented') return [] def add_aov_to_viewport(viewport_api, aov_name: str): if hasattr(viewport_api, 'legacy_window'): return viewport_api.legacy_window.add_aov(aov_name) from pxr import Usd, UsdRender from omni.usd import editor stage = viewport_api.stage render_product_path = viewport_api.render_product_path with Usd.EditContext(stage, stage.GetSessionLayer()): render_prod_prim = stage.GetPrimAtPath(render_product_path) if not render_prod_prim: raise RuntimeError(f'Invalid renderProduct "{render_product_path}"') render_var_prim_path = Sdf.Path(f'/Render/Vars/{aov_name}') render_var_prim = stage.GetPrimAtPath(render_var_prim_path) if not render_var_prim: render_var_prim = stage.DefinePrim(render_var_prim_path) if not render_var_prim: raise RuntimeError(f'Cannot create renderVar "{render_var_prim_path}"') render_var_prim.CreateAttribute("sourceName", Sdf.ValueTypeNames.String).Set(aov_name) render_prod_var_rel = render_prod_prim.GetRelationship('orderedVars') if not render_prod_var_rel: render_prod_prim.CreateRelationship('orderedVars') if not render_prod_var_rel: raise RuntimeError(f'cannot set orderedVars relationship for renderProduct "{render_product_path}"') render_prod_var_rel.AddTarget(render_var_prim_path) editor.set_hide_in_stage_window(render_var_prim, True) editor.set_no_delete(render_var_prim, True) return True def post_viewport_message(viewport_api_or_window, message: str, message_id: str = None): if hasattr(viewport_api_or_window, 'legacy_window'): viewport_api_or_window.legacy_window.post_toast(message) return if hasattr(viewport_api_or_window, '_post_toast_message'): viewport_api_or_window._post_toast_message(message, message_id) return try: from omni.kit.viewport.window import get_viewport_window_instances for window in get_viewport_window_instances(viewport_api_or_window.usd_context_name): if window.viewport_api.id == viewport_api_or_window.id: window._post_toast_message(message, message_id) return except (ImportError, AttributeError): pass class _CaptureHelper: def __init__(self, legacy_window, is_hdr: bool, file_path: str = None, render_product_path: str = None, on_capture_fn: Callable = None, format_desc: dict = None): import omni.renderer_capture self.__future = asyncio.Future() self.__renderer = omni.renderer_capture.acquire_renderer_capture_interface() if render_product_path: self.__future.set_result(True) self.__renderer.capture_next_frame_using_render_product(viewport_handle=legacy_window.get_id(), filepath=file_path, render_product=render_product_path) return self.__is_hdr = is_hdr self.__legacy_window = legacy_window self.__file_path = file_path self.__on_capture_fn = on_capture_fn self.__format_desc = format_desc event_stream = legacy_window.get_ui_draw_event_stream() self.__capture_sub = event_stream.create_subscription_to_pop(self.capture_function, name='omni.kit.viewport.utility.capture_viewport') def capture_function(self, *args): self.__capture_sub = None legacy_window, self.__legacy_window = self.__legacy_window, None renderer, self.__renderer = self.__renderer, None if self.__is_hdr: viewport_rp_resource = legacy_window.get_drawable_hdr_resource() else: viewport_rp_resource = legacy_window.get_drawable_ldr_resource() if self.__on_capture_fn: def _interecept_capture(*args, **kwargs): try: self.__on_capture_fn(*args, **kwargs) finally: if not self.__future.done(): self.__future.set_result(True) renderer.capture_next_frame_rp_resource_callback(_interecept_capture, resource=viewport_rp_resource) elif self.__file_path: if not self.__future.done(): self.__future.set_result(True) if self.__format_desc: if hasattr(renderer, 'capture_next_frame_rp_resource_to_file'): renderer.capture_next_frame_rp_resource_to_file(filepath=self.__file_path, resource=viewport_rp_resource, format_desc=self.__format_desc) return carb.log_error('Format description provided to capture, but not honored') renderer.capture_next_frame_rp_resource(filepath=self.__file_path, resource=viewport_rp_resource) async def wait_for_result(self, completion_frames: int = 2): await self.__future import omni.kit.app app = omni.kit.app.get_app() while completion_frames: await app.next_update_async() completion_frames = completion_frames - 1 return self.__future.result() def capture_viewport_to_buffer(viewport_api, on_capture_fn: Callable, is_hdr: bool = False): '''Capture the provided viewport and send it to a callback.''' if hasattr(viewport_api, 'legacy_window'): return _CaptureHelper(viewport_api.legacy_window, is_hdr=is_hdr, on_capture_fn=on_capture_fn) from omni.kit.widget.viewport.capture import ByteCapture return viewport_api.schedule_capture(ByteCapture(on_capture_fn, aov_name='HdrColor' if is_hdr else 'LdrColor')) def capture_viewport_to_file(viewport_api, file_path: str = None, is_hdr: bool = False, render_product_path: str = None, format_desc: dict = None): '''Capture the provided viewport to a file.''' file_path = str(file_path) if hasattr(viewport_api, 'legacy_window'): return _CaptureHelper(viewport_api.legacy_window, is_hdr=is_hdr, file_path=file_path, render_product_path=render_product_path, format_desc=format_desc) from omni.kit.widget.viewport.capture import MultiAOVFileCapture class HdrCaptureHelper(MultiAOVFileCapture): def __init__(self, file_path: str, is_hdr: bool, format_desc: dict = None): super().__init__(['HdrColor' if is_hdr else 'LdrColor'], [file_path]) # Setup RenderProduct for Hdr def __del__(self): # Setdown RenderProduct for Hdr pass def capture_aov(self, file_path, aov): if render_product_path: self.save_product_to_file(file_path, render_product_path) else: self.save_aov_to_file(file_path, aov, format_desc=format_desc) return viewport_api.schedule_capture(HdrCaptureHelper(file_path, is_hdr)) def get_num_viewports(usd_context_name: str = None): num_viewports = 0 try: from omni.kit.viewport.window import get_viewport_window_instances num_viewports += sum(1 for _ in get_viewport_window_instances(usd_context_name)) except ImportError: pass try: import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() for viewport_handle in vp_iface.get_instance_list(): if usd_context_name and (usd_context_name != vp_iface.get_viewport_window(viewport_handle).get_usd_context_name()): continue num_viewports += 1 except ImportError: pass return num_viewports def create_viewport_window(name: str = None, usd_context_name: str = '', width: int = 1280, height: int = 720, position_x: int = 0, position_y: int = 0, camera_path: Sdf.Path = None, **kwargs): window = None try: from omni.kit.viewport.window import get_viewport_window_instances, ViewportWindow if name is None: name = f"Viewport {get_num_viewports()}" window = ViewportWindow(name, usd_context_name, width=width, height=height, **kwargs) return window except ImportError: pass if window is None: try: import omni.kit.viewport_legacy as vp_legacy from .legacy_viewport_window import LegacyViewportWindow vp_iface = vp_legacy.get_viewport_interface() vp_handle = vp_iface.create_instance() assigned_name = vp_iface.get_viewport_window_name(vp_handle) if name and (name != assigned_name): carb.log_warn('omni.kit.viewport_legacy does not support explicit Window names, using assigned name "{assigned_name}"') window = LegacyViewportWindow(assigned_name, **kwargs) window.width = width window.height = height except ImportError: pass if window: window.setPosition(position_x, position_y) if camera_path: window.viewport_api.camera_path = camera_path return window class ViewportPrimReferencePoint: BOUND_BOX_CENTER = 0 BOUND_BOX_LEFT = 1 BOUND_BOX_RIGHT = 2 BOUND_BOX_TOP = 3 BOUND_BOX_BOTTOM = 4 def get_ui_position_for_prim(viewport_window, prim_path: str, alignment: ViewportPrimReferencePoint = ViewportPrimReferencePoint.BOUND_BOX_CENTER, force_legacy_api: bool = False): if isinstance(viewport_window, str): window_name = str(viewport_window) viewport_window = get_active_viewport_window(window_name=window_name) if viewport_window is None: carb.log_error('No ViewportWindow found with name "{window_name}"') return (0, 0), False # XXX: omni.ui constants needed import omni.ui dpi = omni.ui.Workspace.get_dpi_scale() if dpi <= 0.0: dpi = 1 # XXX: kit default dock splitter size (4) dock_splitter_size = 4 * dpi tab_bar_height = 0 if viewport_window.dock_tab_bar_visible or not (viewport_window.flags & omni.ui.WINDOW_FLAGS_NO_TITLE_BAR): tab_bar_height = 22 * dpi # Force legacy Viewport code path if requested if force_legacy_api and hasattr(viewport_window, 'legacy_window'): import omni.ui import omni.kit.viewport_legacy as vp_legacy legacy_window = viewport_window.legacy_window alignment = { ViewportPrimReferencePoint.BOUND_BOX_LEFT: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_LEFT, ViewportPrimReferencePoint.BOUND_BOX_RIGHT: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_RIGHT, ViewportPrimReferencePoint.BOUND_BOX_TOP: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_TOP, ViewportPrimReferencePoint.BOUND_BOX_BOTTOM: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_BOTTOM, }.get(alignment, vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_CENTER) success, x, y, z = legacy_window.get_prim_clipping_pos(str(prim_path), alignment) if not success: return (0, 0), False # Changing xy to match the window coord system. x = (x + 1.0) / 2.0 # x to [0, 1] y = 1 - (y + 1.0) / 2.0 # y to [0, 1] and reverse its direction. min_x, min_y, max_x, max_y = legacy_window.get_viewport_rect() prim_window_pos_x = (max_x - min_x) * x + min_x - dock_splitter_size prim_window_pos_y = (max_y - min_y) * y + min_y - tab_bar_height - dock_splitter_size else: from pxr import UsdGeom, Gf viewport_api = viewport_window.viewport_api usd_context = viewport_window.viewport_api.usd_context stage = usd_context.get_stage() usd_prim = stage.GetPrimAtPath(prim_path) if stage else False if usd_prim: xformable_prim = UsdGeom.Xformable(usd_prim) else: xformable_prim = None if (not stage) or (not xformable_prim): return (0, 0), False # Get bounding box from prim aabb_min, aabb_max = usd_context.compute_path_world_bounding_box(str(prim_path)) gf_range = Gf.Range3d(Gf.Vec3d(aabb_min[0], aabb_min[1], aabb_min[2]), Gf.Vec3d(aabb_max[0], aabb_max[1], aabb_max[2])) if gf_range.IsEmpty(): # May be empty (UsdGeom.Xform for example), so build a scene-scaled constant box world_units = UsdGeom.GetStageMetersPerUnit(stage) if Gf.IsClose(world_units, 0.0, 1e-6): world_units = 0.01 # XXX: compute_path_world_transform is identity in this case if False: world_xform = Gf.Matrix4d(*usd_context.compute_path_world_transform(str(prim_path))) else: import omni.timeline time = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond() world_xform = xformable_prim.ComputeLocalToWorldTransform(time) ref_position = world_xform.ExtractTranslation() extent = Gf.Vec3d(0.2 / world_units) # 20cm by default gf_range.SetMin(ref_position - extent) gf_range.SetMax(ref_position + extent) # Computes the extent in clipping pos mvp = viewport_api.world_to_ndc min_x, min_y, min_z = 2.0, 2.0, 2.0 max_x, max_y, max_z = -2.0, -2.0, -2.0 for i in range(8): corner = gf_range.GetCorner(i) pos = mvp.Transform(corner) min_x = min(min_x, pos[0]) min_y = min(min_y, pos[1]) min_z = min(min_z, pos[2]) max_x = max(max_x, pos[0]) max_y = max(max_y, pos[1]) max_z = max(max_z, pos[2]) min_point = Gf.Vec3d(min_x, min_y, min_z) max_point = Gf.Vec3d(max_x, max_y, max_z) mid_point = (min_point + max_point) / 2 # Map to reference point in screen space if alignment == ViewportPrimReferencePoint.BOUND_BOX_LEFT: ndc_pos = mid_point - Gf.Vec3d((max_x - min_x) / 2, 0, 0) elif alignment == ViewportPrimReferencePoint.BOUND_BOX_RIGHT: ndc_pos = mid_point + Gf.Vec3d((max_x - min_x) / 2, 0, 0) elif alignment == ViewportPrimReferencePoint.BOUND_BOX_TOP: ndc_pos = mid_point + Gf.Vec3d(0, (max_y - min_y) / 2, 0) elif alignment == ViewportPrimReferencePoint.BOUND_BOX_BOTTOM: ndc_pos = mid_point - Gf.Vec3d(0, (max_y - min_y) / 2, 0) else: ndc_pos = mid_point # Make sure its not clipped if (ndc_pos[2] < 0) or (ndc_pos[0] < -1) or (ndc_pos[0] > 1) or (ndc_pos[1] < -1) or (ndc_pos[1] > 1): return (0, 0), False ''' XXX: Simpler world calculation world_pos = gf_range.GetMidpoint() dir_sel = (0, 1) up_axis = UsdGeom.GetStageUpAxis(stage) if up_axis == UsdGeom.Tokens.z: dir_sel = (0, 2) if up_axis == UsdGeom.Tokens.x: dir_sel = (2, 1) if alignment == ViewportPrimReferencePoint.BOUND_BOX_LEFT: world_pos[dir_sel[0]] = gf_range.GetMin()[dir_sel[0]] elif alignment == ViewportPrimReferencePoint.BOUND_BOX_RIGHT: world_pos[dir_sel[0]] = gf_range.GetMax()[dir_sel[0]] elif alignment == ViewportPrimReferencePoint.BOUND_BOX_TOP: world_pos[dir_sel[1]] = gf_range.GetMax()[dir_sel[1]] elif alignment == ViewportPrimReferencePoint.BOUND_BOX_BOTTOM: world_pos[dir_sel[1]] = gf_range.GetMin()[dir_sel[1]] ndc_pos = viewport_api.world_to_ndc.Transform(world_pos) ''' x = (ndc_pos[0] + 1.0) / 2.0 # x to [0, 1] y = 1 - (ndc_pos[1] + 1.0) / 2.0 # y to [0, 1] and reverse its direction. frame = viewport_window.frame prim_window_pos_x = dpi * (frame.screen_position_x + x * frame.computed_width) - dock_splitter_size prim_window_pos_y = dpi * (frame.screen_position_y + y * frame.computed_height) - tab_bar_height - dock_splitter_size return (prim_window_pos_x, prim_window_pos_y), True def frame_viewport_prims(viewport_api=None, prims: List[str] = None): if not prims: return False return __frame_viewport_objects(viewport_api, prims=prims, force_legacy_api=False) def frame_viewport_selection(viewport_api=None, force_legacy_api: bool = False): return __frame_viewport_objects(viewport_api, prims=None, force_legacy_api=force_legacy_api) def __frame_viewport_objects(viewport_api=None, prims: Optional[List[str]] = None, force_legacy_api: bool = False): if not viewport_api: viewport_api = get_active_viewport() if not viewport_api: return False if force_legacy_api and hasattr(viewport_api, "legacy_window"): viewport_api.legacy_window.focus_on_selected() return # This is new CODE if prims is None: # Get current selection prims = viewport_api.usd_context.get_selection().get_selected_prim_paths() # Pass None to underlying command to signal "frame all" if selection is empty prims = prims if prims else None stage = viewport_api.stage cam_path = viewport_api.camera_path if not stage or not cam_path: return False cam_prim = stage.GetPrimAtPath(cam_path) if not cam_prim: return False import omni.kit.undo import omni.kit.commands from pxr import UsdGeom look_through = None # Loop over all targets (should really be only one) and see if we can get a valid UsdGeom.Imageable for target in cam_prim.GetRelationship('omni:kit:viewport:lookThrough:target').GetForwardedTargets(): target_prim = stage.GetPrimAtPath(target) if not target_prim: continue if UsdGeom.Imageable(target_prim): look_through = target_prim break try: omni.kit.undo.begin_group() resolution = viewport_api.resolution omni.kit.commands.execute( 'FramePrimsCommand', prim_to_move=cam_path if not look_through else look_through.GetPath(), prims_to_frame=prims, time_code=viewport_api.time, usd_context_name=viewport_api.usd_context_name, aspect_ratio=resolution[0] / resolution[1] ) finally: omni.kit.undo.end_group() return True def toggle_global_visibility(force_legacy_api: bool = False): # Forward to omni.kit.viewport.actions and propogate an errors so caller should update code carb.log_warn("omni.kit.viewport.utility.toggle_global_visibility is deprecated, use omni.kit.viewport.actions.toggle_global_visibility") import omni.kit.actions.core action_registry = omni.kit.actions.core.get_action_registry() action_registry.get_action("omni.kit.viewport.actions", "toggle_global_visibility").execute() async def next_viewport_frame_async(viewport, n_frames: int = 0): """ Waits until frames have been delivered to the Viewport. Args: viewport: the Viewport to wait for a frame on. n_frames: the number of rendered frames to wait for. """ import omni.kit.app app = omni.kit.app.get_app() # Make sure at least one frame has been delivered viewport_handle = viewport.frame_info.get('viewport_handle') while viewport_handle is None: await app.next_update_async() viewport_handle = viewport.frame_info.get('viewport_handle') # Now wait for any additional frames usd_context = viewport.usd_context while n_frames: await usd_context.next_frame_async(viewport_handle) n_frames = n_frames - 1 def create_drop_helper(*args, **kwargs): try: from omni.kit.viewport.window.dragdrop.legacy import create_drop_helper return create_drop_helper(*args, **kwargs) except (ImportError, ModuleNotFoundError): try: import omni.kit.viewport_legacy as vp_legacy return vp_legacy.get_viewport_interface().create_drop_helper(*args, **kwargs) except (ImportError, ModuleNotFoundError): pass class _DisableViewportWindowLayer: def __init__(self, viewport_or_window, layers_and_categories): self.__layers = [] # Find the omni.ui.Window for this Viewport to disable selection manipulator viewport_window = None from omni.kit.viewport.window import ViewportWindow, get_viewport_window_instances if not isinstance(viewport_or_window, ViewportWindow): viewport_id = viewport_or_window.id for window_instance in get_viewport_window_instances(viewport_or_window.usd_context_name): viewport_window_viewport = window_instance.viewport_api if viewport_window_viewport.id == viewport_id: viewport_window = window_instance break else: viewport_window = viewport_or_window if viewport_window: for layer, category in layers_and_categories: found_layer = viewport_window._find_viewport_layer(layer, category) if found_layer: self.__layers.append((found_layer, found_layer.visible)) found_layer.visible = False def __del__(self): for layer, visible in self.__layers: layer.visible = visible self.__layers = tuple() def disable_selection(viewport_or_window, disable_click: bool = True): '''Disable selection rect and possible the single click selection on a Viewport or ViewportWindow. Returns an object that resets selection when it goes out of scope.''' # First check if the Viewport is a legacy Viewport from .legacy_viewport_window import LegacyViewportWindow legacy_window = None if hasattr(viewport_or_window, 'legacy_window'): legacy_window = viewport_or_window.legacy_window elif isinstance(viewport_or_window, LegacyViewportWindow): legacy_window = viewport_or_window.legacy_window if legacy_window: class LegacySelectionState: def __init__(self, viewport_window, disable_click): self.__viewport_window = viewport_window self.__restore_picking = viewport_window.is_enabled_picking() if disable_click: self.__viewport_window.set_enabled_picking(False) self.__viewport_window.disable_selection_rect(True) def __del__(self): self.__viewport_window.set_enabled_picking(self.__restore_picking) return LegacySelectionState(legacy_window, disable_click) disable_items = [('Selection', 'manipulator')] if disable_click: disable_items.append(('ObjectClick', 'manipulator')) return _DisableViewportWindowLayer(viewport_or_window, disable_items) def disable_context_menu(viewport_or_window=None): '''Disable context menu on a Viewport or ViewportWindow. Returns an object that resets context menu visibility when it goes out of scope.''' if viewport_or_window: # Check if the Viewport is a legacy Viewport, s can only operate on all Viewportwindows in that case from .legacy_viewport_window import LegacyViewportWindow if hasattr(viewport_or_window, 'legacy_window') or isinstance(viewport_or_window, LegacyViewportWindow): carb.log_warn("Cannot disable context menu on an individual Viewport, disabling it for all") viewport_or_window = None if viewport_or_window is None: class _DisableAllContextMenus: def __init__(self): # When setting is initially unset, then context menu is enabled self.__settings = carb.settings.get_settings() enabled = self.__settings.get('/exts/omni.kit.window.viewport/showContextMenu') self.__settings.set('/exts/omni.kit.window.viewport/showContextMenu', False) self.__restore = enabled if (enabled is not None) else True def __del__(self): self.__settings.set('/exts/omni.kit.window.viewport/showContextMenu', self.__restore) return _DisableAllContextMenus() return _DisableViewportWindowLayer(viewport_or_window, [('ContextMenu', 'manipulator')]) def get_ground_plane_info(viewport, ortho_special: bool = True) -> Tuple[Gf.Vec3d, List[str]]: """For a given Viewport returns a tuple representing the ground plane. @param viewport: ViewportAPI to use for ground plane info @param ortho_special: bool Use an alternate ground plane for orthographic cameras that are looking down a single axis @return: A tuple of type (normal: Gf.Vec3d, planes: List[str]), where planes is a list of axis' occupied (x, y, z) """ stage = viewport.stage cam_path = viewport.camera_path from pxr import UsdGeom up_axis = UsdGeom.GetStageUpAxis(stage) if stage else UsdGeom.Tokens.y if up_axis == UsdGeom.Tokens.y: normal = Gf.Vec3d.YAxis() planes = ['x', 'z'] elif up_axis == UsdGeom.Tokens.z: normal = Gf.Vec3d.ZAxis() planes = ['x', 'y'] else: normal = Gf.Vec3d.XAxis() planes = ['y', 'z'] if ortho_special: cam_prim = stage.GetPrimAtPath(cam_path) if stage else None if cam_prim: usd_camera = UsdGeom.Camera(cam_prim) if usd_camera and usd_camera.GetProjectionAttr().Get(viewport.time) == UsdGeom.Tokens.orthographic: orthoEpsilon = 0.0001 viewNormal = viewport.transform.TransformDir(Gf.Vec3d(0, 0, -1)) if Gf.IsClose(abs(viewNormal[1]), 1.0, orthoEpsilon): normal = Gf.Vec3d.YAxis() planes = ['x', 'z'] elif Gf.IsClose(abs(viewNormal[2]), 1.0, orthoEpsilon): normal = Gf.Vec3d.ZAxis() planes = ['x', 'y'] elif Gf.IsClose(abs(viewNormal[0]), 1.0, orthoEpsilon): normal = Gf.Vec3d.XAxis() planes = ['y', 'z'] return normal, planes
34,909
Python
42.528678
193
0.63783
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/legacy_viewport_window.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['LegacyViewportWindow'] import omni.ui import carb import weakref # Wrap a legacy viewport Window in an object that poses as a new omni.kit.viewport.window.ViewportWindow (omni.ui.Window) class class LegacyViewportWindow(omni.ui.Window): def __init__(self, window_name: str, viewport_api = None, **kwargs): kwargs.update({ 'window_flags': omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE }) super().__init__(window_name, **kwargs) self.__z_stack = None with self.frame: self.__z_stack = omni.ui.ZStack() self.__window_name = window_name if not viewport_api: from .legacy_viewport_api import LegacyViewportAPI viewport_api = LegacyViewportAPI(window_name) self.__viewport_api = viewport_api self.__added_frames = {} @property def name(self): return self.__window_name @property def viewport_api(self): return weakref.proxy(self.__viewport_api) def get_frame(self, name: str): frame = self.__added_frames.get(name) if frame is None: with self.__z_stack: frame = omni.ui.Frame(horizontal_clipping=True) self.__added_frames[name] = frame return frame @property def legacy_window(self): return self.__get_legacy_window() @property def width(self): return super().width @property def height(self): return super().height @width.setter def width(self, width: float): width = int(width) legacy_window = self.legacy_window if legacy_window: legacy_window.set_window_size(width, int(self.height)) super(LegacyViewportWindow, self.__class__).width.fset(self, width) @height.setter def height(self, height: float): height = int(height) legacy_window = self.legacy_window if legacy_window: legacy_window.set_window_size(int(self.width), height) super(LegacyViewportWindow, self.__class__).height.fset(self, height) @property def position_x(self): pos_x = super().position_x # Workaround omni.ui reporting massive position_y unless laid out ? return pos_x if pos_x != 340282346638528859811704183484516925440 else 0 @property def position_y(self): pos_y = super().position_y # Workaround omni.ui reporting massive position_y unless laid out ? return pos_y if pos_y != 340282346638528859811704183484516925440 else 0 @position_x.setter def position_x(self, position_x: float): position_x = int(position_x) legacy_window = self.legacy_window if legacy_window: legacy_window.set_window_pos(position_x, int(self.position_y)) super(LegacyViewportWindow, self.__class__).position_x.fset(self, position_x) @position_y.setter def position_y(self, position_y: float): position_y = int(position_y) legacy_window = self.legacy_window if legacy_window: legacy_window.set_window_pos(int(self.position_x), position_y) super(LegacyViewportWindow, self.__class__).position_y.fset(self, position_y) def setPosition(self, x: float, y: float): return self.set_position(x, y) def set_position(self, x: float, y: float): x, y = int(x), int(y) legacy_window = self.legacy_window if legacy_window: legacy_window.set_window_pos(x, y) super().setPosition(x, y) @property def visible(self): legacy_window = self.legacy_window if legacy_window: return legacy_window.is_visible() return super().visible @visible.setter def visible(self, visible: bool): visible = bool(visible) legacy_window = self.legacy_window if legacy_window: legacy_window.set_visible(visible) super(LegacyViewportWindow, self.__class__).visible.fset(self, visible) def __del__(self): self.destroy() def destroy(self): self.__viewport_api = None if self.__z_stack: self.__z_stack.clear() self.__z_stack.destroy() self.__z_stack = None if self.__added_frames: for name, frame in self.__added_frames.items(): try: frame.destroy() except Exception: import traceback carb.log_error(f"Error destroying {self.__window_name}. Traceback:\n{traceback.format_exc()}") self.__added_frames = None super().destroy() def _post_toast_message(self, message: str, message_id: str = None): legacy_window = self.legacy_window if legacy_window: return legacy_window.post_toast(message) def __get_legacy_window(self): import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() viewport_handle = vp_iface.get_instance(self.__window_name) return vp_iface.get_viewport_window(viewport_handle)
5,623
Python
33.716049
130
0.624755
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/camera_state.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportCameraState'] from pxr import Gf, Sdf, Usd, UsdGeom class ViewportCameraState: def __init__(self, camera_path: str = None, viewport = None, time: Usd.TimeCode = None, force_legacy_api: bool = False): if viewport is None: from omni.kit.viewport.utility import get_active_viewport viewport = get_active_viewport() if viewport is None: raise RuntimeError('No default or provided Viewport') self.__viewport_api = viewport self.__camera_path = str(camera_path if camera_path else viewport.camera_path) self.__time = Usd.TimeCode.Default() if time is None else time self.__legacy_window = viewport.legacy_window if (force_legacy_api and hasattr(viewport, 'legacy_window')) else None def get_world_camera_up(self, stage) -> Gf.Vec3d: up_axis = UsdGeom.GetStageUpAxis(stage) if stage else UsdGeom.Tokens.y if up_axis == UsdGeom.Tokens.y: return Gf.Vec3d(0, 1, 0) if up_axis == UsdGeom.Tokens.z: return Gf.Vec3d(0, 0, 1) if up_axis == UsdGeom.Tokens.x: return Gf.Vec3d(1, 0, 0) return Gf.Vec3d(0, 1, 0) @property def usd_camera(self) -> Usd.Prim: camera_prim = self.__viewport_api.stage.GetPrimAtPath(self.__camera_path) usd_camera = UsdGeom.Camera(camera_prim) if camera_prim else None if usd_camera: return usd_camera raise RuntimeError(f'"{self.__camera_path}" is not a valid Usd.Prim or UsdGeom.Camera') @property def position_world(self): if self.__legacy_window: success, x, y, z = self.__legacy_window.get_camera_position(self.__camera_path) if success: return Gf.Vec3d(x, y, z) return self.usd_camera.ComputeLocalToWorldTransform(self.__time).Transform(Gf.Vec3d(0, 0, 0)) @property def target_world(self): if self.__legacy_window: success, x, y, z = self.__legacy_window.get_camera_target(self.__camera_path) if success: return Gf.Vec3d(x, y, z) local_coi = self.usd_camera.GetPrim().GetAttribute('omni:kit:centerOfInterest').Get(self.__time) return self.usd_camera.ComputeLocalToWorldTransform(self.__time).Transform(local_coi) def set_position_world(self, world_position: Gf.Vec3d, rotate: bool): if self.__legacy_window: self.__legacy_window.set_camera_position(self.__camera_path, world_position[0], world_position[1], world_position[2], rotate) return usd_camera = self.usd_camera world_xform = usd_camera.ComputeLocalToWorldTransform(self.__time) parent_xform = usd_camera.ComputeParentToWorldTransform(self.__time) iparent_xform = parent_xform.GetInverse() initial_local_xform = world_xform * iparent_xform pos_in_parent = iparent_xform.Transform(world_position) if rotate: cam_prim = usd_camera.GetPrim() coi_attr = cam_prim.GetAttribute('omni:kit:centerOfInterest') prev_local_coi = coi_attr.Get(self.__time) coi_in_parent = iparent_xform.Transform(world_xform.Transform(prev_local_coi)) cam_up = self.get_world_camera_up(cam_prim.GetStage()) new_local_transform = Gf.Matrix4d(1).SetLookAt(pos_in_parent, coi_in_parent, cam_up).GetInverse() else: coi_attr, prev_local_coi = None, None new_local_transform = Gf.Matrix4d(initial_local_xform) new_local_transform = new_local_transform.SetTranslateOnly(pos_in_parent) import omni.kit.commands omni.kit.commands.create( 'TransformPrimCommand', path=self.__camera_path, new_transform_matrix=new_local_transform, old_transform_matrix=initial_local_xform, time_code=self.__time, usd_context_name=self.__viewport_api.usd_context_name ).do() if coi_attr and prev_local_coi: prev_world_coi = world_xform.Transform(prev_local_coi) new_local_coi = (new_local_transform * parent_xform).GetInverse().Transform(prev_world_coi) omni.kit.commands.create( 'ChangePropertyCommand', prop_path=coi_attr.GetPath(), value=new_local_coi, prev=prev_local_coi, timecode=self.__time, usd_context_name=self.__viewport_api.usd_context_name, type_to_create_if_not_exist=Sdf.ValueTypeNames.Vector3d ).do() def set_target_world(self, world_target: Gf.Vec3d, rotate: bool): if self.__legacy_window: self.__legacy_window.set_camera_target(self.__camera_path, world_target[0], world_target[1], world_target[2], rotate) return usd_camera = self.usd_camera world_xform = usd_camera.ComputeLocalToWorldTransform(self.__time) parent_xform = usd_camera.ComputeParentToWorldTransform(self.__time) iparent_xform = parent_xform.GetInverse() initial_local_xform = world_xform * iparent_xform cam_prim = usd_camera.GetPrim() coi_attr = cam_prim.GetAttribute('omni:kit:centerOfInterest') prev_local_coi = coi_attr.Get(self.__time) pos_in_parent = iparent_xform.Transform(initial_local_xform.Transform(Gf.Vec3d(0, 0, 0))) if rotate: # Rotate camera to look at new target, leaving it where it is cam_up = self.get_world_camera_up(cam_prim.GetStage()) coi_in_parent = iparent_xform.Transform(world_target) new_local_transform = Gf.Matrix4d(1).SetLookAt(pos_in_parent, coi_in_parent, cam_up).GetInverse() new_local_coi = (new_local_transform * parent_xform).GetInverse().Transform(world_target) else: # Camera keeps orientation and distance relative to target # Calculate movement of center-of-interest in parent's space target_move = iparent_xform.Transform(world_target) - iparent_xform.Transform(world_xform.Transform(prev_local_coi)) # Copy the camera's local transform new_local_transform = Gf.Matrix4d(initial_local_xform) # And move it by the delta new_local_transform.SetTranslateOnly(pos_in_parent + target_move) import omni.kit.commands if rotate: omni.kit.commands.create( 'ChangePropertyCommand', prop_path=coi_attr.GetPath(), value=new_local_coi, prev=prev_local_coi, timecode=self.__time, usd_context_name=self.__viewport_api.usd_context_name, type_to_create_if_not_exist=Sdf.ValueTypeNames.Vector3d ).do() omni.kit.commands.create( 'TransformPrimCommand', path=self.__camera_path, new_transform_matrix=new_local_transform, old_transform_matrix=initial_local_xform, time_code=self.__time, usd_context_name=self.__viewport_api.usd_context_name ).do()
7,593
Python
45.588957
137
0.629
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/legacy_viewport_api.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['LegacyViewportAPI'] import carb import omni.ui import omni.usd import omni.timeline import omni.kit.app from pxr import Gf, Sdf, Usd, UsdGeom, CameraUtil from typing import Callable, List, Tuple, Sequence # Wrap a legacy viewport Window in an object that poses as a new ViewportAPI class LegacyViewportAPI: def __init__(self, window_name: str): self.__window_name = window_name self.__settings = carb.settings.get_settings() # All legacy Viewports are locked to timeline time self.__timeline = None self.__saved_resolution = None self.__fill_frame = None @property def camera_path(self) -> Sdf.Path: '''Return an Sdf.Path to the active rendering camera''' path_str = self.legacy_window.get_active_camera() return Sdf.Path(path_str) if path_str else Sdf.Path() @camera_path.setter def camera_path(self, camera_path: Sdf.Path): '''Set the active rendering camera from an Sdf.Path''' self.legacy_window.set_active_camera(str(camera_path)) @property def render_product_path(self) -> str: '''Return a string to the UsdRender.Product used by the Viewport''' return self.legacy_window.get_render_product_path() @render_product_path.setter def render_product_path(self, product_path: str): '''Set the UsdRender.Product used by the Viewport with a string''' self.legacy_window.set_render_product_path(str(product_path)) @property def resolution(self) -> Tuple[float]: '''Return a tuple of (resolution_x, resolution_y) this Viewport is rendering at.''' # Legacy Viewport applies scale internally, so returned value accounts for scale factor. return self.legacy_window.get_texture_resolution() @resolution.setter def resolution(self, value: Tuple[float]): '''Set the resolution to render with (resolution_x, resolution_y).''' # Legacy Viewport applies scale internally based on single carb setting, so just use that self.legacy_window.set_texture_resolution(value[0], value[1]) @property def resolution_scale(self) -> float: '''Get the scaling factor for the Viewport's render resolution.''' # Legacy Viewport applies scale internally based on single carb setting, so just use that or fallback to 1 return self.__settings.get("/app/renderer/resolution/multiplier") or 1.0 @resolution_scale.setter def resolution_scale(self, value: float): '''Set the scaling factor for the Viewport's render resolution.''' value = float(value) if value <= 0: raise ValueError("Viewport resolution scale must be greater than 0.") self.__settings.set("/app/renderer/resolution/multiplier", value) @property def full_resolution(self) -> Tuple[float]: '''Return a tuple of the full (full_resolution_x, full_resolution_y) this Viewport is rendering at, not accounting for scale.''' # Legacy Viewport applies scale internally, so undo any scaling factor resolution = self.resolution resolution_scale = self.resolution_scale return (resolution[0] / resolution_scale, resolution[1] / resolution_scale) # Legacy methods that we also support def get_active_camera(self) -> Sdf.Path: '''Return an Sdf.Path to the active rendering camera''' return self.camera_path def set_active_camera(self, camera_path: Sdf.Path): '''Set the active rendering camera from an Sdf.Path''' self.camera_path = camera_path def get_render_product_path(self) -> str: '''Return a string to the UsdRender.Product used by the Viewport''' return self.render_product_path def set_render_product_path(self, product_path: str): '''Set the UsdRender.Product used by the Viewport with a string''' self.render_product_path = product_path def get_texture_resolution(self) -> Tuple[float]: '''Return a tuple of (resolution_x, resolution_y)''' return self.resolution def set_texture_resolution(self, value: Tuple[float]): '''Set the resolution to render with (resolution_x, resolution_y)''' self.resolution = value def get_texture_resolution_scale(self) -> float: '''Get the scaling factor for the Viewport's render resolution.''' return self.resolution_scale def set_texture_resolution_scale(self, value: float): '''Set the scaling factor for the Viewport's render resolution.''' self.resolution_scale = value def get_full_texture_resolution(self) -> Tuple[float]: '''Return a tuple of (full_resolution_x, full_resolution_y)''' return self.full_resolution @property def fill_frame(self) -> bool: if self.__fill_frame is None: settings = carb.settings.get_settings() width, height = settings.get('/app/renderer/resolution/width') or 0, settings.get('/app/renderer/resolution/height') or 0 self.__fill_frame = (width <= 0) or (height <= 0) return self.__fill_frame @fill_frame.setter def fill_frame(self, value: bool): settings = carb.settings.get_settings() legacy_window = self.legacy_window self.__fill_frame = bool(value) if self.__fill_frame: self.__saved_resolution = legacy_window.get_texture_resolution() legacy_window.set_texture_resolution(-1, -1) settings.set('/app/renderer/resolution/width', -1) settings.set('/app/renderer/resolution/height', -1) else: if self.__saved_resolution is None: width, height = settings.get('/app/renderer/resolution/width') or 0, settings.get('/app/renderer/resolution/height') or 0 self.__saved_resolution = (width, height) if (width > 0 and height > 0) else (1280, 720) legacy_window.set_texture_resolution(self.__saved_resolution[0], self.__saved_resolution[1]) @property def fps(self) -> float: '''Return the frames-per-second this Viewport is running at''' return self.legacy_window.get_fps() @property def id(self): '''Return a hashable value for the Viewport''' return self.legacy_window.get_id() @property def frame_info(self): return { 'viewport_handle' : self.legacy_window.get_id() } @property def usd_context_name(self) -> str: '''Return the name of the omni.usd.UsdContext this Viewport is attached to''' return self.legacy_window.get_usd_context_name() @property def usd_context(self): '''Return the omni.usd.UsdContext this Viewport is attached to''' return omni.usd.get_context(self.usd_context_name) @property def stage(self): '''Return the Usd.Stage of the omni.usd.UsdContext this Viewport is attached to''' return self.usd_context.get_stage() @property def projection(self): '''Return the projection of the UsdCamera in terms of the ui element it sits in.''' # Check if there are cached values from the ScenView subscriptions legacy_subs = _LegacySceneView.get(self.__window_name) if legacy_subs: projection = legacy_subs.projection if projection: return projection # Get the info from USD stage = self.stage cam_prim = stage.GetPrimAtPath(self.camera_path) if stage else None if cam_prim: usd_camera = UsdGeom.Camera(cam_prim) if usd_camera: image_aspect, canvas_aspect = self._aspect_ratios return self._conform_projection(self._conform_policy(), usd_camera, image_aspect, canvas_aspect) return Gf.Matrix4d(1) @property def transform(self) -> Gf.Matrix4d: '''Return the world-space transform of the UsdGeom.Camera being used to render''' # Check if there are cached values from the ScenView subscriptions legacy_subs = _LegacySceneView.get(self.__window_name) if legacy_subs: view = legacy_subs.view if view: return view.GetInverse() # Get the info from USD stage = self.stage cam_prim = stage.GetPrimAtPath(self.camera_path) if stage else None if cam_prim: imageable = UsdGeom.Imageable(cam_prim) if imageable: return imageable.ComputeLocalToWorldTransform(self.time) return Gf.Matrix4d(1) @property def view(self) -> Gf.Matrix4d: '''Return the inverse of the world-space transform of the UsdGeom.Camera being used to render''' # Check if there are cached values from the ScenView subscriptions legacy_subs = _LegacySceneView.get(self.__window_name) if legacy_subs: view = legacy_subs.view if view: return view # Get the info from USD return self.transform.GetInverse() @property def world_to_ndc(self): return self.view * self.projection @property def ndc_to_world(self): return self.world_to_ndc.GetInverse() @property def time(self) -> Usd.TimeCode: '''Return the Usd.TimeCode this Viewport is using''' if self.__timeline is None: self.__timeline = omni.timeline.get_timeline_interface() time = self.__timeline.get_current_time() return Usd.TimeCode(omni.usd.get_frame_time_code(time, self.stage.GetTimeCodesPerSecond())) def map_ndc_to_texture(self, mouse: Sequence[float]): image_aspect, canvas_aspect = self._aspect_ratios if image_aspect < canvas_aspect: ratios = (image_aspect / canvas_aspect, 1) else: ratios = (1, canvas_aspect / image_aspect) # Move into viewport's NDC-space: [-1, 1] bound by viewport mouse = (mouse[0] / ratios[0], mouse[1] / ratios[1]) # Move from NDC space to texture-space [-1, 1] to [0, 1] def check_bounds(coord): return coord >= -1 and coord <= 1 return tuple((x + 1.0) * 0.5 for x in mouse), self if (check_bounds(mouse[0]) and check_bounds(mouse[1])) else None def map_ndc_to_texture_pixel(self, mouse: Sequence[float]): # Move into viewport's uv-space: [0, 1] mouse, viewport = self.map_ndc_to_texture(mouse) # Then scale by resolution flipping-y resolution = self.resolution return (int(mouse[0] * resolution[0]), int((1.0 - mouse[1]) * resolution[1])), viewport def request_query(self, pixel: Sequence[int], callback: Callable, *args): # TODO: This can't be made 100% compatible without changes to legacy Viewport # New Viewport will query based on a pixel co-ordinate, regardless of mouse-state; with object and world-space-position # Legacy Viewport will invoke callback on mouse-click only; with world-space-position info only self.legacy_window.query_next_picked_world_position(lambda pos: callback(True, pos) if pos else callback(False, None)) carb.log_warn("request_query not full implemented, will only receive a position from a Viewport click") @property def hydra_engine(self) -> str: '''Get the name of the active omni.hydra.engine for this Viewport''' return self.legacy_window.get_active_hydra_engine() @hydra_engine.setter def hydra_engine(self, hd_engine: str) -> str: '''Set the name of the active omni.hydra.engine for this Viewport''' return self.set_hd_engine(hd_engine) @property def render_mode(self): '''Get the render-mode for the active omni.hydra.engine used in this Viewport''' hd_engine = self.hydra_engine if bool(hd_engine): return self.__settings.get(self.__render_mode_setting(hd_engine)) @render_mode.setter def render_mode(self, render_mode: str): '''Set the render-mode for the active omni.hydra.engine used in this Viewport''' hd_engine = self.hydra_engine if bool(hd_engine): self.__settings.set_string(self.__render_mode_setting(hd_engine), str(render_mode)) def set_hd_engine(self, hd_engine: str, render_mode: str = None): '''Set the active omni.hydra.engine for this Viewport, and optionally its render-mode''' # self.__settings.set_string("/renderer/active", hd_engine) if bool(hd_engine) and bool(render_mode): self.__settings.set_string(self.__render_mode_setting(hd_engine), render_mode) self.legacy_window.set_active_hydra_engine(hd_engine) async def wait_for_rendered_frames(self, additional_frames: int = 0) -> bool: '''Asynchrnously wait until the renderer has delivered an image''' app = omni.kit.app.get_app_interface() legacy_window = self.legacy_window if legacy_window: viewport_ldr_rp = None while viewport_ldr_rp is None: await app.next_update_async() viewport_ldr_rp = legacy_window.get_drawable_ldr_resource() while additional_frames > 0: additional_frames = additional_frames - 1 await app.next_update_async() return True def add_scene_view(self, scene_view): window_name = self.__window_name legacy_subs = _LegacySceneView.get(self.__window_name, self.legacy_window) if not legacy_subs: raise RuntimeError('Could not create _LegacySceneView subscriptions') legacy_subs.add_scene_view(scene_view, self.projection, self.view) def remove_scene_view(self, scene_view): if not scene_view: raise RuntimeError('Provided scene_view is invalid') _LegacySceneView.remove_scene_view_for_window(self.__window_name, scene_view) ### Everything below is NOT part of the new Viewport-API @property def legacy_window(self): '''Expose the underlying legacy viewport for access if needed (not a real ViewportAPI method)''' import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() return vp_iface.get_viewport_window(vp_iface.get_instance(self.__window_name)) @property def _aspect_ratios(self) -> Tuple[float]: return _LegacySceneView.aspect_ratios(self.__window_name, self.legacy_window) def _conform_projection(self, policy, camera: UsdGeom.Camera, image_aspect: float, canvas_aspect: float, projection: Sequence[float] = None): '''For the given camera (or possible incoming projection) return a projection matrix that matches the rendered image but keeps NDC co-ordinates for the texture bound to [-1, 1]''' if projection is None: # If no projection is provided, conform the camera based on settings # This wil adjust apertures on the gf_camera gf_camera = camera.GetCamera(self.time) if policy == CameraUtil.DontConform: # For DontConform, still have to conform for the final canvas if image_aspect < canvas_aspect: gf_camera.horizontalAperture = gf_camera.horizontalAperture * (canvas_aspect / image_aspect) else: gf_camera.verticalAperture = gf_camera.verticalAperture * (image_aspect / canvas_aspect) else: CameraUtil.ConformWindow(gf_camera, policy, image_aspect) projection = gf_camera.frustum.ComputeProjectionMatrix() else: projection = Gf.Matrix4d(*projection) # projection now has the rendered image projection # Conform again based on canvas size so projection extends with the Viewport sits in the UI if image_aspect < canvas_aspect: policy2 = CameraUtil.MatchVertically else: policy2 = CameraUtil.MatchHorizontally if policy != CameraUtil.DontConform: projection = CameraUtil.ConformedWindow(projection, policy2, canvas_aspect) return projection def _conform_policy(self): conform_setting = self.__settings.get("/app/hydra/aperture/conform") if (conform_setting is None) or (conform_setting == 1) or (conform_setting == 'horizontal'): return CameraUtil.MatchHorizontally if (conform_setting == 0) or (conform_setting == 'vertical'): return CameraUtil.MatchVertically if (conform_setting == 2) or (conform_setting == 'fit'): return CameraUtil.Fit if (conform_setting == 3) or (conform_setting == 'crop'): return CameraUtil.Crop if (conform_setting == 4) or (conform_setting == 'stretch'): return CameraUtil.DontConform return CameraUtil.MatchHorizontally def __render_mode_setting(self, hd_engine: str) -> str: return f'/{hd_engine}/rendermode' if hd_engine != 'iray' else '/rtx/iray/rendermode' class _LegacySceneView: __g_legacy_subs = {} @staticmethod def aspect_ratios(window_name: str, legacy_window): canvas_aspect = 1 viewport_window = omni.ui.Workspace.get_window(window_name) if viewport_window: # XXX: Why do some windows have no frame !? if hasattr(viewport_window, 'frame'): canvas = viewport_window.frame canvas_size = (canvas.computed_width, canvas.computed_height) else: canvas_size = (1, 1) canvas_aspect = canvas_size[0] / canvas_size[1] if canvas_size[1] else 1 resolution = legacy_window.get_texture_resolution() image_aspect = resolution[0] / resolution[1] if resolution[1] else 1 return image_aspect, canvas_aspect @staticmethod def get(window_name: str, legacy_window = None): legacy_subs = _LegacySceneView.__g_legacy_subs.get(window_name) if legacy_subs is None and legacy_window: legacy_subs = _LegacySceneView(window_name, legacy_window) _LegacySceneView.__g_legacy_subs[window_name] = legacy_subs return legacy_subs @staticmethod def remove_scene_view_for_window(window_name: str, scene_view): if not scene_view: raise RuntimeError('Provided scene_view is invalid') legacy_subs = _LegacySceneView.__g_legacy_subs.get(window_name) if not legacy_subs: raise RuntimeError('Removing a SceneView for Viewport that is not trakcing any') if legacy_subs.remove_scene_view(scene_view): return legacy_subs.destroy() del _LegacySceneView.__g_legacy_subs[window_name] def __init__(self, window_name: str, legacy_window): self.__window_name = window_name self.__draw_sub, self.__update_sub = None, None self.__scene_views = [] self.__projection = None self.__view = None events = legacy_window.get_ui_draw_event_stream() self.__draw_sub = events.create_subscription_to_pop(self.__on_draw, name=f'omni.kit.viewport.utility.LegacyViewportAPI.{window_name}.draw') events = omni.kit.app.get_app().get_update_event_stream() self.__update_sub = events.create_subscription_to_pop(self.__on_update, name='omni.kit.viewport.utility.LegacyViewportAPI.{window_name}.update') @property def projection(self) -> Gf.Matrix4d: # Return a copy as the reference would be mutable return Gf.Matrix4d(self.__projection) if self.__projection else None @property def view(self) -> Gf.Matrix4d: # Return a copy as the reference would be mutable return Gf.Matrix4d(self.__view) if self.__view else None def __del__(self): self.destroy() def destroy(self): self.__scene_views = [] if self.__draw_sub: self.__draw_sub = None if self.__update_sub: self.__update_sub = None self.__save_position = None self.__scene_views = [] @staticmethod def _flatten_matrix(m: Gf.Matrix4d) -> List[float]: m0, m1, m2, m3 = m[0], m[1], m[2], m[3] return [m0[0], m0[1], m0[2], m0[3], m1[0], m1[1], m1[2], m1[3], m2[0], m2[1], m2[2], m2[3], m3[0], m3[1], m3[2], m3[3]] def __get_legacy_window(self): import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() window_name = self.__window_name viewport_handle = vp_iface.get_instance(window_name) viewport_window = vp_iface.get_viewport_window(viewport_handle) if not viewport_window: self.destroy() del _LegacySceneView.__g_legacy_subs[window_name] return window_name, viewport_window def __on_update(self, *args): window_name, legacy_window = self.__get_legacy_window() visible = legacy_window.is_visible() if legacy_window else False viewport_window = omni.ui.Workspace.get_window(window_name) if viewport_window and (visible != viewport_window.visible): pruned_views = [] for sv in self.__scene_views: scene_view = sv() if scene_view: scene_view.visible = visible pruned_views.append(sv) self.__scene_views = pruned_views omni.ui.Workspace.show_window(window_name, visible) # viewport_window.visible = visible # if not visible: # self.__save_position = viewport_window.position_x, viewport_window.position_y # viewport_window.position_x = omni.ui.Workspace.get_main_window_width() # viewport_window.position_y = omni.ui.Workspace.get_main_window_height() # elif self.__save_position: # viewport_window.position_x = self.__save_position[0] # viewport_window.position_y = self.__save_position[1] # self.__save_position = None def __on_draw(self, event, *args): vm = event.payload["viewMatrix"] pm = event.payload["projMatrix"] # Conform the Projection to the layout of the texture in the Window window_name, legacy_window = self.__get_legacy_window() image_aspect, canvas_aspect = _LegacySceneView.aspect_ratios(window_name, legacy_window) if image_aspect < canvas_aspect: policy = CameraUtil.MatchVertically else: policy = CameraUtil.MatchHorizontally proj_matrix = Gf.Matrix4d(pm[0], pm[1], pm[2], pm[3], pm[4], pm[5], pm[6], pm[7], pm[8], pm[9], pm[10], pm[11], pm[12], pm[13], pm[14], pm[15]) # Fix up RTX projection Matrix for omni.ui.scene...ultimately this should be passed without any compensation if pm[15] == 0.0: proj_matrix = Gf.Matrix4d(1.0, 0.0, -0.0, 0.0, 0.0, 1.0, 0.0, -0.0, -0.0, 0.0, 1.0, -1.0, 0.0, -0.0, 0.0, -2.0) * proj_matrix proj_matrix = CameraUtil.ConformedWindow(proj_matrix, policy, canvas_aspect) # Cache these for lokkup later self.__projection = proj_matrix self.__view = Gf.Matrix4d(vm[0], vm[1], vm[2], vm[3], vm[4], vm[5], vm[6], vm[7], vm[8], vm[9], vm[10], vm[11], vm[12], vm[13], vm[14], vm[15]) # Flatten into list for model pm = _LegacySceneView._flatten_matrix(proj_matrix) pruned_views = [] for sv in self.__scene_views: scene_view = sv() if scene_view: model = scene_view.model model.set_floats("projection", pm) model.set_floats("view", vm) pruned_views.append(sv) self.__scene_views = pruned_views def add_scene_view(self, scene_view, projection: Gf.Matrix4d, view: Gf.Matrix4d): # Sync the model once now model = scene_view.model model.set_floats("projection", _LegacySceneView._flatten_matrix(projection)) model.set_floats("view", _LegacySceneView._flatten_matrix(view)) # And save it for subsequent synchrnoizations import weakref self.__scene_views.append(weakref.ref(scene_view)) def remove_scene_view(self, scene_view) -> bool: for sv in self.__scene_views: if sv() == scene_view: self.__scene_views.remove(sv) break # Return whether this sub is needed anymore return True if self.__scene_views else False
24,854
Python
43.147424
152
0.634948
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/tests/capture.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = [ 'DEFAULT_THRESHOLD', 'capture_viewport_and_compare' ] import carb import omni.kit.app import omni.renderer_capture from omni.kit.test_helpers_gfx import compare, CompareError from omni.kit.test.teamcity import teamcity_log_fail, teamcity_publish_image_artifact import pathlib import traceback DEFAULT_THRESHOLD = 10.0 def viewport_capture(image_name: str, output_img_dir: str, viewport=None, use_log: bool = True): """ Captures a Viewport texture into a file. Args: image_name: the image name of the image and golden image. output_img_dir: the directory path that the capture will be saved to. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. use_log: whether to log the comparison image path """ from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file image1 = str(pathlib.Path(output_img_dir).joinpath(image_name)) if use_log: carb.log_info(f"[tests.compare] Capturing {image1}") if viewport is None: viewport = get_active_viewport() return capture_viewport_to_file(viewport, file_path=image1) def finalize_capture_and_compare(image_name: str, output_img_dir: str, golden_img_dir: str, threshold: float = DEFAULT_THRESHOLD): """ Finalizes capture and compares it with the golden image. Args: image_name: the image name of the image and golden image. threshold: the max threshold to collect TC artifacts. output_img_dir: the directory path that the capture will be saved to. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. Returns: A value that indicates the maximum difference between pixels. 0 is no difference in the range [0-255]. """ image1 = pathlib.Path(output_img_dir).joinpath(image_name) image2 = pathlib.Path(golden_img_dir).joinpath(image_name) image_diffmap_name = f"{pathlib.Path(image_name).stem}.diffmap.png" image_diffmap = pathlib.Path(output_img_dir).joinpath(image_diffmap_name) carb.log_info(f"[tests.compare] Comparing {image1} to {image2}") try: diff = compare(image1, image2, image_diffmap) if diff >= threshold: # TODO pass specific test name here instead of omni.rtx.tests teamcity_log_fail("omni.rtx.tests", f"Reference image {image_name} differ from golden.") teamcity_publish_image_artifact(image2, "golden", "Reference") teamcity_publish_image_artifact(image1, "results", "Generated") teamcity_publish_image_artifact(image_diffmap, "results", "Diff") return diff except CompareError as e: carb.log_error(f"[tests.compare] Failed to compare images for {image_name}. Error: {e}") exc = traceback.format_exc() carb.log_error(f"[tests.compare] Traceback:\n{exc}") async def capture_viewport_and_wait(image_name: str, output_img_dir: str, viewport = None): viewport_capture(image_name, output_img_dir, viewport) app = omni.kit.app.get_app() capure_iface = omni.renderer_capture.acquire_renderer_capture_interface() for i in range(3): capure_iface.wait_async_capture() await app.next_update_async() async def capture_viewport_and_compare(image_name: str, output_img_dir: str, golden_img_dir: str, threshold: float = DEFAULT_THRESHOLD, viewport = None, test_caller: str = None): """ Captures frame and compares it with the golden image. Args: image_name: the image name of the image and golden image. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. threshold: the max threshold to collect TC artifacts. viewport: the viewport to capture or None for the active Viewport Returns: A value that indicates the maximum difference between pixels. 0 is no difference in the range [0-255]. """ await capture_viewport_and_wait(image_name=image_name, output_img_dir=output_img_dir, viewport=viewport) diff = finalize_capture_and_compare(image_name=image_name, output_img_dir=output_img_dir, golden_img_dir=golden_img_dir, threshold=threshold) if diff is not None and diff < DEFAULT_THRESHOLD: return True, '' carb.log_warn(f"[{image_name}] the generated image has difference {diff}") if test_caller is None: import os.path test_caller = os.path.splitext(image_name)[0] return False, f"The image for test '{test_caller}' doesn't match the golden one. Difference of {diff} is is not less than threshold of {threshold}."
5,144
Python
39.511811
178
0.700428
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/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 .capture import * from .test_suite import * async def setup_viewport_test_window(resolution_x: int, resolution_y: int, position_x: int = 0, position_y: int = 0): from omni.kit.viewport.utility import get_active_viewport_window viewport_window = get_active_viewport_window() if viewport_window: viewport_window.position_x = position_x viewport_window.position_y = position_y viewport_window.width = resolution_x viewport_window.height = resolution_y viewport_window.viewport_api.resolution = (resolution_x, resolution_y) return viewport_window
1,043
Python
42.499998
117
0.744966
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/tests/test_suite.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ['TestViewportUtility'] import omni.kit.test from omni.kit.test import AsyncTestCase import omni.kit.viewport.utility import omni.kit.renderer_capture import omni.kit.app import omni.usd import omni.ui as ui from pathlib import Path from pxr import Gf, UsdGeom, Sdf, Usd TEST_OUTPUT = Path(omni.kit.test.get_test_output_path()).resolve().absolute() TEST_WIDTH, TEST_HEIGHT = (500, 500) class TestViewportUtility(AsyncTestCase): # Before running each test async def setUp(self): super().setUp() await omni.usd.get_context().new_stage_async() async def tearDown(self): super().tearDown() # Legacy Viewport needs some time to adopt the resolution changes async def wait_for_resolution_change(self, viewport_api): await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) for i in range(3): await omni.kit.app.get_app().next_update_async() async def test_get_viewport_from_window_name(self): '''Test getting a default Viewport from a Window without a name''' viewport_window = omni.kit.viewport.utility.get_viewport_from_window_name() self.assertIsNotNone(viewport_window) async def test_get_viewport_from_window_name_with_name(self): '''Test getting a default Viewport from a Window name''' viewport_window = omni.kit.viewport.utility.get_viewport_from_window_name(window_name='Viewport') self.assertIsNotNone(viewport_window) async def test_get_active_viewport(self): '''Test getting a default Viewport''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) viewport_api = omni.kit.viewport.utility.get_active_viewport(usd_context_name='') self.assertIsNotNone(viewport_api) async def test_get_viewport_from_non_existant_window_name_with_name(self): '''Test getting a non-existent Viewport via Window name''' viewport_window = omni.kit.viewport.utility.get_viewport_from_window_name(window_name='NotExisting') self.assertIsNone(viewport_window) async def test_get_non_existant_viewport(self): '''Test getting a non-existent Viewport via UsdContext name''' viewport_api = omni.kit.viewport.utility.get_active_viewport(usd_context_name='NotExisting') self.assertIsNone(viewport_api) async def test_get_camera_path_api(self): '''Test camera access API''' # Test camera-path as an Sdf.Path cam_path = omni.kit.viewport.utility.get_viewport_window_camera_path() self.assertTrue(bool(cam_path)) self.assertTrue(isinstance(cam_path, Sdf.Path)) cam_path = omni.kit.viewport.utility.get_viewport_window_camera_path(window_name='Viewport') self.assertTrue(bool(cam_path)) self.assertTrue(isinstance(cam_path, Sdf.Path)) cam_path = omni.kit.viewport.utility.get_viewport_window_camera_path(window_name='NO_Viewport') self.assertIsNone(cam_path) cam_path = omni.kit.viewport.utility.get_active_viewport_camera_path() self.assertTrue(bool(cam_path)) self.assertTrue(isinstance(cam_path, Sdf.Path)) cam_path = omni.kit.viewport.utility.get_active_viewport_camera_path(usd_context_name='') self.assertTrue(bool(cam_path)) self.assertTrue(isinstance(cam_path, Sdf.Path)) cam_path = omni.kit.viewport.utility.get_active_viewport_camera_path(usd_context_name='DoesntExist') self.assertIsNone(cam_path) # Test camera-path as a string cam_path_str = omni.kit.viewport.utility.get_viewport_window_camera_string() self.assertTrue(bool(cam_path_str)) self.assertTrue(isinstance(cam_path_str, str)) cam_path_str = omni.kit.viewport.utility.get_viewport_window_camera_string(window_name='Viewport') self.assertTrue(bool(cam_path_str)) self.assertTrue(isinstance(cam_path_str, str)) cam_path_str = omni.kit.viewport.utility.get_viewport_window_camera_string(window_name='NO_Viewport') self.assertIsNone(cam_path_str) cam_path_str = omni.kit.viewport.utility.get_active_viewport_camera_string() self.assertTrue(bool(cam_path_str)) self.assertTrue(isinstance(cam_path_str, str)) cam_path_str = omni.kit.viewport.utility.get_active_viewport_camera_string(usd_context_name='') self.assertTrue(bool(cam_path_str)) self.assertTrue(isinstance(cam_path_str, str)) cam_path_str = omni.kit.viewport.utility.get_active_viewport_camera_string(usd_context_name='DoesntExist') self.assertIsNone(cam_path_str) viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) # Test property and method accessors are equal self.assertEqual(viewport_api.get_active_camera(), viewport_api.camera_path) async def test_setup_viewport_test_window(self): '''Test the test-suite utility setup_viewport_test_window''' from omni.kit.viewport.utility.tests import setup_viewport_test_window viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) resolution = viewport_api.resolution # Test the keywords arguments for the function await setup_viewport_test_window(resolution_x=128, resolution_y=128, position_x=10, position_y=10) # Test the arguments for the function and restore Viewport resolution await setup_viewport_test_window(resolution[0], resolution[1], 0, 0) async def test_viewport_resolution(self): '''Test the test-suite utility setup_viewport_test_window''' from omni.kit.viewport.utility.tests import setup_viewport_test_window viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) # Legacy Viewport needs some time to adopt the resolution changes try: resolution = viewport_api.resolution self.assertIsNotNone(resolution) full_resolution = viewport_api.full_resolution self.assertEqual(resolution, full_resolution) resolution_scale = viewport_api.resolution_scale # Resolution scale factor should be 1 by default self.assertEqual(resolution_scale, 1.0) viewport_api.resolution_scale = 0.5 await self.wait_for_resolution_change(viewport_api) # Resolution scale factor should stick self.assertEqual(viewport_api.resolution_scale, 0.5) # Full resolution should still be the same self.assertEqual(viewport_api.full_resolution, full_resolution) # New resolution should now be half of the original self.assertEqual(viewport_api.resolution, (resolution[0] * 0.5, resolution[1] * 0.5)) finally: viewport_api.resolution_scale = 1.0 self.assertEqual(viewport_api.resolution_scale, 1.0) async def test_testsuite_capture_helpers(self): '''Test the API exposed to assist other extensions testing/capturing Viewport''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) from omni.kit.viewport.utility.tests.capture import viewport_capture, capture_viewport_and_wait # Test keyword arguments with an explicit Viewport await capture_viewport_and_wait(image_name='test_testsuite_capture_helper_01', output_img_dir=str(TEST_OUTPUT), viewport = viewport_api) # Test arguments with an implicit Viewport await capture_viewport_and_wait('test_testsuite_capture_helper_02', str(TEST_OUTPUT)) async def test_legacy_as_new_api(self): '''Test the new API against a new or legacy Viewport''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) self.assertEqual(viewport_api.camera_path.pathString, '/OmniverseKit_Persp') # Test camera property setter viewport_api.camera_path = '/OmniverseKit_Top' self.assertEqual(viewport_api.camera_path.pathString, '/OmniverseKit_Top') # Test camera method setter viewport_api.set_active_camera('/OmniverseKit_Persp') resolution = viewport_api.resolution self.assertIsNotNone(resolution) # Test access via legacy method-name self.assertEqual(resolution, viewport_api.get_texture_resolution()) # Test setting via property viewport_api.resolution = (128, 128) await self.wait_for_resolution_change(viewport_api) self.assertEqual(viewport_api.resolution, (128, 128)) # Test setting via method viewport_api.set_texture_resolution((256, 256)) await self.wait_for_resolution_change(viewport_api) self.assertEqual(viewport_api.get_texture_resolution(), (256, 256)) # Test matrix access self.assertIsNotNone(viewport_api.projection) self.assertIsNotNone(viewport_api.transform) self.assertIsNotNone(viewport_api.view) # Test world-NDC matrix convertor access self.assertIsNotNone(viewport_api.world_to_ndc) self.assertIsNotNone(viewport_api.ndc_to_world) # Test UsdContext and Stage access self.assertIsNotNone(viewport_api.usd_context_name) self.assertIsNotNone(viewport_api.usd_context) self.assertIsNotNone(viewport_api.stage) render_product_path = viewport_api.render_product_path self.assertIsNotNone(render_product_path) # Test access via legacy method-name self.assertEqual(render_product_path, viewport_api.get_render_product_path()) # Test setting via property viewport_api.render_product_path = render_product_path # Test setting via method viewport_api.set_render_product_path(render_product_path) # Should have an id property self.assertIsNotNone(viewport_api.id) # Should have a frame_info dictionary self.assertIsNotNone(viewport_api.frame_info) # Test the NDC to texture-uv mapping API uv, valid = viewport_api.map_ndc_to_texture((0, 0)) self.assertTrue(bool(valid)) self.assertEqual(uv, (0.5, 0.5)) # Test the NDC to texture-pixel mapping API pixel, valid = viewport_api.map_ndc_to_texture_pixel((0, 0)) self.assertTrue(bool(valid)) # Test API to set fill-frame resolution self.assertFalse(viewport_api.fill_frame) viewport_api.fill_frame = True await self.wait_for_resolution_change(viewport_api) self.assertTrue(viewport_api.fill_frame) viewport_api.fill_frame = False await self.wait_for_resolution_change(viewport_api) self.assertFalse(viewport_api.fill_frame) async def test_viewport_window_api(self): '''Test the legacy API exposure into the omni.ui window wrapper''' viewport_window = omni.kit.viewport.utility.get_active_viewport_window() self.assertIsNotNone(viewport_window) # Test the get_frame API frame_1 = viewport_window.get_frame('omni.kit.viewport.utility.test_frame_1') self.assertIsNotNone(frame_1) frame_2 = viewport_window.get_frame('omni.kit.viewport.utility.test_frame_1') self.assertEqual(frame_1, frame_2) frame_3 = viewport_window.get_frame('omni.kit.viewport.utility.test_frame_3') self.assertNotEqual(frame_1, frame_3) # Test setting visible attribute on Window viewport_window.visible = True self.assertTrue(viewport_window.visible) # Test utility function for legacy usage only if viewport_window and hasattr(viewport_window.viewport_api, 'legacy_window'): viewport_window.setPosition(0, 0) viewport_window.set_position(0, 0) async def test_toggle_global_visibility(self): """Test the expected setting change for omni.kit.viewport.utility.toggle_global_visibility""" import carb settings = carb.settings.get_settings() viewport_api = omni.kit.viewport.utility.get_active_viewport() if hasattr(viewport_api, 'legacy_window'): def collect_settings(settings): return settings.get('/persistent/app/viewport/displayOptions') else: def collect_settings(settings): setting_keys = [ "/persistent/app/viewport/Viewport/Viewport0/guide/grid/visible", "/persistent/app/viewport/Viewport/Viewport0/hud/deviceMemory/visible", "/persistent/app/viewport/Viewport/Viewport0/hud/hostMemory/visible", "/persistent/app/viewport/Viewport/Viewport0/hud/renderFPS/visible", "/persistent/app/viewport/Viewport/Viewport0/hud/renderProgress/visible", "/persistent/app/viewport/Viewport/Viewport0/hud/renderResolution/visible", "/persistent/app/viewport/Viewport/Viewport0/scene/cameras/visible", "/persistent/app/viewport/Viewport/Viewport0/scene/lights/visible", "/persistent/app/viewport/Viewport/Viewport0/scene/skeletons/visible", ] return {k: settings.get(k) for k in setting_keys} omni.kit.viewport.utility.toggle_global_visibility() options_1 = collect_settings(settings) omni.kit.viewport.utility.toggle_global_visibility() options_2 = collect_settings(settings) self.assertNotEqual(options_1, options_2) omni.kit.viewport.utility.toggle_global_visibility() options_3 = collect_settings(settings) self.assertEqual(options_1, options_3) omni.kit.viewport.utility.toggle_global_visibility() options_4 = collect_settings(settings) self.assertEqual(options_2, options_4) async def test_ui_scene_view_model_sync(self): '''Test API to autmoatically set view and projection on a SceneView model''' class ModelPoser: def __init__(model_self): model_self.set_items = set() def get_item(model_self, name: str): if name == 'view' or name == 'projection': return name self.assertTrue(False) def set_floats(model_self, item, floats): self.assertEqual(len(floats), 16) self.assertTrue(item == model_self.get_item(item)) model_self.set_items.add(item) class SceneViewPoser: def __init__(model_self): model_self.model = ModelPoser() viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) scene_view = SceneViewPoser() # Test add_scene_view API viewport_api.add_scene_view(scene_view) # Test both view and projection have been set into self.assertTrue('view' in scene_view.model.set_items) self.assertTrue('projection' in scene_view.model.set_items) # Test remove_scene_view API viewport_api.remove_scene_view(scene_view) async def test_legacy_drag_drop_helper(self): pickable = False add_outline = False def on_drop_accepted_fn(url): pass def on_drop_fn(url, prim_path, unused_viewport_name, usd_context_name): pass def on_pick_fn(payload, prim_path, usd_context_name): pass dd_from_args = omni.kit.viewport.utility.create_drop_helper( pickable, add_outline, on_drop_accepted_fn, on_drop_fn, on_pick_fn ) self.assertIsNotNone(dd_from_args) dd_from_kw = omni.kit.viewport.utility.create_drop_helper( pickable=pickable, add_outline=add_outline, on_drop_accepted_fn=on_drop_accepted_fn, on_drop_fn=on_drop_fn, on_pick_fn=on_pick_fn ) self.assertIsNotNone(dd_from_kw) async def test_capture_file(self): '''Test the capture_viewport_to_file capture to a file''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertTrue(bool(viewport_api)) # Make sure renderer is rendering images (also a good place to up the coverage %) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) file = TEST_OUTPUT.joinpath('capture_01.png') cap_obj = omni.kit.viewport.utility.capture_viewport_to_file(viewport_api, file_path=str(file)) # API should return an object we can await on self.assertIsNotNone(cap_obj) # Test that we can in fact wait on that object result = await cap_obj.wait_for_result(completion_frames=30) self.assertTrue(result) # File should exists by now omni.kit.renderer_capture.acquire_renderer_capture_interface().wait_async_capture() self.assertTrue(file.exists()) async def test_capture_file_with_exr_compression(self): '''Test the capture_viewport_to_file capture to a file''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertTrue(bool(viewport_api)) # Make sure renderer is rendering images (also a good place to up the coverage %) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) format_desc = {} format_desc["format"] = "exr" format_desc["compression"] = "b44" file = TEST_OUTPUT.joinpath(f'capture_{format_desc["compression"]}.{format_desc["format"]}') cap_obj = omni.kit.viewport.utility.capture_viewport_to_file(viewport_api, file_path=str(file), format_desc=format_desc) # API should return an object we can await on self.assertIsNotNone(cap_obj) # Test that we can in fact wait on that object result = await cap_obj.wait_for_result(completion_frames=30) self.assertTrue(result) # File should exists by now omni.kit.renderer_capture.acquire_renderer_capture_interface().wait_async_capture() self.assertTrue(file.exists()) async def test_capture_file_str_convert(self): '''Test the capture_viewport_to_file capture to a file when passed an path-like object''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertTrue(bool(viewport_api)) # Make sure renderer is rendering images (also a good place to up the coverage %) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) file = TEST_OUTPUT.joinpath('capture_02.png') cap_obj = omni.kit.viewport.utility.capture_viewport_to_file(viewport_api, file_path=file) # API should return an object we can await on self.assertIsNotNone(cap_obj) # Test that we can in fact wait on that object result = await cap_obj.wait_for_result(completion_frames=15) self.assertTrue(result) # File should exists by now # self.assertTrue(file.exists()) async def test_capture_to_buffer(self): '''Test the capture_viewport_to_file capture to a callback function''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertTrue(bool(viewport_api)) # Make sure renderer is rendering images (also a good place to up the coverage %) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) callback_called = False def capture_callback(*args, **kwargs): nonlocal callback_called callback_called = True cap_obj = omni.kit.viewport.utility.capture_viewport_to_buffer(viewport_api, capture_callback) # API should return an object we can await on self.assertIsNotNone(cap_obj) # Test that we can in fact wait on that object result = await cap_obj.wait_for_result() self.assertTrue(result) # Callback should have been called self.assertTrue(callback_called) async def test_new_viewport_api(self): '''Test the ability to create a new Viewport and retrieve the number of Viewports open''' num_vp_1 = omni.kit.viewport.utility.get_num_viewports() self.assertEqual(num_vp_1, 1) # Test Window creation, but that would require a renderer other than Storm which can only be created once # Which would make the tests run slower and in L2 # new_window = omni.kit.viewport.utility.create_viewport_window('TEST WINDOW', width=128, height=128, camera_path='/OmniverseKit_Top') # self.assertEqual(new_window.viewport_api.camera_path.pathString, '/OmniverseKit_Top') # num_vp_2 = omni.kit.viewport.utility.get_num_viewports() # self.assertEqual(num_vp_2, 2) async def test_post_toast_api(self): # Post a message with a Viewport only viewport_api = omni.kit.viewport.utility.get_active_viewport() omni.kit.viewport.utility.post_viewport_message(viewport_api, "Message from ViewportAPI") # Post a message with the same API, but a Window viewport_window = omni.kit.viewport.utility.get_active_viewport_window() omni.kit.viewport.utility.post_viewport_message(viewport_window, "Message from ViewportWindow") # Post a message with the same API, but with a method viewport_window._post_toast_message("Message from ViewportWindow method") async def test_disable_picking(self): '''Test ability to disable picking on a Viewport or ViewportWindow''' from omni.kit import ui_test viewport_window = omni.kit.viewport.utility.get_active_viewport_window() self.assertIsNotNone(viewport_window) # viewport_window.position_x = 0 # viewport_window.position_y = 0 # viewport_window.width = TEST_WIDTH # viewport_window.height = TEST_HEIGHT viewport_api = viewport_window.viewport_api self.assertIsNotNone(viewport_api) usd_cube = UsdGeom.Cube.Define(viewport_window.viewport_api.stage, "/cube") usd_cube.GetSizeAttr().Set(100) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) async def test_selection_rect(wait_frames: int = 5): selection = viewport_api.usd_context.get_selection() self.assertIsNotNone(selection) selection.set_selected_prim_paths([], False) selected_prims = selection.get_selected_prim_paths() self.assertFalse(bool(selected_prims)) for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_drag_and_drop(ui_test.Vec2(100, 100), ui_test.Vec2(400, 400)) for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() return selection.get_selected_prim_paths() # Test initial selection works as expected selection = await test_selection_rect() self.assertTrue(len(selection) == 1) self.assertTrue(selection[0] == '/cube') # Test disabling selection on the Window leads to no selection picking_disabled = omni.kit.viewport.utility.disable_selection(viewport_window) selection = await test_selection_rect() self.assertTrue(len(selection) == 0) del picking_disabled # Test restore of selection works as expected selection = await test_selection_rect() self.assertTrue(len(selection) == 1) self.assertTrue(selection[0] == '/cube') # Test disabling selection on the Viewport leads to no selection picking_disabled = omni.kit.viewport.utility.disable_selection(viewport_api) selection = await test_selection_rect() self.assertTrue(len(selection) == 0) del picking_disabled async def test_frame_viewport(self): time = Usd.TimeCode.Default() def set_camera(cam_path: str, camera_pos=None, target_pos=None): from omni.kit.viewport.utility.camera_state import ViewportCameraState camera_state = ViewportCameraState(cam_path) camera_state.set_position_world(camera_pos, True) camera_state.set_target_world(target_pos, True) def test_camera_position(cam_path: str, expected_pos: Gf.Vec3d): prim = viewport_api.stage.GetPrimAtPath(cam_path) camera = UsdGeom.Camera(prim) if prim else None world_xform = camera.ComputeLocalToWorldTransform(time) world_pos = world_xform.Transform(Gf.Vec3d(0, 0, 0)) for w_pos, ex_pos in zip(world_pos, expected_pos): self.assertAlmostEqual(float(w_pos), float(ex_pos), 4) viewport_window = omni.kit.viewport.utility.get_active_viewport_window() self.assertIsNotNone(viewport_window) viewport_api = viewport_window.viewport_api usd_cube1 = UsdGeom.Cube.Define(viewport_window.viewport_api.stage, "/cube1") #usd_cube1.GetSizeAttr().Set(10) usd_cube1_xformable = UsdGeom.Xformable(usd_cube1.GetPrim()) usd_cube1_xformable.AddTranslateOp() attr = usd_cube1.GetPrim().GetAttribute("xformOp:translate") attr.Set((200, 800, 4)) usd_cube2 = UsdGeom.Cube.Define(viewport_window.viewport_api.stage, "/cube2") #usd_cube2.GetSizeAttr().Set(100) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) selection = viewport_api.usd_context.get_selection() self.assertIsNotNone(selection) camera_path = '/OmniverseKit_Persp' test_camera_position(camera_path, Gf.Vec3d(500, 500, 500)) # select cube1 selection.set_selected_prim_paths(["/cube1"], True) # frame to the selection omni.kit.viewport.utility.frame_viewport_selection(viewport_api=viewport_api) # test test_camera_position(camera_path, Gf.Vec3d(202.49306, 802.49306, 6.49306)) # select cube2 selection.set_selected_prim_paths(["/cube2"], True) # frame to the selection omni.kit.viewport.utility.frame_viewport_selection(viewport_api=viewport_api) # test test_camera_position(camera_path, Gf.Vec3d(2.49306, 2.49306, 2.49306)) # unselect selection.set_selected_prim_paths([], True) # reset camera position set_camera(camera_path, (500, 500, 500), (0, 0, 0)) test_camera_position(camera_path, Gf.Vec3d(500, 500, 500)) # frame. Because nothing is selected, it should frame to all. omni.kit.viewport.utility.frame_viewport_selection(viewport_api=viewport_api) test_camera_position(camera_path, Gf.Vec3d(522.65586, 822.65585, 424.65586)) # unselect selection.set_selected_prim_paths([], True) # reset camera position set_camera(camera_path, (500, 500, 500), (0, 0, 0)) test_camera_position(camera_path, Gf.Vec3d(500, 500, 500)) # no frame on cube2 without to select it omni.kit.viewport.utility.frame_viewport_prims(viewport_api=viewport_api, prims=["/cube2"]) # should be the same as when we select test_camera_position(camera_path, Gf.Vec3d(2.49306, 2.49306, 2.49306)) # reset camera position set_camera(camera_path, (500, 500, 500), (0, 0, 0)) test_camera_position(camera_path, Gf.Vec3d(500, 500, 500)) # try on cube1 omni.kit.viewport.utility.frame_viewport_prims(viewport_api=viewport_api, prims=["/cube1"]) test_camera_position(camera_path, Gf.Vec3d(202.49306, 802.49306, 6.49306)) # call frame on prims with no list given omni.kit.viewport.utility.frame_viewport_prims(viewport_api=viewport_api) # camera should not move test_camera_position(camera_path, Gf.Vec3d(202.49306, 802.49306, 6.49306)) async def test_disable_context_menu(self): '''Test ability to disable context-menu on a Viewport or ViewportWindow''' from omni.kit import ui_test ctx_menu_wait = 50 # # Initial checks about assumption that objects are reachable and that no context manu is visible # ui_viewport = ui_test.find("Viewport") self.assertIsNotNone(ui_viewport) self.assertIsNone(ui.Menu.get_current()) # # Test context-menu is working by default # await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNotNone(ui.Menu.get_current()) # # Test disabling context-menu with a ViewportWindow # viewport_window = omni.kit.viewport.utility.get_active_viewport_window() self.assertIsNotNone(viewport_window) context_menu_disabled = omni.kit.viewport.utility.disable_context_menu(viewport_window) await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNone(ui.Menu.get_current()) del context_menu_disabled # Context menu should work again await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNotNone(ui.Menu.get_current()) # # Test disabling context-menu with a Viewport instance # viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) context_menu_disabled = omni.kit.viewport.utility.disable_context_menu(viewport_api) await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNone(ui.Menu.get_current()) del context_menu_disabled # Context menu should work again await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNotNone(ui.Menu.get_current()) # # Test disabling context-menu globally # context_menu_disabled = omni.kit.viewport.utility.disable_context_menu() await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNone(ui.Menu.get_current()) del context_menu_disabled # Context menu should work again await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNotNone(ui.Menu.get_current()) async def testget_ground_plane_info(self): '''Test results from get_ground_plane_info''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) async def get_camera_ground_plane(path: str, ortho_special: bool = True, wait_frames: int = 3): app = omni.kit.app.get_app() viewport_api.camera_path = path for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() return omni.kit.viewport.utility.get_ground_plane_info(viewport_api, ortho_special) def test_results(results, normal, planes): self.assertTrue(Gf.IsClose(results[0], normal, 1e-5)) self.assertEqual(results[1], planes) # Test ground plane info against Y-up stage UsdGeom.SetStageUpAxis(viewport_api.stage, UsdGeom.Tokens.y) persp_info = await get_camera_ground_plane('/OmniverseKit_Persp') front_info = await get_camera_ground_plane('/OmniverseKit_Front') top_info = await get_camera_ground_plane('/OmniverseKit_Top') right_info = await get_camera_ground_plane('/OmniverseKit_Right') right_info_world = await get_camera_ground_plane('/OmniverseKit_Right', False) test_results(persp_info, Gf.Vec3d(0, 1, 0), ['x', 'z']) test_results(front_info, Gf.Vec3d(0, 0, 1), ['x', 'y']) test_results(top_info, Gf.Vec3d(0, 1, 0), ['x', 'z']) test_results(right_info, Gf.Vec3d(1, 0, 0), ['y', 'z']) test_results(right_info_world, Gf.Vec3d(0, 1, 0), ['x', 'z']) # Test ground plane info against Z-up stage UsdGeom.SetStageUpAxis(viewport_api.stage, UsdGeom.Tokens.z) persp_info = await get_camera_ground_plane('/OmniverseKit_Persp') front_info = await get_camera_ground_plane('/OmniverseKit_Front') top_info = await get_camera_ground_plane('/OmniverseKit_Top') right_info = await get_camera_ground_plane('/OmniverseKit_Right') right_info_world = await get_camera_ground_plane('/OmniverseKit_Right', False) test_results(persp_info, Gf.Vec3d(0, 0, 1), ['x', 'y']) test_results(front_info, Gf.Vec3d(1, 0, 0), ['y', 'z']) test_results(top_info, Gf.Vec3d(0, 0, 1), ['x', 'y']) test_results(right_info, Gf.Vec3d(0, 1, 0), ['x', 'z']) test_results(right_info_world, Gf.Vec3d(0, 0, 1), ['x', 'y'])
33,188
Python
43.789474
144
0.664578
omniverse-code/kit/exts/omni.kit.viewport.utility/docs/CHANGELOG.md
# CHANGELOG The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.14] - 2023-01-25 ### Added - get_ground_plane_info API call. ## [1.0.13] - 2022-12-09 ### Added - Be able to pass a prim path to focus on ## [1.0.12] - 2022-10-17 ### Added - disable_context_menu API to disable contet menu for single or all Viewport. - Support legacy global disabling of context-menu by carb-setting. - Ability to also disable object-click (or not) when disabling selection-rect. ### Fixed - A few typos. ## [1.0.11] - 2022-09-27 ### Added - Use new ViewportWindow.active_window API. ### Fixed - Possibly import error from omni.usd.editor ## [1.0.10] - 2022-09-10 ### Added - disable_selection API to disable Viewport selection. ## [1.0.9] - 2022-08-25 ### Fixed - Convert to Gf.Camera at Viewport time. ## [1.0.8] - 2022-08-22 ### Added - Re-enable possibility of more than one Viewport. ## [1.0.7] - 2022-08-10 ### Added - Ability to specify format_desc dictionary to new capture-file API. ## [1.0.6] - 2022-07-28 ### Added - Accept a ViewportWindow or ViewportAPI for toast-message API. - Add _post_toast_message method to LegacyViewportWindow ## [1.0.5] - 2022-07-06 ### Added - Add resolution and scaling API to mirror new Viewport ## [1.0.4] - 2022-06-22 ### Added - Add capture_viewport_to_buffer function ### Changed - Return an object from capture_viewport_to_file and capture_viewport_to_buffer. - Get test-suite coverage above 70%. ### Fixed - Query of fill_frame atribute after toggling with legacy Viewport ## [1.0.3] - 2022-06-16 ### Added - Add create_drop_helper function ## [1.0.2] - 2022-05-25 ### Added - Add framing and toggle-visibility function for edit menu. ## [1.0.1] - 2022-05-25 ### Added - Fix issue with usage durring startup with only Legacy viewport ## [1.0.0] - 2022-04-29 ### Added - Initial release
1,867
Markdown
23.578947
80
0.688806
omniverse-code/kit/exts/omni.kit.example.toolbar_button/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.0" # 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 = "Kit Toolbar Button Example" desciption="Extension to demostrate how to add and remove custom button to Omniverse Kit Toolbar." category = "Example" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "example"] # 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" # We only depend on testing framework currently: [dependencies] "omni.ui" = {} "omni.kit.window.toolbar" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.kit.example.toolbar_button" [[test]] waiver = "an example extension"
1,061
TOML
29.342856
107
0.745523
omniverse-code/kit/exts/omni.kit.example.toolbar_button/omni/kit/example/toolbar_button/__init__.py
from .toolbar_button import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.kit.example.toolbar_button/omni/kit/example/toolbar_button/toolbar_button.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.ext import omni.kit.app import omni.kit.window.toolbar import omni.ui import os from carb.input import KeyboardInput as Key from omni.kit.widget.toolbar import SimpleToolButton, WidgetGroup class ExampleSimpleToolButton(SimpleToolButton): """ Example of how to use SimpleToolButton """ def __init__(self, icon_path): super().__init__( name="example_simple", tooltip="Example Simple ToolButton", icon_path=f"{icon_path}/plus.svg", icon_checked_path=f"{icon_path}/plus.svg", hotkey=Key.L, toggled_fn=lambda c: carb.log_warn(f"Example button toggled {c}"), ) class ExampleToolButtonGroup(WidgetGroup): """ Example of how to create two ToolButton in one WidgetGroup """ def __init__(self, icon_path): super().__init__() self._icon_path = icon_path def clean(self): super().clean() def get_style(self): style = { "Button.Image::example1": {"image_url": f"{self._icon_path}/plus.svg"}, "Button.Image::example1:checked": {"image_url": f"{self._icon_path}/minus.svg"}, "Button.Image::example2": {"image_url": f"{self._icon_path}/minus.svg"}, "Button.Image::example2:checked": {"image_url": f"{self._icon_path}/plus.svg"}, } return style def create(self, default_size): def on_clicked(): # example of getting a button by name from toolbar toolbar = omni.kit.window.toolbar.get_instance() button = toolbar.get_widget("scale_op") if button is not None: button.enabled = not button.enabled button1 = omni.ui.ToolButton( name="example1", tooltip="Example Button 1", width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: on_clicked(), ) button2 = omni.ui.ToolButton( name="example2", tooltip="Example Button 2", width=default_size, height=default_size ) # return a dictionary of name -> widget if you want to expose it to other widget_group return {"example1": button1, "example2": button2} class ToolbarButtonExample(omni.ext.IExt): def on_startup(self, ext_id): ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id) icon_path = os.path.join(ext_path, "icons") self._toolbar = omni.kit.window.toolbar.get_instance() self._widget_simple = ExampleSimpleToolButton(icon_path) self._widget = ExampleToolButtonGroup(icon_path) self._toolbar.add_widget(self._widget, -100) self._toolbar.add_widget(self._widget_simple, -200) def on_shutdown(self): self._toolbar.remove_widget(self._widget) self._toolbar.remove_widget(self._widget_simple) self._widget.clean() self._widget = None self._widget_simple.clean() self._widget_simple = None self._toolbar = None
3,501
Python
33.673267
96
0.630963
omniverse-code/kit/exts/omni.kit.example.toolbar_button/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [0.1.0] - 2020-07-23 ### Added - Initial implementation
156
Markdown
18.624998
80
0.673077
omniverse-code/kit/exts/omni.kit.example.toolbar_button/docs/index.rst
omni.kit.example.toolbar_button ############################### Omniverse Kit Toolbar Button Example .. toctree:: :maxdepth: 1 CHANGELOG
150
reStructuredText
9.785714
36
0.56
omniverse-code/kit/exts/omni.kit.window.preferences/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.3.8" category = "Internal" feature = true # 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 = "Preferences Window" description="Preferences Window" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "ui", "preferences"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" [ui] name = "Python preferences Window" [dependencies] "omni.usd" = {} "omni.kit.context_menu" = {} "omni.client" = {} "omni.ui" = {} "omni.kit.audiodeviceenum" = {} "omni.kit.window.filepicker" = {} "omni.kit.menu.utils" = {} "omni.kit.widget.settings" = {} "omni.kit.actions.core" = {} [[python.module]] name = "omni.kit.window.preferences" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/file/ignoreUnsavedOnExit=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/persistent/app/omniverse/filepicker/options_menu/show_details=false", "--/persistent/app/stage/dragDropImport='reference'", "--/persistent/app/material/dragDropMaterialPath='Absolute'", "--no-window" ] dependencies = [ "omni.hydra.pxr", "omni.kit.mainwindow", "omni.usd", "omni.kit.ui_test", "omni.kit.test_suite.helpers", ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop "*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available ]
2,222
TOML
28.64
122
0.69757
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/preference_builder.py
import asyncio import os from typing import List, Callable, Union from typing import List, Callable, Union import carb import omni.kit.menu.utils import omni.ui as ui from omni.ui import color as cl from functools import partial from omni.kit.widget.settings import create_setting_widget, create_setting_widget_combo, SettingType from omni.kit.widget.settings import get_style, get_ui_style_name # Base class for a preference builder class PreferenceBuilder: WINDOW_NAME = "Preferences" def __init__(self, title): self._title = title carb.settings.get_settings().set_default_string("/placeholder", "missing setting") def __del__(self): pass def label(self, name: str, tooltip: str=None): """ Create a UI widget label. Args: name: Name to be in label tooltip: The Tooltip string to be displayed when mouse hovers on the label Returns: :class:`ui.Widget` connected with the setting on the path specified. """ if tooltip: ui.Label(name, word_wrap=True, name="title", width=ui.Percent(50), tooltip=tooltip) else: ui.Label(name, word_wrap=True, name="title", width=ui.Percent(50)) def create_setting_widget_combo(self, name: str, setting_path: str, list: List[str], setting_is_index=False, **kwargs) -> ui.Widget: """ Creating a Combo Setting widget. This function creates a combo box that shows a provided list of names and it is connected with setting by path specified. Underlying setting values are used from values of `items` dict. Args: setting_path: Path to the setting to show and edit. items: Can be either :py:obj:`dict` or :py:obj:`list`. For :py:obj:`dict` keys are UI displayed names, values are actual values set into settings. If it is a :py:obj:`list` UI displayed names are equal to setting values. setting_is_index: True - setting_path value is index into items list False - setting_path value is string in items list (default) """ with ui.HStack(height=24): self.label(name) widget, model = create_setting_widget_combo(setting_path, list, setting_is_index=setting_is_index, **kwargs) return widget def create_setting_widget( self, label_name: str, setting_path: str, setting_type: SettingType, **kwargs ) -> ui.Widget: """ Create a UI widget connected with a setting. If ``range_from`` >= ``range_to`` there is no limit. Undo/redo operations are also supported, because changing setting goes through the :mod:`omni.kit.commands` module, using :class:`.ChangeSettingCommand`. Args: setting_path: Path to the setting to show and edit. setting_type: Type of the setting to expect. range_from: Limit setting value lower bound. range_to: Limit setting value upper bound. Returns: :class:`ui.Widget` connected with the setting on the path specified. """ if carb.settings.get_settings().get(setting_path) is None: return self.create_setting_widget(label_name, "/placeholder", SettingType.STRING) clicked_fn = None if "clicked_fn" in kwargs: clicked_fn = kwargs["clicked_fn"] del kwargs["clicked_fn"] # omni.kit.widget.settings.create_drag_or_slider won't use min/max unless hard_range is set to True if 'range_from' in kwargs and 'range_to' in kwargs: kwargs['hard_range'] = True vheight = 24 vpadding = 0 if setting_type == SettingType.FLOAT or setting_type == SettingType.INT or setting_type == SettingType.STRING: vheight = 20 vpadding = 3 with ui.HStack(height=vheight): tooltip = kwargs.pop('tooltip', '') self.label(label_name, tooltip) widget, model = create_setting_widget(setting_path, setting_type, **kwargs) if clicked_fn: ui.Button( style={"image_url": "resources/icons/folder.png"}, clicked_fn=partial(clicked_fn, widget), width=24 ) ui.Spacer(height=vpadding) return widget def add_frame(self, name: str) -> ui.CollapsableFrame: """ Create a UI collapsable frame. Args: name: Name to be in frame Returns: :class:`ui.Widget` connected with the setting on the path specified. """ return ui.CollapsableFrame(title=name, identifier=f"preferences_builder_{name}") def spacer(self) -> ui.Spacer: """ Create a UI spacer. Args: None Returns: :class:`ui.Widget` connected with the setting on the path specified. """ return ui.Spacer(height=10) def get_title(self) -> str: """ Gets the page title Args: None Returns: str name of the page """ return self._title def cleanup_slashes(self, path: str, is_directory: bool = False) -> str: """ Makes path/slashes uniform Args: path: path is_directory is path a directory, so final slash can be added Returns: path """ path = os.path.normpath(path) if is_directory: if path[-1] != "/": path += "/" return path.replace("\\", "/") class PageItem(ui.AbstractItem): """Single item of the model""" def __init__(self, pages): super().__init__() self.name = pages[0].get_title() self.name_model = ui.SimpleStringModel(self.name) self.pages = pages class PageModel(ui.AbstractItemModel): def __init__(self, page_list: List[str]): super().__init__() self._pages = [] for key in page_list: page = page_list[key] self._pages.append(PageItem(page)) self._item_changed(None) def get_item_children(self, item: PageItem) -> List[PageItem]: if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._pages def get_item_value_model_count(self, item: PageItem) -> int: """The number of columns""" return 1 def get_item_value_model(self, item: PageItem, column_id: int) -> ui.SimpleStringModel: if item and isinstance(item, PageItem): return item.name_model class PreferenceBuilderUI: def __init__(self, visibility_changed_fn: Callable): self._visibility_changed_fn = visibility_changed_fn self._active_page = "" self._treeview = None def destroy(self): ui.Workspace.set_show_window_fn(PreferenceBuilder.WINDOW_NAME, None) self._page_list = None self._pages_model = None self._visibility_changed_fn = None self._treeview = None del self._window def __del__(self): pass def update_page_list(self, page_list: List) -> None: """ Updates page list Args: page_list: list of pages Returns: None """ self._page_list = {} self._page_header = [] for page in page_list: if isinstance(page, PreferenceBuilder): if not page._title: self._page_header.append(page) elif not page._title in self._page_list: self._page_list[page.get_title()] = [page] else: self._page_list[page.get_title()].append(page) def create_window(self): """ Create omni.ui.window Args: None Returns: None """ def set_window_state(v): self._show_window(None, v) if v: self.rebuild_pages() self._treeview = None self._window = None ui.Workspace.set_show_window_fn(PreferenceBuilder.WINDOW_NAME, set_window_state) def _show_window(self, menu, value): if value: self._window = ui.Window(PreferenceBuilder.WINDOW_NAME, width=1000, height=600, dockPreference=ui.DockPreference.LEFT_BOTTOM) self._window.set_visibility_changed_fn(self._on_visibility_changed_fn) self._window.frame.set_style(get_style()) self._window.deferred_dock_in("Content") elif self._window: self._treeview = None self._window.destroy() self._window = None def rebuild_pages(self) -> None: """ Rebuilds window pages using current page list Args: None Returns: None """ self._pages_model = PageModel(self._page_list) full_list = self._pages_model.get_item_children(None) if not full_list or not self._window: return elif not self._active_page in self._page_list: self._active_page = next(iter(self._page_list)) def treeview_clicked(treeview): async def get_selection(): await omni.kit.app.get_app().next_update_async() if treeview.selection: selection = treeview.selection[0] self.set_active_page(selection.name) asyncio.ensure_future(get_selection()) with self._window.frame: prefs_style = {"ScrollingFrame::header": {"background_color": 0xFF444444}, "ScrollingFrame::header:hovered": {"background_color": 0xFF444444}, "ScrollingFrame::header:pressed": {"background_color": 0xFF444444}, "Button::global": {"color": cl("#34C7FF"), "margin": 0, "margin_width": 0, "padding": 5}, "Button.Label::global": {"color": cl("#34C7FF")}, "Button::global:hovered": {"background_color": 0xFF545454}, "Button::global:pressed": {"background_color": 0xFF555555}, } with ui.VStack(style=prefs_style, name="header"): if self._page_header: with ui.HStack(width=0, height=10): for page in self._page_header: page.build() ui.Spacer(height=3) with ui.HStack(): with ui.ScrollingFrame( width=175, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF ): if get_ui_style_name() == "NvidiaLight": FIELD_BACKGROUND = 0xFF545454 FIELD_TEXT_COLOR = 0xFFD6D6D6 else: FIELD_BACKGROUND = 0xFF23211F FIELD_TEXT_COLOR = 0xFFD5D5D5 self._treeview = ui.TreeView( self._pages_model, root_visible=False, header_visible=False, style={ "TreeView.Item": {"margin": 4}, "margin_width": 0.5, "margin_height": 0.5, "background_color": FIELD_BACKGROUND, "color": FIELD_TEXT_COLOR, }, ) if not self._treeview.selection and len(full_list) > 0: for page in full_list: if page.name == self._active_page: self._treeview.selection = [page] break selection = self._treeview.selection self._treeview.set_mouse_released_fn(lambda x, y, b, c, tv=self._treeview: treeview_clicked(tv)) with ui.VStack(): ui.Spacer(height=7) self._page_frame = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED ) if selection: self._build_page(selection[0].pages) def set_active_page(self, page_index: Union[int, str]) -> None: """ Set the given page index as the active one. Args: page_index: Index of page of the page list to set as the active one. Returns: None """ if isinstance(page_index, str): self._active_page = page_index else: for index, key in enumerate(self._page_list): if index == page_index: self._active_page = self._page_list[key].get_title() break # Build and display the list of preference widgets on the right-hand column of the panel: async def rebuild(): await omni.kit.app.get_app().next_update_async() self._build_page(self._page_list[self._active_page]) asyncio.ensure_future(rebuild()) # Select the title of the page on the left-hand column of the panel, acting as navigation tabs between the # Preference pages: if self._pages_model and self._treeview: for page in self._pages_model.get_item_children(None): if page.name == self._active_page: self._treeview.selection = [page] break def select_page(self, page: PreferenceBuilder) -> bool: """ If found, display the given Preference page and select its title in the TreeView. Args: page: One of the page from the list of pages. Returns: bool: A flag indicating if the given page was successfully selected. """ for key in self._page_list: items = self._page_list[key] for item in items: if item == page: self.set_active_page(item.get_title()) return True return False def _build_page(self, pages: List[PreferenceBuilder]) -> None: with self._page_frame: with ui.VStack(): for page in pages: page.build() if len(pages) > 1: ui.Spacer(height=7) def show_window(self) -> None: """ show window Args: None Returns: None """ if not self._window: self._show_window(None, True) self.rebuild_pages() def hide_window(self) -> None: """ hide window Args: None Returns: None """ if self._window: self._show_window(None, False) def _on_visibility_changed_fn(self, visible) -> None: self._visibility_changed_fn(visible) omni.kit.menu.utils.rebuild_menus()
15,348
Python
33.804989
137
0.537464
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/__init__.py
from .preferences_window import *
34
Python
16.499992
33
0.794118
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/preferences_window.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 import asyncio import carb import omni.ext from enum import IntFlag from .preference_builder import PreferenceBuilder, PreferenceBuilderUI, SettingType from .preferences_actions import register_actions, deregister_actions _extension_instance = None _preferences_page_list = [] PERSISTENT_SETTINGS_PREFIX = "/persistent" DEVELOPER_PREFERENCE_PATH = "/app/show_developer_preference_section" GLOBAL_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_globals" AUDIO_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_audio" RENDERING_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_rendering" RESOURCE_MONITOR_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_resource_monitor" TAGGING_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_tagging" class PreferencesExtension(omni.ext.IExt): class PreferencesState(IntFlag): Invalid = 0 Created = 1 def on_startup(self, ext_id): global _extension_instance _extension_instance = self self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name, PreferencesExtension, lambda: _extension_instance) self._hooks = [] self._ready_state = PreferencesExtension.PreferencesState.Invalid self._window = PreferenceBuilderUI(self._on_visibility_changed_fn) self._window.update_page_list(get_page_list()) self._window.create_window() self._window_is_visible = False self._create_menu() self._register_pages() self._resourcemonitor_preferences = None manager = omni.kit.app.get_app().get_extension_manager() if carb.settings.get_settings().get(RESOURCE_MONITOR_PREFERENCES_PATH): self._hooks.append( manager.subscribe_to_extension_enable( on_enable_fn=lambda _: self._register_resourcemonitor_preferences(), on_disable_fn=lambda _: self._unregister_resourcemonitor_preferences(), ext_name="omni.resourcemonitor", hook_name="omni.kit.window.preferences omni.resourcemonitor listener", ) ) # set app started trigger. refresh_menu_items & rebuild_menus won't do anything until self._ready_state is MenuState.Created self._app_ready_sub = ( omni.kit.app.get_app() .get_startup_event_stream() .create_subscription_to_pop_by_type( omni.kit.app.EVENT_APP_READY, self._rebuild_after_loading, name="omni.kit.menu.utils app started trigger" ) ) def on_shutdown(self): self._hooks = None deregister_actions(self._ext_name) self._window.destroy() del self._window self._window = None self._remove_menu() self._unregister_resourcemonitor_preferences() for page in self._created_preferences: unregister_page(page, rebuild=False) self._created_preferences = None # clear globals global _preferences_page_list _preferences_page_list = None global _extension_instance _extension_instance = None def _rebuild_after_loading(self, event): self._ready_state = PreferencesExtension.PreferencesState.Created self.rebuild_pages() def _register_pages(self): from .pages.stage_page import StagePreferences from .pages.rendering_page import RenderingPreferences from .pages.screenshot_page import ScreenshotPreferences from .pages.thumbnail_generation_page import ThumbnailGenerationPreferences from .pages.audio_page import AudioPreferences from .pages.tagging_page import TaggingPreferences from .pages.datetime_format_page import DatetimeFormatPreferences from .pages.globals import GlobalPreferences self._developer_preferences = None self._created_preferences = [] for page in [ ScreenshotPreferences(), ThumbnailGenerationPreferences(), StagePreferences(), DatetimeFormatPreferences(), ]: self._created_preferences.append(register_page(page)) if carb.settings.get_settings().get(GLOBAL_PREFERENCES_PATH): self._created_preferences.append(register_page(GlobalPreferences())) if carb.settings.get_settings().get(AUDIO_PREFERENCES_PATH): self._created_preferences.append(register_page(AudioPreferences())) if carb.settings.get_settings().get(RENDERING_PREFERENCES_PATH): self._created_preferences.append(register_page(RenderingPreferences())) if carb.settings.get_settings().get(TAGGING_PREFERENCES_PATH): self._created_preferences.append(register_page(TaggingPreferences())) # developer options self._hooks.append(carb.settings.get_settings().subscribe_to_node_change_events( DEVELOPER_PREFERENCE_PATH, self._on_developer_preference_section_changed )) self._on_developer_preference_section_changed(None, None) def _on_developer_preference_section_changed(self, item, event_type): if event_type == carb.settings.ChangeEventType.CHANGED: if carb.settings.get_settings().get(DEVELOPER_PREFERENCE_PATH): if not self._developer_preferences: from .pages.developer_page import DeveloperPreferences self._developer_preferences = register_page(DeveloperPreferences()) elif self._developer_preferences: self._developer_preferences = unregister_page(self._developer_preferences) def _register_resourcemonitor_preferences(self): from .pages.resourcemonitor_page import ResourceMonitorPreferences self._resourcemonitor_preferences = register_page(ResourceMonitorPreferences()) def _unregister_resourcemonitor_preferences(self): if self._resourcemonitor_preferences: unregister_page(self._resourcemonitor_preferences) self._resourcemonitor_preferences = None def rebuild_pages(self): if self._ready_state == PreferencesExtension.PreferencesState.Invalid: return if self._window: self._window.update_page_list(get_page_list()) self._window.rebuild_pages() def select_page(self, page): if self._window: if self._window.select_page(page): return True return False async def _refresh_menu_async(self): omni.kit.menu.utils.refresh_menu_items("Edit") self._refresh_menu_task = None def _on_visibility_changed_fn(self, visible): self._window_is_visible = visible if visible: self._window.show_window() else: self._window.hide_window() def _create_menu(self): from omni.kit.menu.utils import MenuItemDescription, MenuItemOrder self._edit_menu_list = None self._refresh_menu_task = None self._edit_menu_list = [ MenuItemDescription( name="Preferences", glyph="cog.svg", appear_after=["Capture Screenshot", MenuItemOrder.LAST], ticked=True, ticked_fn=lambda: self._window_is_visible, onclick_action=("omni.kit.window.preferences", "toggle_preferences_window"), ), MenuItemDescription( appear_after=["Capture Screenshot", MenuItemOrder.LAST], ), ] omni.kit.menu.utils.add_menu_items(self._edit_menu_list, "Edit", -9) def _remove_menu(self): if self._refresh_menu_task: self._refresh_menu_task.cancel() self._refresh_menu_task = None # remove menu omni.kit.menu.utils.remove_menu_items(self._edit_menu_list, "Edit") def _toggle_preferences_window(self): self._window_is_visible = not self._window_is_visible async def show_windows(): if self._window_is_visible: self._window.show_window() else: self._window.hide_window() asyncio.ensure_future(show_windows()) asyncio.ensure_future(self._refresh_menu_async()) def show_preferences_window(self): """Show the Preferences window to the User.""" if not self._window_is_visible: self._toggle_preferences_window() def hide_preferences_window(self): """Hide the Preferences window from the User.""" if self._window_is_visible: self._toggle_preferences_window() def get_instance(): global _extension_instance return _extension_instance def show_preferences_window(): """Show the Preferences window to the User.""" get_instance().show_preferences_window() def hide_preferences_window(): """Hide the Preferences window from the User.""" get_instance().hide_preferences_window() def get_page_list(): global _preferences_page_list return _preferences_page_list def register_page(page): global _preferences_page_list _preferences_page_list.append(page) _preferences_page_list = sorted(_preferences_page_list, key=lambda page: page._title) get_instance().rebuild_pages() return page def select_page(page): return get_instance().select_page(page) def rebuild_pages(): get_instance().rebuild_pages() def unregister_page(page, rebuild: bool=True): global _preferences_page_list if hasattr(page, 'destroy'): page.destroy() # Explicitly clear properties, that helps to release some C++ objects page.__dict__.clear() if _preferences_page_list: _preferences_page_list.remove(page) preferences = get_instance() if preferences and rebuild: preferences.rebuild_pages() def show_file_importer( title: str, file_exts: list = [("All Files(*)", "")], filename_url: str = None, click_apply_fn: Callable = None, show_only_folders: bool = False, ): from functools import partial from omni.kit.window.file_importer import get_file_importer def on_import(click_fn: Callable, filename: str, dirname: str, selections=[]): dirname = dirname.strip() if dirname and not dirname.endswith("/"): dirname += "/" fullpath = f"{dirname}{filename}" if click_fn: click_fn(fullpath) file_importer = get_file_importer() if file_importer: file_importer.show_window( title=title, import_button_label="Select", import_handler=partial(on_import, click_apply_fn), file_extension_types=file_exts, filename_url=filename_url, # OM-96626: Add show_only_folders option to file importer show_only_folders=show_only_folders, )
11,373
Python
35.107936
132
0.652686
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/material_config_widget.py
import os import carb.settings import omni.kit.notification_manager as nm import omni.ui as ui from omni.ui import color as cl from . import material_config_utils class EditableListItem(ui.AbstractItem): def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) class EditableListItemDelegate(ui.AbstractItemDelegate): _ITEM_LABEL_STYLE = { "margin": 3, "font_size": 16.0, ":selected": { "color": cl("#333333") } } _DELETE_BUTTON_STYLE = { "margin": 2, "padding": 0, "": { "image_url": "", "alignment": ui.Alignment.CENTER, "background_color": 0x00000000 }, ":hovered": { "image_url": "resources/glyphs/trash.svg", "color": cl("#cccccc"), "background_color": 0x00000000 }, ":selected": { "image_url": "resources/glyphs/trash.svg", "color": cl("#cccccc"), "background_color": 0x00000000 } } def build_widget(self, model, item, column_id, level, expanded): with ui.ZStack(height=20): value_model = model.get_item_value_model(item, column_id) if column_id == 0: # entry text label = ui.Label(value_model.as_string, style=self._ITEM_LABEL_STYLE) field = ui.StringField() field.model = value_model field.visible = False label.set_mouse_double_clicked_fn( lambda x, y, b, m, f=field, l=label: self.on_label_double_click(b, f, l) ) elif column_id == 1: # remove button with ui.HStack(): ui.Spacer() button = ui.Button(width=20, style=self._DELETE_BUTTON_STYLE) button.set_clicked_fn(lambda i=item, m=model: self.on_button_clicked(i, m)) ui.Spacer(width=5) else: pass def on_label_double_click(self, mouse_button, field, label): if mouse_button != 0: return field.visible = True field.focus_keyboard() self.subscription = field.model.subscribe_end_edit_fn( lambda m, f=field, l=label: self.on_field_end_edit(m, f, l) ) def on_field_end_edit(self, model, field, label): field.visible = False if model.as_string: # avoid empty string label.text = model.as_string self.subscription = None def on_button_clicked(self, item, model): model.remove_item(item) class EditableListModel(ui.AbstractItemModel): def __init__( self, item_class=EditableListItem, setting_path=None ): super().__init__() self._settings = carb.settings.get_settings() self._setting_path = setting_path self._item_class = item_class self._items = [] self.populate_items() def populate_items(self): entries = self._settings.get(self._setting_path) if not entries: entries = [] self._items.clear() for entry in entries: if not entry: continue self._items.append(self._item_class(entry)) self._item_changed(None) def get_item_children(self, item): if item is not None: return [] return self._items def get_item_value_model_count(self, item): return 2 def get_item_value_model(self, item, column_id): if item and isinstance(item, self._item_class): if column_id == 0: return item.name_model else: return None def get_drag_mime_data(self, item): return item.name_model.as_string def drop_accepted(self, target_item, source, drop_location=1): return not target_item and drop_location >= 0 def drop(self, target_item, source, drop_location=-1): try: source_id = self._items.index(source) except ValueError: return if source_id == drop_location: return self._items.remove(source) if drop_location > len(self._items): self._items.append(source) else: if source_id < drop_location: drop_location = drop_location - 1 self._items.insert(drop_location, source) self._item_changed(None) def add_entry(self, text): self._items.insert(0, self._item_class(text)) self._item_changed(None) def remove_item(self, item): self._items.remove(item) self._item_changed(None) def save_entries_to_settings(self): entries = [item.name_model.as_string for item in self._items] self._settings.set(self._setting_path, entries) def save_to_material_config_file(self): material_config_utils.save_live_config_to_file() class EditableListWidget(ui.Widget): _ADD_BUTTON_STYLE = { "image_url": "resources/glyphs/plus.svg", "color": cl("#cccccc") } def __init__( self, model_class=EditableListModel, item_delegate_class=EditableListItemDelegate, setting_path=None, list_height=100 ): super(EditableListWidget).__init__() self._model = model_class(setting_path=setting_path) self._delegate = item_delegate_class() # build UI with ui.VStack(): with ui.HStack(): # list widget with ui.ScrollingFrame(height=list_height): ui.Spacer(height=5) self._view = ui.TreeView( self._model, delegate=self._delegate, header_visible=False, root_visible=False, column_widths=[ui.Percent(95)], drop_between_items=True ) self._view.set_selection_changed_fn(self.on_item_selection_changed) ui.Spacer(width=5) # "+" button self._add_new_entry_button = ui.Button( width=20, height=20, style=self._ADD_BUTTON_STYLE, clicked_fn=self.on_add_new_entry_button_clicked ) ui.Spacer(height=5) with ui.HStack(): ui.Spacer() # save button self._save_button = ui.Button( "Save", width=100, height=0, clicked_fn=self.on_save_button_clicked ) ui.Spacer(width=5) # reset button self._reset_button = ui.Button( "Reset", width=100, height=0, clicked_fn=self.on_reset_button_clicked ) ui.Spacer(width=25) def on_add_new_entry_button_clicked(self): self._view.clear_selection() self._model.add_entry("New Entry") def on_item_selection_changed(self, items): # not to allow multi-selection num_items = len(items) if num_items > 1: for i in range(1, num_items): self._view.toggle_selection(items[i]) def on_save_button_clicked(self): self._model.save_entries_to_settings() config_file = material_config_utils.get_config_file_path() if not os.path.exists(config_file): ok_button = nm.NotificationButtonInfo( "OK", on_complete=self._model.save_to_material_config_file ) cancel_button = nm.NotificationButtonInfo( "Cancel", on_complete=None ) nm.post_notification( f"Material config file does not exist. Create?\n\n{config_file}", status=nm.NotificationStatus.INFO, button_infos=[ok_button, cancel_button], hide_after_timeout=False ) else: self._model.save_to_material_config_file() def on_reset_button_clicked(self): self._view.clear_selection() self._model.populate_items()
8,497
Python
29.134752
95
0.520184