file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prims.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from add_on_msgs:srv/GetPrims.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GetPrims_Request(type): """Metaclass of message 'GetPrims_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrims_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prims__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prims__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prims__request cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prims__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prims__request @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrims_Request(metaclass=Metaclass_GetPrims_Request): """Message class 'GetPrims_Request'.""" __slots__ = [ '_path', ] _fields_and_field_types = { 'path': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.path = kwargs.get('path', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.path != other.path: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def path(self): """Message field 'path'.""" return self._path @path.setter def path(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'path' field must be of type 'str'" self._path = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GetPrims_Response(type): """Metaclass of message 'GetPrims_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrims_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prims__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prims__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prims__response cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prims__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prims__response @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrims_Response(metaclass=Metaclass_GetPrims_Response): """Message class 'GetPrims_Response'.""" __slots__ = [ '_paths', '_types', '_success', '_message', ] _fields_and_field_types = { 'paths': 'sequence<string>', 'types': 'sequence<string>', 'success': 'boolean', 'message': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.paths = kwargs.get('paths', []) self.types = kwargs.get('types', []) self.success = kwargs.get('success', bool()) self.message = kwargs.get('message', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.paths != other.paths: return False if self.types != other.types: return False if self.success != other.success: return False if self.message != other.message: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def paths(self): """Message field 'paths'.""" return self._paths @paths.setter def paths(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'paths' field must be a set or sequence and each value of type 'str'" self._paths = value @property def types(self): """Message field 'types'.""" return self._types @types.setter def types(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'types' field must be a set or sequence and each value of type 'str'" self._types = value @property def success(self): """Message field 'success'.""" return self._success @success.setter def success(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'success' field must be of type 'bool'" self._success = value @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value class Metaclass_GetPrims(type): """Metaclass of service 'GetPrims'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrims') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__get_prims from add_on_msgs.srv import _get_prims if _get_prims.Metaclass_GetPrims_Request._TYPE_SUPPORT is None: _get_prims.Metaclass_GetPrims_Request.__import_type_support__() if _get_prims.Metaclass_GetPrims_Response._TYPE_SUPPORT is None: _get_prims.Metaclass_GetPrims_Response.__import_type_support__() class GetPrims(metaclass=Metaclass_GetPrims): from add_on_msgs.srv._get_prims import GetPrims_Request as Request from add_on_msgs.srv._get_prims import GetPrims_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
12,577
Python
34.331461
134
0.563091
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prim_attribute.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from add_on_msgs:srv/GetPrimAttribute.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GetPrimAttribute_Request(type): """Metaclass of message 'GetPrimAttribute_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttribute_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prim_attribute__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prim_attribute__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prim_attribute__request cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prim_attribute__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prim_attribute__request @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrimAttribute_Request(metaclass=Metaclass_GetPrimAttribute_Request): """Message class 'GetPrimAttribute_Request'.""" __slots__ = [ '_path', '_attribute', ] _fields_and_field_types = { 'path': 'string', 'attribute': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.path = kwargs.get('path', str()) self.attribute = kwargs.get('attribute', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.path != other.path: return False if self.attribute != other.attribute: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def path(self): """Message field 'path'.""" return self._path @path.setter def path(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'path' field must be of type 'str'" self._path = value @property def attribute(self): """Message field 'attribute'.""" return self._attribute @attribute.setter def attribute(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'attribute' field must be of type 'str'" self._attribute = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GetPrimAttribute_Response(type): """Metaclass of message 'GetPrimAttribute_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttribute_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prim_attribute__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prim_attribute__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prim_attribute__response cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prim_attribute__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prim_attribute__response @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrimAttribute_Response(metaclass=Metaclass_GetPrimAttribute_Response): """Message class 'GetPrimAttribute_Response'.""" __slots__ = [ '_value', '_type', '_success', '_message', ] _fields_and_field_types = { 'value': 'string', 'type': 'string', 'success': 'boolean', 'message': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.value = kwargs.get('value', str()) self.type = kwargs.get('type', str()) self.success = kwargs.get('success', bool()) self.message = kwargs.get('message', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.value != other.value: return False if self.type != other.type: return False if self.success != other.success: return False if self.message != other.message: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def value(self): """Message field 'value'.""" return self._value @value.setter def value(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'value' field must be of type 'str'" self._value = value @property # noqa: A003 def type(self): # noqa: A003 """Message field 'type'.""" return self._type @type.setter # noqa: A003 def type(self, value): # noqa: A003 if __debug__: assert \ isinstance(value, str), \ "The 'type' field must be of type 'str'" self._type = value @property def success(self): """Message field 'success'.""" return self._success @success.setter def success(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'success' field must be of type 'bool'" self._success = value @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value class Metaclass_GetPrimAttribute(type): """Metaclass of service 'GetPrimAttribute'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttribute') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__get_prim_attribute from add_on_msgs.srv import _get_prim_attribute if _get_prim_attribute.Metaclass_GetPrimAttribute_Request._TYPE_SUPPORT is None: _get_prim_attribute.Metaclass_GetPrimAttribute_Request.__import_type_support__() if _get_prim_attribute.Metaclass_GetPrimAttribute_Response._TYPE_SUPPORT is None: _get_prim_attribute.Metaclass_GetPrimAttribute_Response.__import_type_support__() class GetPrimAttribute(metaclass=Metaclass_GetPrimAttribute): from add_on_msgs.srv._get_prim_attribute import GetPrimAttribute_Request as Request from add_on_msgs.srv._get_prim_attribute import GetPrimAttribute_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
12,446
Python
34.061972
134
0.570223
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prim_attributes.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from add_on_msgs:srv/GetPrimAttributes.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GetPrimAttributes_Request(type): """Metaclass of message 'GetPrimAttributes_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttributes_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prim_attributes__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prim_attributes__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prim_attributes__request cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prim_attributes__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prim_attributes__request @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrimAttributes_Request(metaclass=Metaclass_GetPrimAttributes_Request): """Message class 'GetPrimAttributes_Request'.""" __slots__ = [ '_path', ] _fields_and_field_types = { 'path': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.path = kwargs.get('path', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.path != other.path: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def path(self): """Message field 'path'.""" return self._path @path.setter def path(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'path' field must be of type 'str'" self._path = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GetPrimAttributes_Response(type): """Metaclass of message 'GetPrimAttributes_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttributes_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prim_attributes__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prim_attributes__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prim_attributes__response cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prim_attributes__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prim_attributes__response @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrimAttributes_Response(metaclass=Metaclass_GetPrimAttributes_Response): """Message class 'GetPrimAttributes_Response'.""" __slots__ = [ '_names', '_displays', '_types', '_success', '_message', ] _fields_and_field_types = { 'names': 'sequence<string>', 'displays': 'sequence<string>', 'types': 'sequence<string>', 'success': 'boolean', 'message': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.names = kwargs.get('names', []) self.displays = kwargs.get('displays', []) self.types = kwargs.get('types', []) self.success = kwargs.get('success', bool()) self.message = kwargs.get('message', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.names != other.names: return False if self.displays != other.displays: return False if self.types != other.types: return False if self.success != other.success: return False if self.message != other.message: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def names(self): """Message field 'names'.""" return self._names @names.setter def names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'names' field must be a set or sequence and each value of type 'str'" self._names = value @property def displays(self): """Message field 'displays'.""" return self._displays @displays.setter def displays(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'displays' field must be a set or sequence and each value of type 'str'" self._displays = value @property def types(self): """Message field 'types'.""" return self._types @types.setter def types(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'types' field must be a set or sequence and each value of type 'str'" self._types = value @property def success(self): """Message field 'success'.""" return self._success @success.setter def success(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'success' field must be of type 'bool'" self._success = value @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value class Metaclass_GetPrimAttributes(type): """Metaclass of service 'GetPrimAttributes'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttributes') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__get_prim_attributes from add_on_msgs.srv import _get_prim_attributes if _get_prim_attributes.Metaclass_GetPrimAttributes_Request._TYPE_SUPPORT is None: _get_prim_attributes.Metaclass_GetPrimAttributes_Request.__import_type_support__() if _get_prim_attributes.Metaclass_GetPrimAttributes_Response._TYPE_SUPPORT is None: _get_prim_attributes.Metaclass_GetPrimAttributes_Response.__import_type_support__() class GetPrimAttributes(metaclass=Metaclass_GetPrimAttributes): from add_on_msgs.srv._get_prim_attributes import GetPrimAttributes_Request as Request from add_on_msgs.srv._get_prim_attributes import GetPrimAttributes_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
14,112
Python
35.657143
134
0.574192
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prims_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from add_on_msgs:srv/GetPrims.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "add_on_msgs/srv/detail/get_prims__struct.h" #include "add_on_msgs/srv/detail/get_prims__functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool add_on_msgs__srv__get_prims__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[44]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("add_on_msgs.srv._get_prims.GetPrims_Request", full_classname_dest, 43) == 0); } add_on_msgs__srv__GetPrims_Request * ros_message = _ros_message; { // path PyObject * field = PyObject_GetAttrString(_pymsg, "path"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->path, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * add_on_msgs__srv__get_prims__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GetPrims_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prims"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrims_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } add_on_msgs__srv__GetPrims_Request * ros_message = (add_on_msgs__srv__GetPrims_Request *)raw_ros_message; { // path PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->path.data, strlen(ros_message->path.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "path", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "add_on_msgs/srv/detail/get_prims__struct.h" // already included above // #include "add_on_msgs/srv/detail/get_prims__functions.h" #include "rosidl_runtime_c/primitives_sequence.h" #include "rosidl_runtime_c/primitives_sequence_functions.h" // already included above // #include "rosidl_runtime_c/string.h" // already included above // #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool add_on_msgs__srv__get_prims__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[45]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("add_on_msgs.srv._get_prims.GetPrims_Response", full_classname_dest, 44) == 0); } add_on_msgs__srv__GetPrims_Response * ros_message = _ros_message; { // paths PyObject * field = PyObject_GetAttrString(_pymsg, "paths"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'paths'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->paths), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->paths.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // types PyObject * field = PyObject_GetAttrString(_pymsg, "types"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'types'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->types), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->types.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // success PyObject * field = PyObject_GetAttrString(_pymsg, "success"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->success = (Py_True == field); Py_DECREF(field); } { // message PyObject * field = PyObject_GetAttrString(_pymsg, "message"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->message, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * add_on_msgs__srv__get_prims__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GetPrims_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prims"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrims_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } add_on_msgs__srv__GetPrims_Response * ros_message = (add_on_msgs__srv__GetPrims_Response *)raw_ros_message; { // paths PyObject * field = NULL; size_t size = ros_message->paths.size; rosidl_runtime_c__String * src = ros_message->paths.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "paths", field); Py_DECREF(field); if (rc) { return NULL; } } } { // types PyObject * field = NULL; size_t size = ros_message->types.size; rosidl_runtime_c__String * src = ros_message->types.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "types", field); Py_DECREF(field); if (rc) { return NULL; } } } { // success PyObject * field = NULL; field = PyBool_FromLong(ros_message->success ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "success", field); Py_DECREF(field); if (rc) { return NULL; } } } { // message PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->message.data, strlen(ros_message->message.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "message", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
11,800
C
29.572539
109
0.611356
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/tests/test_ros2_bridge.py
try: import omni.kit.test TestCase = omni.kit.test.AsyncTestCaseFailOnLogError except: class TestCase: pass import json import rclpy from rclpy.node import Node from rclpy.duration import Duration from rclpy.action import ActionClient from action_msgs.msg import GoalStatus from trajectory_msgs.msg import JointTrajectoryPoint from control_msgs.action import FollowJointTrajectory from control_msgs.action import GripperCommand import add_on_msgs.srv # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class TestROS2Bridge(TestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_ros2_bridge(self): pass class TestROS2BridgeNode(Node): def __init__(self): super().__init__('test_ros2_bridge') self.get_attribute_service_name = '/get_attribute' self.set_attribute_service_name = '/set_attribute' self.gripper_command_action_name = "/panda_hand_controller/gripper_command" self.follow_joint_trajectory_action_name = "/panda_arm_controller/follow_joint_trajectory" self.get_attribute_client = self.create_client(add_on_msgs.srv.GetPrimAttribute, self.get_attribute_service_name) self.set_attribute_client = self.create_client(add_on_msgs.srv.SetPrimAttribute, self.set_attribute_service_name) self.gripper_command_client = ActionClient(self, GripperCommand, self.gripper_command_action_name) self.follow_joint_trajectory_client = ActionClient(self, FollowJointTrajectory, self.follow_joint_trajectory_action_name) self.follow_joint_trajectory_goal_msg = FollowJointTrajectory.Goal() self.follow_joint_trajectory_goal_msg.path_tolerance = [] self.follow_joint_trajectory_goal_msg.goal_tolerance = [] self.follow_joint_trajectory_goal_msg.goal_time_tolerance = Duration().to_msg() self.follow_joint_trajectory_goal_msg.trajectory.header.frame_id = "panda_link0" self.follow_joint_trajectory_goal_msg.trajectory.joint_names = ["panda_joint1", "panda_joint2", "panda_joint3", "panda_joint4", "panda_joint5", "panda_joint6", "panda_joint7"] self.follow_joint_trajectory_goal_msg.trajectory.points = [ JointTrajectoryPoint(positions=[0.012, -0.5689, 0.0, -2.8123, 0.0, 3.0367, 0.741], time_from_start=Duration(seconds=0, nanoseconds=0).to_msg()), JointTrajectoryPoint(positions=[0.011073551914608105, -0.5251352171920526, 6.967729509163362e-06, -2.698296723677182, 7.613460540484924e-06, 2.93314462685839, 0.6840062390114862], time_from_start=Duration(seconds=0, nanoseconds= 524152995).to_msg()), JointTrajectoryPoint(positions=[0.010147103829216212, -0.48137043438410526, 1.3935459018326723e-05, -2.5842934473543644, 1.5226921080969849e-05, 2.82958925371678, 0.6270124780229722], time_from_start=Duration(seconds=1, nanoseconds= 48305989).to_msg()), JointTrajectoryPoint(positions=[0.009220655743824318, -0.43760565157615794, 2.0903188527490087e-05, -2.4702901710315466, 2.2840381621454772e-05, 2.72603388057517, 0.5700187170344584], time_from_start=Duration(seconds=1, nanoseconds= 572458984).to_msg()), JointTrajectoryPoint(positions=[0.008294207658432425, -0.39384086876821056, 2.7870918036653447e-05, -2.3562868947087283, 3.0453842161939697e-05, 2.6224785074335597, 0.5130249560459446], time_from_start=Duration(seconds=2, nanoseconds= 96611978).to_msg()), JointTrajectoryPoint(positions=[0.00736775957304053, -0.3500760859602632, 3.483864754581681e-05, -2.2422836183859105, 3.806730270242462e-05, 2.518923134291949, 0.45603119505743067], time_from_start=Duration(seconds=2, nanoseconds= 620764973).to_msg()), JointTrajectoryPoint(positions=[0.006441311487648636, -0.30631130315231586, 4.1806377054980174e-05, -2.1282803420630927, 4.5680763242909544e-05, 2.415367761150339, 0.3990374340689168], time_from_start=Duration(seconds=3, nanoseconds= 144917968).to_msg()), JointTrajectoryPoint(positions=[0.005514863402256743, -0.2625465203443685, 4.877410656414353e-05, -2.014277065740275, 5.3294223783394466e-05, 2.311812388008729, 0.34204367308040295], time_from_start=Duration(seconds=3, nanoseconds= 669070962).to_msg()), JointTrajectoryPoint(positions=[0.004588415316864848, -0.2187817375364211, 5.5741836073306894e-05, -1.900273789417457, 6.0907684323879394e-05, 2.208257014867119, 0.28504991209188907], time_from_start=Duration(seconds=4, nanoseconds= 193223957).to_msg()), ] self.gripper_command_open_goal_msg = GripperCommand.Goal() self.gripper_command_open_goal_msg.command.position = 0.03990753115697298 self.gripper_command_open_goal_msg.command.max_effort = 0.0 self.gripper_command_close_goal_msg = GripperCommand.Goal() self.gripper_command_close_goal_msg.command.position = 8.962388141080737e-05 self.gripper_command_close_goal_msg.command.max_effort = 0.0 if __name__ == '__main__': rclpy.init() node = TestROS2BridgeNode() # ==== Gripper Command ==== assert node.gripper_command_client.wait_for_server(timeout_sec=1.0), \ "Action server {} not available".format(node.gripper_command_action_name) # close gripper command (with obstacle) future = node.gripper_command_client.send_goal_async(node.gripper_command_close_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.stalled is True assert result.result.reached_goal is False assert abs(result.result.position - 0.0295) < 1e-3 # open gripper command future = node.gripper_command_client.send_goal_async(node.gripper_command_open_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.stalled is False assert result.result.reached_goal is True assert abs(result.result.position - 0.0389) < 1e-3 # ==== Attribute ==== assert node.get_attribute_client.wait_for_service(timeout_sec=5.0), \ "Service {} not available".format(node.get_attribute_service_name) assert node.set_attribute_client.wait_for_service(timeout_sec=5.0), \ "Service {} not available".format(node.set_attribute_service_name) request_get_attribute = add_on_msgs.srv.GetPrimAttribute.Request() request_get_attribute.path = "/Cylinder" request_get_attribute.attribute = "physics:collisionEnabled" request_set_attribute = add_on_msgs.srv.SetPrimAttribute.Request() request_set_attribute.path = request_get_attribute.path request_set_attribute.attribute = request_get_attribute.attribute request_set_attribute.value = json.dumps(False) # get obstacle collisionEnabled attribute future = node.get_attribute_client.call_async(request_get_attribute) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.success is True assert json.loads(result.value) is True # disable obstacle collision shape future = node.set_attribute_client.call_async(request_set_attribute) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.success is True # get obstacle collisionEnabled attribute future = node.get_attribute_client.call_async(request_get_attribute) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.success is True assert json.loads(result.value) is False # ==== Gripper Command ==== assert node.gripper_command_client.wait_for_server(timeout_sec=1.0), \ "Action server {} not available".format(node.gripper_command_action_name) # close gripper command (without obstacle) future = node.gripper_command_client.send_goal_async(node.gripper_command_close_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.stalled is False assert result.result.reached_goal is True assert abs(result.result.position - 0.0) < 1e-3 # ==== Follow Joint Trajectory ==== assert node.follow_joint_trajectory_client.wait_for_server(timeout_sec=1.0), \ "Action server {} not available".format(node.follow_joint_trajectory_action_name) # move to goal future = node.follow_joint_trajectory_client.send_goal_async(node.follow_joint_trajectory_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=10.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.error_code == result.result.SUCCESSFUL print("Test passed")
9,613
Python
52.116022
268
0.730885
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/tests/__init__.py
from .test_ros2_bridge import *
32
Python
15.499992
31
0.75
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/config/extension.toml
[core] reloadable = true order = 0 [package] version = "0.1.1" category = "Simulation" feature = false app = false title = "ROS2 Bridge (semu namespace)" description = "ROS2 interfaces (semu namespace)" authors = ["Toni-SM"] repository = "https://github.com/Toni-SM/semu.robotics.ros2_bridge" keywords = ["ROS2", "control"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" preview_image = "data/preview.png" icon = "data/icon.png" [package.target] config = ["release"] platform = ["linux-x86_64"] python = ["py37", "cp37"] [dependencies] "omni.kit.uiapp" = {} "omni.isaac.dynamic_control" = {} "omni.isaac.ros2_bridge" = {} "semu.usd.schemas" = {} "semu.robotics.ros_bridge_ui" = {} [[python.module]] name = "semu.robotics.ros2_bridge" [[python.module]] name = "semu.robotics.ros2_bridge.tests" [settings] exts."semu.robotics.ros2_bridge".nodeName = "SemuRos2Bridge" exts."semu.robotics.ros2_bridge".eventTimeout = 5.0 exts."semu.robotics.ros2_bridge".setAttributeUsingAsyncio = false [[native.library]] path = "bin/libadd_on_msgs__python.so" [[native.library]] path = "bin/libadd_on_msgs__rosidl_generator_c.so" [[native.library]] path = "bin/libadd_on_msgs__rosidl_typesupport_c.so" [[native.library]] path = "bin/libadd_on_msgs__rosidl_typesupport_fastrtps_c.so" [[native.library]] path = "bin/libadd_on_msgs__rosidl_typesupport_introspection_c.so" [[native.library]] path = "bin/libcontrol_msgs__rosidl_generator_c.so" [[native.library]] path = "bin/libcontrol_msgs__python.so" [[native.library]] path = "bin/libcontrol_msgs__rosidl_typesupport_c.so" [[native.library]] path = "bin/libcontrol_msgs__rosidl_typesupport_fastrtps_c.so" [[native.library]] path = "bin/libcontrol_msgs__rosidl_typesupport_introspection_c.so"
1,740
TOML
26.63492
67
0.717816
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [0.1.1] - 2022-05-28 ### Changed - Rename the extension to `semu.robotics.ros2_bridge` ## [0.1.0] - 2022-04-12 ### Added - Source code (src folder) - FollowJointTrajectory action server (contribution with [@09ubberboy90](https://github.com/09ubberboy90)) - GripperCommand action server ### Changed - Improve the extension implementation ## [0.0.1] - 2021-12-18 ### Added - Attribute service - Create extension based on omni.add_on.ros_bridge
543
Markdown
23.727272
106
0.714549
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/docs/README.md
# semu.robotics.ros2_bridge This extension enables the ROS2 action server interfaces for controlling robots (particularly those used by MoveIt to talk to robot controllers: FollowJointTrajectory and GripperCommand) and enables services for agile prototyping of robotic applications in ROS2 Visit https://github.com/Toni-SM/semu.robotics.ros2_bridge to read more about its use
379
Markdown
53.285707
261
0.828496
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/__init__.py
from .scripts.extension import *
33
Python
15.999992
32
0.787879
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/scripts/extension.py
import os import sys import carb import omni.ext try: from .. import _ros2_bridge except: print(">>>> [DEVELOPMENT] import ros2_bridge") from .. import ros2_bridge as _ros2_bridge class Extension(omni.ext.IExt): def on_startup(self, ext_id): self._ros2bridge = None self._extension_path = None ext_manager = omni.kit.app.get_app().get_extension_manager() if ext_manager.is_extension_enabled("omni.isaac.ros_bridge"): carb.log_error("ROS 2 Bridge external extension cannot be enabled if ROS Bridge is enabled") ext_manager.set_extension_enabled("semu.robotics.ros2_bridge", False) return self._extension_path = ext_manager.get_extension_path(ext_id) sys.path.append(os.path.join(self._extension_path, "semu", "robotics", "ros2_bridge", "packages")) if os.environ.get("LD_LIBRARY_PATH"): os.environ["LD_LIBRARY_PATH"] = os.environ.get("LD_LIBRARY_PATH") + ":{}/bin".format(self._extension_path) else: os.environ["LD_LIBRARY_PATH"] = "{}/bin".format(self._extension_path) self._ros2bridge = _ros2_bridge.acquire_ros2_bridge_interface(ext_id) def on_shutdown(self): if self._extension_path is not None: sys.path.remove(os.path.join(self._extension_path, "semu", "robotics", "ros2_bridge", "packages")) self._extension_path = None if self._ros2bridge is not None: _ros2_bridge.release_ros2_bridge_interface(self._ros2bridge) self._ros2bridge = None
1,574
Python
39.384614
118
0.635959
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/_query_trajectory_state_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:srv/QueryTrajectoryState.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/srv/detail/query_trajectory_state__struct.h" #include "control_msgs/srv/detail/query_trajectory_state__functions.h" ROSIDL_GENERATOR_C_IMPORT bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__srv__query_trajectory_state__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[70]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.srv._query_trajectory_state.QueryTrajectoryState_Request", full_classname_dest, 69) == 0); } control_msgs__srv__QueryTrajectoryState_Request * ros_message = _ros_message; { // time PyObject * field = PyObject_GetAttrString(_pymsg, "time"); if (!field) { return false; } if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->time)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__srv__query_trajectory_state__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of QueryTrajectoryState_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.srv._query_trajectory_state"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "QueryTrajectoryState_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__srv__QueryTrajectoryState_Request * ros_message = (control_msgs__srv__QueryTrajectoryState_Request *)raw_ros_message; { // time PyObject * field = NULL; field = builtin_interfaces__msg__time__convert_to_py(&ros_message->time); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "time", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/srv/detail/query_trajectory_state__struct.h" // already included above // #include "control_msgs/srv/detail/query_trajectory_state__functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" #include "rosidl_runtime_c/primitives_sequence.h" #include "rosidl_runtime_c/primitives_sequence_functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__srv__query_trajectory_state__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[71]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.srv._query_trajectory_state.QueryTrajectoryState_Response", full_classname_dest, 70) == 0); } control_msgs__srv__QueryTrajectoryState_Response * ros_message = _ros_message; { // success PyObject * field = PyObject_GetAttrString(_pymsg, "success"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->success = (Py_True == field); Py_DECREF(field); } { // message PyObject * field = PyObject_GetAttrString(_pymsg, "message"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->message, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } { // name PyObject * field = PyObject_GetAttrString(_pymsg, "name"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'name'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->name), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->name.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // position PyObject * field = PyObject_GetAttrString(_pymsg, "position"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'position'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->position), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } double * dest = ros_message->position.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyFloat_Check(item)); double tmp = PyFloat_AS_DOUBLE(item); memcpy(&dest[i], &tmp, sizeof(double)); } Py_DECREF(seq_field); Py_DECREF(field); } { // velocity PyObject * field = PyObject_GetAttrString(_pymsg, "velocity"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'velocity'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->velocity), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } double * dest = ros_message->velocity.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyFloat_Check(item)); double tmp = PyFloat_AS_DOUBLE(item); memcpy(&dest[i], &tmp, sizeof(double)); } Py_DECREF(seq_field); Py_DECREF(field); } { // acceleration PyObject * field = PyObject_GetAttrString(_pymsg, "acceleration"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'acceleration'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->acceleration), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } double * dest = ros_message->acceleration.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyFloat_Check(item)); double tmp = PyFloat_AS_DOUBLE(item); memcpy(&dest[i], &tmp, sizeof(double)); } Py_DECREF(seq_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__srv__query_trajectory_state__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of QueryTrajectoryState_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.srv._query_trajectory_state"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "QueryTrajectoryState_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__srv__QueryTrajectoryState_Response * ros_message = (control_msgs__srv__QueryTrajectoryState_Response *)raw_ros_message; { // success PyObject * field = NULL; field = PyBool_FromLong(ros_message->success ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "success", field); Py_DECREF(field); if (rc) { return NULL; } } } { // message PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->message.data, strlen(ros_message->message.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "message", field); Py_DECREF(field); if (rc) { return NULL; } } } { // name PyObject * field = NULL; size_t size = ros_message->name.size; rosidl_runtime_c__String * src = ros_message->name.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "name", field); Py_DECREF(field); if (rc) { return NULL; } } } { // position PyObject * field = NULL; field = PyObject_GetAttrString(_pymessage, "position"); if (!field) { return NULL; } assert(field->ob_type != NULL); assert(field->ob_type->tp_name != NULL); assert(strcmp(field->ob_type->tp_name, "array.array") == 0); // ensure that itemsize matches the sizeof of the ROS message field PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize"); assert(itemsize_attr != NULL); size_t itemsize = PyLong_AsSize_t(itemsize_attr); Py_DECREF(itemsize_attr); if (itemsize != sizeof(double)) { PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation"); Py_DECREF(field); return NULL; } // clear the array, poor approach to remove potential default values Py_ssize_t length = PyObject_Length(field); if (-1 == length) { Py_DECREF(field); return NULL; } if (length > 0) { PyObject * pop = PyObject_GetAttrString(field, "pop"); assert(pop != NULL); for (Py_ssize_t i = 0; i < length; ++i) { PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL); if (!ret) { Py_DECREF(pop); Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(pop); } if (ros_message->position.size > 0) { // populating the array.array using the frombytes method PyObject * frombytes = PyObject_GetAttrString(field, "frombytes"); assert(frombytes != NULL); double * src = &(ros_message->position.data[0]); PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->position.size * sizeof(double)); assert(data != NULL); PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL); Py_DECREF(data); Py_DECREF(frombytes); if (!ret) { Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(field); } { // velocity PyObject * field = NULL; field = PyObject_GetAttrString(_pymessage, "velocity"); if (!field) { return NULL; } assert(field->ob_type != NULL); assert(field->ob_type->tp_name != NULL); assert(strcmp(field->ob_type->tp_name, "array.array") == 0); // ensure that itemsize matches the sizeof of the ROS message field PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize"); assert(itemsize_attr != NULL); size_t itemsize = PyLong_AsSize_t(itemsize_attr); Py_DECREF(itemsize_attr); if (itemsize != sizeof(double)) { PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation"); Py_DECREF(field); return NULL; } // clear the array, poor approach to remove potential default values Py_ssize_t length = PyObject_Length(field); if (-1 == length) { Py_DECREF(field); return NULL; } if (length > 0) { PyObject * pop = PyObject_GetAttrString(field, "pop"); assert(pop != NULL); for (Py_ssize_t i = 0; i < length; ++i) { PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL); if (!ret) { Py_DECREF(pop); Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(pop); } if (ros_message->velocity.size > 0) { // populating the array.array using the frombytes method PyObject * frombytes = PyObject_GetAttrString(field, "frombytes"); assert(frombytes != NULL); double * src = &(ros_message->velocity.data[0]); PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->velocity.size * sizeof(double)); assert(data != NULL); PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL); Py_DECREF(data); Py_DECREF(frombytes); if (!ret) { Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(field); } { // acceleration PyObject * field = NULL; field = PyObject_GetAttrString(_pymessage, "acceleration"); if (!field) { return NULL; } assert(field->ob_type != NULL); assert(field->ob_type->tp_name != NULL); assert(strcmp(field->ob_type->tp_name, "array.array") == 0); // ensure that itemsize matches the sizeof of the ROS message field PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize"); assert(itemsize_attr != NULL); size_t itemsize = PyLong_AsSize_t(itemsize_attr); Py_DECREF(itemsize_attr); if (itemsize != sizeof(double)) { PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation"); Py_DECREF(field); return NULL; } // clear the array, poor approach to remove potential default values Py_ssize_t length = PyObject_Length(field); if (-1 == length) { Py_DECREF(field); return NULL; } if (length > 0) { PyObject * pop = PyObject_GetAttrString(field, "pop"); assert(pop != NULL); for (Py_ssize_t i = 0; i < length; ++i) { PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL); if (!ret) { Py_DECREF(pop); Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(pop); } if (ros_message->acceleration.size > 0) { // populating the array.array using the frombytes method PyObject * frombytes = PyObject_GetAttrString(field, "frombytes"); assert(frombytes != NULL); double * src = &(ros_message->acceleration.data[0]); PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->acceleration.size * sizeof(double)); assert(data != NULL); PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL); Py_DECREF(data); Py_DECREF(frombytes); if (!ret) { Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(field); } // ownership of _pymessage is transferred to the caller return _pymessage; }
19,331
C
31.655405
135
0.61435
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/_query_calibration_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:srv/QueryCalibrationState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_QueryCalibrationState_Request(type): """Metaclass of message 'QueryCalibrationState_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryCalibrationState_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__query_calibration_state__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_calibration_state__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_calibration_state__request cls._TYPE_SUPPORT = module.type_support_msg__srv__query_calibration_state__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_calibration_state__request @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class QueryCalibrationState_Request(metaclass=Metaclass_QueryCalibrationState_Request): """Message class 'QueryCalibrationState_Request'.""" __slots__ = [ ] _fields_and_field_types = { } SLOT_TYPES = ( ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_QueryCalibrationState_Response(type): """Metaclass of message 'QueryCalibrationState_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryCalibrationState_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__query_calibration_state__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_calibration_state__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_calibration_state__response cls._TYPE_SUPPORT = module.type_support_msg__srv__query_calibration_state__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_calibration_state__response @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class QueryCalibrationState_Response(metaclass=Metaclass_QueryCalibrationState_Response): """Message class 'QueryCalibrationState_Response'.""" __slots__ = [ '_is_calibrated', ] _fields_and_field_types = { 'is_calibrated': 'boolean', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.is_calibrated = kwargs.get('is_calibrated', bool()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.is_calibrated != other.is_calibrated: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def is_calibrated(self): """Message field 'is_calibrated'.""" return self._is_calibrated @is_calibrated.setter def is_calibrated(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'is_calibrated' field must be of type 'bool'" self._is_calibrated = value class Metaclass_QueryCalibrationState(type): """Metaclass of service 'QueryCalibrationState'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryCalibrationState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__query_calibration_state from control_msgs.srv import _query_calibration_state if _query_calibration_state.Metaclass_QueryCalibrationState_Request._TYPE_SUPPORT is None: _query_calibration_state.Metaclass_QueryCalibrationState_Request.__import_type_support__() if _query_calibration_state.Metaclass_QueryCalibrationState_Response._TYPE_SUPPORT is None: _query_calibration_state.Metaclass_QueryCalibrationState_Response.__import_type_support__() class QueryCalibrationState(metaclass=Metaclass_QueryCalibrationState): from control_msgs.srv._query_calibration_state import QueryCalibrationState_Request as Request from control_msgs.srv._query_calibration_state import QueryCalibrationState_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
9,936
Python
37.219231
134
0.598631
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/__init__.py
from control_msgs.srv._query_calibration_state import QueryCalibrationState # noqa: F401 from control_msgs.srv._query_trajectory_state import QueryTrajectoryState # noqa: F401
178
Python
58.666647
89
0.820225
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/_query_trajectory_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:srv/QueryTrajectoryState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_QueryTrajectoryState_Request(type): """Metaclass of message 'QueryTrajectoryState_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryTrajectoryState_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__query_trajectory_state__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_trajectory_state__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_trajectory_state__request cls._TYPE_SUPPORT = module.type_support_msg__srv__query_trajectory_state__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_trajectory_state__request from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class QueryTrajectoryState_Request(metaclass=Metaclass_QueryTrajectoryState_Request): """Message class 'QueryTrajectoryState_Request'.""" __slots__ = [ '_time', ] _fields_and_field_types = { 'time': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from builtin_interfaces.msg import Time self.time = kwargs.get('time', Time()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.time != other.time: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def time(self): """Message field 'time'.""" return self._time @time.setter def time(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'time' field must be a sub message of type 'Time'" self._time = value # Import statements for member types # Member 'position' # Member 'velocity' # Member 'acceleration' import array # noqa: E402, I100 # already imported above # import rosidl_parser.definition class Metaclass_QueryTrajectoryState_Response(type): """Metaclass of message 'QueryTrajectoryState_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryTrajectoryState_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__query_trajectory_state__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__query_trajectory_state__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__query_trajectory_state__response cls._TYPE_SUPPORT = module.type_support_msg__srv__query_trajectory_state__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__query_trajectory_state__response @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class QueryTrajectoryState_Response(metaclass=Metaclass_QueryTrajectoryState_Response): """Message class 'QueryTrajectoryState_Response'.""" __slots__ = [ '_success', '_message', '_name', '_position', '_velocity', '_acceleration', ] _fields_and_field_types = { 'success': 'boolean', 'message': 'string', 'name': 'sequence<string>', 'position': 'sequence<double>', 'velocity': 'sequence<double>', 'acceleration': 'sequence<double>', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.success = kwargs.get('success', bool()) self.message = kwargs.get('message', str()) self.name = kwargs.get('name', []) self.position = array.array('d', kwargs.get('position', [])) self.velocity = array.array('d', kwargs.get('velocity', [])) self.acceleration = array.array('d', kwargs.get('acceleration', [])) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.success != other.success: return False if self.message != other.message: return False if self.name != other.name: return False if self.position != other.position: return False if self.velocity != other.velocity: return False if self.acceleration != other.acceleration: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def success(self): """Message field 'success'.""" return self._success @success.setter def success(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'success' field must be of type 'bool'" self._success = value @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value @property def name(self): """Message field 'name'.""" return self._name @name.setter def name(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'name' field must be a set or sequence and each value of type 'str'" self._name = value @property def position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if isinstance(value, array.array): assert value.typecode == 'd', \ "The 'position' array.array() must have the type code of 'd'" self._position = value return if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, float) for v in value) and True), \ "The 'position' field must be a set or sequence and each value of type 'float'" self._position = array.array('d', value) @property def velocity(self): """Message field 'velocity'.""" return self._velocity @velocity.setter def velocity(self, value): if isinstance(value, array.array): assert value.typecode == 'd', \ "The 'velocity' array.array() must have the type code of 'd'" self._velocity = value return if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, float) for v in value) and True), \ "The 'velocity' field must be a set or sequence and each value of type 'float'" self._velocity = array.array('d', value) @property def acceleration(self): """Message field 'acceleration'.""" return self._acceleration @acceleration.setter def acceleration(self, value): if isinstance(value, array.array): assert value.typecode == 'd', \ "The 'acceleration' array.array() must have the type code of 'd'" self._acceleration = value return if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, float) for v in value) and True), \ "The 'acceleration' field must be a set or sequence and each value of type 'float'" self._acceleration = array.array('d', value) class Metaclass_QueryTrajectoryState(type): """Metaclass of service 'QueryTrajectoryState'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.srv.QueryTrajectoryState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__query_trajectory_state from control_msgs.srv import _query_trajectory_state if _query_trajectory_state.Metaclass_QueryTrajectoryState_Request._TYPE_SUPPORT is None: _query_trajectory_state.Metaclass_QueryTrajectoryState_Request.__import_type_support__() if _query_trajectory_state.Metaclass_QueryTrajectoryState_Response._TYPE_SUPPORT is None: _query_trajectory_state.Metaclass_QueryTrajectoryState_Response.__import_type_support__() class QueryTrajectoryState(metaclass=Metaclass_QueryTrajectoryState): from control_msgs.srv._query_trajectory_state import QueryTrajectoryState_Request as Request from control_msgs.srv._query_trajectory_state import QueryTrajectoryState_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
16,687
Python
36.927273
134
0.579613
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/srv/_query_calibration_state_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:srv/QueryCalibrationState.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/srv/detail/query_calibration_state__struct.h" #include "control_msgs/srv/detail/query_calibration_state__functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__srv__query_calibration_state__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[72]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.srv._query_calibration_state.QueryCalibrationState_Request", full_classname_dest, 71) == 0); } control_msgs__srv__QueryCalibrationState_Request * ros_message = _ros_message; ros_message->structure_needs_at_least_one_member = 0; return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__srv__query_calibration_state__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of QueryCalibrationState_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.srv._query_calibration_state"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "QueryCalibrationState_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } (void)raw_ros_message; // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/srv/detail/query_calibration_state__struct.h" // already included above // #include "control_msgs/srv/detail/query_calibration_state__functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__srv__query_calibration_state__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[73]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.srv._query_calibration_state.QueryCalibrationState_Response", full_classname_dest, 72) == 0); } control_msgs__srv__QueryCalibrationState_Response * ros_message = _ros_message; { // is_calibrated PyObject * field = PyObject_GetAttrString(_pymsg, "is_calibrated"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->is_calibrated = (Py_True == field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__srv__query_calibration_state__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of QueryCalibrationState_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.srv._query_calibration_state"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "QueryCalibrationState_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__srv__QueryCalibrationState_Response * ros_message = (control_msgs__srv__QueryCalibrationState_Response *)raw_ros_message; { // is_calibrated PyObject * field = NULL; field = PyBool_FromLong(ros_message->is_calibrated ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "is_calibrated", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
6,102
C
33.874286
137
0.6647
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_joint_trajectory_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:action/JointTrajectory.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/action/detail/joint_trajectory__struct.h" #include "control_msgs/action/detail/joint_trajectory__functions.h" ROSIDL_GENERATOR_C_IMPORT bool trajectory_msgs__msg__joint_trajectory__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * trajectory_msgs__msg__joint_trajectory__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__joint_trajectory__goal__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[59]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_Goal", full_classname_dest, 58) == 0); } control_msgs__action__JointTrajectory_Goal * ros_message = _ros_message; { // trajectory PyObject * field = PyObject_GetAttrString(_pymsg, "trajectory"); if (!field) { return false; } if (!trajectory_msgs__msg__joint_trajectory__convert_from_py(field, &ros_message->trajectory)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__joint_trajectory__goal__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointTrajectory_Goal */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_Goal"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__JointTrajectory_Goal * ros_message = (control_msgs__action__JointTrajectory_Goal *)raw_ros_message; { // trajectory PyObject * field = NULL; field = trajectory_msgs__msg__joint_trajectory__convert_to_py(&ros_message->trajectory); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "trajectory", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__joint_trajectory__result__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[61]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_Result", full_classname_dest, 60) == 0); } control_msgs__action__JointTrajectory_Result * ros_message = _ros_message; ros_message->structure_needs_at_least_one_member = 0; return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__joint_trajectory__result__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointTrajectory_Result */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_Result"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } (void)raw_ros_message; // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__joint_trajectory__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[63]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_Feedback", full_classname_dest, 62) == 0); } control_msgs__action__JointTrajectory_Feedback * ros_message = _ros_message; ros_message->structure_needs_at_least_one_member = 0; return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__joint_trajectory__feedback__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointTrajectory_Feedback */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_Feedback"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } (void)raw_ros_message; // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); bool control_msgs__action__joint_trajectory__goal__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__joint_trajectory__goal__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__joint_trajectory__send_goal__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[71]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_SendGoal_Request", full_classname_dest, 70) == 0); } control_msgs__action__JointTrajectory_SendGoal_Request * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // goal PyObject * field = PyObject_GetAttrString(_pymsg, "goal"); if (!field) { return false; } if (!control_msgs__action__joint_trajectory__goal__convert_from_py(field, &ros_message->goal)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__joint_trajectory__send_goal__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointTrajectory_SendGoal_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_SendGoal_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__JointTrajectory_SendGoal_Request * ros_message = (control_msgs__action__JointTrajectory_SendGoal_Request *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } { // goal PyObject * field = NULL; field = control_msgs__action__joint_trajectory__goal__convert_to_py(&ros_message->goal); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__functions.h" ROSIDL_GENERATOR_C_IMPORT bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__joint_trajectory__send_goal__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[72]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_SendGoal_Response", full_classname_dest, 71) == 0); } control_msgs__action__JointTrajectory_SendGoal_Response * ros_message = _ros_message; { // accepted PyObject * field = PyObject_GetAttrString(_pymsg, "accepted"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->accepted = (Py_True == field); Py_DECREF(field); } { // stamp PyObject * field = PyObject_GetAttrString(_pymsg, "stamp"); if (!field) { return false; } if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->stamp)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__joint_trajectory__send_goal__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointTrajectory_SendGoal_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_SendGoal_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__JointTrajectory_SendGoal_Response * ros_message = (control_msgs__action__JointTrajectory_SendGoal_Response *)raw_ros_message; { // accepted PyObject * field = NULL; field = PyBool_FromLong(ros_message->accepted ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "accepted", field); Py_DECREF(field); if (rc) { return NULL; } } } { // stamp PyObject * field = NULL; field = builtin_interfaces__msg__time__convert_to_py(&ros_message->stamp); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "stamp", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__joint_trajectory__get_result__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[72]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_GetResult_Request", full_classname_dest, 71) == 0); } control_msgs__action__JointTrajectory_GetResult_Request * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__joint_trajectory__get_result__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointTrajectory_GetResult_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_GetResult_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__JointTrajectory_GetResult_Request * ros_message = (control_msgs__action__JointTrajectory_GetResult_Request *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__functions.h" bool control_msgs__action__joint_trajectory__result__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__joint_trajectory__result__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__joint_trajectory__get_result__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[73]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_GetResult_Response", full_classname_dest, 72) == 0); } control_msgs__action__JointTrajectory_GetResult_Response * ros_message = _ros_message; { // status PyObject * field = PyObject_GetAttrString(_pymsg, "status"); if (!field) { return false; } assert(PyLong_Check(field)); ros_message->status = (int8_t)PyLong_AsLong(field); Py_DECREF(field); } { // result PyObject * field = PyObject_GetAttrString(_pymsg, "result"); if (!field) { return false; } if (!control_msgs__action__joint_trajectory__result__convert_from_py(field, &ros_message->result)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__joint_trajectory__get_result__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointTrajectory_GetResult_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_GetResult_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__JointTrajectory_GetResult_Response * ros_message = (control_msgs__action__JointTrajectory_GetResult_Response *)raw_ros_message; { // status PyObject * field = NULL; field = PyLong_FromLong(ros_message->status); { int rc = PyObject_SetAttrString(_pymessage, "status", field); Py_DECREF(field); if (rc) { return NULL; } } } { // result PyObject * field = NULL; field = control_msgs__action__joint_trajectory__result__convert_to_py(&ros_message->result); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "result", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/joint_trajectory__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); bool control_msgs__action__joint_trajectory__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__joint_trajectory__feedback__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__joint_trajectory__feedback_message__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[70]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._joint_trajectory.JointTrajectory_FeedbackMessage", full_classname_dest, 69) == 0); } control_msgs__action__JointTrajectory_FeedbackMessage * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // feedback PyObject * field = PyObject_GetAttrString(_pymsg, "feedback"); if (!field) { return false; } if (!control_msgs__action__joint_trajectory__feedback__convert_from_py(field, &ros_message->feedback)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__joint_trajectory__feedback_message__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointTrajectory_FeedbackMessage */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectory_FeedbackMessage"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__JointTrajectory_FeedbackMessage * ros_message = (control_msgs__action__JointTrajectory_FeedbackMessage *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } { // feedback PyObject * field = NULL; field = control_msgs__action__joint_trajectory__feedback__convert_to_py(&ros_message->feedback); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "feedback", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
29,706
C
33.067661
151
0.651889
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_joint_trajectory.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:action/JointTrajectory.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_JointTrajectory_Goal(type): """Metaclass of message 'JointTrajectory_Goal'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_Goal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__goal cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__goal cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__goal cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__goal cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__goal from trajectory_msgs.msg import JointTrajectory if JointTrajectory.__class__._TYPE_SUPPORT is None: JointTrajectory.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointTrajectory_Goal(metaclass=Metaclass_JointTrajectory_Goal): """Message class 'JointTrajectory_Goal'.""" __slots__ = [ '_trajectory', ] _fields_and_field_types = { 'trajectory': 'trajectory_msgs/JointTrajectory', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectory'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from trajectory_msgs.msg import JointTrajectory self.trajectory = kwargs.get('trajectory', JointTrajectory()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.trajectory != other.trajectory: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def trajectory(self): """Message field 'trajectory'.""" return self._trajectory @trajectory.setter def trajectory(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectory assert \ isinstance(value, JointTrajectory), \ "The 'trajectory' field must be a sub message of type 'JointTrajectory'" self._trajectory = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_Result(type): """Metaclass of message 'JointTrajectory_Result'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_Result') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__result cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__result cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__result cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__result cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__result @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointTrajectory_Result(metaclass=Metaclass_JointTrajectory_Result): """Message class 'JointTrajectory_Result'.""" __slots__ = [ ] _fields_and_field_types = { } SLOT_TYPES = ( ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_Feedback(type): """Metaclass of message 'JointTrajectory_Feedback'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_Feedback') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__feedback cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__feedback cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__feedback cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__feedback cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__feedback @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointTrajectory_Feedback(metaclass=Metaclass_JointTrajectory_Feedback): """Message class 'JointTrajectory_Feedback'.""" __slots__ = [ ] _fields_and_field_types = { } SLOT_TYPES = ( ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_SendGoal_Request(type): """Metaclass of message 'JointTrajectory_SendGoal_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_SendGoal_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__send_goal__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__send_goal__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__send_goal__request cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__send_goal__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__send_goal__request from control_msgs.action import JointTrajectory if JointTrajectory.Goal.__class__._TYPE_SUPPORT is None: JointTrajectory.Goal.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointTrajectory_SendGoal_Request(metaclass=Metaclass_JointTrajectory_SendGoal_Request): """Message class 'JointTrajectory_SendGoal_Request'.""" __slots__ = [ '_goal_id', '_goal', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'goal': 'control_msgs/JointTrajectory_Goal', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'JointTrajectory_Goal'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._joint_trajectory import JointTrajectory_Goal self.goal = kwargs.get('goal', JointTrajectory_Goal()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False if self.goal != other.goal: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def goal(self): """Message field 'goal'.""" return self._goal @goal.setter def goal(self, value): if __debug__: from control_msgs.action._joint_trajectory import JointTrajectory_Goal assert \ isinstance(value, JointTrajectory_Goal), \ "The 'goal' field must be a sub message of type 'JointTrajectory_Goal'" self._goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_SendGoal_Response(type): """Metaclass of message 'JointTrajectory_SendGoal_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_SendGoal_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__send_goal__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__send_goal__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__send_goal__response cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__send_goal__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__send_goal__response from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointTrajectory_SendGoal_Response(metaclass=Metaclass_JointTrajectory_SendGoal_Response): """Message class 'JointTrajectory_SendGoal_Response'.""" __slots__ = [ '_accepted', '_stamp', ] _fields_and_field_types = { 'accepted': 'boolean', 'stamp': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.accepted = kwargs.get('accepted', bool()) from builtin_interfaces.msg import Time self.stamp = kwargs.get('stamp', Time()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.accepted != other.accepted: return False if self.stamp != other.stamp: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def accepted(self): """Message field 'accepted'.""" return self._accepted @accepted.setter def accepted(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'accepted' field must be of type 'bool'" self._accepted = value @property def stamp(self): """Message field 'stamp'.""" return self._stamp @stamp.setter def stamp(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'stamp' field must be a sub message of type 'Time'" self._stamp = value class Metaclass_JointTrajectory_SendGoal(type): """Metaclass of service 'JointTrajectory_SendGoal'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_SendGoal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__joint_trajectory__send_goal from control_msgs.action import _joint_trajectory if _joint_trajectory.Metaclass_JointTrajectory_SendGoal_Request._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_SendGoal_Request.__import_type_support__() if _joint_trajectory.Metaclass_JointTrajectory_SendGoal_Response._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_SendGoal_Response.__import_type_support__() class JointTrajectory_SendGoal(metaclass=Metaclass_JointTrajectory_SendGoal): from control_msgs.action._joint_trajectory import JointTrajectory_SendGoal_Request as Request from control_msgs.action._joint_trajectory import JointTrajectory_SendGoal_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_GetResult_Request(type): """Metaclass of message 'JointTrajectory_GetResult_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_GetResult_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__get_result__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__get_result__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__get_result__request cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__get_result__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__get_result__request from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointTrajectory_GetResult_Request(metaclass=Metaclass_JointTrajectory_GetResult_Request): """Message class 'JointTrajectory_GetResult_Request'.""" __slots__ = [ '_goal_id', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_GetResult_Response(type): """Metaclass of message 'JointTrajectory_GetResult_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_GetResult_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__get_result__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__get_result__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__get_result__response cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__get_result__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__get_result__response from control_msgs.action import JointTrajectory if JointTrajectory.Result.__class__._TYPE_SUPPORT is None: JointTrajectory.Result.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointTrajectory_GetResult_Response(metaclass=Metaclass_JointTrajectory_GetResult_Response): """Message class 'JointTrajectory_GetResult_Response'.""" __slots__ = [ '_status', '_result', ] _fields_and_field_types = { 'status': 'int8', 'result': 'control_msgs/JointTrajectory_Result', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int8'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'JointTrajectory_Result'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.status = kwargs.get('status', int()) from control_msgs.action._joint_trajectory import JointTrajectory_Result self.result = kwargs.get('result', JointTrajectory_Result()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.status != other.status: return False if self.result != other.result: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def status(self): """Message field 'status'.""" return self._status @status.setter def status(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'status' field must be of type 'int'" assert value >= -128 and value < 128, \ "The 'status' field must be an integer in [-128, 127]" self._status = value @property def result(self): """Message field 'result'.""" return self._result @result.setter def result(self, value): if __debug__: from control_msgs.action._joint_trajectory import JointTrajectory_Result assert \ isinstance(value, JointTrajectory_Result), \ "The 'result' field must be a sub message of type 'JointTrajectory_Result'" self._result = value class Metaclass_JointTrajectory_GetResult(type): """Metaclass of service 'JointTrajectory_GetResult'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_GetResult') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__joint_trajectory__get_result from control_msgs.action import _joint_trajectory if _joint_trajectory.Metaclass_JointTrajectory_GetResult_Request._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_GetResult_Request.__import_type_support__() if _joint_trajectory.Metaclass_JointTrajectory_GetResult_Response._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_GetResult_Response.__import_type_support__() class JointTrajectory_GetResult(metaclass=Metaclass_JointTrajectory_GetResult): from control_msgs.action._joint_trajectory import JointTrajectory_GetResult_Request as Request from control_msgs.action._joint_trajectory import JointTrajectory_GetResult_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_JointTrajectory_FeedbackMessage(type): """Metaclass of message 'JointTrajectory_FeedbackMessage'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory_FeedbackMessage') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__joint_trajectory__feedback_message cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__joint_trajectory__feedback_message cls._CONVERT_TO_PY = module.convert_to_py_msg__action__joint_trajectory__feedback_message cls._TYPE_SUPPORT = module.type_support_msg__action__joint_trajectory__feedback_message cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__joint_trajectory__feedback_message from control_msgs.action import JointTrajectory if JointTrajectory.Feedback.__class__._TYPE_SUPPORT is None: JointTrajectory.Feedback.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointTrajectory_FeedbackMessage(metaclass=Metaclass_JointTrajectory_FeedbackMessage): """Message class 'JointTrajectory_FeedbackMessage'.""" __slots__ = [ '_goal_id', '_feedback', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'feedback': 'control_msgs/JointTrajectory_Feedback', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'JointTrajectory_Feedback'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._joint_trajectory import JointTrajectory_Feedback self.feedback = kwargs.get('feedback', JointTrajectory_Feedback()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False if self.feedback != other.feedback: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def feedback(self): """Message field 'feedback'.""" return self._feedback @feedback.setter def feedback(self, value): if __debug__: from control_msgs.action._joint_trajectory import JointTrajectory_Feedback assert \ isinstance(value, JointTrajectory_Feedback), \ "The 'feedback' field must be a sub message of type 'JointTrajectory_Feedback'" self._feedback = value class Metaclass_JointTrajectory(type): """Metaclass of action 'JointTrajectory'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.JointTrajectory') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_action__action__joint_trajectory from action_msgs.msg import _goal_status_array if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None: _goal_status_array.Metaclass_GoalStatusArray.__import_type_support__() from action_msgs.srv import _cancel_goal if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None: _cancel_goal.Metaclass_CancelGoal.__import_type_support__() from control_msgs.action import _joint_trajectory if _joint_trajectory.Metaclass_JointTrajectory_SendGoal._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_SendGoal.__import_type_support__() if _joint_trajectory.Metaclass_JointTrajectory_GetResult._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_GetResult.__import_type_support__() if _joint_trajectory.Metaclass_JointTrajectory_FeedbackMessage._TYPE_SUPPORT is None: _joint_trajectory.Metaclass_JointTrajectory_FeedbackMessage.__import_type_support__() class JointTrajectory(metaclass=Metaclass_JointTrajectory): # The goal message defined in the action definition. from control_msgs.action._joint_trajectory import JointTrajectory_Goal as Goal # The result message defined in the action definition. from control_msgs.action._joint_trajectory import JointTrajectory_Result as Result # The feedback message defined in the action definition. from control_msgs.action._joint_trajectory import JointTrajectory_Feedback as Feedback class Impl: # The send_goal service using a wrapped version of the goal message as a request. from control_msgs.action._joint_trajectory import JointTrajectory_SendGoal as SendGoalService # The get_result service using a wrapped version of the result message as a response. from control_msgs.action._joint_trajectory import JointTrajectory_GetResult as GetResultService # The feedback message with generic fields which wraps the feedback message. from control_msgs.action._joint_trajectory import JointTrajectory_FeedbackMessage as FeedbackMessage # The generic service to cancel a goal. from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService # The generic message for get the status of a goal. from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage def __init__(self): raise NotImplementedError('Action classes can not be instantiated')
45,957
Python
37.717776
134
0.595274
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_point_head_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:action/PointHead.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/action/detail/point_head__struct.h" #include "control_msgs/action/detail/point_head__functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_IMPORT bool geometry_msgs__msg__point_stamped__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * geometry_msgs__msg__point_stamped__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_IMPORT bool geometry_msgs__msg__vector3__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * geometry_msgs__msg__vector3__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_IMPORT bool builtin_interfaces__msg__duration__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * builtin_interfaces__msg__duration__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__point_head__goal__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[47]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._point_head.PointHead_Goal", full_classname_dest, 46) == 0); } control_msgs__action__PointHead_Goal * ros_message = _ros_message; { // target PyObject * field = PyObject_GetAttrString(_pymsg, "target"); if (!field) { return false; } if (!geometry_msgs__msg__point_stamped__convert_from_py(field, &ros_message->target)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // pointing_axis PyObject * field = PyObject_GetAttrString(_pymsg, "pointing_axis"); if (!field) { return false; } if (!geometry_msgs__msg__vector3__convert_from_py(field, &ros_message->pointing_axis)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // pointing_frame PyObject * field = PyObject_GetAttrString(_pymsg, "pointing_frame"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->pointing_frame, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } { // min_duration PyObject * field = PyObject_GetAttrString(_pymsg, "min_duration"); if (!field) { return false; } if (!builtin_interfaces__msg__duration__convert_from_py(field, &ros_message->min_duration)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // max_velocity PyObject * field = PyObject_GetAttrString(_pymsg, "max_velocity"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->max_velocity = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__point_head__goal__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PointHead_Goal */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_Goal"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__PointHead_Goal * ros_message = (control_msgs__action__PointHead_Goal *)raw_ros_message; { // target PyObject * field = NULL; field = geometry_msgs__msg__point_stamped__convert_to_py(&ros_message->target); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "target", field); Py_DECREF(field); if (rc) { return NULL; } } } { // pointing_axis PyObject * field = NULL; field = geometry_msgs__msg__vector3__convert_to_py(&ros_message->pointing_axis); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "pointing_axis", field); Py_DECREF(field); if (rc) { return NULL; } } } { // pointing_frame PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->pointing_frame.data, strlen(ros_message->pointing_frame.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "pointing_frame", field); Py_DECREF(field); if (rc) { return NULL; } } } { // min_duration PyObject * field = NULL; field = builtin_interfaces__msg__duration__convert_to_py(&ros_message->min_duration); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "min_duration", field); Py_DECREF(field); if (rc) { return NULL; } } } { // max_velocity PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->max_velocity); { int rc = PyObject_SetAttrString(_pymessage, "max_velocity", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/point_head__struct.h" // already included above // #include "control_msgs/action/detail/point_head__functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__point_head__result__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[49]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._point_head.PointHead_Result", full_classname_dest, 48) == 0); } control_msgs__action__PointHead_Result * ros_message = _ros_message; ros_message->structure_needs_at_least_one_member = 0; return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__point_head__result__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PointHead_Result */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_Result"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } (void)raw_ros_message; // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/point_head__struct.h" // already included above // #include "control_msgs/action/detail/point_head__functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__point_head__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[51]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._point_head.PointHead_Feedback", full_classname_dest, 50) == 0); } control_msgs__action__PointHead_Feedback * ros_message = _ros_message; { // pointing_angle_error PyObject * field = PyObject_GetAttrString(_pymsg, "pointing_angle_error"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->pointing_angle_error = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__point_head__feedback__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PointHead_Feedback */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_Feedback"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__PointHead_Feedback * ros_message = (control_msgs__action__PointHead_Feedback *)raw_ros_message; { // pointing_angle_error PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->pointing_angle_error); { int rc = PyObject_SetAttrString(_pymessage, "pointing_angle_error", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/point_head__struct.h" // already included above // #include "control_msgs/action/detail/point_head__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); bool control_msgs__action__point_head__goal__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__point_head__goal__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__point_head__send_goal__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[59]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._point_head.PointHead_SendGoal_Request", full_classname_dest, 58) == 0); } control_msgs__action__PointHead_SendGoal_Request * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // goal PyObject * field = PyObject_GetAttrString(_pymsg, "goal"); if (!field) { return false; } if (!control_msgs__action__point_head__goal__convert_from_py(field, &ros_message->goal)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__point_head__send_goal__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PointHead_SendGoal_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_SendGoal_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__PointHead_SendGoal_Request * ros_message = (control_msgs__action__PointHead_SendGoal_Request *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } { // goal PyObject * field = NULL; field = control_msgs__action__point_head__goal__convert_to_py(&ros_message->goal); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/point_head__struct.h" // already included above // #include "control_msgs/action/detail/point_head__functions.h" ROSIDL_GENERATOR_C_IMPORT bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__point_head__send_goal__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[60]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._point_head.PointHead_SendGoal_Response", full_classname_dest, 59) == 0); } control_msgs__action__PointHead_SendGoal_Response * ros_message = _ros_message; { // accepted PyObject * field = PyObject_GetAttrString(_pymsg, "accepted"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->accepted = (Py_True == field); Py_DECREF(field); } { // stamp PyObject * field = PyObject_GetAttrString(_pymsg, "stamp"); if (!field) { return false; } if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->stamp)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__point_head__send_goal__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PointHead_SendGoal_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_SendGoal_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__PointHead_SendGoal_Response * ros_message = (control_msgs__action__PointHead_SendGoal_Response *)raw_ros_message; { // accepted PyObject * field = NULL; field = PyBool_FromLong(ros_message->accepted ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "accepted", field); Py_DECREF(field); if (rc) { return NULL; } } } { // stamp PyObject * field = NULL; field = builtin_interfaces__msg__time__convert_to_py(&ros_message->stamp); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "stamp", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/point_head__struct.h" // already included above // #include "control_msgs/action/detail/point_head__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__point_head__get_result__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[60]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._point_head.PointHead_GetResult_Request", full_classname_dest, 59) == 0); } control_msgs__action__PointHead_GetResult_Request * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__point_head__get_result__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PointHead_GetResult_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_GetResult_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__PointHead_GetResult_Request * ros_message = (control_msgs__action__PointHead_GetResult_Request *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/point_head__struct.h" // already included above // #include "control_msgs/action/detail/point_head__functions.h" bool control_msgs__action__point_head__result__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__point_head__result__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__point_head__get_result__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[61]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._point_head.PointHead_GetResult_Response", full_classname_dest, 60) == 0); } control_msgs__action__PointHead_GetResult_Response * ros_message = _ros_message; { // status PyObject * field = PyObject_GetAttrString(_pymsg, "status"); if (!field) { return false; } assert(PyLong_Check(field)); ros_message->status = (int8_t)PyLong_AsLong(field); Py_DECREF(field); } { // result PyObject * field = PyObject_GetAttrString(_pymsg, "result"); if (!field) { return false; } if (!control_msgs__action__point_head__result__convert_from_py(field, &ros_message->result)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__point_head__get_result__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PointHead_GetResult_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_GetResult_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__PointHead_GetResult_Response * ros_message = (control_msgs__action__PointHead_GetResult_Response *)raw_ros_message; { // status PyObject * field = NULL; field = PyLong_FromLong(ros_message->status); { int rc = PyObject_SetAttrString(_pymessage, "status", field); Py_DECREF(field); if (rc) { return NULL; } } } { // result PyObject * field = NULL; field = control_msgs__action__point_head__result__convert_to_py(&ros_message->result); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "result", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/point_head__struct.h" // already included above // #include "control_msgs/action/detail/point_head__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); bool control_msgs__action__point_head__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__point_head__feedback__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__point_head__feedback_message__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[58]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._point_head.PointHead_FeedbackMessage", full_classname_dest, 57) == 0); } control_msgs__action__PointHead_FeedbackMessage * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // feedback PyObject * field = PyObject_GetAttrString(_pymsg, "feedback"); if (!field) { return false; } if (!control_msgs__action__point_head__feedback__convert_from_py(field, &ros_message->feedback)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__point_head__feedback_message__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PointHead_FeedbackMessage */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._point_head"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PointHead_FeedbackMessage"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__PointHead_FeedbackMessage * ros_message = (control_msgs__action__PointHead_FeedbackMessage *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } { // feedback PyObject * field = NULL; field = control_msgs__action__point_head__feedback__convert_to_py(&ros_message->feedback); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "feedback", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
32,869
C
31.739044
139
0.64033
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/__init__.py
from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory # noqa: F401 from control_msgs.action._gripper_command import GripperCommand # noqa: F401 from control_msgs.action._joint_trajectory import JointTrajectory # noqa: F401 from control_msgs.action._point_head import PointHead # noqa: F401 from control_msgs.action._single_joint_position import SingleJointPosition # noqa: F401
408
Python
67.166655
92
0.811275
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_gripper_command_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:action/GripperCommand.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/action/detail/gripper_command__struct.h" #include "control_msgs/action/detail/gripper_command__functions.h" bool control_msgs__msg__gripper_command__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__msg__gripper_command__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__gripper_command__goal__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[57]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._gripper_command.GripperCommand_Goal", full_classname_dest, 56) == 0); } control_msgs__action__GripperCommand_Goal * ros_message = _ros_message; { // command PyObject * field = PyObject_GetAttrString(_pymsg, "command"); if (!field) { return false; } if (!control_msgs__msg__gripper_command__convert_from_py(field, &ros_message->command)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__gripper_command__goal__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GripperCommand_Goal */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_Goal"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__GripperCommand_Goal * ros_message = (control_msgs__action__GripperCommand_Goal *)raw_ros_message; { // command PyObject * field = NULL; field = control_msgs__msg__gripper_command__convert_to_py(&ros_message->command); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "command", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/gripper_command__struct.h" // already included above // #include "control_msgs/action/detail/gripper_command__functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__gripper_command__result__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[59]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._gripper_command.GripperCommand_Result", full_classname_dest, 58) == 0); } control_msgs__action__GripperCommand_Result * ros_message = _ros_message; { // position PyObject * field = PyObject_GetAttrString(_pymsg, "position"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->position = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // effort PyObject * field = PyObject_GetAttrString(_pymsg, "effort"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->effort = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // stalled PyObject * field = PyObject_GetAttrString(_pymsg, "stalled"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->stalled = (Py_True == field); Py_DECREF(field); } { // reached_goal PyObject * field = PyObject_GetAttrString(_pymsg, "reached_goal"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->reached_goal = (Py_True == field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__gripper_command__result__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GripperCommand_Result */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_Result"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__GripperCommand_Result * ros_message = (control_msgs__action__GripperCommand_Result *)raw_ros_message; { // position PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->position); { int rc = PyObject_SetAttrString(_pymessage, "position", field); Py_DECREF(field); if (rc) { return NULL; } } } { // effort PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->effort); { int rc = PyObject_SetAttrString(_pymessage, "effort", field); Py_DECREF(field); if (rc) { return NULL; } } } { // stalled PyObject * field = NULL; field = PyBool_FromLong(ros_message->stalled ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "stalled", field); Py_DECREF(field); if (rc) { return NULL; } } } { // reached_goal PyObject * field = NULL; field = PyBool_FromLong(ros_message->reached_goal ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "reached_goal", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/gripper_command__struct.h" // already included above // #include "control_msgs/action/detail/gripper_command__functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__gripper_command__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[61]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._gripper_command.GripperCommand_Feedback", full_classname_dest, 60) == 0); } control_msgs__action__GripperCommand_Feedback * ros_message = _ros_message; { // position PyObject * field = PyObject_GetAttrString(_pymsg, "position"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->position = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // effort PyObject * field = PyObject_GetAttrString(_pymsg, "effort"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->effort = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // stalled PyObject * field = PyObject_GetAttrString(_pymsg, "stalled"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->stalled = (Py_True == field); Py_DECREF(field); } { // reached_goal PyObject * field = PyObject_GetAttrString(_pymsg, "reached_goal"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->reached_goal = (Py_True == field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__gripper_command__feedback__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GripperCommand_Feedback */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_Feedback"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__GripperCommand_Feedback * ros_message = (control_msgs__action__GripperCommand_Feedback *)raw_ros_message; { // position PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->position); { int rc = PyObject_SetAttrString(_pymessage, "position", field); Py_DECREF(field); if (rc) { return NULL; } } } { // effort PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->effort); { int rc = PyObject_SetAttrString(_pymessage, "effort", field); Py_DECREF(field); if (rc) { return NULL; } } } { // stalled PyObject * field = NULL; field = PyBool_FromLong(ros_message->stalled ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "stalled", field); Py_DECREF(field); if (rc) { return NULL; } } } { // reached_goal PyObject * field = NULL; field = PyBool_FromLong(ros_message->reached_goal ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "reached_goal", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/gripper_command__struct.h" // already included above // #include "control_msgs/action/detail/gripper_command__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); bool control_msgs__action__gripper_command__goal__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__gripper_command__goal__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__gripper_command__send_goal__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[69]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._gripper_command.GripperCommand_SendGoal_Request", full_classname_dest, 68) == 0); } control_msgs__action__GripperCommand_SendGoal_Request * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // goal PyObject * field = PyObject_GetAttrString(_pymsg, "goal"); if (!field) { return false; } if (!control_msgs__action__gripper_command__goal__convert_from_py(field, &ros_message->goal)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__gripper_command__send_goal__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GripperCommand_SendGoal_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_SendGoal_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__GripperCommand_SendGoal_Request * ros_message = (control_msgs__action__GripperCommand_SendGoal_Request *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } { // goal PyObject * field = NULL; field = control_msgs__action__gripper_command__goal__convert_to_py(&ros_message->goal); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/gripper_command__struct.h" // already included above // #include "control_msgs/action/detail/gripper_command__functions.h" ROSIDL_GENERATOR_C_IMPORT bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__gripper_command__send_goal__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[70]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._gripper_command.GripperCommand_SendGoal_Response", full_classname_dest, 69) == 0); } control_msgs__action__GripperCommand_SendGoal_Response * ros_message = _ros_message; { // accepted PyObject * field = PyObject_GetAttrString(_pymsg, "accepted"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->accepted = (Py_True == field); Py_DECREF(field); } { // stamp PyObject * field = PyObject_GetAttrString(_pymsg, "stamp"); if (!field) { return false; } if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->stamp)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__gripper_command__send_goal__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GripperCommand_SendGoal_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_SendGoal_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__GripperCommand_SendGoal_Response * ros_message = (control_msgs__action__GripperCommand_SendGoal_Response *)raw_ros_message; { // accepted PyObject * field = NULL; field = PyBool_FromLong(ros_message->accepted ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "accepted", field); Py_DECREF(field); if (rc) { return NULL; } } } { // stamp PyObject * field = NULL; field = builtin_interfaces__msg__time__convert_to_py(&ros_message->stamp); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "stamp", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/gripper_command__struct.h" // already included above // #include "control_msgs/action/detail/gripper_command__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__gripper_command__get_result__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[70]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._gripper_command.GripperCommand_GetResult_Request", full_classname_dest, 69) == 0); } control_msgs__action__GripperCommand_GetResult_Request * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__gripper_command__get_result__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GripperCommand_GetResult_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_GetResult_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__GripperCommand_GetResult_Request * ros_message = (control_msgs__action__GripperCommand_GetResult_Request *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/gripper_command__struct.h" // already included above // #include "control_msgs/action/detail/gripper_command__functions.h" bool control_msgs__action__gripper_command__result__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__gripper_command__result__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__gripper_command__get_result__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[71]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._gripper_command.GripperCommand_GetResult_Response", full_classname_dest, 70) == 0); } control_msgs__action__GripperCommand_GetResult_Response * ros_message = _ros_message; { // status PyObject * field = PyObject_GetAttrString(_pymsg, "status"); if (!field) { return false; } assert(PyLong_Check(field)); ros_message->status = (int8_t)PyLong_AsLong(field); Py_DECREF(field); } { // result PyObject * field = PyObject_GetAttrString(_pymsg, "result"); if (!field) { return false; } if (!control_msgs__action__gripper_command__result__convert_from_py(field, &ros_message->result)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__gripper_command__get_result__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GripperCommand_GetResult_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_GetResult_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__GripperCommand_GetResult_Response * ros_message = (control_msgs__action__GripperCommand_GetResult_Response *)raw_ros_message; { // status PyObject * field = NULL; field = PyLong_FromLong(ros_message->status); { int rc = PyObject_SetAttrString(_pymessage, "status", field); Py_DECREF(field); if (rc) { return NULL; } } } { // result PyObject * field = NULL; field = control_msgs__action__gripper_command__result__convert_to_py(&ros_message->result); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "result", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/gripper_command__struct.h" // already included above // #include "control_msgs/action/detail/gripper_command__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); bool control_msgs__action__gripper_command__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__gripper_command__feedback__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__gripper_command__feedback_message__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[68]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._gripper_command.GripperCommand_FeedbackMessage", full_classname_dest, 67) == 0); } control_msgs__action__GripperCommand_FeedbackMessage * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // feedback PyObject * field = PyObject_GetAttrString(_pymsg, "feedback"); if (!field) { return false; } if (!control_msgs__action__gripper_command__feedback__convert_from_py(field, &ros_message->feedback)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__gripper_command__feedback_message__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GripperCommand_FeedbackMessage */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._gripper_command"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand_FeedbackMessage"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__GripperCommand_FeedbackMessage * ros_message = (control_msgs__action__GripperCommand_FeedbackMessage *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } { // feedback PyObject * field = NULL; field = control_msgs__action__gripper_command__feedback__convert_to_py(&ros_message->feedback); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "feedback", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
33,597
C
31.682879
149
0.640414
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_gripper_command.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:action/GripperCommand.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GripperCommand_Goal(type): """Metaclass of message 'GripperCommand_Goal'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_Goal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__goal cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__goal cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__goal cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__goal cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__goal from control_msgs.msg import GripperCommand if GripperCommand.__class__._TYPE_SUPPORT is None: GripperCommand.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GripperCommand_Goal(metaclass=Metaclass_GripperCommand_Goal): """Message class 'GripperCommand_Goal'.""" __slots__ = [ '_command', ] _fields_and_field_types = { 'command': 'control_msgs/GripperCommand', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'GripperCommand'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from control_msgs.msg import GripperCommand self.command = kwargs.get('command', GripperCommand()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.command != other.command: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def command(self): """Message field 'command'.""" return self._command @command.setter def command(self, value): if __debug__: from control_msgs.msg import GripperCommand assert \ isinstance(value, GripperCommand), \ "The 'command' field must be a sub message of type 'GripperCommand'" self._command = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_Result(type): """Metaclass of message 'GripperCommand_Result'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_Result') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__result cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__result cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__result cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__result cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__result @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GripperCommand_Result(metaclass=Metaclass_GripperCommand_Result): """Message class 'GripperCommand_Result'.""" __slots__ = [ '_position', '_effort', '_stalled', '_reached_goal', ] _fields_and_field_types = { 'position': 'double', 'effort': 'double', 'stalled': 'boolean', 'reached_goal': 'boolean', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.position = kwargs.get('position', float()) self.effort = kwargs.get('effort', float()) self.stalled = kwargs.get('stalled', bool()) self.reached_goal = kwargs.get('reached_goal', bool()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.position != other.position: return False if self.effort != other.effort: return False if self.stalled != other.stalled: return False if self.reached_goal != other.reached_goal: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def effort(self): """Message field 'effort'.""" return self._effort @effort.setter def effort(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'effort' field must be of type 'float'" self._effort = value @property def stalled(self): """Message field 'stalled'.""" return self._stalled @stalled.setter def stalled(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'stalled' field must be of type 'bool'" self._stalled = value @property def reached_goal(self): """Message field 'reached_goal'.""" return self._reached_goal @reached_goal.setter def reached_goal(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'reached_goal' field must be of type 'bool'" self._reached_goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_Feedback(type): """Metaclass of message 'GripperCommand_Feedback'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_Feedback') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__feedback cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__feedback cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__feedback cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__feedback cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__feedback @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GripperCommand_Feedback(metaclass=Metaclass_GripperCommand_Feedback): """Message class 'GripperCommand_Feedback'.""" __slots__ = [ '_position', '_effort', '_stalled', '_reached_goal', ] _fields_and_field_types = { 'position': 'double', 'effort': 'double', 'stalled': 'boolean', 'reached_goal': 'boolean', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.position = kwargs.get('position', float()) self.effort = kwargs.get('effort', float()) self.stalled = kwargs.get('stalled', bool()) self.reached_goal = kwargs.get('reached_goal', bool()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.position != other.position: return False if self.effort != other.effort: return False if self.stalled != other.stalled: return False if self.reached_goal != other.reached_goal: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def effort(self): """Message field 'effort'.""" return self._effort @effort.setter def effort(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'effort' field must be of type 'float'" self._effort = value @property def stalled(self): """Message field 'stalled'.""" return self._stalled @stalled.setter def stalled(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'stalled' field must be of type 'bool'" self._stalled = value @property def reached_goal(self): """Message field 'reached_goal'.""" return self._reached_goal @reached_goal.setter def reached_goal(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'reached_goal' field must be of type 'bool'" self._reached_goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_SendGoal_Request(type): """Metaclass of message 'GripperCommand_SendGoal_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_SendGoal_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__send_goal__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__send_goal__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__send_goal__request cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__send_goal__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__send_goal__request from control_msgs.action import GripperCommand if GripperCommand.Goal.__class__._TYPE_SUPPORT is None: GripperCommand.Goal.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GripperCommand_SendGoal_Request(metaclass=Metaclass_GripperCommand_SendGoal_Request): """Message class 'GripperCommand_SendGoal_Request'.""" __slots__ = [ '_goal_id', '_goal', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'goal': 'control_msgs/GripperCommand_Goal', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'GripperCommand_Goal'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._gripper_command import GripperCommand_Goal self.goal = kwargs.get('goal', GripperCommand_Goal()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False if self.goal != other.goal: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def goal(self): """Message field 'goal'.""" return self._goal @goal.setter def goal(self, value): if __debug__: from control_msgs.action._gripper_command import GripperCommand_Goal assert \ isinstance(value, GripperCommand_Goal), \ "The 'goal' field must be a sub message of type 'GripperCommand_Goal'" self._goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_SendGoal_Response(type): """Metaclass of message 'GripperCommand_SendGoal_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_SendGoal_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__send_goal__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__send_goal__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__send_goal__response cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__send_goal__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__send_goal__response from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GripperCommand_SendGoal_Response(metaclass=Metaclass_GripperCommand_SendGoal_Response): """Message class 'GripperCommand_SendGoal_Response'.""" __slots__ = [ '_accepted', '_stamp', ] _fields_and_field_types = { 'accepted': 'boolean', 'stamp': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.accepted = kwargs.get('accepted', bool()) from builtin_interfaces.msg import Time self.stamp = kwargs.get('stamp', Time()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.accepted != other.accepted: return False if self.stamp != other.stamp: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def accepted(self): """Message field 'accepted'.""" return self._accepted @accepted.setter def accepted(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'accepted' field must be of type 'bool'" self._accepted = value @property def stamp(self): """Message field 'stamp'.""" return self._stamp @stamp.setter def stamp(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'stamp' field must be a sub message of type 'Time'" self._stamp = value class Metaclass_GripperCommand_SendGoal(type): """Metaclass of service 'GripperCommand_SendGoal'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_SendGoal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__gripper_command__send_goal from control_msgs.action import _gripper_command if _gripper_command.Metaclass_GripperCommand_SendGoal_Request._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_SendGoal_Request.__import_type_support__() if _gripper_command.Metaclass_GripperCommand_SendGoal_Response._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_SendGoal_Response.__import_type_support__() class GripperCommand_SendGoal(metaclass=Metaclass_GripperCommand_SendGoal): from control_msgs.action._gripper_command import GripperCommand_SendGoal_Request as Request from control_msgs.action._gripper_command import GripperCommand_SendGoal_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_GetResult_Request(type): """Metaclass of message 'GripperCommand_GetResult_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_GetResult_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__get_result__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__get_result__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__get_result__request cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__get_result__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__get_result__request from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GripperCommand_GetResult_Request(metaclass=Metaclass_GripperCommand_GetResult_Request): """Message class 'GripperCommand_GetResult_Request'.""" __slots__ = [ '_goal_id', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_GetResult_Response(type): """Metaclass of message 'GripperCommand_GetResult_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_GetResult_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__get_result__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__get_result__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__get_result__response cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__get_result__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__get_result__response from control_msgs.action import GripperCommand if GripperCommand.Result.__class__._TYPE_SUPPORT is None: GripperCommand.Result.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GripperCommand_GetResult_Response(metaclass=Metaclass_GripperCommand_GetResult_Response): """Message class 'GripperCommand_GetResult_Response'.""" __slots__ = [ '_status', '_result', ] _fields_and_field_types = { 'status': 'int8', 'result': 'control_msgs/GripperCommand_Result', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int8'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'GripperCommand_Result'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.status = kwargs.get('status', int()) from control_msgs.action._gripper_command import GripperCommand_Result self.result = kwargs.get('result', GripperCommand_Result()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.status != other.status: return False if self.result != other.result: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def status(self): """Message field 'status'.""" return self._status @status.setter def status(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'status' field must be of type 'int'" assert value >= -128 and value < 128, \ "The 'status' field must be an integer in [-128, 127]" self._status = value @property def result(self): """Message field 'result'.""" return self._result @result.setter def result(self, value): if __debug__: from control_msgs.action._gripper_command import GripperCommand_Result assert \ isinstance(value, GripperCommand_Result), \ "The 'result' field must be a sub message of type 'GripperCommand_Result'" self._result = value class Metaclass_GripperCommand_GetResult(type): """Metaclass of service 'GripperCommand_GetResult'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_GetResult') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__gripper_command__get_result from control_msgs.action import _gripper_command if _gripper_command.Metaclass_GripperCommand_GetResult_Request._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_GetResult_Request.__import_type_support__() if _gripper_command.Metaclass_GripperCommand_GetResult_Response._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_GetResult_Response.__import_type_support__() class GripperCommand_GetResult(metaclass=Metaclass_GripperCommand_GetResult): from control_msgs.action._gripper_command import GripperCommand_GetResult_Request as Request from control_msgs.action._gripper_command import GripperCommand_GetResult_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GripperCommand_FeedbackMessage(type): """Metaclass of message 'GripperCommand_FeedbackMessage'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand_FeedbackMessage') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__gripper_command__feedback_message cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__gripper_command__feedback_message cls._CONVERT_TO_PY = module.convert_to_py_msg__action__gripper_command__feedback_message cls._TYPE_SUPPORT = module.type_support_msg__action__gripper_command__feedback_message cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__gripper_command__feedback_message from control_msgs.action import GripperCommand if GripperCommand.Feedback.__class__._TYPE_SUPPORT is None: GripperCommand.Feedback.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GripperCommand_FeedbackMessage(metaclass=Metaclass_GripperCommand_FeedbackMessage): """Message class 'GripperCommand_FeedbackMessage'.""" __slots__ = [ '_goal_id', '_feedback', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'feedback': 'control_msgs/GripperCommand_Feedback', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'GripperCommand_Feedback'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._gripper_command import GripperCommand_Feedback self.feedback = kwargs.get('feedback', GripperCommand_Feedback()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False if self.feedback != other.feedback: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def feedback(self): """Message field 'feedback'.""" return self._feedback @feedback.setter def feedback(self, value): if __debug__: from control_msgs.action._gripper_command import GripperCommand_Feedback assert \ isinstance(value, GripperCommand_Feedback), \ "The 'feedback' field must be a sub message of type 'GripperCommand_Feedback'" self._feedback = value class Metaclass_GripperCommand(type): """Metaclass of action 'GripperCommand'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.GripperCommand') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_action__action__gripper_command from action_msgs.msg import _goal_status_array if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None: _goal_status_array.Metaclass_GoalStatusArray.__import_type_support__() from action_msgs.srv import _cancel_goal if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None: _cancel_goal.Metaclass_CancelGoal.__import_type_support__() from control_msgs.action import _gripper_command if _gripper_command.Metaclass_GripperCommand_SendGoal._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_SendGoal.__import_type_support__() if _gripper_command.Metaclass_GripperCommand_GetResult._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_GetResult.__import_type_support__() if _gripper_command.Metaclass_GripperCommand_FeedbackMessage._TYPE_SUPPORT is None: _gripper_command.Metaclass_GripperCommand_FeedbackMessage.__import_type_support__() class GripperCommand(metaclass=Metaclass_GripperCommand): # The goal message defined in the action definition. from control_msgs.action._gripper_command import GripperCommand_Goal as Goal # The result message defined in the action definition. from control_msgs.action._gripper_command import GripperCommand_Result as Result # The feedback message defined in the action definition. from control_msgs.action._gripper_command import GripperCommand_Feedback as Feedback class Impl: # The send_goal service using a wrapped version of the goal message as a request. from control_msgs.action._gripper_command import GripperCommand_SendGoal as SendGoalService # The get_result service using a wrapped version of the result message as a response. from control_msgs.action._gripper_command import GripperCommand_GetResult as GetResultService # The feedback message with generic fields which wraps the feedback message. from control_msgs.action._gripper_command import GripperCommand_FeedbackMessage as FeedbackMessage # The generic service to cancel a goal. from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService # The generic message for get the status of a goal. from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage def __init__(self): raise NotImplementedError('Action classes can not be instantiated')
50,417
Python
36.653473
134
0.587718
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_single_joint_position.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:action/SingleJointPosition.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_SingleJointPosition_Goal(type): """Metaclass of message 'SingleJointPosition_Goal'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_Goal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__goal cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__goal cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__goal cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__goal cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__goal from builtin_interfaces.msg import Duration if Duration.__class__._TYPE_SUPPORT is None: Duration.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class SingleJointPosition_Goal(metaclass=Metaclass_SingleJointPosition_Goal): """Message class 'SingleJointPosition_Goal'.""" __slots__ = [ '_position', '_min_duration', '_max_velocity', ] _fields_and_field_types = { 'position': 'double', 'min_duration': 'builtin_interfaces/Duration', 'max_velocity': 'double', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.position = kwargs.get('position', float()) from builtin_interfaces.msg import Duration self.min_duration = kwargs.get('min_duration', Duration()) self.max_velocity = kwargs.get('max_velocity', float()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.position != other.position: return False if self.min_duration != other.min_duration: return False if self.max_velocity != other.max_velocity: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def min_duration(self): """Message field 'min_duration'.""" return self._min_duration @min_duration.setter def min_duration(self, value): if __debug__: from builtin_interfaces.msg import Duration assert \ isinstance(value, Duration), \ "The 'min_duration' field must be a sub message of type 'Duration'" self._min_duration = value @property def max_velocity(self): """Message field 'max_velocity'.""" return self._max_velocity @max_velocity.setter def max_velocity(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'max_velocity' field must be of type 'float'" self._max_velocity = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_Result(type): """Metaclass of message 'SingleJointPosition_Result'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_Result') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__result cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__result cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__result cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__result cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__result @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class SingleJointPosition_Result(metaclass=Metaclass_SingleJointPosition_Result): """Message class 'SingleJointPosition_Result'.""" __slots__ = [ ] _fields_and_field_types = { } SLOT_TYPES = ( ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_Feedback(type): """Metaclass of message 'SingleJointPosition_Feedback'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_Feedback') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__feedback cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__feedback cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__feedback cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__feedback cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__feedback from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class SingleJointPosition_Feedback(metaclass=Metaclass_SingleJointPosition_Feedback): """Message class 'SingleJointPosition_Feedback'.""" __slots__ = [ '_header', '_position', '_velocity', '_error', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'position': 'double', 'velocity': 'double', 'error': 'double', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.position = kwargs.get('position', float()) self.velocity = kwargs.get('velocity', float()) self.error = kwargs.get('error', float()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.header != other.header: return False if self.position != other.position: return False if self.velocity != other.velocity: return False if self.error != other.error: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def velocity(self): """Message field 'velocity'.""" return self._velocity @velocity.setter def velocity(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'velocity' field must be of type 'float'" self._velocity = value @property def error(self): """Message field 'error'.""" return self._error @error.setter def error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'error' field must be of type 'float'" self._error = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_SendGoal_Request(type): """Metaclass of message 'SingleJointPosition_SendGoal_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_SendGoal_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__send_goal__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__send_goal__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__send_goal__request cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__send_goal__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__send_goal__request from control_msgs.action import SingleJointPosition if SingleJointPosition.Goal.__class__._TYPE_SUPPORT is None: SingleJointPosition.Goal.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class SingleJointPosition_SendGoal_Request(metaclass=Metaclass_SingleJointPosition_SendGoal_Request): """Message class 'SingleJointPosition_SendGoal_Request'.""" __slots__ = [ '_goal_id', '_goal', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'goal': 'control_msgs/SingleJointPosition_Goal', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'SingleJointPosition_Goal'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._single_joint_position import SingleJointPosition_Goal self.goal = kwargs.get('goal', SingleJointPosition_Goal()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False if self.goal != other.goal: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def goal(self): """Message field 'goal'.""" return self._goal @goal.setter def goal(self, value): if __debug__: from control_msgs.action._single_joint_position import SingleJointPosition_Goal assert \ isinstance(value, SingleJointPosition_Goal), \ "The 'goal' field must be a sub message of type 'SingleJointPosition_Goal'" self._goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_SendGoal_Response(type): """Metaclass of message 'SingleJointPosition_SendGoal_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_SendGoal_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__send_goal__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__send_goal__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__send_goal__response cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__send_goal__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__send_goal__response from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class SingleJointPosition_SendGoal_Response(metaclass=Metaclass_SingleJointPosition_SendGoal_Response): """Message class 'SingleJointPosition_SendGoal_Response'.""" __slots__ = [ '_accepted', '_stamp', ] _fields_and_field_types = { 'accepted': 'boolean', 'stamp': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.accepted = kwargs.get('accepted', bool()) from builtin_interfaces.msg import Time self.stamp = kwargs.get('stamp', Time()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.accepted != other.accepted: return False if self.stamp != other.stamp: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def accepted(self): """Message field 'accepted'.""" return self._accepted @accepted.setter def accepted(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'accepted' field must be of type 'bool'" self._accepted = value @property def stamp(self): """Message field 'stamp'.""" return self._stamp @stamp.setter def stamp(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'stamp' field must be a sub message of type 'Time'" self._stamp = value class Metaclass_SingleJointPosition_SendGoal(type): """Metaclass of service 'SingleJointPosition_SendGoal'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_SendGoal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__single_joint_position__send_goal from control_msgs.action import _single_joint_position if _single_joint_position.Metaclass_SingleJointPosition_SendGoal_Request._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_SendGoal_Request.__import_type_support__() if _single_joint_position.Metaclass_SingleJointPosition_SendGoal_Response._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_SendGoal_Response.__import_type_support__() class SingleJointPosition_SendGoal(metaclass=Metaclass_SingleJointPosition_SendGoal): from control_msgs.action._single_joint_position import SingleJointPosition_SendGoal_Request as Request from control_msgs.action._single_joint_position import SingleJointPosition_SendGoal_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_GetResult_Request(type): """Metaclass of message 'SingleJointPosition_GetResult_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_GetResult_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__get_result__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__get_result__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__get_result__request cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__get_result__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__get_result__request from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class SingleJointPosition_GetResult_Request(metaclass=Metaclass_SingleJointPosition_GetResult_Request): """Message class 'SingleJointPosition_GetResult_Request'.""" __slots__ = [ '_goal_id', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_GetResult_Response(type): """Metaclass of message 'SingleJointPosition_GetResult_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_GetResult_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__get_result__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__get_result__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__get_result__response cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__get_result__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__get_result__response from control_msgs.action import SingleJointPosition if SingleJointPosition.Result.__class__._TYPE_SUPPORT is None: SingleJointPosition.Result.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class SingleJointPosition_GetResult_Response(metaclass=Metaclass_SingleJointPosition_GetResult_Response): """Message class 'SingleJointPosition_GetResult_Response'.""" __slots__ = [ '_status', '_result', ] _fields_and_field_types = { 'status': 'int8', 'result': 'control_msgs/SingleJointPosition_Result', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int8'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'SingleJointPosition_Result'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.status = kwargs.get('status', int()) from control_msgs.action._single_joint_position import SingleJointPosition_Result self.result = kwargs.get('result', SingleJointPosition_Result()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.status != other.status: return False if self.result != other.result: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def status(self): """Message field 'status'.""" return self._status @status.setter def status(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'status' field must be of type 'int'" assert value >= -128 and value < 128, \ "The 'status' field must be an integer in [-128, 127]" self._status = value @property def result(self): """Message field 'result'.""" return self._result @result.setter def result(self, value): if __debug__: from control_msgs.action._single_joint_position import SingleJointPosition_Result assert \ isinstance(value, SingleJointPosition_Result), \ "The 'result' field must be a sub message of type 'SingleJointPosition_Result'" self._result = value class Metaclass_SingleJointPosition_GetResult(type): """Metaclass of service 'SingleJointPosition_GetResult'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_GetResult') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__single_joint_position__get_result from control_msgs.action import _single_joint_position if _single_joint_position.Metaclass_SingleJointPosition_GetResult_Request._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_GetResult_Request.__import_type_support__() if _single_joint_position.Metaclass_SingleJointPosition_GetResult_Response._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_GetResult_Response.__import_type_support__() class SingleJointPosition_GetResult(metaclass=Metaclass_SingleJointPosition_GetResult): from control_msgs.action._single_joint_position import SingleJointPosition_GetResult_Request as Request from control_msgs.action._single_joint_position import SingleJointPosition_GetResult_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SingleJointPosition_FeedbackMessage(type): """Metaclass of message 'SingleJointPosition_FeedbackMessage'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition_FeedbackMessage') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__single_joint_position__feedback_message cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__single_joint_position__feedback_message cls._CONVERT_TO_PY = module.convert_to_py_msg__action__single_joint_position__feedback_message cls._TYPE_SUPPORT = module.type_support_msg__action__single_joint_position__feedback_message cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__single_joint_position__feedback_message from control_msgs.action import SingleJointPosition if SingleJointPosition.Feedback.__class__._TYPE_SUPPORT is None: SingleJointPosition.Feedback.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class SingleJointPosition_FeedbackMessage(metaclass=Metaclass_SingleJointPosition_FeedbackMessage): """Message class 'SingleJointPosition_FeedbackMessage'.""" __slots__ = [ '_goal_id', '_feedback', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'feedback': 'control_msgs/SingleJointPosition_Feedback', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'SingleJointPosition_Feedback'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._single_joint_position import SingleJointPosition_Feedback self.feedback = kwargs.get('feedback', SingleJointPosition_Feedback()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False if self.feedback != other.feedback: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def feedback(self): """Message field 'feedback'.""" return self._feedback @feedback.setter def feedback(self, value): if __debug__: from control_msgs.action._single_joint_position import SingleJointPosition_Feedback assert \ isinstance(value, SingleJointPosition_Feedback), \ "The 'feedback' field must be a sub message of type 'SingleJointPosition_Feedback'" self._feedback = value class Metaclass_SingleJointPosition(type): """Metaclass of action 'SingleJointPosition'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.SingleJointPosition') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_action__action__single_joint_position from action_msgs.msg import _goal_status_array if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None: _goal_status_array.Metaclass_GoalStatusArray.__import_type_support__() from action_msgs.srv import _cancel_goal if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None: _cancel_goal.Metaclass_CancelGoal.__import_type_support__() from control_msgs.action import _single_joint_position if _single_joint_position.Metaclass_SingleJointPosition_SendGoal._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_SendGoal.__import_type_support__() if _single_joint_position.Metaclass_SingleJointPosition_GetResult._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_GetResult.__import_type_support__() if _single_joint_position.Metaclass_SingleJointPosition_FeedbackMessage._TYPE_SUPPORT is None: _single_joint_position.Metaclass_SingleJointPosition_FeedbackMessage.__import_type_support__() class SingleJointPosition(metaclass=Metaclass_SingleJointPosition): # The goal message defined in the action definition. from control_msgs.action._single_joint_position import SingleJointPosition_Goal as Goal # The result message defined in the action definition. from control_msgs.action._single_joint_position import SingleJointPosition_Result as Result # The feedback message defined in the action definition. from control_msgs.action._single_joint_position import SingleJointPosition_Feedback as Feedback class Impl: # The send_goal service using a wrapped version of the goal message as a request. from control_msgs.action._single_joint_position import SingleJointPosition_SendGoal as SendGoalService # The get_result service using a wrapped version of the result message as a response. from control_msgs.action._single_joint_position import SingleJointPosition_GetResult as GetResultService # The feedback message with generic fields which wraps the feedback message. from control_msgs.action._single_joint_position import SingleJointPosition_FeedbackMessage as FeedbackMessage # The generic service to cancel a goal. from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService # The generic message for get the status of a goal. from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage def __init__(self): raise NotImplementedError('Action classes can not be instantiated')
50,584
Python
37.703137
134
0.595821
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_follow_joint_trajectory.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:action/FollowJointTrajectory.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_FollowJointTrajectory_Goal(type): """Metaclass of message 'FollowJointTrajectory_Goal'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_Goal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__goal cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__goal cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__goal cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__goal cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__goal from builtin_interfaces.msg import Duration if Duration.__class__._TYPE_SUPPORT is None: Duration.__class__.__import_type_support__() from control_msgs.msg import JointTolerance if JointTolerance.__class__._TYPE_SUPPORT is None: JointTolerance.__class__.__import_type_support__() from trajectory_msgs.msg import JointTrajectory if JointTrajectory.__class__._TYPE_SUPPORT is None: JointTrajectory.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class FollowJointTrajectory_Goal(metaclass=Metaclass_FollowJointTrajectory_Goal): """Message class 'FollowJointTrajectory_Goal'.""" __slots__ = [ '_trajectory', '_path_tolerance', '_goal_tolerance', '_goal_time_tolerance', ] _fields_and_field_types = { 'trajectory': 'trajectory_msgs/JointTrajectory', 'path_tolerance': 'sequence<control_msgs/JointTolerance>', 'goal_tolerance': 'sequence<control_msgs/JointTolerance>', 'goal_time_tolerance': 'builtin_interfaces/Duration', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectory'), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'JointTolerance')), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'JointTolerance')), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from trajectory_msgs.msg import JointTrajectory self.trajectory = kwargs.get('trajectory', JointTrajectory()) self.path_tolerance = kwargs.get('path_tolerance', []) self.goal_tolerance = kwargs.get('goal_tolerance', []) from builtin_interfaces.msg import Duration self.goal_time_tolerance = kwargs.get('goal_time_tolerance', Duration()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.trajectory != other.trajectory: return False if self.path_tolerance != other.path_tolerance: return False if self.goal_tolerance != other.goal_tolerance: return False if self.goal_time_tolerance != other.goal_time_tolerance: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def trajectory(self): """Message field 'trajectory'.""" return self._trajectory @trajectory.setter def trajectory(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectory assert \ isinstance(value, JointTrajectory), \ "The 'trajectory' field must be a sub message of type 'JointTrajectory'" self._trajectory = value @property def path_tolerance(self): """Message field 'path_tolerance'.""" return self._path_tolerance @path_tolerance.setter def path_tolerance(self, value): if __debug__: from control_msgs.msg import JointTolerance from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, JointTolerance) for v in value) and True), \ "The 'path_tolerance' field must be a set or sequence and each value of type 'JointTolerance'" self._path_tolerance = value @property def goal_tolerance(self): """Message field 'goal_tolerance'.""" return self._goal_tolerance @goal_tolerance.setter def goal_tolerance(self, value): if __debug__: from control_msgs.msg import JointTolerance from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, JointTolerance) for v in value) and True), \ "The 'goal_tolerance' field must be a set or sequence and each value of type 'JointTolerance'" self._goal_tolerance = value @property def goal_time_tolerance(self): """Message field 'goal_time_tolerance'.""" return self._goal_time_tolerance @goal_time_tolerance.setter def goal_time_tolerance(self, value): if __debug__: from builtin_interfaces.msg import Duration assert \ isinstance(value, Duration), \ "The 'goal_time_tolerance' field must be a sub message of type 'Duration'" self._goal_time_tolerance = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_Result(type): """Metaclass of message 'FollowJointTrajectory_Result'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { 'SUCCESSFUL': 0, 'INVALID_GOAL': -1, 'INVALID_JOINTS': -2, 'OLD_HEADER_TIMESTAMP': -3, 'PATH_TOLERANCE_VIOLATED': -4, 'GOAL_TOLERANCE_VIOLATED': -5, } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_Result') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__result cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__result cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__result cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__result cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__result @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { 'SUCCESSFUL': cls.__constants['SUCCESSFUL'], 'INVALID_GOAL': cls.__constants['INVALID_GOAL'], 'INVALID_JOINTS': cls.__constants['INVALID_JOINTS'], 'OLD_HEADER_TIMESTAMP': cls.__constants['OLD_HEADER_TIMESTAMP'], 'PATH_TOLERANCE_VIOLATED': cls.__constants['PATH_TOLERANCE_VIOLATED'], 'GOAL_TOLERANCE_VIOLATED': cls.__constants['GOAL_TOLERANCE_VIOLATED'], } @property def SUCCESSFUL(self): """Message constant 'SUCCESSFUL'.""" return Metaclass_FollowJointTrajectory_Result.__constants['SUCCESSFUL'] @property def INVALID_GOAL(self): """Message constant 'INVALID_GOAL'.""" return Metaclass_FollowJointTrajectory_Result.__constants['INVALID_GOAL'] @property def INVALID_JOINTS(self): """Message constant 'INVALID_JOINTS'.""" return Metaclass_FollowJointTrajectory_Result.__constants['INVALID_JOINTS'] @property def OLD_HEADER_TIMESTAMP(self): """Message constant 'OLD_HEADER_TIMESTAMP'.""" return Metaclass_FollowJointTrajectory_Result.__constants['OLD_HEADER_TIMESTAMP'] @property def PATH_TOLERANCE_VIOLATED(self): """Message constant 'PATH_TOLERANCE_VIOLATED'.""" return Metaclass_FollowJointTrajectory_Result.__constants['PATH_TOLERANCE_VIOLATED'] @property def GOAL_TOLERANCE_VIOLATED(self): """Message constant 'GOAL_TOLERANCE_VIOLATED'.""" return Metaclass_FollowJointTrajectory_Result.__constants['GOAL_TOLERANCE_VIOLATED'] class FollowJointTrajectory_Result(metaclass=Metaclass_FollowJointTrajectory_Result): """ Message class 'FollowJointTrajectory_Result'. Constants: SUCCESSFUL INVALID_GOAL INVALID_JOINTS OLD_HEADER_TIMESTAMP PATH_TOLERANCE_VIOLATED GOAL_TOLERANCE_VIOLATED """ __slots__ = [ '_error_code', '_error_string', ] _fields_and_field_types = { 'error_code': 'int32', 'error_string': 'string', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int32'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.error_code = kwargs.get('error_code', int()) self.error_string = kwargs.get('error_string', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.error_code != other.error_code: return False if self.error_string != other.error_string: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def error_code(self): """Message field 'error_code'.""" return self._error_code @error_code.setter def error_code(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'error_code' field must be of type 'int'" assert value >= -2147483648 and value < 2147483648, \ "The 'error_code' field must be an integer in [-2147483648, 2147483647]" self._error_code = value @property def error_string(self): """Message field 'error_string'.""" return self._error_string @error_string.setter def error_string(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'error_string' field must be of type 'str'" self._error_string = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_Feedback(type): """Metaclass of message 'FollowJointTrajectory_Feedback'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_Feedback') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__feedback cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__feedback cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__feedback cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__feedback cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__feedback from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__class__.__import_type_support__() from trajectory_msgs.msg import JointTrajectoryPoint if JointTrajectoryPoint.__class__._TYPE_SUPPORT is None: JointTrajectoryPoint.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class FollowJointTrajectory_Feedback(metaclass=Metaclass_FollowJointTrajectory_Feedback): """Message class 'FollowJointTrajectory_Feedback'.""" __slots__ = [ '_header', '_joint_names', '_desired', '_actual', '_error', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'joint_names': 'sequence<string>', 'desired': 'trajectory_msgs/JointTrajectoryPoint', 'actual': 'trajectory_msgs/JointTrajectoryPoint', 'error': 'trajectory_msgs/JointTrajectoryPoint', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.joint_names = kwargs.get('joint_names', []) from trajectory_msgs.msg import JointTrajectoryPoint self.desired = kwargs.get('desired', JointTrajectoryPoint()) from trajectory_msgs.msg import JointTrajectoryPoint self.actual = kwargs.get('actual', JointTrajectoryPoint()) from trajectory_msgs.msg import JointTrajectoryPoint self.error = kwargs.get('error', JointTrajectoryPoint()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.header != other.header: return False if self.joint_names != other.joint_names: return False if self.desired != other.desired: return False if self.actual != other.actual: return False if self.error != other.error: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def joint_names(self): """Message field 'joint_names'.""" return self._joint_names @joint_names.setter def joint_names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'joint_names' field must be a set or sequence and each value of type 'str'" self._joint_names = value @property def desired(self): """Message field 'desired'.""" return self._desired @desired.setter def desired(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'desired' field must be a sub message of type 'JointTrajectoryPoint'" self._desired = value @property def actual(self): """Message field 'actual'.""" return self._actual @actual.setter def actual(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'actual' field must be a sub message of type 'JointTrajectoryPoint'" self._actual = value @property def error(self): """Message field 'error'.""" return self._error @error.setter def error(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'error' field must be a sub message of type 'JointTrajectoryPoint'" self._error = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_SendGoal_Request(type): """Metaclass of message 'FollowJointTrajectory_SendGoal_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_SendGoal_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__send_goal__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__send_goal__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__send_goal__request cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__send_goal__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__send_goal__request from control_msgs.action import FollowJointTrajectory if FollowJointTrajectory.Goal.__class__._TYPE_SUPPORT is None: FollowJointTrajectory.Goal.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class FollowJointTrajectory_SendGoal_Request(metaclass=Metaclass_FollowJointTrajectory_SendGoal_Request): """Message class 'FollowJointTrajectory_SendGoal_Request'.""" __slots__ = [ '_goal_id', '_goal', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'goal': 'control_msgs/FollowJointTrajectory_Goal', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'FollowJointTrajectory_Goal'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Goal self.goal = kwargs.get('goal', FollowJointTrajectory_Goal()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False if self.goal != other.goal: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def goal(self): """Message field 'goal'.""" return self._goal @goal.setter def goal(self, value): if __debug__: from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Goal assert \ isinstance(value, FollowJointTrajectory_Goal), \ "The 'goal' field must be a sub message of type 'FollowJointTrajectory_Goal'" self._goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_SendGoal_Response(type): """Metaclass of message 'FollowJointTrajectory_SendGoal_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_SendGoal_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__send_goal__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__send_goal__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__send_goal__response cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__send_goal__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__send_goal__response from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class FollowJointTrajectory_SendGoal_Response(metaclass=Metaclass_FollowJointTrajectory_SendGoal_Response): """Message class 'FollowJointTrajectory_SendGoal_Response'.""" __slots__ = [ '_accepted', '_stamp', ] _fields_and_field_types = { 'accepted': 'boolean', 'stamp': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.accepted = kwargs.get('accepted', bool()) from builtin_interfaces.msg import Time self.stamp = kwargs.get('stamp', Time()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.accepted != other.accepted: return False if self.stamp != other.stamp: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def accepted(self): """Message field 'accepted'.""" return self._accepted @accepted.setter def accepted(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'accepted' field must be of type 'bool'" self._accepted = value @property def stamp(self): """Message field 'stamp'.""" return self._stamp @stamp.setter def stamp(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'stamp' field must be a sub message of type 'Time'" self._stamp = value class Metaclass_FollowJointTrajectory_SendGoal(type): """Metaclass of service 'FollowJointTrajectory_SendGoal'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_SendGoal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__follow_joint_trajectory__send_goal from control_msgs.action import _follow_joint_trajectory if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Request._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Request.__import_type_support__() if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Response._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal_Response.__import_type_support__() class FollowJointTrajectory_SendGoal(metaclass=Metaclass_FollowJointTrajectory_SendGoal): from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_SendGoal_Request as Request from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_SendGoal_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_GetResult_Request(type): """Metaclass of message 'FollowJointTrajectory_GetResult_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_GetResult_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__get_result__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__get_result__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__get_result__request cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__get_result__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__get_result__request from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class FollowJointTrajectory_GetResult_Request(metaclass=Metaclass_FollowJointTrajectory_GetResult_Request): """Message class 'FollowJointTrajectory_GetResult_Request'.""" __slots__ = [ '_goal_id', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_GetResult_Response(type): """Metaclass of message 'FollowJointTrajectory_GetResult_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_GetResult_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__get_result__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__get_result__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__get_result__response cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__get_result__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__get_result__response from control_msgs.action import FollowJointTrajectory if FollowJointTrajectory.Result.__class__._TYPE_SUPPORT is None: FollowJointTrajectory.Result.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class FollowJointTrajectory_GetResult_Response(metaclass=Metaclass_FollowJointTrajectory_GetResult_Response): """Message class 'FollowJointTrajectory_GetResult_Response'.""" __slots__ = [ '_status', '_result', ] _fields_and_field_types = { 'status': 'int8', 'result': 'control_msgs/FollowJointTrajectory_Result', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int8'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'FollowJointTrajectory_Result'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.status = kwargs.get('status', int()) from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Result self.result = kwargs.get('result', FollowJointTrajectory_Result()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.status != other.status: return False if self.result != other.result: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def status(self): """Message field 'status'.""" return self._status @status.setter def status(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'status' field must be of type 'int'" assert value >= -128 and value < 128, \ "The 'status' field must be an integer in [-128, 127]" self._status = value @property def result(self): """Message field 'result'.""" return self._result @result.setter def result(self, value): if __debug__: from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Result assert \ isinstance(value, FollowJointTrajectory_Result), \ "The 'result' field must be a sub message of type 'FollowJointTrajectory_Result'" self._result = value class Metaclass_FollowJointTrajectory_GetResult(type): """Metaclass of service 'FollowJointTrajectory_GetResult'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_GetResult') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__follow_joint_trajectory__get_result from control_msgs.action import _follow_joint_trajectory if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Request._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Request.__import_type_support__() if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Response._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult_Response.__import_type_support__() class FollowJointTrajectory_GetResult(metaclass=Metaclass_FollowJointTrajectory_GetResult): from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_GetResult_Request as Request from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_GetResult_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_FollowJointTrajectory_FeedbackMessage(type): """Metaclass of message 'FollowJointTrajectory_FeedbackMessage'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory_FeedbackMessage') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__follow_joint_trajectory__feedback_message cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__follow_joint_trajectory__feedback_message cls._CONVERT_TO_PY = module.convert_to_py_msg__action__follow_joint_trajectory__feedback_message cls._TYPE_SUPPORT = module.type_support_msg__action__follow_joint_trajectory__feedback_message cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__follow_joint_trajectory__feedback_message from control_msgs.action import FollowJointTrajectory if FollowJointTrajectory.Feedback.__class__._TYPE_SUPPORT is None: FollowJointTrajectory.Feedback.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class FollowJointTrajectory_FeedbackMessage(metaclass=Metaclass_FollowJointTrajectory_FeedbackMessage): """Message class 'FollowJointTrajectory_FeedbackMessage'.""" __slots__ = [ '_goal_id', '_feedback', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'feedback': 'control_msgs/FollowJointTrajectory_Feedback', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'FollowJointTrajectory_Feedback'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Feedback self.feedback = kwargs.get('feedback', FollowJointTrajectory_Feedback()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False if self.feedback != other.feedback: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def feedback(self): """Message field 'feedback'.""" return self._feedback @feedback.setter def feedback(self, value): if __debug__: from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Feedback assert \ isinstance(value, FollowJointTrajectory_Feedback), \ "The 'feedback' field must be a sub message of type 'FollowJointTrajectory_Feedback'" self._feedback = value class Metaclass_FollowJointTrajectory(type): """Metaclass of action 'FollowJointTrajectory'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.FollowJointTrajectory') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_action__action__follow_joint_trajectory from action_msgs.msg import _goal_status_array if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None: _goal_status_array.Metaclass_GoalStatusArray.__import_type_support__() from action_msgs.srv import _cancel_goal if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None: _cancel_goal.Metaclass_CancelGoal.__import_type_support__() from control_msgs.action import _follow_joint_trajectory if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_SendGoal.__import_type_support__() if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_GetResult.__import_type_support__() if _follow_joint_trajectory.Metaclass_FollowJointTrajectory_FeedbackMessage._TYPE_SUPPORT is None: _follow_joint_trajectory.Metaclass_FollowJointTrajectory_FeedbackMessage.__import_type_support__() class FollowJointTrajectory(metaclass=Metaclass_FollowJointTrajectory): # The goal message defined in the action definition. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Goal as Goal # The result message defined in the action definition. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Result as Result # The feedback message defined in the action definition. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_Feedback as Feedback class Impl: # The send_goal service using a wrapped version of the goal message as a request. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_SendGoal as SendGoalService # The get_result service using a wrapped version of the result message as a response. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_GetResult as GetResultService # The feedback message with generic fields which wraps the feedback message. from control_msgs.action._follow_joint_trajectory import FollowJointTrajectory_FeedbackMessage as FeedbackMessage # The generic service to cancel a goal. from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService # The generic message for get the status of a goal. from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage def __init__(self): raise NotImplementedError('Action classes can not be instantiated')
59,208
Python
38.764271
149
0.603179
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_point_head.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:action/PointHead.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_PointHead_Goal(type): """Metaclass of message 'PointHead_Goal'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_Goal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__goal cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__goal cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__goal cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__goal cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__goal from builtin_interfaces.msg import Duration if Duration.__class__._TYPE_SUPPORT is None: Duration.__class__.__import_type_support__() from geometry_msgs.msg import PointStamped if PointStamped.__class__._TYPE_SUPPORT is None: PointStamped.__class__.__import_type_support__() from geometry_msgs.msg import Vector3 if Vector3.__class__._TYPE_SUPPORT is None: Vector3.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PointHead_Goal(metaclass=Metaclass_PointHead_Goal): """Message class 'PointHead_Goal'.""" __slots__ = [ '_target', '_pointing_axis', '_pointing_frame', '_min_duration', '_max_velocity', ] _fields_and_field_types = { 'target': 'geometry_msgs/PointStamped', 'pointing_axis': 'geometry_msgs/Vector3', 'pointing_frame': 'string', 'min_duration': 'builtin_interfaces/Duration', 'max_velocity': 'double', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['geometry_msgs', 'msg'], 'PointStamped'), # noqa: E501 rosidl_parser.definition.NamespacedType(['geometry_msgs', 'msg'], 'Vector3'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from geometry_msgs.msg import PointStamped self.target = kwargs.get('target', PointStamped()) from geometry_msgs.msg import Vector3 self.pointing_axis = kwargs.get('pointing_axis', Vector3()) self.pointing_frame = kwargs.get('pointing_frame', str()) from builtin_interfaces.msg import Duration self.min_duration = kwargs.get('min_duration', Duration()) self.max_velocity = kwargs.get('max_velocity', float()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.target != other.target: return False if self.pointing_axis != other.pointing_axis: return False if self.pointing_frame != other.pointing_frame: return False if self.min_duration != other.min_duration: return False if self.max_velocity != other.max_velocity: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def target(self): """Message field 'target'.""" return self._target @target.setter def target(self, value): if __debug__: from geometry_msgs.msg import PointStamped assert \ isinstance(value, PointStamped), \ "The 'target' field must be a sub message of type 'PointStamped'" self._target = value @property def pointing_axis(self): """Message field 'pointing_axis'.""" return self._pointing_axis @pointing_axis.setter def pointing_axis(self, value): if __debug__: from geometry_msgs.msg import Vector3 assert \ isinstance(value, Vector3), \ "The 'pointing_axis' field must be a sub message of type 'Vector3'" self._pointing_axis = value @property def pointing_frame(self): """Message field 'pointing_frame'.""" return self._pointing_frame @pointing_frame.setter def pointing_frame(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'pointing_frame' field must be of type 'str'" self._pointing_frame = value @property def min_duration(self): """Message field 'min_duration'.""" return self._min_duration @min_duration.setter def min_duration(self, value): if __debug__: from builtin_interfaces.msg import Duration assert \ isinstance(value, Duration), \ "The 'min_duration' field must be a sub message of type 'Duration'" self._min_duration = value @property def max_velocity(self): """Message field 'max_velocity'.""" return self._max_velocity @max_velocity.setter def max_velocity(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'max_velocity' field must be of type 'float'" self._max_velocity = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_Result(type): """Metaclass of message 'PointHead_Result'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_Result') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__result cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__result cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__result cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__result cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__result @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PointHead_Result(metaclass=Metaclass_PointHead_Result): """Message class 'PointHead_Result'.""" __slots__ = [ ] _fields_and_field_types = { } SLOT_TYPES = ( ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_Feedback(type): """Metaclass of message 'PointHead_Feedback'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_Feedback') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__feedback cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__feedback cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__feedback cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__feedback cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__feedback @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PointHead_Feedback(metaclass=Metaclass_PointHead_Feedback): """Message class 'PointHead_Feedback'.""" __slots__ = [ '_pointing_angle_error', ] _fields_and_field_types = { 'pointing_angle_error': 'double', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('double'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.pointing_angle_error = kwargs.get('pointing_angle_error', float()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.pointing_angle_error != other.pointing_angle_error: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def pointing_angle_error(self): """Message field 'pointing_angle_error'.""" return self._pointing_angle_error @pointing_angle_error.setter def pointing_angle_error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'pointing_angle_error' field must be of type 'float'" self._pointing_angle_error = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_SendGoal_Request(type): """Metaclass of message 'PointHead_SendGoal_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_SendGoal_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__send_goal__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__send_goal__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__send_goal__request cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__send_goal__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__send_goal__request from control_msgs.action import PointHead if PointHead.Goal.__class__._TYPE_SUPPORT is None: PointHead.Goal.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PointHead_SendGoal_Request(metaclass=Metaclass_PointHead_SendGoal_Request): """Message class 'PointHead_SendGoal_Request'.""" __slots__ = [ '_goal_id', '_goal', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'goal': 'control_msgs/PointHead_Goal', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'PointHead_Goal'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._point_head import PointHead_Goal self.goal = kwargs.get('goal', PointHead_Goal()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False if self.goal != other.goal: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def goal(self): """Message field 'goal'.""" return self._goal @goal.setter def goal(self, value): if __debug__: from control_msgs.action._point_head import PointHead_Goal assert \ isinstance(value, PointHead_Goal), \ "The 'goal' field must be a sub message of type 'PointHead_Goal'" self._goal = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_SendGoal_Response(type): """Metaclass of message 'PointHead_SendGoal_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_SendGoal_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__send_goal__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__send_goal__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__send_goal__response cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__send_goal__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__send_goal__response from builtin_interfaces.msg import Time if Time.__class__._TYPE_SUPPORT is None: Time.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PointHead_SendGoal_Response(metaclass=Metaclass_PointHead_SendGoal_Response): """Message class 'PointHead_SendGoal_Response'.""" __slots__ = [ '_accepted', '_stamp', ] _fields_and_field_types = { 'accepted': 'boolean', 'stamp': 'builtin_interfaces/Time', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.accepted = kwargs.get('accepted', bool()) from builtin_interfaces.msg import Time self.stamp = kwargs.get('stamp', Time()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.accepted != other.accepted: return False if self.stamp != other.stamp: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def accepted(self): """Message field 'accepted'.""" return self._accepted @accepted.setter def accepted(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'accepted' field must be of type 'bool'" self._accepted = value @property def stamp(self): """Message field 'stamp'.""" return self._stamp @stamp.setter def stamp(self, value): if __debug__: from builtin_interfaces.msg import Time assert \ isinstance(value, Time), \ "The 'stamp' field must be a sub message of type 'Time'" self._stamp = value class Metaclass_PointHead_SendGoal(type): """Metaclass of service 'PointHead_SendGoal'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_SendGoal') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__point_head__send_goal from control_msgs.action import _point_head if _point_head.Metaclass_PointHead_SendGoal_Request._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_SendGoal_Request.__import_type_support__() if _point_head.Metaclass_PointHead_SendGoal_Response._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_SendGoal_Response.__import_type_support__() class PointHead_SendGoal(metaclass=Metaclass_PointHead_SendGoal): from control_msgs.action._point_head import PointHead_SendGoal_Request as Request from control_msgs.action._point_head import PointHead_SendGoal_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_GetResult_Request(type): """Metaclass of message 'PointHead_GetResult_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_GetResult_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__get_result__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__get_result__request cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__get_result__request cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__get_result__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__get_result__request from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PointHead_GetResult_Request(metaclass=Metaclass_PointHead_GetResult_Request): """Message class 'PointHead_GetResult_Request'.""" __slots__ = [ '_goal_id', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_GetResult_Response(type): """Metaclass of message 'PointHead_GetResult_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_GetResult_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__get_result__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__get_result__response cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__get_result__response cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__get_result__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__get_result__response from control_msgs.action import PointHead if PointHead.Result.__class__._TYPE_SUPPORT is None: PointHead.Result.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PointHead_GetResult_Response(metaclass=Metaclass_PointHead_GetResult_Response): """Message class 'PointHead_GetResult_Response'.""" __slots__ = [ '_status', '_result', ] _fields_and_field_types = { 'status': 'int8', 'result': 'control_msgs/PointHead_Result', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('int8'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'PointHead_Result'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.status = kwargs.get('status', int()) from control_msgs.action._point_head import PointHead_Result self.result = kwargs.get('result', PointHead_Result()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.status != other.status: return False if self.result != other.result: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def status(self): """Message field 'status'.""" return self._status @status.setter def status(self, value): if __debug__: assert \ isinstance(value, int), \ "The 'status' field must be of type 'int'" assert value >= -128 and value < 128, \ "The 'status' field must be an integer in [-128, 127]" self._status = value @property def result(self): """Message field 'result'.""" return self._result @result.setter def result(self, value): if __debug__: from control_msgs.action._point_head import PointHead_Result assert \ isinstance(value, PointHead_Result), \ "The 'result' field must be a sub message of type 'PointHead_Result'" self._result = value class Metaclass_PointHead_GetResult(type): """Metaclass of service 'PointHead_GetResult'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_GetResult') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__action__point_head__get_result from control_msgs.action import _point_head if _point_head.Metaclass_PointHead_GetResult_Request._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_GetResult_Request.__import_type_support__() if _point_head.Metaclass_PointHead_GetResult_Response._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_GetResult_Response.__import_type_support__() class PointHead_GetResult(metaclass=Metaclass_PointHead_GetResult): from control_msgs.action._point_head import PointHead_GetResult_Request as Request from control_msgs.action._point_head import PointHead_GetResult_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated') # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_PointHead_FeedbackMessage(type): """Metaclass of message 'PointHead_FeedbackMessage'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead_FeedbackMessage') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__action__point_head__feedback_message cls._CONVERT_FROM_PY = module.convert_from_py_msg__action__point_head__feedback_message cls._CONVERT_TO_PY = module.convert_to_py_msg__action__point_head__feedback_message cls._TYPE_SUPPORT = module.type_support_msg__action__point_head__feedback_message cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__action__point_head__feedback_message from control_msgs.action import PointHead if PointHead.Feedback.__class__._TYPE_SUPPORT is None: PointHead.Feedback.__class__.__import_type_support__() from unique_identifier_msgs.msg import UUID if UUID.__class__._TYPE_SUPPORT is None: UUID.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PointHead_FeedbackMessage(metaclass=Metaclass_PointHead_FeedbackMessage): """Message class 'PointHead_FeedbackMessage'.""" __slots__ = [ '_goal_id', '_feedback', ] _fields_and_field_types = { 'goal_id': 'unique_identifier_msgs/UUID', 'feedback': 'control_msgs/PointHead_Feedback', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['unique_identifier_msgs', 'msg'], 'UUID'), # noqa: E501 rosidl_parser.definition.NamespacedType(['control_msgs', 'action'], 'PointHead_Feedback'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from unique_identifier_msgs.msg import UUID self.goal_id = kwargs.get('goal_id', UUID()) from control_msgs.action._point_head import PointHead_Feedback self.feedback = kwargs.get('feedback', PointHead_Feedback()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.goal_id != other.goal_id: return False if self.feedback != other.feedback: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def goal_id(self): """Message field 'goal_id'.""" return self._goal_id @goal_id.setter def goal_id(self, value): if __debug__: from unique_identifier_msgs.msg import UUID assert \ isinstance(value, UUID), \ "The 'goal_id' field must be a sub message of type 'UUID'" self._goal_id = value @property def feedback(self): """Message field 'feedback'.""" return self._feedback @feedback.setter def feedback(self, value): if __debug__: from control_msgs.action._point_head import PointHead_Feedback assert \ isinstance(value, PointHead_Feedback), \ "The 'feedback' field must be a sub message of type 'PointHead_Feedback'" self._feedback = value class Metaclass_PointHead(type): """Metaclass of action 'PointHead'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.action.PointHead') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_action__action__point_head from action_msgs.msg import _goal_status_array if _goal_status_array.Metaclass_GoalStatusArray._TYPE_SUPPORT is None: _goal_status_array.Metaclass_GoalStatusArray.__import_type_support__() from action_msgs.srv import _cancel_goal if _cancel_goal.Metaclass_CancelGoal._TYPE_SUPPORT is None: _cancel_goal.Metaclass_CancelGoal.__import_type_support__() from control_msgs.action import _point_head if _point_head.Metaclass_PointHead_SendGoal._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_SendGoal.__import_type_support__() if _point_head.Metaclass_PointHead_GetResult._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_GetResult.__import_type_support__() if _point_head.Metaclass_PointHead_FeedbackMessage._TYPE_SUPPORT is None: _point_head.Metaclass_PointHead_FeedbackMessage.__import_type_support__() class PointHead(metaclass=Metaclass_PointHead): # The goal message defined in the action definition. from control_msgs.action._point_head import PointHead_Goal as Goal # The result message defined in the action definition. from control_msgs.action._point_head import PointHead_Result as Result # The feedback message defined in the action definition. from control_msgs.action._point_head import PointHead_Feedback as Feedback class Impl: # The send_goal service using a wrapped version of the goal message as a request. from control_msgs.action._point_head import PointHead_SendGoal as SendGoalService # The get_result service using a wrapped version of the result message as a response. from control_msgs.action._point_head import PointHead_GetResult as GetResultService # The feedback message with generic fields which wraps the feedback message. from control_msgs.action._point_head import PointHead_FeedbackMessage as FeedbackMessage # The generic service to cancel a goal. from action_msgs.srv._cancel_goal import CancelGoal as CancelGoalService # The generic message for get the status of a goal. from action_msgs.msg._goal_status_array import GoalStatusArray as GoalStatusMessage def __init__(self): raise NotImplementedError('Action classes can not be instantiated')
48,726
Python
36.656105
134
0.583959
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_follow_joint_trajectory_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:action/FollowJointTrajectory.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/action/detail/follow_joint_trajectory__struct.h" #include "control_msgs/action/detail/follow_joint_trajectory__functions.h" #include "rosidl_runtime_c/primitives_sequence.h" #include "rosidl_runtime_c/primitives_sequence_functions.h" // Nested array functions includes #include "control_msgs/msg/detail/joint_tolerance__functions.h" // end nested array functions include ROSIDL_GENERATOR_C_IMPORT bool trajectory_msgs__msg__joint_trajectory__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * trajectory_msgs__msg__joint_trajectory__convert_to_py(void * raw_ros_message); bool control_msgs__msg__joint_tolerance__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__msg__joint_tolerance__convert_to_py(void * raw_ros_message); bool control_msgs__msg__joint_tolerance__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__msg__joint_tolerance__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_IMPORT bool builtin_interfaces__msg__duration__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * builtin_interfaces__msg__duration__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__follow_joint_trajectory__goal__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[72]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_Goal", full_classname_dest, 71) == 0); } control_msgs__action__FollowJointTrajectory_Goal * ros_message = _ros_message; { // trajectory PyObject * field = PyObject_GetAttrString(_pymsg, "trajectory"); if (!field) { return false; } if (!trajectory_msgs__msg__joint_trajectory__convert_from_py(field, &ros_message->trajectory)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // path_tolerance PyObject * field = PyObject_GetAttrString(_pymsg, "path_tolerance"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'path_tolerance'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!control_msgs__msg__JointTolerance__Sequence__init(&(ros_message->path_tolerance), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create control_msgs__msg__JointTolerance__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } control_msgs__msg__JointTolerance * dest = ros_message->path_tolerance.data; for (Py_ssize_t i = 0; i < size; ++i) { if (!control_msgs__msg__joint_tolerance__convert_from_py(PySequence_Fast_GET_ITEM(seq_field, i), &dest[i])) { Py_DECREF(seq_field); Py_DECREF(field); return false; } } Py_DECREF(seq_field); Py_DECREF(field); } { // goal_tolerance PyObject * field = PyObject_GetAttrString(_pymsg, "goal_tolerance"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'goal_tolerance'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!control_msgs__msg__JointTolerance__Sequence__init(&(ros_message->goal_tolerance), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create control_msgs__msg__JointTolerance__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } control_msgs__msg__JointTolerance * dest = ros_message->goal_tolerance.data; for (Py_ssize_t i = 0; i < size; ++i) { if (!control_msgs__msg__joint_tolerance__convert_from_py(PySequence_Fast_GET_ITEM(seq_field, i), &dest[i])) { Py_DECREF(seq_field); Py_DECREF(field); return false; } } Py_DECREF(seq_field); Py_DECREF(field); } { // goal_time_tolerance PyObject * field = PyObject_GetAttrString(_pymsg, "goal_time_tolerance"); if (!field) { return false; } if (!builtin_interfaces__msg__duration__convert_from_py(field, &ros_message->goal_time_tolerance)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__follow_joint_trajectory__goal__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of FollowJointTrajectory_Goal */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_Goal"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__FollowJointTrajectory_Goal * ros_message = (control_msgs__action__FollowJointTrajectory_Goal *)raw_ros_message; { // trajectory PyObject * field = NULL; field = trajectory_msgs__msg__joint_trajectory__convert_to_py(&ros_message->trajectory); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "trajectory", field); Py_DECREF(field); if (rc) { return NULL; } } } { // path_tolerance PyObject * field = NULL; size_t size = ros_message->path_tolerance.size; field = PyList_New(size); if (!field) { return NULL; } control_msgs__msg__JointTolerance * item; for (size_t i = 0; i < size; ++i) { item = &(ros_message->path_tolerance.data[i]); PyObject * pyitem = control_msgs__msg__joint_tolerance__convert_to_py(item); if (!pyitem) { Py_DECREF(field); return NULL; } int rc = PyList_SetItem(field, i, pyitem); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "path_tolerance", field); Py_DECREF(field); if (rc) { return NULL; } } } { // goal_tolerance PyObject * field = NULL; size_t size = ros_message->goal_tolerance.size; field = PyList_New(size); if (!field) { return NULL; } control_msgs__msg__JointTolerance * item; for (size_t i = 0; i < size; ++i) { item = &(ros_message->goal_tolerance.data[i]); PyObject * pyitem = control_msgs__msg__joint_tolerance__convert_to_py(item); if (!pyitem) { Py_DECREF(field); return NULL; } int rc = PyList_SetItem(field, i, pyitem); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "goal_tolerance", field); Py_DECREF(field); if (rc) { return NULL; } } } { // goal_time_tolerance PyObject * field = NULL; field = builtin_interfaces__msg__duration__convert_to_py(&ros_message->goal_time_tolerance); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_time_tolerance", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__follow_joint_trajectory__result__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[74]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_Result", full_classname_dest, 73) == 0); } control_msgs__action__FollowJointTrajectory_Result * ros_message = _ros_message; { // error_code PyObject * field = PyObject_GetAttrString(_pymsg, "error_code"); if (!field) { return false; } assert(PyLong_Check(field)); ros_message->error_code = (int32_t)PyLong_AsLong(field); Py_DECREF(field); } { // error_string PyObject * field = PyObject_GetAttrString(_pymsg, "error_string"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->error_string, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__follow_joint_trajectory__result__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of FollowJointTrajectory_Result */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_Result"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__FollowJointTrajectory_Result * ros_message = (control_msgs__action__FollowJointTrajectory_Result *)raw_ros_message; { // error_code PyObject * field = NULL; field = PyLong_FromLong(ros_message->error_code); { int rc = PyObject_SetAttrString(_pymessage, "error_code", field); Py_DECREF(field); if (rc) { return NULL; } } } { // error_string PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->error_string.data, strlen(ros_message->error_string.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "error_string", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__functions.h" // already included above // #include "rosidl_runtime_c/primitives_sequence.h" // already included above // #include "rosidl_runtime_c/primitives_sequence_functions.h" // already included above // #include "rosidl_runtime_c/string.h" // already included above // #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_IMPORT bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_IMPORT bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_IMPORT bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_IMPORT bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__follow_joint_trajectory__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[76]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_Feedback", full_classname_dest, 75) == 0); } control_msgs__action__FollowJointTrajectory_Feedback * ros_message = _ros_message; { // header PyObject * field = PyObject_GetAttrString(_pymsg, "header"); if (!field) { return false; } if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // joint_names PyObject * field = PyObject_GetAttrString(_pymsg, "joint_names"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'joint_names'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->joint_names), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->joint_names.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // desired PyObject * field = PyObject_GetAttrString(_pymsg, "desired"); if (!field) { return false; } if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->desired)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // actual PyObject * field = PyObject_GetAttrString(_pymsg, "actual"); if (!field) { return false; } if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->actual)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // error PyObject * field = PyObject_GetAttrString(_pymsg, "error"); if (!field) { return false; } if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->error)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__follow_joint_trajectory__feedback__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of FollowJointTrajectory_Feedback */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_Feedback"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__FollowJointTrajectory_Feedback * ros_message = (control_msgs__action__FollowJointTrajectory_Feedback *)raw_ros_message; { // header PyObject * field = NULL; field = std_msgs__msg__header__convert_to_py(&ros_message->header); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "header", field); Py_DECREF(field); if (rc) { return NULL; } } } { // joint_names PyObject * field = NULL; size_t size = ros_message->joint_names.size; rosidl_runtime_c__String * src = ros_message->joint_names.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "joint_names", field); Py_DECREF(field); if (rc) { return NULL; } } } { // desired PyObject * field = NULL; field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->desired); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "desired", field); Py_DECREF(field); if (rc) { return NULL; } } } { // actual PyObject * field = NULL; field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->actual); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "actual", field); Py_DECREF(field); if (rc) { return NULL; } } } { // error PyObject * field = NULL; field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->error); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "error", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); bool control_msgs__action__follow_joint_trajectory__goal__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__follow_joint_trajectory__goal__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__follow_joint_trajectory__send_goal__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[84]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_SendGoal_Request", full_classname_dest, 83) == 0); } control_msgs__action__FollowJointTrajectory_SendGoal_Request * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // goal PyObject * field = PyObject_GetAttrString(_pymsg, "goal"); if (!field) { return false; } if (!control_msgs__action__follow_joint_trajectory__goal__convert_from_py(field, &ros_message->goal)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__follow_joint_trajectory__send_goal__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of FollowJointTrajectory_SendGoal_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_SendGoal_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__FollowJointTrajectory_SendGoal_Request * ros_message = (control_msgs__action__FollowJointTrajectory_SendGoal_Request *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } { // goal PyObject * field = NULL; field = control_msgs__action__follow_joint_trajectory__goal__convert_to_py(&ros_message->goal); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__functions.h" ROSIDL_GENERATOR_C_IMPORT bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__follow_joint_trajectory__send_goal__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[85]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_SendGoal_Response", full_classname_dest, 84) == 0); } control_msgs__action__FollowJointTrajectory_SendGoal_Response * ros_message = _ros_message; { // accepted PyObject * field = PyObject_GetAttrString(_pymsg, "accepted"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->accepted = (Py_True == field); Py_DECREF(field); } { // stamp PyObject * field = PyObject_GetAttrString(_pymsg, "stamp"); if (!field) { return false; } if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->stamp)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__follow_joint_trajectory__send_goal__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of FollowJointTrajectory_SendGoal_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_SendGoal_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__FollowJointTrajectory_SendGoal_Response * ros_message = (control_msgs__action__FollowJointTrajectory_SendGoal_Response *)raw_ros_message; { // accepted PyObject * field = NULL; field = PyBool_FromLong(ros_message->accepted ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "accepted", field); Py_DECREF(field); if (rc) { return NULL; } } } { // stamp PyObject * field = NULL; field = builtin_interfaces__msg__time__convert_to_py(&ros_message->stamp); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "stamp", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__follow_joint_trajectory__get_result__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[85]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_GetResult_Request", full_classname_dest, 84) == 0); } control_msgs__action__FollowJointTrajectory_GetResult_Request * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__follow_joint_trajectory__get_result__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of FollowJointTrajectory_GetResult_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_GetResult_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__FollowJointTrajectory_GetResult_Request * ros_message = (control_msgs__action__FollowJointTrajectory_GetResult_Request *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__functions.h" bool control_msgs__action__follow_joint_trajectory__result__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__follow_joint_trajectory__result__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__follow_joint_trajectory__get_result__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[86]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_GetResult_Response", full_classname_dest, 85) == 0); } control_msgs__action__FollowJointTrajectory_GetResult_Response * ros_message = _ros_message; { // status PyObject * field = PyObject_GetAttrString(_pymsg, "status"); if (!field) { return false; } assert(PyLong_Check(field)); ros_message->status = (int8_t)PyLong_AsLong(field); Py_DECREF(field); } { // result PyObject * field = PyObject_GetAttrString(_pymsg, "result"); if (!field) { return false; } if (!control_msgs__action__follow_joint_trajectory__result__convert_from_py(field, &ros_message->result)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__follow_joint_trajectory__get_result__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of FollowJointTrajectory_GetResult_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_GetResult_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__FollowJointTrajectory_GetResult_Response * ros_message = (control_msgs__action__FollowJointTrajectory_GetResult_Response *)raw_ros_message; { // status PyObject * field = NULL; field = PyLong_FromLong(ros_message->status); { int rc = PyObject_SetAttrString(_pymessage, "status", field); Py_DECREF(field); if (rc) { return NULL; } } } { // result PyObject * field = NULL; field = control_msgs__action__follow_joint_trajectory__result__convert_to_py(&ros_message->result); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "result", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__struct.h" // already included above // #include "control_msgs/action/detail/follow_joint_trajectory__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); bool control_msgs__action__follow_joint_trajectory__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__follow_joint_trajectory__feedback__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__follow_joint_trajectory__feedback_message__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[83]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._follow_joint_trajectory.FollowJointTrajectory_FeedbackMessage", full_classname_dest, 82) == 0); } control_msgs__action__FollowJointTrajectory_FeedbackMessage * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // feedback PyObject * field = PyObject_GetAttrString(_pymsg, "feedback"); if (!field) { return false; } if (!control_msgs__action__follow_joint_trajectory__feedback__convert_from_py(field, &ros_message->feedback)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__follow_joint_trajectory__feedback_message__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of FollowJointTrajectory_FeedbackMessage */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._follow_joint_trajectory"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "FollowJointTrajectory_FeedbackMessage"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__FollowJointTrajectory_FeedbackMessage * ros_message = (control_msgs__action__FollowJointTrajectory_FeedbackMessage *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } { // feedback PyObject * field = NULL; field = control_msgs__action__follow_joint_trajectory__feedback__convert_to_py(&ros_message->feedback); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "feedback", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
43,203
C
32.753125
163
0.644076
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/action/_single_joint_position_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:action/SingleJointPosition.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/action/detail/single_joint_position__struct.h" #include "control_msgs/action/detail/single_joint_position__functions.h" ROSIDL_GENERATOR_C_IMPORT bool builtin_interfaces__msg__duration__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * builtin_interfaces__msg__duration__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__single_joint_position__goal__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[68]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_Goal", full_classname_dest, 67) == 0); } control_msgs__action__SingleJointPosition_Goal * ros_message = _ros_message; { // position PyObject * field = PyObject_GetAttrString(_pymsg, "position"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->position = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // min_duration PyObject * field = PyObject_GetAttrString(_pymsg, "min_duration"); if (!field) { return false; } if (!builtin_interfaces__msg__duration__convert_from_py(field, &ros_message->min_duration)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // max_velocity PyObject * field = PyObject_GetAttrString(_pymsg, "max_velocity"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->max_velocity = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__single_joint_position__goal__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of SingleJointPosition_Goal */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_Goal"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__SingleJointPosition_Goal * ros_message = (control_msgs__action__SingleJointPosition_Goal *)raw_ros_message; { // position PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->position); { int rc = PyObject_SetAttrString(_pymessage, "position", field); Py_DECREF(field); if (rc) { return NULL; } } } { // min_duration PyObject * field = NULL; field = builtin_interfaces__msg__duration__convert_to_py(&ros_message->min_duration); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "min_duration", field); Py_DECREF(field); if (rc) { return NULL; } } } { // max_velocity PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->max_velocity); { int rc = PyObject_SetAttrString(_pymessage, "max_velocity", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/single_joint_position__struct.h" // already included above // #include "control_msgs/action/detail/single_joint_position__functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__single_joint_position__result__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[70]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_Result", full_classname_dest, 69) == 0); } control_msgs__action__SingleJointPosition_Result * ros_message = _ros_message; ros_message->structure_needs_at_least_one_member = 0; return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__single_joint_position__result__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of SingleJointPosition_Result */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_Result"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } (void)raw_ros_message; // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/single_joint_position__struct.h" // already included above // #include "control_msgs/action/detail/single_joint_position__functions.h" ROSIDL_GENERATOR_C_IMPORT bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__single_joint_position__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[72]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_Feedback", full_classname_dest, 71) == 0); } control_msgs__action__SingleJointPosition_Feedback * ros_message = _ros_message; { // header PyObject * field = PyObject_GetAttrString(_pymsg, "header"); if (!field) { return false; } if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // position PyObject * field = PyObject_GetAttrString(_pymsg, "position"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->position = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // velocity PyObject * field = PyObject_GetAttrString(_pymsg, "velocity"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->velocity = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // error PyObject * field = PyObject_GetAttrString(_pymsg, "error"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->error = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__single_joint_position__feedback__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of SingleJointPosition_Feedback */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_Feedback"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__SingleJointPosition_Feedback * ros_message = (control_msgs__action__SingleJointPosition_Feedback *)raw_ros_message; { // header PyObject * field = NULL; field = std_msgs__msg__header__convert_to_py(&ros_message->header); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "header", field); Py_DECREF(field); if (rc) { return NULL; } } } { // position PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->position); { int rc = PyObject_SetAttrString(_pymessage, "position", field); Py_DECREF(field); if (rc) { return NULL; } } } { // velocity PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->velocity); { int rc = PyObject_SetAttrString(_pymessage, "velocity", field); Py_DECREF(field); if (rc) { return NULL; } } } { // error PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->error); { int rc = PyObject_SetAttrString(_pymessage, "error", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/single_joint_position__struct.h" // already included above // #include "control_msgs/action/detail/single_joint_position__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); bool control_msgs__action__single_joint_position__goal__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__single_joint_position__goal__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__single_joint_position__send_goal__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[80]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_SendGoal_Request", full_classname_dest, 79) == 0); } control_msgs__action__SingleJointPosition_SendGoal_Request * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // goal PyObject * field = PyObject_GetAttrString(_pymsg, "goal"); if (!field) { return false; } if (!control_msgs__action__single_joint_position__goal__convert_from_py(field, &ros_message->goal)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__single_joint_position__send_goal__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of SingleJointPosition_SendGoal_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_SendGoal_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__SingleJointPosition_SendGoal_Request * ros_message = (control_msgs__action__SingleJointPosition_SendGoal_Request *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } { // goal PyObject * field = NULL; field = control_msgs__action__single_joint_position__goal__convert_to_py(&ros_message->goal); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/single_joint_position__struct.h" // already included above // #include "control_msgs/action/detail/single_joint_position__functions.h" ROSIDL_GENERATOR_C_IMPORT bool builtin_interfaces__msg__time__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * builtin_interfaces__msg__time__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__single_joint_position__send_goal__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[81]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_SendGoal_Response", full_classname_dest, 80) == 0); } control_msgs__action__SingleJointPosition_SendGoal_Response * ros_message = _ros_message; { // accepted PyObject * field = PyObject_GetAttrString(_pymsg, "accepted"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->accepted = (Py_True == field); Py_DECREF(field); } { // stamp PyObject * field = PyObject_GetAttrString(_pymsg, "stamp"); if (!field) { return false; } if (!builtin_interfaces__msg__time__convert_from_py(field, &ros_message->stamp)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__single_joint_position__send_goal__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of SingleJointPosition_SendGoal_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_SendGoal_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__SingleJointPosition_SendGoal_Response * ros_message = (control_msgs__action__SingleJointPosition_SendGoal_Response *)raw_ros_message; { // accepted PyObject * field = NULL; field = PyBool_FromLong(ros_message->accepted ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "accepted", field); Py_DECREF(field); if (rc) { return NULL; } } } { // stamp PyObject * field = NULL; field = builtin_interfaces__msg__time__convert_to_py(&ros_message->stamp); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "stamp", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/single_joint_position__struct.h" // already included above // #include "control_msgs/action/detail/single_joint_position__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__single_joint_position__get_result__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[81]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_GetResult_Request", full_classname_dest, 80) == 0); } control_msgs__action__SingleJointPosition_GetResult_Request * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__single_joint_position__get_result__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of SingleJointPosition_GetResult_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_GetResult_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__SingleJointPosition_GetResult_Request * ros_message = (control_msgs__action__SingleJointPosition_GetResult_Request *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/single_joint_position__struct.h" // already included above // #include "control_msgs/action/detail/single_joint_position__functions.h" bool control_msgs__action__single_joint_position__result__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__single_joint_position__result__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__single_joint_position__get_result__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[82]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_GetResult_Response", full_classname_dest, 81) == 0); } control_msgs__action__SingleJointPosition_GetResult_Response * ros_message = _ros_message; { // status PyObject * field = PyObject_GetAttrString(_pymsg, "status"); if (!field) { return false; } assert(PyLong_Check(field)); ros_message->status = (int8_t)PyLong_AsLong(field); Py_DECREF(field); } { // result PyObject * field = PyObject_GetAttrString(_pymsg, "result"); if (!field) { return false; } if (!control_msgs__action__single_joint_position__result__convert_from_py(field, &ros_message->result)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__single_joint_position__get_result__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of SingleJointPosition_GetResult_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_GetResult_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__SingleJointPosition_GetResult_Response * ros_message = (control_msgs__action__SingleJointPosition_GetResult_Response *)raw_ros_message; { // status PyObject * field = NULL; field = PyLong_FromLong(ros_message->status); { int rc = PyObject_SetAttrString(_pymessage, "status", field); Py_DECREF(field); if (rc) { return NULL; } } } { // result PyObject * field = NULL; field = control_msgs__action__single_joint_position__result__convert_to_py(&ros_message->result); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "result", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "control_msgs/action/detail/single_joint_position__struct.h" // already included above // #include "control_msgs/action/detail/single_joint_position__functions.h" ROSIDL_GENERATOR_C_IMPORT bool unique_identifier_msgs__msg__uuid__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * unique_identifier_msgs__msg__uuid__convert_to_py(void * raw_ros_message); bool control_msgs__action__single_joint_position__feedback__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__action__single_joint_position__feedback__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__action__single_joint_position__feedback_message__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[79]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.action._single_joint_position.SingleJointPosition_FeedbackMessage", full_classname_dest, 78) == 0); } control_msgs__action__SingleJointPosition_FeedbackMessage * ros_message = _ros_message; { // goal_id PyObject * field = PyObject_GetAttrString(_pymsg, "goal_id"); if (!field) { return false; } if (!unique_identifier_msgs__msg__uuid__convert_from_py(field, &ros_message->goal_id)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // feedback PyObject * field = PyObject_GetAttrString(_pymsg, "feedback"); if (!field) { return false; } if (!control_msgs__action__single_joint_position__feedback__convert_from_py(field, &ros_message->feedback)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__action__single_joint_position__feedback_message__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of SingleJointPosition_FeedbackMessage */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.action._single_joint_position"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SingleJointPosition_FeedbackMessage"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__action__SingleJointPosition_FeedbackMessage * ros_message = (control_msgs__action__SingleJointPosition_FeedbackMessage *)raw_ros_message; { // goal_id PyObject * field = NULL; field = unique_identifier_msgs__msg__uuid__convert_to_py(&ros_message->goal_id); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "goal_id", field); Py_DECREF(field); if (rc) { return NULL; } } } { // feedback PyObject * field = NULL; field = control_msgs__action__single_joint_position__feedback__convert_to_py(&ros_message->feedback); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "feedback", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
33,535
C
32.536
159
0.648218
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_tolerance_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:msg/JointTolerance.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/msg/detail/joint_tolerance__struct.h" #include "control_msgs/msg/detail/joint_tolerance__functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__msg__joint_tolerance__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[49]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.msg._joint_tolerance.JointTolerance", full_classname_dest, 48) == 0); } control_msgs__msg__JointTolerance * ros_message = _ros_message; { // name PyObject * field = PyObject_GetAttrString(_pymsg, "name"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->name, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } { // position PyObject * field = PyObject_GetAttrString(_pymsg, "position"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->position = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // velocity PyObject * field = PyObject_GetAttrString(_pymsg, "velocity"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->velocity = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // acceleration PyObject * field = PyObject_GetAttrString(_pymsg, "acceleration"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->acceleration = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__msg__joint_tolerance__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointTolerance */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._joint_tolerance"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTolerance"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__msg__JointTolerance * ros_message = (control_msgs__msg__JointTolerance *)raw_ros_message; { // name PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->name.data, strlen(ros_message->name.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "name", field); Py_DECREF(field); if (rc) { return NULL; } } } { // position PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->position); { int rc = PyObject_SetAttrString(_pymessage, "position", field); Py_DECREF(field); if (rc) { return NULL; } } } { // velocity PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->velocity); { int rc = PyObject_SetAttrString(_pymessage, "velocity", field); Py_DECREF(field); if (rc) { return NULL; } } } { // acceleration PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->acceleration); { int rc = PyObject_SetAttrString(_pymessage, "acceleration", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
5,128
C
28.477011
105
0.629485
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_interface_value.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/InterfaceValue.idl # generated code does not contain a copyright notice # Import statements for member types # Member 'values' import array # noqa: E402, I100 import rosidl_parser.definition # noqa: E402, I100 class Metaclass_InterfaceValue(type): """Metaclass of message 'InterfaceValue'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.InterfaceValue') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__interface_value cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__interface_value cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__interface_value cls._TYPE_SUPPORT = module.type_support_msg__msg__interface_value cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__interface_value @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class InterfaceValue(metaclass=Metaclass_InterfaceValue): """Message class 'InterfaceValue'.""" __slots__ = [ '_interface_names', '_values', ] _fields_and_field_types = { 'interface_names': 'sequence<string>', 'values': 'sequence<double>', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.interface_names = kwargs.get('interface_names', []) self.values = array.array('d', kwargs.get('values', [])) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.interface_names != other.interface_names: return False if self.values != other.values: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def interface_names(self): """Message field 'interface_names'.""" return self._interface_names @interface_names.setter def interface_names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'interface_names' field must be a set or sequence and each value of type 'str'" self._interface_names = value @property def values(self): """Message field 'values'.""" return self._values @values.setter def values(self, value): if isinstance(value, array.array): assert value.typecode == 'd', \ "The 'values' array.array() must have the type code of 'd'" self._values = value return if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, float) for v in value) and True), \ "The 'values' field must be a set or sequence and each value of type 'float'" self._values = array.array('d', value)
6,387
Python
36.57647
134
0.571473
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_trajectory_controller_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/JointTrajectoryControllerState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_JointTrajectoryControllerState(type): """Metaclass of message 'JointTrajectoryControllerState'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.JointTrajectoryControllerState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_trajectory_controller_state cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_trajectory_controller_state cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_trajectory_controller_state cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_trajectory_controller_state cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_trajectory_controller_state from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__class__.__import_type_support__() from trajectory_msgs.msg import JointTrajectoryPoint if JointTrajectoryPoint.__class__._TYPE_SUPPORT is None: JointTrajectoryPoint.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointTrajectoryControllerState(metaclass=Metaclass_JointTrajectoryControllerState): """Message class 'JointTrajectoryControllerState'.""" __slots__ = [ '_header', '_joint_names', '_desired', '_actual', '_error', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'joint_names': 'sequence<string>', 'desired': 'trajectory_msgs/JointTrajectoryPoint', 'actual': 'trajectory_msgs/JointTrajectoryPoint', 'error': 'trajectory_msgs/JointTrajectoryPoint', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501 rosidl_parser.definition.NamespacedType(['trajectory_msgs', 'msg'], 'JointTrajectoryPoint'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.joint_names = kwargs.get('joint_names', []) from trajectory_msgs.msg import JointTrajectoryPoint self.desired = kwargs.get('desired', JointTrajectoryPoint()) from trajectory_msgs.msg import JointTrajectoryPoint self.actual = kwargs.get('actual', JointTrajectoryPoint()) from trajectory_msgs.msg import JointTrajectoryPoint self.error = kwargs.get('error', JointTrajectoryPoint()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.header != other.header: return False if self.joint_names != other.joint_names: return False if self.desired != other.desired: return False if self.actual != other.actual: return False if self.error != other.error: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def joint_names(self): """Message field 'joint_names'.""" return self._joint_names @joint_names.setter def joint_names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'joint_names' field must be a set or sequence and each value of type 'str'" self._joint_names = value @property def desired(self): """Message field 'desired'.""" return self._desired @desired.setter def desired(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'desired' field must be a sub message of type 'JointTrajectoryPoint'" self._desired = value @property def actual(self): """Message field 'actual'.""" return self._actual @actual.setter def actual(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'actual' field must be a sub message of type 'JointTrajectoryPoint'" self._actual = value @property def error(self): """Message field 'error'.""" return self._error @error.setter def error(self, value): if __debug__: from trajectory_msgs.msg import JointTrajectoryPoint assert \ isinstance(value, JointTrajectoryPoint), \ "The 'error' field must be a sub message of type 'JointTrajectoryPoint'" self._error = value
8,648
Python
37.44
134
0.591351
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_interface_value_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:msg/InterfaceValue.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/msg/detail/interface_value__struct.h" #include "control_msgs/msg/detail/interface_value__functions.h" #include "rosidl_runtime_c/primitives_sequence.h" #include "rosidl_runtime_c/primitives_sequence_functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__msg__interface_value__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[49]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.msg._interface_value.InterfaceValue", full_classname_dest, 48) == 0); } control_msgs__msg__InterfaceValue * ros_message = _ros_message; { // interface_names PyObject * field = PyObject_GetAttrString(_pymsg, "interface_names"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'interface_names'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->interface_names), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->interface_names.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // values PyObject * field = PyObject_GetAttrString(_pymsg, "values"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'values'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->values), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } double * dest = ros_message->values.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyFloat_Check(item)); double tmp = PyFloat_AS_DOUBLE(item); memcpy(&dest[i], &tmp, sizeof(double)); } Py_DECREF(seq_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__msg__interface_value__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of InterfaceValue */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._interface_value"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "InterfaceValue"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__msg__InterfaceValue * ros_message = (control_msgs__msg__InterfaceValue *)raw_ros_message; { // interface_names PyObject * field = NULL; size_t size = ros_message->interface_names.size; rosidl_runtime_c__String * src = ros_message->interface_names.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "interface_names", field); Py_DECREF(field); if (rc) { return NULL; } } } { // values PyObject * field = NULL; field = PyObject_GetAttrString(_pymessage, "values"); if (!field) { return NULL; } assert(field->ob_type != NULL); assert(field->ob_type->tp_name != NULL); assert(strcmp(field->ob_type->tp_name, "array.array") == 0); // ensure that itemsize matches the sizeof of the ROS message field PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize"); assert(itemsize_attr != NULL); size_t itemsize = PyLong_AsSize_t(itemsize_attr); Py_DECREF(itemsize_attr); if (itemsize != sizeof(double)) { PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation"); Py_DECREF(field); return NULL; } // clear the array, poor approach to remove potential default values Py_ssize_t length = PyObject_Length(field); if (-1 == length) { Py_DECREF(field); return NULL; } if (length > 0) { PyObject * pop = PyObject_GetAttrString(field, "pop"); assert(pop != NULL); for (Py_ssize_t i = 0; i < length; ++i) { PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL); if (!ret) { Py_DECREF(pop); Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(pop); } if (ros_message->values.size > 0) { // populating the array.array using the frombytes method PyObject * frombytes = PyObject_GetAttrString(field, "frombytes"); assert(frombytes != NULL); double * src = &(ros_message->values.data[0]); PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->values.size * sizeof(double)); assert(data != NULL); PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL); Py_DECREF(data); Py_DECREF(frombytes); if (!ret) { Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(field); } // ownership of _pymessage is transferred to the caller return _pymessage; }
8,143
C
31.97166
112
0.617954
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_pid_state_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:msg/PidState.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/msg/detail/pid_state__struct.h" #include "control_msgs/msg/detail/pid_state__functions.h" ROSIDL_GENERATOR_C_IMPORT bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_IMPORT bool builtin_interfaces__msg__duration__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * builtin_interfaces__msg__duration__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__msg__pid_state__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[37]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.msg._pid_state.PidState", full_classname_dest, 36) == 0); } control_msgs__msg__PidState * ros_message = _ros_message; { // header PyObject * field = PyObject_GetAttrString(_pymsg, "header"); if (!field) { return false; } if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // timestep PyObject * field = PyObject_GetAttrString(_pymsg, "timestep"); if (!field) { return false; } if (!builtin_interfaces__msg__duration__convert_from_py(field, &ros_message->timestep)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // error PyObject * field = PyObject_GetAttrString(_pymsg, "error"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->error = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // error_dot PyObject * field = PyObject_GetAttrString(_pymsg, "error_dot"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->error_dot = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // p_error PyObject * field = PyObject_GetAttrString(_pymsg, "p_error"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->p_error = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // i_error PyObject * field = PyObject_GetAttrString(_pymsg, "i_error"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->i_error = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // d_error PyObject * field = PyObject_GetAttrString(_pymsg, "d_error"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->d_error = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // p_term PyObject * field = PyObject_GetAttrString(_pymsg, "p_term"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->p_term = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // i_term PyObject * field = PyObject_GetAttrString(_pymsg, "i_term"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->i_term = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // d_term PyObject * field = PyObject_GetAttrString(_pymsg, "d_term"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->d_term = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // i_max PyObject * field = PyObject_GetAttrString(_pymsg, "i_max"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->i_max = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // i_min PyObject * field = PyObject_GetAttrString(_pymsg, "i_min"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->i_min = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // output PyObject * field = PyObject_GetAttrString(_pymsg, "output"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->output = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__msg__pid_state__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of PidState */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._pid_state"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "PidState"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__msg__PidState * ros_message = (control_msgs__msg__PidState *)raw_ros_message; { // header PyObject * field = NULL; field = std_msgs__msg__header__convert_to_py(&ros_message->header); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "header", field); Py_DECREF(field); if (rc) { return NULL; } } } { // timestep PyObject * field = NULL; field = builtin_interfaces__msg__duration__convert_to_py(&ros_message->timestep); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "timestep", field); Py_DECREF(field); if (rc) { return NULL; } } } { // error PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->error); { int rc = PyObject_SetAttrString(_pymessage, "error", field); Py_DECREF(field); if (rc) { return NULL; } } } { // error_dot PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->error_dot); { int rc = PyObject_SetAttrString(_pymessage, "error_dot", field); Py_DECREF(field); if (rc) { return NULL; } } } { // p_error PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->p_error); { int rc = PyObject_SetAttrString(_pymessage, "p_error", field); Py_DECREF(field); if (rc) { return NULL; } } } { // i_error PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->i_error); { int rc = PyObject_SetAttrString(_pymessage, "i_error", field); Py_DECREF(field); if (rc) { return NULL; } } } { // d_error PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->d_error); { int rc = PyObject_SetAttrString(_pymessage, "d_error", field); Py_DECREF(field); if (rc) { return NULL; } } } { // p_term PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->p_term); { int rc = PyObject_SetAttrString(_pymessage, "p_term", field); Py_DECREF(field); if (rc) { return NULL; } } } { // i_term PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->i_term); { int rc = PyObject_SetAttrString(_pymessage, "i_term", field); Py_DECREF(field); if (rc) { return NULL; } } } { // d_term PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->d_term); { int rc = PyObject_SetAttrString(_pymessage, "d_term", field); Py_DECREF(field); if (rc) { return NULL; } } } { // i_max PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->i_max); { int rc = PyObject_SetAttrString(_pymessage, "i_max", field); Py_DECREF(field); if (rc) { return NULL; } } } { // i_min PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->i_min); { int rc = PyObject_SetAttrString(_pymessage, "i_min", field); Py_DECREF(field); if (rc) { return NULL; } } } { // output PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->output); { int rc = PyObject_SetAttrString(_pymessage, "output", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
9,678
C
26.112045
99
0.593511
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_tolerance.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/JointTolerance.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_JointTolerance(type): """Metaclass of message 'JointTolerance'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.JointTolerance') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_tolerance cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_tolerance cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_tolerance cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_tolerance cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_tolerance @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointTolerance(metaclass=Metaclass_JointTolerance): """Message class 'JointTolerance'.""" __slots__ = [ '_name', '_position', '_velocity', '_acceleration', ] _fields_and_field_types = { 'name': 'string', 'position': 'double', 'velocity': 'double', 'acceleration': 'double', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.name = kwargs.get('name', str()) self.position = kwargs.get('position', float()) self.velocity = kwargs.get('velocity', float()) self.acceleration = kwargs.get('acceleration', float()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.name != other.name: return False if self.position != other.position: return False if self.velocity != other.velocity: return False if self.acceleration != other.acceleration: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def name(self): """Message field 'name'.""" return self._name @name.setter def name(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'name' field must be of type 'str'" self._name = value @property def position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def velocity(self): """Message field 'velocity'.""" return self._velocity @velocity.setter def velocity(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'velocity' field must be of type 'float'" self._velocity = value @property def acceleration(self): """Message field 'acceleration'.""" return self._acceleration @acceleration.setter def acceleration(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'acceleration' field must be of type 'float'" self._acceleration = value
6,075
Python
32.755555
134
0.560329
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_dynamic_joint_state_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:msg/DynamicJointState.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/msg/detail/dynamic_joint_state__struct.h" #include "control_msgs/msg/detail/dynamic_joint_state__functions.h" #include "rosidl_runtime_c/primitives_sequence.h" #include "rosidl_runtime_c/primitives_sequence_functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" // Nested array functions includes #include "control_msgs/msg/detail/interface_value__functions.h" // end nested array functions include ROSIDL_GENERATOR_C_IMPORT bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message); bool control_msgs__msg__interface_value__convert_from_py(PyObject * _pymsg, void * _ros_message); PyObject * control_msgs__msg__interface_value__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__msg__dynamic_joint_state__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[56]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.msg._dynamic_joint_state.DynamicJointState", full_classname_dest, 55) == 0); } control_msgs__msg__DynamicJointState * ros_message = _ros_message; { // header PyObject * field = PyObject_GetAttrString(_pymsg, "header"); if (!field) { return false; } if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // joint_names PyObject * field = PyObject_GetAttrString(_pymsg, "joint_names"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'joint_names'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->joint_names), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->joint_names.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // interface_values PyObject * field = PyObject_GetAttrString(_pymsg, "interface_values"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'interface_values'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!control_msgs__msg__InterfaceValue__Sequence__init(&(ros_message->interface_values), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create control_msgs__msg__InterfaceValue__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } control_msgs__msg__InterfaceValue * dest = ros_message->interface_values.data; for (Py_ssize_t i = 0; i < size; ++i) { if (!control_msgs__msg__interface_value__convert_from_py(PySequence_Fast_GET_ITEM(seq_field, i), &dest[i])) { Py_DECREF(seq_field); Py_DECREF(field); return false; } } Py_DECREF(seq_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__msg__dynamic_joint_state__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of DynamicJointState */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._dynamic_joint_state"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "DynamicJointState"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__msg__DynamicJointState * ros_message = (control_msgs__msg__DynamicJointState *)raw_ros_message; { // header PyObject * field = NULL; field = std_msgs__msg__header__convert_to_py(&ros_message->header); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "header", field); Py_DECREF(field); if (rc) { return NULL; } } } { // joint_names PyObject * field = NULL; size_t size = ros_message->joint_names.size; rosidl_runtime_c__String * src = ros_message->joint_names.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "joint_names", field); Py_DECREF(field); if (rc) { return NULL; } } } { // interface_values PyObject * field = NULL; size_t size = ros_message->interface_values.size; field = PyList_New(size); if (!field) { return NULL; } control_msgs__msg__InterfaceValue * item; for (size_t i = 0; i < size; ++i) { item = &(ros_message->interface_values.data[i]); PyObject * pyitem = control_msgs__msg__interface_value__convert_to_py(item); if (!pyitem) { Py_DECREF(field); return NULL; } int rc = PyList_SetItem(field, i, pyitem); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "interface_values", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
8,105
C
31.685484
118
0.624553
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_controller_state_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:msg/JointControllerState.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/msg/detail/joint_controller_state__struct.h" #include "control_msgs/msg/detail/joint_controller_state__functions.h" ROSIDL_GENERATOR_C_IMPORT bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__msg__joint_controller_state__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[62]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.msg._joint_controller_state.JointControllerState", full_classname_dest, 61) == 0); } control_msgs__msg__JointControllerState * ros_message = _ros_message; { // header PyObject * field = PyObject_GetAttrString(_pymsg, "header"); if (!field) { return false; } if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // set_point PyObject * field = PyObject_GetAttrString(_pymsg, "set_point"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->set_point = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // process_value PyObject * field = PyObject_GetAttrString(_pymsg, "process_value"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->process_value = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // process_value_dot PyObject * field = PyObject_GetAttrString(_pymsg, "process_value_dot"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->process_value_dot = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // error PyObject * field = PyObject_GetAttrString(_pymsg, "error"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->error = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // time_step PyObject * field = PyObject_GetAttrString(_pymsg, "time_step"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->time_step = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // command PyObject * field = PyObject_GetAttrString(_pymsg, "command"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->command = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // p PyObject * field = PyObject_GetAttrString(_pymsg, "p"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->p = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // i PyObject * field = PyObject_GetAttrString(_pymsg, "i"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->i = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // d PyObject * field = PyObject_GetAttrString(_pymsg, "d"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->d = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // i_clamp PyObject * field = PyObject_GetAttrString(_pymsg, "i_clamp"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->i_clamp = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // antiwindup PyObject * field = PyObject_GetAttrString(_pymsg, "antiwindup"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->antiwindup = (Py_True == field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__msg__joint_controller_state__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointControllerState */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._joint_controller_state"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointControllerState"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__msg__JointControllerState * ros_message = (control_msgs__msg__JointControllerState *)raw_ros_message; { // header PyObject * field = NULL; field = std_msgs__msg__header__convert_to_py(&ros_message->header); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "header", field); Py_DECREF(field); if (rc) { return NULL; } } } { // set_point PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->set_point); { int rc = PyObject_SetAttrString(_pymessage, "set_point", field); Py_DECREF(field); if (rc) { return NULL; } } } { // process_value PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->process_value); { int rc = PyObject_SetAttrString(_pymessage, "process_value", field); Py_DECREF(field); if (rc) { return NULL; } } } { // process_value_dot PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->process_value_dot); { int rc = PyObject_SetAttrString(_pymessage, "process_value_dot", field); Py_DECREF(field); if (rc) { return NULL; } } } { // error PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->error); { int rc = PyObject_SetAttrString(_pymessage, "error", field); Py_DECREF(field); if (rc) { return NULL; } } } { // time_step PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->time_step); { int rc = PyObject_SetAttrString(_pymessage, "time_step", field); Py_DECREF(field); if (rc) { return NULL; } } } { // command PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->command); { int rc = PyObject_SetAttrString(_pymessage, "command", field); Py_DECREF(field); if (rc) { return NULL; } } } { // p PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->p); { int rc = PyObject_SetAttrString(_pymessage, "p", field); Py_DECREF(field); if (rc) { return NULL; } } } { // i PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->i); { int rc = PyObject_SetAttrString(_pymessage, "i", field); Py_DECREF(field); if (rc) { return NULL; } } } { // d PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->d); { int rc = PyObject_SetAttrString(_pymessage, "d", field); Py_DECREF(field); if (rc) { return NULL; } } } { // i_clamp PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->i_clamp); { int rc = PyObject_SetAttrString(_pymessage, "i_clamp", field); Py_DECREF(field); if (rc) { return NULL; } } } { // antiwindup PyObject * field = NULL; field = PyBool_FromLong(ros_message->antiwindup ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "antiwindup", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
9,042
C
26.570122
117
0.601416
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_pid_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/PidState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_PidState(type): """Metaclass of message 'PidState'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.PidState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__pid_state cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__pid_state cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__pid_state cls._TYPE_SUPPORT = module.type_support_msg__msg__pid_state cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__pid_state from builtin_interfaces.msg import Duration if Duration.__class__._TYPE_SUPPORT is None: Duration.__class__.__import_type_support__() from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class PidState(metaclass=Metaclass_PidState): """Message class 'PidState'.""" __slots__ = [ '_header', '_timestep', '_error', '_error_dot', '_p_error', '_i_error', '_d_error', '_p_term', '_i_term', '_d_term', '_i_max', '_i_min', '_output', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'timestep': 'builtin_interfaces/Duration', 'error': 'double', 'error_dot': 'double', 'p_error': 'double', 'i_error': 'double', 'd_error': 'double', 'p_term': 'double', 'i_term': 'double', 'd_term': 'double', 'i_max': 'double', 'i_min': 'double', 'output': 'double', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Duration'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) from builtin_interfaces.msg import Duration self.timestep = kwargs.get('timestep', Duration()) self.error = kwargs.get('error', float()) self.error_dot = kwargs.get('error_dot', float()) self.p_error = kwargs.get('p_error', float()) self.i_error = kwargs.get('i_error', float()) self.d_error = kwargs.get('d_error', float()) self.p_term = kwargs.get('p_term', float()) self.i_term = kwargs.get('i_term', float()) self.d_term = kwargs.get('d_term', float()) self.i_max = kwargs.get('i_max', float()) self.i_min = kwargs.get('i_min', float()) self.output = kwargs.get('output', float()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.header != other.header: return False if self.timestep != other.timestep: return False if self.error != other.error: return False if self.error_dot != other.error_dot: return False if self.p_error != other.p_error: return False if self.i_error != other.i_error: return False if self.d_error != other.d_error: return False if self.p_term != other.p_term: return False if self.i_term != other.i_term: return False if self.d_term != other.d_term: return False if self.i_max != other.i_max: return False if self.i_min != other.i_min: return False if self.output != other.output: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def timestep(self): """Message field 'timestep'.""" return self._timestep @timestep.setter def timestep(self, value): if __debug__: from builtin_interfaces.msg import Duration assert \ isinstance(value, Duration), \ "The 'timestep' field must be a sub message of type 'Duration'" self._timestep = value @property def error(self): """Message field 'error'.""" return self._error @error.setter def error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'error' field must be of type 'float'" self._error = value @property def error_dot(self): """Message field 'error_dot'.""" return self._error_dot @error_dot.setter def error_dot(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'error_dot' field must be of type 'float'" self._error_dot = value @property def p_error(self): """Message field 'p_error'.""" return self._p_error @p_error.setter def p_error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'p_error' field must be of type 'float'" self._p_error = value @property def i_error(self): """Message field 'i_error'.""" return self._i_error @i_error.setter def i_error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i_error' field must be of type 'float'" self._i_error = value @property def d_error(self): """Message field 'd_error'.""" return self._d_error @d_error.setter def d_error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'd_error' field must be of type 'float'" self._d_error = value @property def p_term(self): """Message field 'p_term'.""" return self._p_term @p_term.setter def p_term(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'p_term' field must be of type 'float'" self._p_term = value @property def i_term(self): """Message field 'i_term'.""" return self._i_term @i_term.setter def i_term(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i_term' field must be of type 'float'" self._i_term = value @property def d_term(self): """Message field 'd_term'.""" return self._d_term @d_term.setter def d_term(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'd_term' field must be of type 'float'" self._d_term = value @property def i_max(self): """Message field 'i_max'.""" return self._i_max @i_max.setter def i_max(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i_max' field must be of type 'float'" self._i_max = value @property def i_min(self): """Message field 'i_min'.""" return self._i_min @i_min.setter def i_min(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i_min' field must be of type 'float'" self._i_min = value @property def output(self): """Message field 'output'.""" return self._output @output.setter def output(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'output' field must be of type 'float'" self._output = value
11,681
Python
31.181818
134
0.532061
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_controller_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/JointControllerState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_JointControllerState(type): """Metaclass of message 'JointControllerState'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.JointControllerState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_controller_state cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_controller_state cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_controller_state cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_controller_state cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_controller_state from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointControllerState(metaclass=Metaclass_JointControllerState): """Message class 'JointControllerState'.""" __slots__ = [ '_header', '_set_point', '_process_value', '_process_value_dot', '_error', '_time_step', '_command', '_p', '_i', '_d', '_i_clamp', '_antiwindup', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'set_point': 'double', 'process_value': 'double', 'process_value_dot': 'double', 'error': 'double', 'time_step': 'double', 'command': 'double', 'p': 'double', 'i': 'double', 'd': 'double', 'i_clamp': 'double', 'antiwindup': 'boolean', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.set_point = kwargs.get('set_point', float()) self.process_value = kwargs.get('process_value', float()) self.process_value_dot = kwargs.get('process_value_dot', float()) self.error = kwargs.get('error', float()) self.time_step = kwargs.get('time_step', float()) self.command = kwargs.get('command', float()) self.p = kwargs.get('p', float()) self.i = kwargs.get('i', float()) self.d = kwargs.get('d', float()) self.i_clamp = kwargs.get('i_clamp', float()) self.antiwindup = kwargs.get('antiwindup', bool()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.header != other.header: return False if self.set_point != other.set_point: return False if self.process_value != other.process_value: return False if self.process_value_dot != other.process_value_dot: return False if self.error != other.error: return False if self.time_step != other.time_step: return False if self.command != other.command: return False if self.p != other.p: return False if self.i != other.i: return False if self.d != other.d: return False if self.i_clamp != other.i_clamp: return False if self.antiwindup != other.antiwindup: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def set_point(self): """Message field 'set_point'.""" return self._set_point @set_point.setter def set_point(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'set_point' field must be of type 'float'" self._set_point = value @property def process_value(self): """Message field 'process_value'.""" return self._process_value @process_value.setter def process_value(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'process_value' field must be of type 'float'" self._process_value = value @property def process_value_dot(self): """Message field 'process_value_dot'.""" return self._process_value_dot @process_value_dot.setter def process_value_dot(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'process_value_dot' field must be of type 'float'" self._process_value_dot = value @property def error(self): """Message field 'error'.""" return self._error @error.setter def error(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'error' field must be of type 'float'" self._error = value @property def time_step(self): """Message field 'time_step'.""" return self._time_step @time_step.setter def time_step(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'time_step' field must be of type 'float'" self._time_step = value @property def command(self): """Message field 'command'.""" return self._command @command.setter def command(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'command' field must be of type 'float'" self._command = value @property def p(self): """Message field 'p'.""" return self._p @p.setter def p(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'p' field must be of type 'float'" self._p = value @property def i(self): """Message field 'i'.""" return self._i @i.setter def i(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i' field must be of type 'float'" self._i = value @property def d(self): """Message field 'd'.""" return self._d @d.setter def d(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'd' field must be of type 'float'" self._d = value @property def i_clamp(self): """Message field 'i_clamp'.""" return self._i_clamp @i_clamp.setter def i_clamp(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'i_clamp' field must be of type 'float'" self._i_clamp = value @property def antiwindup(self): """Message field 'antiwindup'.""" return self._antiwindup @antiwindup.setter def antiwindup(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'antiwindup' field must be of type 'bool'" self._antiwindup = value
11,020
Python
31.606509
134
0.54274
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/__init__.py
from control_msgs.msg._dynamic_joint_state import DynamicJointState # noqa: F401 from control_msgs.msg._gripper_command import GripperCommand # noqa: F401 from control_msgs.msg._interface_value import InterfaceValue # noqa: F401 from control_msgs.msg._joint_controller_state import JointControllerState # noqa: F401 from control_msgs.msg._joint_jog import JointJog # noqa: F401 from control_msgs.msg._joint_tolerance import JointTolerance # noqa: F401 from control_msgs.msg._joint_trajectory_controller_state import JointTrajectoryControllerState # noqa: F401 from control_msgs.msg._pid_state import PidState # noqa: F401
630
Python
69.111103
108
0.803175
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_gripper_command_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:msg/GripperCommand.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/msg/detail/gripper_command__struct.h" #include "control_msgs/msg/detail/gripper_command__functions.h" ROSIDL_GENERATOR_C_EXPORT bool control_msgs__msg__gripper_command__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[49]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.msg._gripper_command.GripperCommand", full_classname_dest, 48) == 0); } control_msgs__msg__GripperCommand * ros_message = _ros_message; { // position PyObject * field = PyObject_GetAttrString(_pymsg, "position"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->position = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } { // max_effort PyObject * field = PyObject_GetAttrString(_pymsg, "max_effort"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->max_effort = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__msg__gripper_command__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GripperCommand */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._gripper_command"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GripperCommand"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__msg__GripperCommand * ros_message = (control_msgs__msg__GripperCommand *)raw_ros_message; { // position PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->position); { int rc = PyObject_SetAttrString(_pymessage, "position", field); Py_DECREF(field); if (rc) { return NULL; } } } { // max_effort PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->max_effort); { int rc = PyObject_SetAttrString(_pymessage, "max_effort", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
3,736
C
30.403361
105
0.643201
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_gripper_command.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/GripperCommand.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GripperCommand(type): """Metaclass of message 'GripperCommand'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.GripperCommand') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__gripper_command cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__gripper_command cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__gripper_command cls._TYPE_SUPPORT = module.type_support_msg__msg__gripper_command cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__gripper_command @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GripperCommand(metaclass=Metaclass_GripperCommand): """Message class 'GripperCommand'.""" __slots__ = [ '_position', '_max_effort', ] _fields_and_field_types = { 'position': 'double', 'max_effort': 'double', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('double'), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.position = kwargs.get('position', float()) self.max_effort = kwargs.get('max_effort', float()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.position != other.position: return False if self.max_effort != other.max_effort: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def position(self): """Message field 'position'.""" return self._position @position.setter def position(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'position' field must be of type 'float'" self._position = value @property def max_effort(self): """Message field 'max_effort'.""" return self._max_effort @max_effort.setter def max_effort(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'max_effort' field must be of type 'float'" self._max_effort = value
4,935
Python
33.760563
134
0.565147
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_trajectory_controller_state_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:msg/JointTrajectoryControllerState.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/msg/detail/joint_trajectory_controller_state__struct.h" #include "control_msgs/msg/detail/joint_trajectory_controller_state__functions.h" #include "rosidl_runtime_c/primitives_sequence.h" #include "rosidl_runtime_c/primitives_sequence_functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_IMPORT bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_IMPORT bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_IMPORT bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_IMPORT bool trajectory_msgs__msg__joint_trajectory_point__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * trajectory_msgs__msg__joint_trajectory_point__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__msg__joint_trajectory_controller_state__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[83]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.msg._joint_trajectory_controller_state.JointTrajectoryControllerState", full_classname_dest, 82) == 0); } control_msgs__msg__JointTrajectoryControllerState * ros_message = _ros_message; { // header PyObject * field = PyObject_GetAttrString(_pymsg, "header"); if (!field) { return false; } if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // joint_names PyObject * field = PyObject_GetAttrString(_pymsg, "joint_names"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'joint_names'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->joint_names), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->joint_names.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // desired PyObject * field = PyObject_GetAttrString(_pymsg, "desired"); if (!field) { return false; } if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->desired)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // actual PyObject * field = PyObject_GetAttrString(_pymsg, "actual"); if (!field) { return false; } if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->actual)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // error PyObject * field = PyObject_GetAttrString(_pymsg, "error"); if (!field) { return false; } if (!trajectory_msgs__msg__joint_trajectory_point__convert_from_py(field, &ros_message->error)) { Py_DECREF(field); return false; } Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__msg__joint_trajectory_controller_state__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointTrajectoryControllerState */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._joint_trajectory_controller_state"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointTrajectoryControllerState"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__msg__JointTrajectoryControllerState * ros_message = (control_msgs__msg__JointTrajectoryControllerState *)raw_ros_message; { // header PyObject * field = NULL; field = std_msgs__msg__header__convert_to_py(&ros_message->header); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "header", field); Py_DECREF(field); if (rc) { return NULL; } } } { // joint_names PyObject * field = NULL; size_t size = ros_message->joint_names.size; rosidl_runtime_c__String * src = ros_message->joint_names.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "joint_names", field); Py_DECREF(field); if (rc) { return NULL; } } } { // desired PyObject * field = NULL; field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->desired); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "desired", field); Py_DECREF(field); if (rc) { return NULL; } } } { // actual PyObject * field = NULL; field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->actual); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "actual", field); Py_DECREF(field); if (rc) { return NULL; } } } { // error PyObject * field = NULL; field = trajectory_msgs__msg__joint_trajectory_point__convert_to_py(&ros_message->error); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "error", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
8,722
C
31.427509
137
0.634946
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_dynamic_joint_state.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/DynamicJointState.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_DynamicJointState(type): """Metaclass of message 'DynamicJointState'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.DynamicJointState') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__dynamic_joint_state cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__dynamic_joint_state cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__dynamic_joint_state cls._TYPE_SUPPORT = module.type_support_msg__msg__dynamic_joint_state cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__dynamic_joint_state from control_msgs.msg import InterfaceValue if InterfaceValue.__class__._TYPE_SUPPORT is None: InterfaceValue.__class__.__import_type_support__() from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class DynamicJointState(metaclass=Metaclass_DynamicJointState): """Message class 'DynamicJointState'.""" __slots__ = [ '_header', '_joint_names', '_interface_values', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'joint_names': 'sequence<string>', 'interface_values': 'sequence<control_msgs/InterfaceValue>', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.NamespacedType(['control_msgs', 'msg'], 'InterfaceValue')), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.joint_names = kwargs.get('joint_names', []) self.interface_values = kwargs.get('interface_values', []) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.header != other.header: return False if self.joint_names != other.joint_names: return False if self.interface_values != other.interface_values: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def joint_names(self): """Message field 'joint_names'.""" return self._joint_names @joint_names.setter def joint_names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'joint_names' field must be a set or sequence and each value of type 'str'" self._joint_names = value @property def interface_values(self): """Message field 'interface_values'.""" return self._interface_values @interface_values.setter def interface_values(self, value): if __debug__: from control_msgs.msg import InterfaceValue from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, InterfaceValue) for v in value) and True), \ "The 'interface_values' field must be a set or sequence and each value of type 'InterfaceValue'" self._interface_values = value
7,379
Python
37.4375
149
0.577585
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_jog_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from control_msgs:msg/JointJog.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "control_msgs/msg/detail/joint_jog__struct.h" #include "control_msgs/msg/detail/joint_jog__functions.h" #include "rosidl_runtime_c/primitives_sequence.h" #include "rosidl_runtime_c/primitives_sequence_functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_IMPORT bool std_msgs__msg__header__convert_from_py(PyObject * _pymsg, void * _ros_message); ROSIDL_GENERATOR_C_IMPORT PyObject * std_msgs__msg__header__convert_to_py(void * raw_ros_message); ROSIDL_GENERATOR_C_EXPORT bool control_msgs__msg__joint_jog__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[37]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("control_msgs.msg._joint_jog.JointJog", full_classname_dest, 36) == 0); } control_msgs__msg__JointJog * ros_message = _ros_message; { // header PyObject * field = PyObject_GetAttrString(_pymsg, "header"); if (!field) { return false; } if (!std_msgs__msg__header__convert_from_py(field, &ros_message->header)) { Py_DECREF(field); return false; } Py_DECREF(field); } { // joint_names PyObject * field = PyObject_GetAttrString(_pymsg, "joint_names"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'joint_names'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->joint_names), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->joint_names.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // displacements PyObject * field = PyObject_GetAttrString(_pymsg, "displacements"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'displacements'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->displacements), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } double * dest = ros_message->displacements.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyFloat_Check(item)); double tmp = PyFloat_AS_DOUBLE(item); memcpy(&dest[i], &tmp, sizeof(double)); } Py_DECREF(seq_field); Py_DECREF(field); } { // velocities PyObject * field = PyObject_GetAttrString(_pymsg, "velocities"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'velocities'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__double__Sequence__init(&(ros_message->velocities), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create double__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } double * dest = ros_message->velocities.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyFloat_Check(item)); double tmp = PyFloat_AS_DOUBLE(item); memcpy(&dest[i], &tmp, sizeof(double)); } Py_DECREF(seq_field); Py_DECREF(field); } { // duration PyObject * field = PyObject_GetAttrString(_pymsg, "duration"); if (!field) { return false; } assert(PyFloat_Check(field)); ros_message->duration = PyFloat_AS_DOUBLE(field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * control_msgs__msg__joint_jog__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of JointJog */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("control_msgs.msg._joint_jog"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "JointJog"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } control_msgs__msg__JointJog * ros_message = (control_msgs__msg__JointJog *)raw_ros_message; { // header PyObject * field = NULL; field = std_msgs__msg__header__convert_to_py(&ros_message->header); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "header", field); Py_DECREF(field); if (rc) { return NULL; } } } { // joint_names PyObject * field = NULL; size_t size = ros_message->joint_names.size; rosidl_runtime_c__String * src = ros_message->joint_names.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "joint_names", field); Py_DECREF(field); if (rc) { return NULL; } } } { // displacements PyObject * field = NULL; field = PyObject_GetAttrString(_pymessage, "displacements"); if (!field) { return NULL; } assert(field->ob_type != NULL); assert(field->ob_type->tp_name != NULL); assert(strcmp(field->ob_type->tp_name, "array.array") == 0); // ensure that itemsize matches the sizeof of the ROS message field PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize"); assert(itemsize_attr != NULL); size_t itemsize = PyLong_AsSize_t(itemsize_attr); Py_DECREF(itemsize_attr); if (itemsize != sizeof(double)) { PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation"); Py_DECREF(field); return NULL; } // clear the array, poor approach to remove potential default values Py_ssize_t length = PyObject_Length(field); if (-1 == length) { Py_DECREF(field); return NULL; } if (length > 0) { PyObject * pop = PyObject_GetAttrString(field, "pop"); assert(pop != NULL); for (Py_ssize_t i = 0; i < length; ++i) { PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL); if (!ret) { Py_DECREF(pop); Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(pop); } if (ros_message->displacements.size > 0) { // populating the array.array using the frombytes method PyObject * frombytes = PyObject_GetAttrString(field, "frombytes"); assert(frombytes != NULL); double * src = &(ros_message->displacements.data[0]); PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->displacements.size * sizeof(double)); assert(data != NULL); PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL); Py_DECREF(data); Py_DECREF(frombytes); if (!ret) { Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(field); } { // velocities PyObject * field = NULL; field = PyObject_GetAttrString(_pymessage, "velocities"); if (!field) { return NULL; } assert(field->ob_type != NULL); assert(field->ob_type->tp_name != NULL); assert(strcmp(field->ob_type->tp_name, "array.array") == 0); // ensure that itemsize matches the sizeof of the ROS message field PyObject * itemsize_attr = PyObject_GetAttrString(field, "itemsize"); assert(itemsize_attr != NULL); size_t itemsize = PyLong_AsSize_t(itemsize_attr); Py_DECREF(itemsize_attr); if (itemsize != sizeof(double)) { PyErr_SetString(PyExc_RuntimeError, "itemsize doesn't match expectation"); Py_DECREF(field); return NULL; } // clear the array, poor approach to remove potential default values Py_ssize_t length = PyObject_Length(field); if (-1 == length) { Py_DECREF(field); return NULL; } if (length > 0) { PyObject * pop = PyObject_GetAttrString(field, "pop"); assert(pop != NULL); for (Py_ssize_t i = 0; i < length; ++i) { PyObject * ret = PyObject_CallFunctionObjArgs(pop, NULL); if (!ret) { Py_DECREF(pop); Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(pop); } if (ros_message->velocities.size > 0) { // populating the array.array using the frombytes method PyObject * frombytes = PyObject_GetAttrString(field, "frombytes"); assert(frombytes != NULL); double * src = &(ros_message->velocities.data[0]); PyObject * data = PyBytes_FromStringAndSize((const char *)src, ros_message->velocities.size * sizeof(double)); assert(data != NULL); PyObject * ret = PyObject_CallFunctionObjArgs(frombytes, data, NULL); Py_DECREF(data); Py_DECREF(frombytes); if (!ret) { Py_DECREF(field); return NULL; } Py_DECREF(ret); } Py_DECREF(field); } { // duration PyObject * field = NULL; field = PyFloat_FromDouble(ros_message->duration); { int rc = PyObject_SetAttrString(_pymessage, "duration", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
12,528
C
31.125641
119
0.60728
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/control_msgs/msg/_joint_jog.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from control_msgs:msg/JointJog.idl # generated code does not contain a copyright notice # Import statements for member types # Member 'displacements' # Member 'velocities' import array # noqa: E402, I100 import rosidl_parser.definition # noqa: E402, I100 class Metaclass_JointJog(type): """Metaclass of message 'JointJog'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('control_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'control_msgs.msg.JointJog') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__joint_jog cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__joint_jog cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__joint_jog cls._TYPE_SUPPORT = module.type_support_msg__msg__joint_jog cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__joint_jog from std_msgs.msg import Header if Header.__class__._TYPE_SUPPORT is None: Header.__class__.__import_type_support__() @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class JointJog(metaclass=Metaclass_JointJog): """Message class 'JointJog'.""" __slots__ = [ '_header', '_joint_names', '_displacements', '_velocities', '_duration', ] _fields_and_field_types = { 'header': 'std_msgs/Header', 'joint_names': 'sequence<string>', 'displacements': 'sequence<double>', 'velocities': 'sequence<double>', 'duration': 'double', } SLOT_TYPES = ( rosidl_parser.definition.NamespacedType(['std_msgs', 'msg'], 'Header'), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.BasicType('double')), # noqa: E501 rosidl_parser.definition.BasicType('double'), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) from std_msgs.msg import Header self.header = kwargs.get('header', Header()) self.joint_names = kwargs.get('joint_names', []) self.displacements = array.array('d', kwargs.get('displacements', [])) self.velocities = array.array('d', kwargs.get('velocities', [])) self.duration = kwargs.get('duration', float()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.header != other.header: return False if self.joint_names != other.joint_names: return False if self.displacements != other.displacements: return False if self.velocities != other.velocities: return False if self.duration != other.duration: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def header(self): """Message field 'header'.""" return self._header @header.setter def header(self, value): if __debug__: from std_msgs.msg import Header assert \ isinstance(value, Header), \ "The 'header' field must be a sub message of type 'Header'" self._header = value @property def joint_names(self): """Message field 'joint_names'.""" return self._joint_names @joint_names.setter def joint_names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'joint_names' field must be a set or sequence and each value of type 'str'" self._joint_names = value @property def displacements(self): """Message field 'displacements'.""" return self._displacements @displacements.setter def displacements(self, value): if isinstance(value, array.array): assert value.typecode == 'd', \ "The 'displacements' array.array() must have the type code of 'd'" self._displacements = value return if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, float) for v in value) and True), \ "The 'displacements' field must be a set or sequence and each value of type 'float'" self._displacements = array.array('d', value) @property def velocities(self): """Message field 'velocities'.""" return self._velocities @velocities.setter def velocities(self, value): if isinstance(value, array.array): assert value.typecode == 'd', \ "The 'velocities' array.array() must have the type code of 'd'" self._velocities = value return if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, float) for v in value) and True), \ "The 'velocities' field must be a set or sequence and each value of type 'float'" self._velocities = array.array('d', value) @property def duration(self): """Message field 'duration'.""" return self._duration @duration.setter def duration(self, value): if __debug__: assert \ isinstance(value, float), \ "The 'duration' field must be of type 'float'" self._duration = value
9,270
Python
36.232932
134
0.565912
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_set_prim_attribute.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from add_on_msgs:srv/SetPrimAttribute.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_SetPrimAttribute_Request(type): """Metaclass of message 'SetPrimAttribute_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.SetPrimAttribute_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__set_prim_attribute__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__set_prim_attribute__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__set_prim_attribute__request cls._TYPE_SUPPORT = module.type_support_msg__srv__set_prim_attribute__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__set_prim_attribute__request @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class SetPrimAttribute_Request(metaclass=Metaclass_SetPrimAttribute_Request): """Message class 'SetPrimAttribute_Request'.""" __slots__ = [ '_path', '_attribute', '_value', ] _fields_and_field_types = { 'path': 'string', 'attribute': 'string', 'value': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.path = kwargs.get('path', str()) self.attribute = kwargs.get('attribute', str()) self.value = kwargs.get('value', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.path != other.path: return False if self.attribute != other.attribute: return False if self.value != other.value: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def path(self): """Message field 'path'.""" return self._path @path.setter def path(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'path' field must be of type 'str'" self._path = value @property def attribute(self): """Message field 'attribute'.""" return self._attribute @attribute.setter def attribute(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'attribute' field must be of type 'str'" self._attribute = value @property def value(self): """Message field 'value'.""" return self._value @value.setter def value(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'value' field must be of type 'str'" self._value = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_SetPrimAttribute_Response(type): """Metaclass of message 'SetPrimAttribute_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.SetPrimAttribute_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__set_prim_attribute__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__set_prim_attribute__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__set_prim_attribute__response cls._TYPE_SUPPORT = module.type_support_msg__srv__set_prim_attribute__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__set_prim_attribute__response @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class SetPrimAttribute_Response(metaclass=Metaclass_SetPrimAttribute_Response): """Message class 'SetPrimAttribute_Response'.""" __slots__ = [ '_success', '_message', ] _fields_and_field_types = { 'success': 'boolean', 'message': 'string', } SLOT_TYPES = ( rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.success = kwargs.get('success', bool()) self.message = kwargs.get('message', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.success != other.success: return False if self.message != other.message: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def success(self): """Message field 'success'.""" return self._success @success.setter def success(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'success' field must be of type 'bool'" self._success = value @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value class Metaclass_SetPrimAttribute(type): """Metaclass of service 'SetPrimAttribute'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.SetPrimAttribute') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__set_prim_attribute from add_on_msgs.srv import _set_prim_attribute if _set_prim_attribute.Metaclass_SetPrimAttribute_Request._TYPE_SUPPORT is None: _set_prim_attribute.Metaclass_SetPrimAttribute_Request.__import_type_support__() if _set_prim_attribute.Metaclass_SetPrimAttribute_Response._TYPE_SUPPORT is None: _set_prim_attribute.Metaclass_SetPrimAttribute_Response.__import_type_support__() class SetPrimAttribute(metaclass=Metaclass_SetPrimAttribute): from add_on_msgs.srv._set_prim_attribute import SetPrimAttribute_Request as Request from add_on_msgs.srv._set_prim_attribute import SetPrimAttribute_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
11,863
Python
34.309524
134
0.573717
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prim_attributes_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from add_on_msgs:srv/GetPrimAttributes.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "add_on_msgs/srv/detail/get_prim_attributes__struct.h" #include "add_on_msgs/srv/detail/get_prim_attributes__functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool add_on_msgs__srv__get_prim_attributes__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[63]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("add_on_msgs.srv._get_prim_attributes.GetPrimAttributes_Request", full_classname_dest, 62) == 0); } add_on_msgs__srv__GetPrimAttributes_Request * ros_message = _ros_message; { // path PyObject * field = PyObject_GetAttrString(_pymsg, "path"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->path, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * add_on_msgs__srv__get_prim_attributes__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GetPrimAttributes_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prim_attributes"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrimAttributes_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } add_on_msgs__srv__GetPrimAttributes_Request * ros_message = (add_on_msgs__srv__GetPrimAttributes_Request *)raw_ros_message; { // path PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->path.data, strlen(ros_message->path.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "path", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "add_on_msgs/srv/detail/get_prim_attributes__struct.h" // already included above // #include "add_on_msgs/srv/detail/get_prim_attributes__functions.h" #include "rosidl_runtime_c/primitives_sequence.h" #include "rosidl_runtime_c/primitives_sequence_functions.h" // already included above // #include "rosidl_runtime_c/string.h" // already included above // #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool add_on_msgs__srv__get_prim_attributes__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[64]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("add_on_msgs.srv._get_prim_attributes.GetPrimAttributes_Response", full_classname_dest, 63) == 0); } add_on_msgs__srv__GetPrimAttributes_Response * ros_message = _ros_message; { // names PyObject * field = PyObject_GetAttrString(_pymsg, "names"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'names'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->names), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->names.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // displays PyObject * field = PyObject_GetAttrString(_pymsg, "displays"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'displays'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->displays), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->displays.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // types PyObject * field = PyObject_GetAttrString(_pymsg, "types"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'types'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->types), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->types.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // success PyObject * field = PyObject_GetAttrString(_pymsg, "success"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->success = (Py_True == field); Py_DECREF(field); } { // message PyObject * field = PyObject_GetAttrString(_pymsg, "message"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->message, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * add_on_msgs__srv__get_prim_attributes__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GetPrimAttributes_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prim_attributes"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrimAttributes_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } add_on_msgs__srv__GetPrimAttributes_Response * ros_message = (add_on_msgs__srv__GetPrimAttributes_Response *)raw_ros_message; { // names PyObject * field = NULL; size_t size = ros_message->names.size; rosidl_runtime_c__String * src = ros_message->names.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "names", field); Py_DECREF(field); if (rc) { return NULL; } } } { // displays PyObject * field = NULL; size_t size = ros_message->displays.size; rosidl_runtime_c__String * src = ros_message->displays.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "displays", field); Py_DECREF(field); if (rc) { return NULL; } } } { // types PyObject * field = NULL; size_t size = ros_message->types.size; rosidl_runtime_c__String * src = ros_message->types.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "types", field); Py_DECREF(field); if (rc) { return NULL; } } } { // success PyObject * field = NULL; field = PyBool_FromLong(ros_message->success ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "success", field); Py_DECREF(field); if (rc) { return NULL; } } } { // message PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->message.data, strlen(ros_message->message.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "message", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
14,105
C
30.002198
127
0.611273
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prim_attribute_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from add_on_msgs:srv/GetPrimAttribute.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "add_on_msgs/srv/detail/get_prim_attribute__struct.h" #include "add_on_msgs/srv/detail/get_prim_attribute__functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool add_on_msgs__srv__get_prim_attribute__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[61]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("add_on_msgs.srv._get_prim_attribute.GetPrimAttribute_Request", full_classname_dest, 60) == 0); } add_on_msgs__srv__GetPrimAttribute_Request * ros_message = _ros_message; { // path PyObject * field = PyObject_GetAttrString(_pymsg, "path"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->path, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } { // attribute PyObject * field = PyObject_GetAttrString(_pymsg, "attribute"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->attribute, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * add_on_msgs__srv__get_prim_attribute__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GetPrimAttribute_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prim_attribute"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrimAttribute_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } add_on_msgs__srv__GetPrimAttribute_Request * ros_message = (add_on_msgs__srv__GetPrimAttribute_Request *)raw_ros_message; { // path PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->path.data, strlen(ros_message->path.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "path", field); Py_DECREF(field); if (rc) { return NULL; } } } { // attribute PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->attribute.data, strlen(ros_message->attribute.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "attribute", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "add_on_msgs/srv/detail/get_prim_attribute__struct.h" // already included above // #include "add_on_msgs/srv/detail/get_prim_attribute__functions.h" // already included above // #include "rosidl_runtime_c/string.h" // already included above // #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool add_on_msgs__srv__get_prim_attribute__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[62]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("add_on_msgs.srv._get_prim_attribute.GetPrimAttribute_Response", full_classname_dest, 61) == 0); } add_on_msgs__srv__GetPrimAttribute_Response * ros_message = _ros_message; { // value PyObject * field = PyObject_GetAttrString(_pymsg, "value"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->value, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } { // type PyObject * field = PyObject_GetAttrString(_pymsg, "type"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->type, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } { // success PyObject * field = PyObject_GetAttrString(_pymsg, "success"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->success = (Py_True == field); Py_DECREF(field); } { // message PyObject * field = PyObject_GetAttrString(_pymsg, "message"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->message, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * add_on_msgs__srv__get_prim_attribute__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GetPrimAttribute_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prim_attribute"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrimAttribute_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } add_on_msgs__srv__GetPrimAttribute_Response * ros_message = (add_on_msgs__srv__GetPrimAttribute_Response *)raw_ros_message; { // value PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->value.data, strlen(ros_message->value.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "value", field); Py_DECREF(field); if (rc) { return NULL; } } } { // type PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->type.data, strlen(ros_message->type.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "type", field); Py_DECREF(field); if (rc) { return NULL; } } } { // success PyObject * field = NULL; field = PyBool_FromLong(ros_message->success ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "success", field); Py_DECREF(field); if (rc) { return NULL; } } } { // message PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->message.data, strlen(ros_message->message.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "message", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
10,253
C
28.982456
125
0.626158
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_set_prim_attribute_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from add_on_msgs:srv/SetPrimAttribute.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "add_on_msgs/srv/detail/set_prim_attribute__struct.h" #include "add_on_msgs/srv/detail/set_prim_attribute__functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool add_on_msgs__srv__set_prim_attribute__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[61]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("add_on_msgs.srv._set_prim_attribute.SetPrimAttribute_Request", full_classname_dest, 60) == 0); } add_on_msgs__srv__SetPrimAttribute_Request * ros_message = _ros_message; { // path PyObject * field = PyObject_GetAttrString(_pymsg, "path"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->path, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } { // attribute PyObject * field = PyObject_GetAttrString(_pymsg, "attribute"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->attribute, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } { // value PyObject * field = PyObject_GetAttrString(_pymsg, "value"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->value, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * add_on_msgs__srv__set_prim_attribute__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of SetPrimAttribute_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._set_prim_attribute"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SetPrimAttribute_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } add_on_msgs__srv__SetPrimAttribute_Request * ros_message = (add_on_msgs__srv__SetPrimAttribute_Request *)raw_ros_message; { // path PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->path.data, strlen(ros_message->path.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "path", field); Py_DECREF(field); if (rc) { return NULL; } } } { // attribute PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->attribute.data, strlen(ros_message->attribute.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "attribute", field); Py_DECREF(field); if (rc) { return NULL; } } } { // value PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->value.data, strlen(ros_message->value.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "value", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "add_on_msgs/srv/detail/set_prim_attribute__struct.h" // already included above // #include "add_on_msgs/srv/detail/set_prim_attribute__functions.h" // already included above // #include "rosidl_runtime_c/string.h" // already included above // #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool add_on_msgs__srv__set_prim_attribute__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[62]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("add_on_msgs.srv._set_prim_attribute.SetPrimAttribute_Response", full_classname_dest, 61) == 0); } add_on_msgs__srv__SetPrimAttribute_Response * ros_message = _ros_message; { // success PyObject * field = PyObject_GetAttrString(_pymsg, "success"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->success = (Py_True == field); Py_DECREF(field); } { // message PyObject * field = PyObject_GetAttrString(_pymsg, "message"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->message, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * add_on_msgs__srv__set_prim_attribute__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of SetPrimAttribute_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._set_prim_attribute"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "SetPrimAttribute_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } add_on_msgs__srv__SetPrimAttribute_Response * ros_message = (add_on_msgs__srv__SetPrimAttribute_Response *)raw_ros_message; { // success PyObject * field = NULL; field = PyBool_FromLong(ros_message->success ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "success", field); Py_DECREF(field); if (rc) { return NULL; } } } { // message PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->message.data, strlen(ros_message->message.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "message", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
9,456
C
29.506452
125
0.630816
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/__init__.py
from add_on_msgs.srv._get_prim_attribute import GetPrimAttribute # noqa: F401 from add_on_msgs.srv._get_prim_attributes import GetPrimAttributes # noqa: F401 from add_on_msgs.srv._get_prims import GetPrims # noqa: F401 from add_on_msgs.srv._set_prim_attribute import SetPrimAttribute # noqa: F401
301
Python
59.399988
80
0.777409
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prims.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from add_on_msgs:srv/GetPrims.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GetPrims_Request(type): """Metaclass of message 'GetPrims_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrims_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prims__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prims__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prims__request cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prims__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prims__request @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrims_Request(metaclass=Metaclass_GetPrims_Request): """Message class 'GetPrims_Request'.""" __slots__ = [ '_path', ] _fields_and_field_types = { 'path': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.path = kwargs.get('path', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.path != other.path: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def path(self): """Message field 'path'.""" return self._path @path.setter def path(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'path' field must be of type 'str'" self._path = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GetPrims_Response(type): """Metaclass of message 'GetPrims_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrims_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prims__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prims__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prims__response cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prims__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prims__response @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrims_Response(metaclass=Metaclass_GetPrims_Response): """Message class 'GetPrims_Response'.""" __slots__ = [ '_paths', '_types', '_success', '_message', ] _fields_and_field_types = { 'paths': 'sequence<string>', 'types': 'sequence<string>', 'success': 'boolean', 'message': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.paths = kwargs.get('paths', []) self.types = kwargs.get('types', []) self.success = kwargs.get('success', bool()) self.message = kwargs.get('message', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.paths != other.paths: return False if self.types != other.types: return False if self.success != other.success: return False if self.message != other.message: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def paths(self): """Message field 'paths'.""" return self._paths @paths.setter def paths(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'paths' field must be a set or sequence and each value of type 'str'" self._paths = value @property def types(self): """Message field 'types'.""" return self._types @types.setter def types(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'types' field must be a set or sequence and each value of type 'str'" self._types = value @property def success(self): """Message field 'success'.""" return self._success @success.setter def success(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'success' field must be of type 'bool'" self._success = value @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value class Metaclass_GetPrims(type): """Metaclass of service 'GetPrims'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrims') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__get_prims from add_on_msgs.srv import _get_prims if _get_prims.Metaclass_GetPrims_Request._TYPE_SUPPORT is None: _get_prims.Metaclass_GetPrims_Request.__import_type_support__() if _get_prims.Metaclass_GetPrims_Response._TYPE_SUPPORT is None: _get_prims.Metaclass_GetPrims_Response.__import_type_support__() class GetPrims(metaclass=Metaclass_GetPrims): from add_on_msgs.srv._get_prims import GetPrims_Request as Request from add_on_msgs.srv._get_prims import GetPrims_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
12,577
Python
34.331461
134
0.563091
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prim_attribute.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from add_on_msgs:srv/GetPrimAttribute.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GetPrimAttribute_Request(type): """Metaclass of message 'GetPrimAttribute_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttribute_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prim_attribute__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prim_attribute__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prim_attribute__request cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prim_attribute__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prim_attribute__request @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrimAttribute_Request(metaclass=Metaclass_GetPrimAttribute_Request): """Message class 'GetPrimAttribute_Request'.""" __slots__ = [ '_path', '_attribute', ] _fields_and_field_types = { 'path': 'string', 'attribute': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.path = kwargs.get('path', str()) self.attribute = kwargs.get('attribute', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.path != other.path: return False if self.attribute != other.attribute: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def path(self): """Message field 'path'.""" return self._path @path.setter def path(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'path' field must be of type 'str'" self._path = value @property def attribute(self): """Message field 'attribute'.""" return self._attribute @attribute.setter def attribute(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'attribute' field must be of type 'str'" self._attribute = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GetPrimAttribute_Response(type): """Metaclass of message 'GetPrimAttribute_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttribute_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prim_attribute__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prim_attribute__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prim_attribute__response cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prim_attribute__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prim_attribute__response @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrimAttribute_Response(metaclass=Metaclass_GetPrimAttribute_Response): """Message class 'GetPrimAttribute_Response'.""" __slots__ = [ '_value', '_type', '_success', '_message', ] _fields_and_field_types = { 'value': 'string', 'type': 'string', 'success': 'boolean', 'message': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.value = kwargs.get('value', str()) self.type = kwargs.get('type', str()) self.success = kwargs.get('success', bool()) self.message = kwargs.get('message', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.value != other.value: return False if self.type != other.type: return False if self.success != other.success: return False if self.message != other.message: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def value(self): """Message field 'value'.""" return self._value @value.setter def value(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'value' field must be of type 'str'" self._value = value @property # noqa: A003 def type(self): # noqa: A003 """Message field 'type'.""" return self._type @type.setter # noqa: A003 def type(self, value): # noqa: A003 if __debug__: assert \ isinstance(value, str), \ "The 'type' field must be of type 'str'" self._type = value @property def success(self): """Message field 'success'.""" return self._success @success.setter def success(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'success' field must be of type 'bool'" self._success = value @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value class Metaclass_GetPrimAttribute(type): """Metaclass of service 'GetPrimAttribute'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttribute') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__get_prim_attribute from add_on_msgs.srv import _get_prim_attribute if _get_prim_attribute.Metaclass_GetPrimAttribute_Request._TYPE_SUPPORT is None: _get_prim_attribute.Metaclass_GetPrimAttribute_Request.__import_type_support__() if _get_prim_attribute.Metaclass_GetPrimAttribute_Response._TYPE_SUPPORT is None: _get_prim_attribute.Metaclass_GetPrimAttribute_Response.__import_type_support__() class GetPrimAttribute(metaclass=Metaclass_GetPrimAttribute): from add_on_msgs.srv._get_prim_attribute import GetPrimAttribute_Request as Request from add_on_msgs.srv._get_prim_attribute import GetPrimAttribute_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
12,446
Python
34.061972
134
0.570223
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prim_attributes.py
# generated from rosidl_generator_py/resource/_idl.py.em # with input from add_on_msgs:srv/GetPrimAttributes.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_GetPrimAttributes_Request(type): """Metaclass of message 'GetPrimAttributes_Request'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttributes_Request') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prim_attributes__request cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prim_attributes__request cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prim_attributes__request cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prim_attributes__request cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prim_attributes__request @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrimAttributes_Request(metaclass=Metaclass_GetPrimAttributes_Request): """Message class 'GetPrimAttributes_Request'.""" __slots__ = [ '_path', ] _fields_and_field_types = { 'path': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.path = kwargs.get('path', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.path != other.path: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def path(self): """Message field 'path'.""" return self._path @path.setter def path(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'path' field must be of type 'str'" self._path = value # Import statements for member types # already imported above # import rosidl_parser.definition class Metaclass_GetPrimAttributes_Response(type): """Metaclass of message 'GetPrimAttributes_Response'.""" _CREATE_ROS_MESSAGE = None _CONVERT_FROM_PY = None _CONVERT_TO_PY = None _DESTROY_ROS_MESSAGE = None _TYPE_SUPPORT = None __constants = { } @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttributes_Response') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__srv__get_prim_attributes__response cls._CONVERT_FROM_PY = module.convert_from_py_msg__srv__get_prim_attributes__response cls._CONVERT_TO_PY = module.convert_to_py_msg__srv__get_prim_attributes__response cls._TYPE_SUPPORT = module.type_support_msg__srv__get_prim_attributes__response cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__srv__get_prim_attributes__response @classmethod def __prepare__(cls, name, bases, **kwargs): # list constant names here so that they appear in the help text of # the message class under "Data and other attributes defined here:" # as well as populate each message instance return { } class GetPrimAttributes_Response(metaclass=Metaclass_GetPrimAttributes_Response): """Message class 'GetPrimAttributes_Response'.""" __slots__ = [ '_names', '_displays', '_types', '_success', '_message', ] _fields_and_field_types = { 'names': 'sequence<string>', 'displays': 'sequence<string>', 'types': 'sequence<string>', 'success': 'boolean', 'message': 'string', } SLOT_TYPES = ( rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.UnboundedSequence(rosidl_parser.definition.UnboundedString()), # noqa: E501 rosidl_parser.definition.BasicType('boolean'), # noqa: E501 rosidl_parser.definition.UnboundedString(), # noqa: E501 ) def __init__(self, **kwargs): assert all('_' + key in self.__slots__ for key in kwargs.keys()), \ 'Invalid arguments passed to constructor: %s' % \ ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__)) self.names = kwargs.get('names', []) self.displays = kwargs.get('displays', []) self.types = kwargs.get('types', []) self.success = kwargs.get('success', bool()) self.message = kwargs.get('message', str()) def __repr__(self): typename = self.__class__.__module__.split('.') typename.pop() typename.append(self.__class__.__name__) args = [] for s, t in zip(self.__slots__, self.SLOT_TYPES): field = getattr(self, s) fieldstr = repr(field) # We use Python array type for fields that can be directly stored # in them, and "normal" sequences for everything else. If it is # a type that we store in an array, strip off the 'array' portion. if ( isinstance(t, rosidl_parser.definition.AbstractSequence) and isinstance(t.value_type, rosidl_parser.definition.BasicType) and t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'] ): if len(field) == 0: fieldstr = '[]' else: assert fieldstr.startswith('array(') prefix = "array('X', " suffix = ')' fieldstr = fieldstr[len(prefix):-len(suffix)] args.append(s[1:] + '=' + fieldstr) return '%s(%s)' % ('.'.join(typename), ', '.join(args)) def __eq__(self, other): if not isinstance(other, self.__class__): return False if self.names != other.names: return False if self.displays != other.displays: return False if self.types != other.types: return False if self.success != other.success: return False if self.message != other.message: return False return True @classmethod def get_fields_and_field_types(cls): from copy import copy return copy(cls._fields_and_field_types) @property def names(self): """Message field 'names'.""" return self._names @names.setter def names(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'names' field must be a set or sequence and each value of type 'str'" self._names = value @property def displays(self): """Message field 'displays'.""" return self._displays @displays.setter def displays(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'displays' field must be a set or sequence and each value of type 'str'" self._displays = value @property def types(self): """Message field 'types'.""" return self._types @types.setter def types(self, value): if __debug__: from collections.abc import Sequence from collections.abc import Set from collections import UserList from collections import UserString assert \ ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all(isinstance(v, str) for v in value) and True), \ "The 'types' field must be a set or sequence and each value of type 'str'" self._types = value @property def success(self): """Message field 'success'.""" return self._success @success.setter def success(self, value): if __debug__: assert \ isinstance(value, bool), \ "The 'success' field must be of type 'bool'" self._success = value @property def message(self): """Message field 'message'.""" return self._message @message.setter def message(self, value): if __debug__: assert \ isinstance(value, str), \ "The 'message' field must be of type 'str'" self._message = value class Metaclass_GetPrimAttributes(type): """Metaclass of service 'GetPrimAttributes'.""" _TYPE_SUPPORT = None @classmethod def __import_type_support__(cls): try: from rosidl_generator_py import import_type_support module = import_type_support('add_on_msgs') except ImportError: import logging import traceback logger = logging.getLogger( 'add_on_msgs.srv.GetPrimAttributes') logger.debug( 'Failed to import needed modules for type support:\n' + traceback.format_exc()) else: cls._TYPE_SUPPORT = module.type_support_srv__srv__get_prim_attributes from add_on_msgs.srv import _get_prim_attributes if _get_prim_attributes.Metaclass_GetPrimAttributes_Request._TYPE_SUPPORT is None: _get_prim_attributes.Metaclass_GetPrimAttributes_Request.__import_type_support__() if _get_prim_attributes.Metaclass_GetPrimAttributes_Response._TYPE_SUPPORT is None: _get_prim_attributes.Metaclass_GetPrimAttributes_Response.__import_type_support__() class GetPrimAttributes(metaclass=Metaclass_GetPrimAttributes): from add_on_msgs.srv._get_prim_attributes import GetPrimAttributes_Request as Request from add_on_msgs.srv._get_prim_attributes import GetPrimAttributes_Response as Response def __init__(self): raise NotImplementedError('Service classes can not be instantiated')
14,112
Python
35.657143
134
0.574192
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/packages/add_on_msgs/srv/_get_prims_s.c
// generated from rosidl_generator_py/resource/_idl_support.c.em // with input from add_on_msgs:srv/GetPrims.idl // generated code does not contain a copyright notice #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <stdbool.h> #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif #include "numpy/ndarrayobject.h" #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "rosidl_runtime_c/visibility_control.h" #include "add_on_msgs/srv/detail/get_prims__struct.h" #include "add_on_msgs/srv/detail/get_prims__functions.h" #include "rosidl_runtime_c/string.h" #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool add_on_msgs__srv__get_prims__request__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[44]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("add_on_msgs.srv._get_prims.GetPrims_Request", full_classname_dest, 43) == 0); } add_on_msgs__srv__GetPrims_Request * ros_message = _ros_message; { // path PyObject * field = PyObject_GetAttrString(_pymsg, "path"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->path, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * add_on_msgs__srv__get_prims__request__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GetPrims_Request */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prims"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrims_Request"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } add_on_msgs__srv__GetPrims_Request * ros_message = (add_on_msgs__srv__GetPrims_Request *)raw_ros_message; { // path PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->path.data, strlen(ros_message->path.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "path", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; } #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // already included above // #include <Python.h> // already included above // #include <stdbool.h> // already included above // #include "numpy/ndarrayobject.h" // already included above // #include "rosidl_runtime_c/visibility_control.h" // already included above // #include "add_on_msgs/srv/detail/get_prims__struct.h" // already included above // #include "add_on_msgs/srv/detail/get_prims__functions.h" #include "rosidl_runtime_c/primitives_sequence.h" #include "rosidl_runtime_c/primitives_sequence_functions.h" // already included above // #include "rosidl_runtime_c/string.h" // already included above // #include "rosidl_runtime_c/string_functions.h" ROSIDL_GENERATOR_C_EXPORT bool add_on_msgs__srv__get_prims__response__convert_from_py(PyObject * _pymsg, void * _ros_message) { // check that the passed message is of the expected Python class { char full_classname_dest[45]; { char * class_name = NULL; char * module_name = NULL; { PyObject * class_attr = PyObject_GetAttrString(_pymsg, "__class__"); if (class_attr) { PyObject * name_attr = PyObject_GetAttrString(class_attr, "__name__"); if (name_attr) { class_name = (char *)PyUnicode_1BYTE_DATA(name_attr); Py_DECREF(name_attr); } PyObject * module_attr = PyObject_GetAttrString(class_attr, "__module__"); if (module_attr) { module_name = (char *)PyUnicode_1BYTE_DATA(module_attr); Py_DECREF(module_attr); } Py_DECREF(class_attr); } } if (!class_name || !module_name) { return false; } snprintf(full_classname_dest, sizeof(full_classname_dest), "%s.%s", module_name, class_name); } assert(strncmp("add_on_msgs.srv._get_prims.GetPrims_Response", full_classname_dest, 44) == 0); } add_on_msgs__srv__GetPrims_Response * ros_message = _ros_message; { // paths PyObject * field = PyObject_GetAttrString(_pymsg, "paths"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'paths'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->paths), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->paths.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // types PyObject * field = PyObject_GetAttrString(_pymsg, "types"); if (!field) { return false; } PyObject * seq_field = PySequence_Fast(field, "expected a sequence in 'types'"); if (!seq_field) { Py_DECREF(field); return false; } Py_ssize_t size = PySequence_Size(field); if (-1 == size) { Py_DECREF(seq_field); Py_DECREF(field); return false; } if (!rosidl_runtime_c__String__Sequence__init(&(ros_message->types), size)) { PyErr_SetString(PyExc_RuntimeError, "unable to create String__Sequence ros_message"); Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String * dest = ros_message->types.data; for (Py_ssize_t i = 0; i < size; ++i) { PyObject * item = PySequence_Fast_GET_ITEM(seq_field, i); if (!item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } assert(PyUnicode_Check(item)); PyObject * encoded_item = PyUnicode_AsUTF8String(item); if (!encoded_item) { Py_DECREF(seq_field); Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&dest[i], PyBytes_AS_STRING(encoded_item)); Py_DECREF(encoded_item); } Py_DECREF(seq_field); Py_DECREF(field); } { // success PyObject * field = PyObject_GetAttrString(_pymsg, "success"); if (!field) { return false; } assert(PyBool_Check(field)); ros_message->success = (Py_True == field); Py_DECREF(field); } { // message PyObject * field = PyObject_GetAttrString(_pymsg, "message"); if (!field) { return false; } assert(PyUnicode_Check(field)); PyObject * encoded_field = PyUnicode_AsUTF8String(field); if (!encoded_field) { Py_DECREF(field); return false; } rosidl_runtime_c__String__assign(&ros_message->message, PyBytes_AS_STRING(encoded_field)); Py_DECREF(encoded_field); Py_DECREF(field); } return true; } ROSIDL_GENERATOR_C_EXPORT PyObject * add_on_msgs__srv__get_prims__response__convert_to_py(void * raw_ros_message) { /* NOTE(esteve): Call constructor of GetPrims_Response */ PyObject * _pymessage = NULL; { PyObject * pymessage_module = PyImport_ImportModule("add_on_msgs.srv._get_prims"); assert(pymessage_module); PyObject * pymessage_class = PyObject_GetAttrString(pymessage_module, "GetPrims_Response"); assert(pymessage_class); Py_DECREF(pymessage_module); _pymessage = PyObject_CallObject(pymessage_class, NULL); Py_DECREF(pymessage_class); if (!_pymessage) { return NULL; } } add_on_msgs__srv__GetPrims_Response * ros_message = (add_on_msgs__srv__GetPrims_Response *)raw_ros_message; { // paths PyObject * field = NULL; size_t size = ros_message->paths.size; rosidl_runtime_c__String * src = ros_message->paths.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "paths", field); Py_DECREF(field); if (rc) { return NULL; } } } { // types PyObject * field = NULL; size_t size = ros_message->types.size; rosidl_runtime_c__String * src = ros_message->types.data; field = PyList_New(size); if (!field) { return NULL; } for (size_t i = 0; i < size; ++i) { PyObject * decoded_item = PyUnicode_DecodeUTF8(src[i].data, strlen(src[i].data), "strict"); if (!decoded_item) { return NULL; } int rc = PyList_SetItem(field, i, decoded_item); (void)rc; assert(rc == 0); } assert(PySequence_Check(field)); { int rc = PyObject_SetAttrString(_pymessage, "types", field); Py_DECREF(field); if (rc) { return NULL; } } } { // success PyObject * field = NULL; field = PyBool_FromLong(ros_message->success ? 1 : 0); { int rc = PyObject_SetAttrString(_pymessage, "success", field); Py_DECREF(field); if (rc) { return NULL; } } } { // message PyObject * field = NULL; field = PyUnicode_DecodeUTF8( ros_message->message.data, strlen(ros_message->message.data), "strict"); if (!field) { return NULL; } { int rc = PyObject_SetAttrString(_pymessage, "message", field); Py_DECREF(field); if (rc) { return NULL; } } } // ownership of _pymessage is transferred to the caller return _pymessage; }
11,800
C
29.572539
109
0.611356
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/tests/test_ros2_bridge.py
try: import omni.kit.test TestCase = omni.kit.test.AsyncTestCaseFailOnLogError except: class TestCase: pass import json import rclpy from rclpy.node import Node from rclpy.duration import Duration from rclpy.action import ActionClient from action_msgs.msg import GoalStatus from trajectory_msgs.msg import JointTrajectoryPoint from control_msgs.action import FollowJointTrajectory from control_msgs.action import GripperCommand import add_on_msgs.srv # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class TestROS2Bridge(TestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_ros2_bridge(self): pass class TestROS2BridgeNode(Node): def __init__(self): super().__init__('test_ros2_bridge') self.get_attribute_service_name = '/get_attribute' self.set_attribute_service_name = '/set_attribute' self.gripper_command_action_name = "/panda_hand_controller/gripper_command" self.follow_joint_trajectory_action_name = "/panda_arm_controller/follow_joint_trajectory" self.get_attribute_client = self.create_client(add_on_msgs.srv.GetPrimAttribute, self.get_attribute_service_name) self.set_attribute_client = self.create_client(add_on_msgs.srv.SetPrimAttribute, self.set_attribute_service_name) self.gripper_command_client = ActionClient(self, GripperCommand, self.gripper_command_action_name) self.follow_joint_trajectory_client = ActionClient(self, FollowJointTrajectory, self.follow_joint_trajectory_action_name) self.follow_joint_trajectory_goal_msg = FollowJointTrajectory.Goal() self.follow_joint_trajectory_goal_msg.path_tolerance = [] self.follow_joint_trajectory_goal_msg.goal_tolerance = [] self.follow_joint_trajectory_goal_msg.goal_time_tolerance = Duration().to_msg() self.follow_joint_trajectory_goal_msg.trajectory.header.frame_id = "panda_link0" self.follow_joint_trajectory_goal_msg.trajectory.joint_names = ["panda_joint1", "panda_joint2", "panda_joint3", "panda_joint4", "panda_joint5", "panda_joint6", "panda_joint7"] self.follow_joint_trajectory_goal_msg.trajectory.points = [ JointTrajectoryPoint(positions=[0.012, -0.5689, 0.0, -2.8123, 0.0, 3.0367, 0.741], time_from_start=Duration(seconds=0, nanoseconds=0).to_msg()), JointTrajectoryPoint(positions=[0.011073551914608105, -0.5251352171920526, 6.967729509163362e-06, -2.698296723677182, 7.613460540484924e-06, 2.93314462685839, 0.6840062390114862], time_from_start=Duration(seconds=0, nanoseconds= 524152995).to_msg()), JointTrajectoryPoint(positions=[0.010147103829216212, -0.48137043438410526, 1.3935459018326723e-05, -2.5842934473543644, 1.5226921080969849e-05, 2.82958925371678, 0.6270124780229722], time_from_start=Duration(seconds=1, nanoseconds= 48305989).to_msg()), JointTrajectoryPoint(positions=[0.009220655743824318, -0.43760565157615794, 2.0903188527490087e-05, -2.4702901710315466, 2.2840381621454772e-05, 2.72603388057517, 0.5700187170344584], time_from_start=Duration(seconds=1, nanoseconds= 572458984).to_msg()), JointTrajectoryPoint(positions=[0.008294207658432425, -0.39384086876821056, 2.7870918036653447e-05, -2.3562868947087283, 3.0453842161939697e-05, 2.6224785074335597, 0.5130249560459446], time_from_start=Duration(seconds=2, nanoseconds= 96611978).to_msg()), JointTrajectoryPoint(positions=[0.00736775957304053, -0.3500760859602632, 3.483864754581681e-05, -2.2422836183859105, 3.806730270242462e-05, 2.518923134291949, 0.45603119505743067], time_from_start=Duration(seconds=2, nanoseconds= 620764973).to_msg()), JointTrajectoryPoint(positions=[0.006441311487648636, -0.30631130315231586, 4.1806377054980174e-05, -2.1282803420630927, 4.5680763242909544e-05, 2.415367761150339, 0.3990374340689168], time_from_start=Duration(seconds=3, nanoseconds= 144917968).to_msg()), JointTrajectoryPoint(positions=[0.005514863402256743, -0.2625465203443685, 4.877410656414353e-05, -2.014277065740275, 5.3294223783394466e-05, 2.311812388008729, 0.34204367308040295], time_from_start=Duration(seconds=3, nanoseconds= 669070962).to_msg()), JointTrajectoryPoint(positions=[0.004588415316864848, -0.2187817375364211, 5.5741836073306894e-05, -1.900273789417457, 6.0907684323879394e-05, 2.208257014867119, 0.28504991209188907], time_from_start=Duration(seconds=4, nanoseconds= 193223957).to_msg()), ] self.gripper_command_open_goal_msg = GripperCommand.Goal() self.gripper_command_open_goal_msg.command.position = 0.03990753115697298 self.gripper_command_open_goal_msg.command.max_effort = 0.0 self.gripper_command_close_goal_msg = GripperCommand.Goal() self.gripper_command_close_goal_msg.command.position = 8.962388141080737e-05 self.gripper_command_close_goal_msg.command.max_effort = 0.0 if __name__ == '__main__': rclpy.init() node = TestROS2BridgeNode() # ==== Gripper Command ==== assert node.gripper_command_client.wait_for_server(timeout_sec=1.0), \ "Action server {} not available".format(node.gripper_command_action_name) # close gripper command (with obstacle) future = node.gripper_command_client.send_goal_async(node.gripper_command_close_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.stalled is True assert result.result.reached_goal is False assert abs(result.result.position - 0.0295) < 1e-3 # open gripper command future = node.gripper_command_client.send_goal_async(node.gripper_command_open_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.stalled is False assert result.result.reached_goal is True assert abs(result.result.position - 0.0389) < 1e-3 # ==== Attribute ==== assert node.get_attribute_client.wait_for_service(timeout_sec=5.0), \ "Service {} not available".format(node.get_attribute_service_name) assert node.set_attribute_client.wait_for_service(timeout_sec=5.0), \ "Service {} not available".format(node.set_attribute_service_name) request_get_attribute = add_on_msgs.srv.GetPrimAttribute.Request() request_get_attribute.path = "/Cylinder" request_get_attribute.attribute = "physics:collisionEnabled" request_set_attribute = add_on_msgs.srv.SetPrimAttribute.Request() request_set_attribute.path = request_get_attribute.path request_set_attribute.attribute = request_get_attribute.attribute request_set_attribute.value = json.dumps(False) # get obstacle collisionEnabled attribute future = node.get_attribute_client.call_async(request_get_attribute) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.success is True assert json.loads(result.value) is True # disable obstacle collision shape future = node.set_attribute_client.call_async(request_set_attribute) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.success is True # get obstacle collisionEnabled attribute future = node.get_attribute_client.call_async(request_get_attribute) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.success is True assert json.loads(result.value) is False # ==== Gripper Command ==== assert node.gripper_command_client.wait_for_server(timeout_sec=1.0), \ "Action server {} not available".format(node.gripper_command_action_name) # close gripper command (without obstacle) future = node.gripper_command_client.send_goal_async(node.gripper_command_close_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.stalled is False assert result.result.reached_goal is True assert abs(result.result.position - 0.0) < 1e-3 # ==== Follow Joint Trajectory ==== assert node.follow_joint_trajectory_client.wait_for_server(timeout_sec=1.0), \ "Action server {} not available".format(node.follow_joint_trajectory_action_name) # move to goal future = node.follow_joint_trajectory_client.send_goal_async(node.follow_joint_trajectory_goal_msg) rclpy.spin_until_future_complete(node, future, timeout_sec=5.0) future = future.result().get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=10.0) result = future.result() assert result.status == GoalStatus.STATUS_SUCCEEDED assert result.result.error_code == result.result.SUCCESSFUL print("Test passed")
9,613
Python
52.116022
268
0.730885
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/tests/__init__.py
from .test_ros2_bridge import *
32
Python
15.499992
31
0.75
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/config/extension.toml
[core] reloadable = true order = 0 [package] version = "0.1.1" category = "Simulation" feature = false app = false title = "ROS2 Bridge (semu namespace)" description = "ROS2 interfaces (semu namespace)" authors = ["Toni-SM"] repository = "https://github.com/Toni-SM/semu.robotics.ros2_bridge" keywords = ["ROS2", "control"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" preview_image = "data/preview.png" icon = "data/icon.png" [package.target] config = ["release"] platform = ["linux-x86_64"] python = ["py37", "cp37"] [dependencies] "omni.kit.uiapp" = {} "omni.isaac.dynamic_control" = {} "omni.isaac.ros2_bridge" = {} "semu.usd.schemas" = {} "semu.robotics.ros_bridge_ui" = {} [[python.module]] name = "semu.robotics.ros2_bridge" [[python.module]] name = "semu.robotics.ros2_bridge.tests" [settings] exts."semu.robotics.ros2_bridge".nodeName = "SemuRos2Bridge" exts."semu.robotics.ros2_bridge".eventTimeout = 5.0 exts."semu.robotics.ros2_bridge".setAttributeUsingAsyncio = false [[native.library]] path = "bin/libadd_on_msgs__python.so" [[native.library]] path = "bin/libadd_on_msgs__rosidl_generator_c.so" [[native.library]] path = "bin/libadd_on_msgs__rosidl_typesupport_c.so" [[native.library]] path = "bin/libadd_on_msgs__rosidl_typesupport_fastrtps_c.so" [[native.library]] path = "bin/libadd_on_msgs__rosidl_typesupport_introspection_c.so" [[native.library]] path = "bin/libcontrol_msgs__rosidl_generator_c.so" [[native.library]] path = "bin/libcontrol_msgs__python.so" [[native.library]] path = "bin/libcontrol_msgs__rosidl_typesupport_c.so" [[native.library]] path = "bin/libcontrol_msgs__rosidl_typesupport_fastrtps_c.so" [[native.library]] path = "bin/libcontrol_msgs__rosidl_typesupport_introspection_c.so"
1,740
TOML
26.63492
67
0.717816
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [0.1.1] - 2022-05-28 ### Changed - Rename the extension to `semu.robotics.ros2_bridge` ## [0.1.0] - 2022-04-12 ### Added - Source code (src folder) - FollowJointTrajectory action server (contribution with [@09ubberboy90](https://github.com/09ubberboy90)) - GripperCommand action server ### Changed - Improve the extension implementation ## [0.0.1] - 2021-12-18 ### Added - Attribute service - Create extension based on omni.add_on.ros_bridge
543
Markdown
23.727272
106
0.714549
Toni-SM/semu.robotics.ros2_bridge/exts/semu.robotics.ros2_bridge/docs/README.md
# semu.robotics.ros2_bridge This extension enables the ROS2 action server interfaces for controlling robots (particularly those used by MoveIt to talk to robot controllers: FollowJointTrajectory and GripperCommand) and enables services for agile prototyping of robotic applications in ROS2 Visit https://github.com/Toni-SM/semu.robotics.ros2_bridge to read more about its use
379
Markdown
53.285707
261
0.828496
Toni-SM/semu.misc.vscode/README.md
## Embedded VS Code for NVIDIA Omniverse > This extension can be described as the [VS Code](https://code.visualstudio.com/) version of Omniverse's [Script Editor](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_script-editor.html). It allows to execute Python code, embedded in the current NVIDIA Omniverse application scope, from the VS Code editor and displays the results in the OUTPUT panel (under *Embedded VS Code for NVIDIA Omniverse*) of the VS Code editor <br> **Target applications:** Any NVIDIA Omniverse app **Supported OS:** Windows and Linux **Changelog:** [CHANGELOG.md](exts/semu.misc.vscode/docs/CHANGELOG.md) **Table of Contents:** - [Requirements](#requirements) - [Extension setup](#setup) - [Extension usage](#usage) - [VS Code interface](#interface) - [Configuring the extension](#config) - [Limitations](#limitations) - [Contributing](#contributing) <br> ![showcase](exts/semu.misc.vscode/data/preview.png) <hr> <a name="requirements"></a> ### Requirements This extension requires its VS Code pair extension [Embedded VS Code for NVIDIA Omniverse](https://marketplace.visualstudio.com/items?itemName=Toni-SM.embedded-vscode-for-nvidia-omniverse) to be installed and enabled in the VS Code editor instance to be able to execute code in the current NVIDIA Omniverse application scope <br> ![vscode_ext](exts/semu.misc.vscode/data/vscode_ext.png) <hr> <a name="setup"></a> ### Extension setup 1. Add the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Search Paths](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-search-paths) * Git url (git+https) as extension search path :warning: *There seems to be a bug when installing extensions using the git url (git+https) as extension search path in Isaac Sim 2022.1.0. In this case, it is recommended to install the extension by importing the .zip file* ``` git+https://github.com/Toni-SM/semu.misc.vscode.git?branch=main&dir=exts ``` * Compressed (.zip) file for import [semu.misc.vscode.zip](https://github.com/Toni-SM/semu.misc.vscode/releases) 2. Enable the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Enabling/Disabling](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-enabling-disabling) <hr> <a name="usage"></a> ### Extension usage Enabling the extension starts a TCP socket server that executes the code sent to it from the VS Code [Embedded VS Code for NVIDIA Omniverse](https://marketplace.visualstudio.com/items?itemName=Toni-SM.embedded-vscode-for-nvidia-omniverse) pair extension according to the VS Code settings and commands shown in the image below <br> ![preview1](exts/semu.misc.vscode/data/vscode_ext1.png) The VS Code extension communicates via the configured address (`WORKSTATION_IP:PORT`), which is also indicated inside the Omniverse application in the *Windows > Embedded VS Code* menu <br> <p align="center"> <img src="exts/semu.misc.vscode/data/preview1.png" width="75%"> </p> Disabling the extension shutdowns the TCP socket server <hr> <a name="interface"></a> ### VS Code interface <br> ![preview2](exts/semu.misc.vscode/data/vscode_ext2.png) <hr> <a name="config"></a> ### Configuring the extension The extension can be configured by editing the [config.toml](exts/semu.misc.vscode/config/extension.toml) file under `[settings]` section. The following parameters are available: <br> **Extension settings** <table class="table table-striped table-bordered"> <thead> <tr> <th>Parameter</th> <th>Value</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>socket_ip</td> <td>0.0.0.0</td> <td>The IP address on which the TCP socket server will be listening for incoming requests</td> </tr> <tr> <td>socket_port</td> <td>8224</td> <td>The port on which the TCP socket server will be listening for incoming requests. In addition, the same port is used by a UDP socket to send carb logs (carb logging)</td> </tr> <tr> <td>carb_logging</td> <td>true</td> <td>Whether to send carb logging to be displayed in the *Embedded VS Code for NVIDIA Omniverse (carb logging)* output panel in the VS Code editor</td> </tr> </tbody> </table> <hr> <a name="limitations"></a> ### Limitations - Print output will only be available in the VS Code OUTPUT panel after complete execution of the entire or selected code. Very large prints may not be displayed in the output panel - Print output, inside callbacks (such as events), is not displayed in the VS Code OUTPUT panel but in the Omniverse application terminal. For that propose, use the following carb logging functions: `carb.log_info`, `carb.log_warn` or `carb.log_error`. If the carb logging is enabled, the output will be displayed in the *Embedded VS Code for NVIDIA Omniverse (carb logging)* output panel - Carb log displaying is only available from Python calls. Logs generated by NVIDIA Omniverse applications/extensions implemented with another programming language (e.g. C/C++) are not displayed in the output panel - The kit commands snippets (with their parameters, default values and annotations) are automatically generated from the list of commands available from Create, Code and Isaac Sim on Linux. Some commands may not be available in some Omniverse applications <a name="contributing"></a> ### Contributing The source code for both the NVIDIA Omniverse application and VS Code editor extensions are located in the same repository (https://github.com/Toni-SM/semu.misc.vscode): - NVIDIA Omniverse extension: `exts/semu.misc.vscode` - VS Code extension: `exts-vscode/embedded-vscode-for-nvidia-omniverse`
6,010
Markdown
40.171233
445
0.740932
Toni-SM/semu.misc.vscode/exts/semu.misc.vscode/semu/misc/vscode/__init__.py
from .scripts.extension import *
32
Python
31.999968
32
0.8125
Toni-SM/semu.misc.vscode/exts/semu.misc.vscode/semu/misc/vscode/scripts/extension.py
import __future__ import sys import json import time import types import socket import asyncio import threading import traceback import contextlib import subprocess from io import StringIO from dis import COMPILER_FLAG_NAMES try: from ast import PyCF_ALLOW_TOP_LEVEL_AWAIT except ImportError: PyCF_ALLOW_TOP_LEVEL_AWAIT = 0 import carb import omni.ext _udp_server = None _udp_clients = [] def _log_info(msg): # carb logging file, lno, func, mod = carb._get_caller_info() carb.log(mod, carb.logging.LEVEL_INFO, file, func, lno, msg) # send the message to all connected clients if _udp_server is not None: for client in _udp_clients: _udp_server.sendto(f"[Info][{mod}] {msg}".encode(), client) def _log_warn(msg): # carb logging file, lno, func, mod = carb._get_caller_info() carb.log(mod, carb.logging.LEVEL_WARN, file, func, lno, msg) # send the message to all connected clients if _udp_server is not None: for client in _udp_clients: _udp_server.sendto(f"[Warning][{mod}] {msg}".encode(), client) def _log_error(msg): # carb logging file, lno, func, mod = carb._get_caller_info() carb.log(mod, carb.logging.LEVEL_ERROR, file, func, lno, msg) # send the message to all connected clients if _udp_server is not None: for client in _udp_clients: _udp_server.sendto(f"[Error][{mod}] {msg}".encode(), client) def _get_coroutine_flag() -> int: """Get the coroutine flag for the current Python version """ for k, v in COMPILER_FLAG_NAMES.items(): if v == "COROUTINE": return k return -1 COROUTINE_FLAG = _get_coroutine_flag() def _has_coroutine_flag(code) -> bool: """Check if the code has the coroutine flag set """ if COROUTINE_FLAG == -1: return False return bool(code.co_flags & COROUTINE_FLAG) def _get_compiler_flags() -> int: """Get the compiler flags for the current Python version """ flags = 0 for value in globals().values(): try: if isinstance(value, __future__._Feature): f = value.compiler_flag flags |= f except BaseException: pass flags = flags | PyCF_ALLOW_TOP_LEVEL_AWAIT return flags def _get_event_loop() -> asyncio.AbstractEventLoop: """Backward compatible function for getting the event loop """ try: if sys.version_info >= (3, 7): return asyncio.get_running_loop() else: return asyncio.get_event_loop() except RuntimeError: return asyncio.get_event_loop_policy().get_event_loop() class Extension(omni.ext.IExt): WINDOW_NAME = "Embedded VS Code" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self, ext_id): self._globals = {**globals()} self._locals = self._globals # get extension settings self._settings = carb.settings.get_settings() self._socket_ip = self._settings.get("/exts/semu.misc.vscode/socket_ip") self._socket_port = self._settings.get("/exts/semu.misc.vscode/socket_port") self._carb_logging = self._settings.get("/exts/semu.misc.vscode/carb_logging") kill_processes_with_port_in_use = self._settings.get("/exts/semu.misc.vscode/kill_processes_with_port_in_use") # menu item self._editor_menu = omni.kit.ui.get_editor_menu() if self._editor_menu: self._menu = self._editor_menu.add_item(Extension.MENU_PATH, self._show_notification, toggle=False, value=False) # shutdown stream self.shutdown_stream_ebent = omni.kit.app.get_app().get_shutdown_event_stream() \ .create_subscription_to_pop(self._on_shutdown_event, name="semu.misc.vscode", order=0) # ensure port is free if kill_processes_with_port_in_use: if sys.platform == "win32": pids = [] cmd = ["netstat", "-ano"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) for line in p.stdout: if str(self._socket_port).encode() in line: pids.append(line.strip().split(b" ")[-1].decode()) p.wait() for pid in pids: carb.log_warn(f"Forced process shutdown with PID {pid}") cmd = ["taskkill", "/PID", pid, "/F"] subprocess.Popen(cmd).wait() # create socket self._socket_last_error = "" self._server = None self._create_socket() # carb logging to VS Code if self._carb_logging: # create UDP socket self._udp_server_running = False threading.Thread(target=self._create_udp_socket).start() # checkpoint carb log functions self._carb_log_info = types.FunctionType(carb.log_info.__code__, carb.log_info.__globals__, carb.log_info.__name__, carb.log_info.__defaults__, carb.log_info.__closure__) self._carb_log_warn = types.FunctionType(carb.log_warn.__code__, carb.log_warn.__globals__, carb.log_warn.__name__, carb.log_warn.__defaults__, carb.log_warn.__closure__) self._carb_log_error = types.FunctionType(carb.log_error.__code__, carb.log_error.__globals__, carb.log_error.__name__, carb.log_error.__defaults__, carb.log_error.__closure__) # override carb log functions carb.log_info = types.FunctionType(_log_info.__code__, _log_info.__globals__, _log_info.__name__, _log_info.__defaults__, _log_info.__closure__) carb.log_warn = types.FunctionType(_log_warn.__code__, _log_warn.__globals__, _log_warn.__name__, _log_warn.__defaults__, _log_warn.__closure__) carb.log_error = types.FunctionType(_log_error.__code__, _log_error.__globals__, _log_error.__name__, _log_error.__defaults__, _log_error.__closure__) def on_shutdown(self): global _udp_server, _udp_clients # restore carb log functions if self._carb_logging: carb.log_info = self._carb_log_info carb.log_warn = self._carb_log_warn carb.log_error = self._carb_log_error # clean up menu item if self._menu is not None: try: self._editor_menu.remove_item(self._menu) except: self._editor_menu.remove_item(Extension.MENU_PATH) self._menu = None # close the socket if self._server: self._server.close() _get_event_loop().run_until_complete(self._server.wait_closed()) # close the UDP socket if self._carb_logging: _udp_server = None _udp_clients = [] # wait for the UDP socket to close while self._udp_server_running: time.sleep(0.1) # extension ui methods def _on_shutdown_event(self, event): if event.type == omni.kit.app.POST_QUIT_EVENT_TYPE: self.on_shutdown() def _show_notification(self, *args, **kwargs) -> None: """Show extension data in the notification area """ if self._server is None: notification = "Unable to start the socket server at {}:{}. {}".format(self._socket_ip, self._socket_port, self._socket_last_error) status=omni.kit.notification_manager.NotificationStatus.WARNING else: notification = "Embedded VS Code socket server is running at {}:{}.\nUDP socket server for carb logging is {}"\ .format(self._socket_ip, self._socket_port, "enabled" if self._carb_logging else "disabled") status=omni.kit.notification_manager.NotificationStatus.INFO ok_button = omni.kit.notification_manager.NotificationButtonInfo("OK", on_complete=None) omni.kit.notification_manager.post_notification(notification, hide_after_timeout=False, duration=0, status=status, button_infos=[ok_button]) print(notification) carb.log_info(notification) # internal socket methods def _create_udp_socket(self) -> None: """Create the UDP socket for broadcasting carb logging """ global _udp_server, _udp_clients self._udp_server_running = True with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as _server: try: _server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) _server.bind((self._socket_ip, self._socket_port)) _server.setblocking(False) _server.settimeout(0.1) except Exception as e: _udp_server = None _udp_clients = [] carb.log_error(str(e)) self._udp_server_running = False return _udp_server = _server _udp_clients = [] while _udp_server is not None: try: _, addr = _server.recvfrom(1024) if addr not in _udp_clients: _udp_clients.append(addr) except socket.timeout: pass except Exception as e: carb.log_error("UDP server error: {}".format(e)) break self._udp_server_running = False def _create_socket(self) -> None: """Create a socket server to listen for incoming connections from the client """ class ServerProtocol(asyncio.Protocol): def __init__(self, parent) -> None: super().__init__() self._parent = parent def connection_made(self, transport): peername = transport.get_extra_info('peername') self.transport = transport def data_received(self, data): asyncio.run_coroutine_threadsafe(self._parent._exec_code_async(data.decode(), self.transport), _get_event_loop()) async def server_task(): try: self._server = await _get_event_loop().create_server(protocol_factory=lambda: ServerProtocol(self), host=self._socket_ip, port=self._socket_port, family=socket.AF_INET, reuse_port=None if sys.platform == 'win32' else True) except Exception as e: self._server = None self._socket_last_error = str(e) carb.log_error(str(e)) return await self._server.start_serving() task = _get_event_loop().create_task(server_task()) async def _exec_code_async(self, statement: str, transport: asyncio.Transport) -> None: """Execute the statement in the Omniverse scope and send the result to the client :param statement: statement to execute :type statement: str :param transport: transport to send the result to the client :type transport: asyncio.Transport :return: reply dictionary as expected by the client :rtype: dict """ _stdout = StringIO() try: with contextlib.redirect_stdout(_stdout): should_exec_code = True # try 'eval' first try: code = compile(statement, "<string>", "eval", flags= _get_compiler_flags(), dont_inherit=True) except SyntaxError: pass else: result = eval(code, self._globals, self._locals) should_exec_code = False # if 'eval' fails, try 'exec' if should_exec_code: code = compile(statement, "<string>", "exec", flags= _get_compiler_flags(), dont_inherit=True) result = eval(code, self._globals, self._locals) # await the result if it is a coroutine if _has_coroutine_flag(code): result = await result except Exception as e: # clean traceback _traceback = traceback.format_exc() _i = _traceback.find('\n File "<string>"') if _i != -1: _traceback = _traceback[_i + 20:] _traceback = _traceback.replace(", in <module>\n", "\n") # build reply dictionary reply = {"status": "error", "traceback": [_traceback], "ename": str(type(e).__name__), "evalue": str(e)} else: reply = {"status": "ok"} # add output to reply dictionary for printing reply["output"] = _stdout.getvalue() if reply["output"].endswith('\n'): reply["output"] = reply["output"][:-1] # send the reply to the client reply = json.dumps(reply) transport.write(reply.encode()) # close the connection transport.close()
14,679
Python
39.66482
143
0.501328
Toni-SM/semu.misc.vscode/exts/semu.misc.vscode/config/extension.toml
[core] reloadable = true order = 0 [package] version = "0.0.3-beta" category = "Utility" feature = false app = false title = "Embedded VS Code" description = "VS Code version of Omniverse's script editor" authors = ["Toni-SM"] repository = "https://github.com/Toni-SM/semu.misc.vscode" keywords = ["vscode", "code", "editor"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" preview_image = "data/preview.png" icon = "data/icon.png" [package.target] config = ["release"] platform = ["linux-*", "windows-*"] python = ["*"] [dependencies] "omni.kit.test" = {} "omni.kit.uiapp" = {} "omni.kit.notification_manager" = {} [[python.module]] name = "semu.misc.vscode" [settings] exts."semu.misc.vscode".socket_ip = "0.0.0.0" exts."semu.misc.vscode".socket_port = 8226 exts."semu.misc.vscode".carb_logging = true exts."semu.misc.vscode".kill_processes_with_port_in_use = true
882
TOML
22.236842
62
0.685941
Toni-SM/semu.misc.vscode/exts/semu.misc.vscode/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [0.0.3-beta] - 2022-09-03 ### Added - Add `kill_processes_with_port_in_use` to extension settings ### Fixed - Fix port in use when starting up and shutting down ## [0.0.2-beta] - 2022-08-19 ### Added - Send carb logging Python calls to the VS Code extension ## [0.0.1-beta] - 2022-08-15 ### Added - Initial release
416
Markdown
20.947367
80
0.677885
Toni-SM/semu.misc.vscode/exts/semu.misc.vscode/docs/README.md
# semu.misc.vscode This extension can be described as the VS Code version of Omniverse's script editor. It allows to execute python code, embedded in the current NVIDIA Omniverse application scope, from the VS Code editor and display the results in that editor Visit https://github.com/Toni-SM/semu.misc.vscode to read more about its use
341
Markdown
47.857136
241
0.797654
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/CHANGELOG.md
# Change Log All notable changes to the "embedded-vscode-for-nvidia-omniverse" extension will be documented in this file. Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file. ## [0.1.0] - Add Omniverse view container for commands, snippets and resources ## [0.0.3] - Fix duplicated carb log display due to local/remote socket issue ## [0.0.2] - Send carb logging Python calls to the VS Code extension ## [0.0.1] - Initial release
490
Markdown
22.380951
108
0.738776
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/vsc-extension-quickstart.md
# Welcome to your VS Code Extension ## What's in the folder * This folder contains all of the files necessary for your extension. * `package.json` - this is the manifest file in which you declare your extension and command. * The sample plugin registers a command and defines its title and command name. With this information VS Code can show the command in the command palette. It doesn’t yet need to load the plugin. * `src/extension.ts` - this is the main file where you will provide the implementation of your command. * The file exports one function, `activate`, which is called the very first time your extension is activated (in this case by executing the command). Inside the `activate` function we call `registerCommand`. * We pass the function containing the implementation of the command as the second parameter to `registerCommand`. ## Get up and running straight away * Press `F5` to open a new window with your extension loaded. * Run your command from the command palette by pressing (`Ctrl+Shift+P` or `Cmd+Shift+P` on Mac) and typing `Hello World`. * Set breakpoints in your code inside `src/extension.ts` to debug your extension. * Find output from your extension in the debug console. ## Make changes * You can relaunch the extension from the debug toolbar after changing code in `src/extension.ts`. * You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes. ## Explore the API * You can open the full set of our API when you open the file `node_modules/@types/vscode/index.d.ts`. ## Run tests * Open the debug viewlet (`Ctrl+Shift+D` or `Cmd+Shift+D` on Mac) and from the launch configuration dropdown pick `Extension Tests`. * Press `F5` to run the tests in a new window with your extension loaded. * See the output of the test result in the debug console. * Make changes to `src/test/suite/extension.test.ts` or create new test files inside the `test/suite` folder. * The provided test runner will only consider files matching the name pattern `**.test.ts`. * You can create folders inside the `test` folder to structure your tests any way you want. ## Go further * [Follow UX guidelines](https://code.visualstudio.com/api/ux-guidelines/overview) to create extensions that seamlessly integrate with VS Code's native interface and patterns. * Reduce the extension size and improve the startup time by [bundling your extension](https://code.visualstudio.com/api/working-with-extensions/bundling-extension). * [Publish your extension](https://code.visualstudio.com/api/working-with-extensions/publishing-extension) on the VS Code extension marketplace. * Automate builds by setting up [Continuous Integration](https://code.visualstudio.com/api/working-with-extensions/continuous-integration).
2,790
Markdown
63.906975
209
0.768459
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/README.md
# Embedded VS Code for NVIDIA Omniverse This extension is the pair of the [*Embedded VS Code for NVIDIA Omniverse*](https://github.com/Toni-SM/semu.misc.vscode) extension for NVIDIA Omniverse applications that can be described as the [VS Code](https://code.visualstudio.com/) version of Omniverse's [Script Editor](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_script-editor.html). It allows to execute python code, embedded in a local/remote NVIDIA Omniverse application scope, from the VS Code editor and display the results in the OUTPUT panel (under *Embedded VS Code for NVIDIA Omniverse*) of the VS Code editor. <br> ![preview](https://raw.githubusercontent.com/Toni-SM/semu.misc.vscode/main/exts/semu.misc.vscode/data/preview.png) ## Overview <br> ![preview1](https://raw.githubusercontent.com/Toni-SM/semu.misc.vscode/main/exts/semu.misc.vscode/data/vscode_ext1.png) ## VS Code interface <br> ![preview2](https://raw.githubusercontent.com/Toni-SM/semu.misc.vscode/main/exts/semu.misc.vscode/data/vscode_ext2.png) ## Main commands ### Local execution * **Embedded VS Code for NVIDIA Omniverse: Run** - Execute the python code from the active editor in the local configured NVIDIA Omniverse application and display the results in the OUTPUT panel * **Embedded VS Code for NVIDIA Omniverse: Run Selected Text** - Execute the selected text in the active editor in the local configured NVIDIA Omniverse application and display the results in the OUTPUT panel ### Remote execution * **Embedded VS Code for NVIDIA Omniverse: Run Remotely** - Execute the python code from the active editor in the remote configured NVIDIA Omniverse application and display the results in the OUTPUT panel * **Embedded VS Code for NVIDIA Omniverse: Run Selected Text Remotely** - Execute the selected text in the active editor in the remote configured NVIDIA Omniverse application and display the results in the OUTPUT panel ## Extension Settings This extension contributes the following settings: * `remoteSocket.extensionIp`: IP address where the remote Omniverse application is running (default: `"127.0.0.1"`) * `remoteSocket.extensionPort`: Port used by the *Embedded VS Code for NVIDIA Omniverse* extension in the remote Omniverse application (default: `8226`) * `localSocket.extensionPort`: Port used by the *Embedded VS Code for NVIDIA Omniverse* extension in the local Omniverse application (default: `8226`) * `output.clearBeforeRun`: Whether to clear the output before run the code. If unchecked (default value), the output will be appended to the existing content (default: `false`) * `output.carbLogging`: Whether to enable carb logging to be displayed in the *Embedded VS Code for NVIDIA Omniverse (carb logging)* output panel. Changes will take effect after reloading the window (default: `true`) ## Limitations - Print output will only be available in the VS Code OUTPUT panel after complete execution of the entire or selected code. Very large prints may not be displayed in the output panel - Print output, inside callbacks (such as events), is not displayed in the VS Code OUTPUT panel but in the Omniverse application terminal. For that propose, use the following carb logging functions: `carb.log_info`, `carb.log_warn` or `carb.log_error`. If the carb logging is enabled, the output will be displayed in the *Embedded VS Code for NVIDIA Omniverse (carb logging)* output panel - Carb log displaying is only available from Python calls. Logs generated by NVIDIA Omniverse applications/extensions implemented with another programming language (e.g. C/C++) are not displayed in the output panel - The kit commands snippets (with their parameters, default values and annotations) are automatically generated from the list of commands available from Create, Code and Isaac Sim on Linux. Some commands may not be available in some Omniverse applications - The expand-all button in the Snippets view container only reveal 3 levels (limited by VS Code) ## Release Notes ### 0.2.0 - Update snippets - Update resource links - Add expand-all button in the Snippets view container - Add Isaac Sim snippets and resource links ### 0.1.0 - Add Omniverse view container for commands, snippets and resources ### 0.0.3 - Fix duplicated carb log display due to local/remote socket issue ### 0.0.2 - Send carb logging Python calls to the VS Code extension ### 0.0.1 - Initial release ## Contributing The source code for both the NVIDIA Omniverse application and VS Code editor extensions are located in the same repository (https://github.com/Toni-SM/semu.misc.vscode): - NVIDIA Omniverse extension: `exts/semu.misc.vscode` - VS Code extension: `exts-vscode/embedded-vscode-for-nvidia-omniverse`
4,745
Markdown
52.931818
601
0.780611
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/snippets/generate_snippet.py
import json title = "TITLE" description = "DESCRIPTION" # placehorlders syntax: ${1:foo}, ${2:bar}, $0. # placeholder traversal order is ascending by number, starting from one. # zero is an optional special case that always comes last, # and exits snippet mode with the cursor at the specified position snippet = """ CODE """ # generate entry print() print(json.dumps({"title": title, "description": description, "snippet":snippet[1:]}, # remove first line break indent=4)) print()
547
Python
21.833332
72
0.641682
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/snippets/generate_commands_merge.py
import os import json def merge(snippets, app): for s in app["snippets"]: exists = False for ss in snippets: if s["title"] == ss["title"]: exists = True break # add section if not exists: print(" |-- new: {} ({})".format(s["title"], len(s["snippets"]))) snippets.append(s) # update section else: print(" |-- update: {} ({} <- {})".format(s["title"], len(ss["snippets"]), len(s["snippets"]))) for subs in s["snippets"]: exists = False for subss in ss["snippets"]: if subs["title"] == subss["title"]: exists = True break if not exists: print(" | |-- add:", subs["title"]) ss["snippets"].append(subs) snippets = [] # merge print("CREATE") with open(os.path.join("commands", "kit-commands-create.json")) as f: merge(snippets, json.load(f)) print("CODE") with open(os.path.join("commands", "kit-commands-code.json")) as f: merge(snippets, json.load(f)) print("ISAAC SIM") with open(os.path.join("commands", "kit-commands-isaac-sim.json")) as f: merge(snippets, json.load(f)) # sort snippets snippets = sorted(snippets, key=lambda d: d["title"]) for s in snippets: s["snippets"] = sorted(s["snippets"], key=lambda d: d["title"]) # save snippets with open("kit-commands.json", "w") as f: json.dump({"snippets": snippets}, f, indent=0) print("done")
1,618
Python
27.403508
108
0.508035
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/snippets/generate_isaac_sim.py
import json import inspect from types import FunctionType from pxr import Sdf def args_annotations(method): signature = inspect.signature(method) args = [] annotations = [] return_val = signature.return_annotation return_val = class_fullname(return_val) if return_val != type(inspect.Signature.empty) else "None" return_val = "" if return_val in ["inspect._empty", "None"] else return_val for parameter in signature.parameters.values(): if parameter.name in ["self", "args", "kwargs"]: continue # arg if type(parameter.default) == type(inspect.Parameter.empty): args.append("{}={}".format(parameter.name, parameter.name)) else: default_value = parameter.default if type(parameter.default) is str: default_value = '"{}"'.format(parameter.default) elif type(parameter.default) is Sdf.Path: if parameter.default == Sdf.Path.emptyPath: default_value = "Sdf.Path.emptyPath" else: default_value = 'Sdf.Path("{}")'.format(parameter.default) elif inspect.isclass(parameter.default): default_value = class_fullname(parameter.default) args.append("{}={}".format(parameter.name, default_value)) # annotation if parameter.annotation == inspect.Parameter.empty: annotations.append("") else: annotations.append(class_fullname(parameter.annotation)) return args, annotations, return_val def class_fullname(c): try: module = c.__module__ if module == 'builtins': return c.__name__ return module + '.' + c.__name__ except: return str(c) def get_class(klass, object_name): class_name = klass.__qualname__ args, annotations, _ = args_annotations(klass.__init__) # build snippet arguments_as_string = ')' if args: arguments_as_string = '' spaces = len(object_name) + 3 + len(class_name) + 1 for i, arg, annotation in zip(range(len(args)), args, annotations): k = 0 if not i else 1 is_last = i >= len(args) - 1 if annotation: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ") # {}".format(annotation) if is_last else ", # {}\n".format(annotation)) else: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ")" if is_last else ",\n") try: description = klass.__doc__.replace("\n ", "\n") if description.startswith("\n"): description = description[1:] if description.endswith("\n"): description = description[:-1] while " " in description: description = description.replace(" ", " ") except Exception as e: description = None if not description: description = "" snippet = '{} = {}({}'.format(object_name, class_name, arguments_as_string) + "\n" return { "title": class_name, "description": description, "snippet": snippet } def get_methods(klass, object_name): method_names = sorted([x for x, y in klass.__dict__.items() if type(y) == FunctionType and not x.startswith("__")]) snippets = [] for method_name in method_names: if method_name.startswith("_") or method_name.startswith("__"): continue args, annotations, return_val = args_annotations(klass.__dict__[method_name]) # build snippet arguments_as_string = ')' if args: arguments_as_string = '' return_var_name = "" if method_name.startswith("get_"): return_var_name = method_name[4:] + " = " spaces = len(return_var_name) + len(object_name) + 1 + len(method_name) + 1 for i, arg, annotation in zip(range(len(args)), args, annotations): k = 0 if not i else 1 is_last = i >= len(args) - 1 if annotation: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ") # {}".format(annotation) if is_last else ", # {}\n".format(annotation)) else: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ")" if is_last else ",\n") try: description = klass.__dict__[method_name].__doc__.replace("\n ", "\n") while " " in description: description = description.replace(" ", " ") if description.startswith("\n"): description = description[1:] if description.endswith("\n"): description = description[:-1] if description.endswith("\n "): description = description[:-2] except Exception as e: description = None if not description: description = "" if return_var_name: snippet = '{}{}.{}({}'.format(return_var_name, object_name, method_name, arguments_as_string) + "\n" else: snippet = '{}.{}({}'.format(object_name, method_name, arguments_as_string) + "\n" snippets.append({ "title": method_name, "description": description, "snippet": snippet }) return snippets def get_functions(module, module_name, exclude_functions=[]): functions = inspect.getmembers(module, inspect.isfunction) snippets = [] for function in functions: function_name = function[0] if function_name.startswith("_") or function_name.startswith("__"): continue if function_name in exclude_functions: continue args, annotations, return_val = args_annotations(function[1]) # build snippet arguments_as_string = ')' if args: arguments_as_string = '' return_var_name = "" if return_val: return_var_name = "value = " spaces = len(return_var_name) + len(module_name) + 1 + len(function_name) + 1 for i, arg, annotation in zip(range(len(args)), args, annotations): k = 0 if not i else 1 is_last = i >= len(args) - 1 if annotation: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ") # {}".format(annotation) if is_last else ", # {}\n".format(annotation)) else: arguments_as_string += " " * k * spaces + "{}{}".format(arg, ")" if is_last else ",\n") try: description = function[1].__doc__.replace("\n ", "\n") while " " in description: description = description.replace(" ", " ") if description.startswith("\n"): description = description[1:] if description.endswith("\n"): description = description[:-1] if description.endswith("\n "): description = description[:-2] except Exception as e: description = None if not description: description = "" if return_var_name: snippet = '{}{}.{}({}'.format(return_var_name, module_name, function_name, arguments_as_string) + "\n" else: snippet = '{}.{}({}'.format(module_name, function_name, arguments_as_string) + "\n" snippets.append({ "title": function_name, "description": description, "snippet": snippet }) return snippets from omni.isaac.core.articulations import Articulation, ArticulationGripper, ArticulationSubset, ArticulationView from omni.isaac.core.controllers import ArticulationController, BaseController, BaseGripperController from omni.isaac.core.loggers import DataLogger from omni.isaac.core.materials import OmniGlass, OmniPBR, ParticleMaterial, ParticleMaterialView, PhysicsMaterial, PreviewSurface, VisualMaterial from omni.isaac.core.objects import DynamicCapsule, DynamicCone, DynamicCuboid, DynamicCylinder, DynamicSphere from omni.isaac.core.objects import FixedCapsule, FixedCone, FixedCuboid, FixedCylinder, FixedSphere, GroundPlane from omni.isaac.core.objects import VisualCapsule, VisualCone, VisualCuboid, VisualCylinder, VisualSphere from omni.isaac.core.physics_context import PhysicsContext from omni.isaac.core.prims import BaseSensor, ClothPrim, ClothPrimView, GeometryPrim, GeometryPrimView, ParticleSystem, ParticleSystemView, RigidContactView, RigidPrim, RigidPrimView, XFormPrim, XFormPrimView from omni.isaac.core.robots import Robot, RobotView from omni.isaac.core.scenes import Scene, SceneRegistry from omni.isaac.core.simulation_context import SimulationContext from omni.isaac.core.world import World from omni.isaac.core.tasks import BaseTask, FollowTarget, PickPlace, Stacking from omni.isaac.core.prims._impl.single_prim_wrapper import _SinglePrimWrapper import omni.isaac.core.utils.bounds as utils_bounds import omni.isaac.core.utils.carb as utils_carb import omni.isaac.core.utils.collisions as utils_collisions import omni.isaac.core.utils.constants as utils_constants import omni.isaac.core.utils.distance_metrics as utils_distance_metrics import omni.isaac.core.utils.extensions as utils_extensions import omni.isaac.core.utils.math as utils_math import omni.isaac.core.utils.mesh as utils_mesh import omni.isaac.core.utils.nucleus as utils_nucleus import omni.isaac.core.utils.numpy as utils_numpy import omni.isaac.core.utils.physics as utils_physics import omni.isaac.core.utils.prims as utils_prims import omni.isaac.core.utils.random as utils_random import omni.isaac.core.utils.render_product as utils_render_product import omni.isaac.core.utils.rotations as utils_rotations import omni.isaac.core.utils.semantics as utils_semantics import omni.isaac.core.utils.stage as utils_stage import omni.isaac.core.utils.string as utils_string import omni.isaac.core.utils.transformations as utils_transformations import omni.isaac.core.utils.torch as utils_torch import omni.isaac.core.utils.types as utils_types import omni.isaac.core.utils.viewports as utils_viewports import omni.isaac.core.utils.xforms as utils_xforms # from omni.isaac.dynamic_control import _dynamic_control # _dynamic_control_interface = _dynamic_control.acquire_dynamic_control_interface() from omni.isaac.ui import ui_utils from omni.isaac.kit import SimulationApp # core snippets = [] # articulations subsnippets = [] s0 = get_class(Articulation, "articulation") s1 = get_methods(Articulation, "articulation") s2 = get_methods(_SinglePrimWrapper, "articulation") subsnippets.append({"title": "Articulation", "snippets": [s0] + s1 + s2}) s0 = get_class(ArticulationGripper, "articulation_gripper") s1 = get_methods(ArticulationGripper, "articulation_gripper") subsnippets.append({"title": "ArticulationGripper", "snippets": [s0] + s1}) s0 = get_class(ArticulationSubset, "articulation_subset") s1 = get_methods(ArticulationSubset, "articulation_subset") subsnippets.append({"title": "ArticulationSubset", "snippets": [s0] + s1}) s0 = get_class(ArticulationView, "articulation_view") s1 = get_methods(ArticulationView, "articulation_view") s2 = get_methods(XFormPrimView, "articulation_view") subsnippets.append({"title": "ArticulationView", "snippets": [s0] + s1 + s2}) snippets.append({"title": "Articulations", "snippets": subsnippets}) # controllers subsnippets = [] s0 = get_class(ArticulationController, "articulation_controller") s1 = get_methods(ArticulationController, "articulation_controller") subsnippets.append({"title": "ArticulationController", "snippets": [s0] + s1}) s0 = get_class(BaseController, "base_controller") s1 = get_methods(BaseController, "base_controller") subsnippets.append({"title": "BaseController", "snippets": [s0] + s1}) s0 = get_class(BaseGripperController, "base_gripper_controller") s1 = get_methods(BaseGripperController, "base_gripper_controller") subsnippets.append({"title": "BaseGripperController", "snippets": [s0] + s1}) snippets.append({"title": "Controllers", "snippets": subsnippets}) # loggers s0 = get_class(DataLogger, "data_logger") s1 = get_methods(DataLogger, "data_logger") snippets.append({"title": "DataLogger", "snippets": [s0] + s1}) # materials subsnippets = [] s0 = get_class(OmniGlass, "omni_glass") s1 = get_methods(OmniGlass, "omni_glass") subsnippets.append({"title": "OmniGlass", "snippets": [s0] + s1}) s0 = get_class(OmniPBR, "omni_pbr") s1 = get_methods(OmniPBR, "omni_pbr") subsnippets.append({"title": "OmniPBR", "snippets": [s0] + s1}) s0 = get_class(ParticleMaterial, "particle_material") s1 = get_methods(ParticleMaterial, "particle_material") subsnippets.append({"title": "ParticleMaterial", "snippets": [s0] + s1}) s0 = get_class(ParticleMaterialView, "particle_material_view") s1 = get_methods(ParticleMaterialView, "particle_material_view") subsnippets.append({"title": "ParticleMaterialView", "snippets": [s0] + s1}) s0 = get_class(PhysicsMaterial, "physics_material") s1 = get_methods(PhysicsMaterial, "physics_material") subsnippets.append({"title": "PhysicsMaterial", "snippets": [s0] + s1}) s0 = get_class(PreviewSurface, "preview_surface") s1 = get_methods(PreviewSurface, "preview_surface") subsnippets.append({"title": "PreviewSurface", "snippets": [s0] + s1}) s0 = get_class(VisualMaterial, "visual_material") s1 = get_methods(VisualMaterial, "visual_material") subsnippets.append({"title": "VisualMaterial", "snippets": [s0] + s1}) snippets.append({"title": "Materials", "snippets": subsnippets}) # objects subsnippets = [] s0 = get_class(DynamicCapsule, "dynamic_capsule") s1 = get_methods(DynamicCapsule, "dynamic_capsule") s2 = get_methods(RigidPrim, "dynamic_capsule") s3 = get_methods(VisualCapsule, "dynamic_capsule") s4 = get_methods(GeometryPrim, "dynamic_capsule") s5 = get_methods(_SinglePrimWrapper, "dynamic_capsule") subsnippets.append({"title": "DynamicCapsule", "snippets": [s0] + s1 + s2 + s3 + s4 + s5}) s0 = get_class(DynamicCone, "dynamic_cone") s1 = get_methods(DynamicCone, "dynamic_cone") s2 = get_methods(RigidPrim, "dynamic_cone") s3 = get_methods(VisualCone, "dynamic_cone") s4 = get_methods(GeometryPrim, "dynamic_cone") s5 = get_methods(_SinglePrimWrapper, "dynamic_cone") subsnippets.append({"title": "DynamicCone", "snippets": [s0] + s1 + s2 + s3 + s4 + s5}) s0 = get_class(DynamicCuboid, "dynamic_cuboid") s1 = get_methods(DynamicCuboid, "dynamic_cuboid") s2 = get_methods(RigidPrim, "dynamic_cuboid") s3 = get_methods(VisualCuboid, "dynamic_cuboid") s4 = get_methods(GeometryPrim, "dynamic_cuboid") s5 = get_methods(_SinglePrimWrapper, "dynamic_cuboid") subsnippets.append({"title": "DynamicCuboid", "snippets": [s0] + s1 + s2 + s3 + s4 + s5}) s0 = get_class(DynamicCylinder, "dynamic_cylinder") s1 = get_methods(DynamicCylinder, "dynamic_cylinder") s2 = get_methods(RigidPrim, "dynamic_cylinder") s3 = get_methods(VisualCylinder, "dynamic_cylinder") s4 = get_methods(GeometryPrim, "dynamic_cylinder") s5 = get_methods(_SinglePrimWrapper, "dynamic_cylinder") subsnippets.append({"title": "DynamicCylinder", "snippets": [s0] + s1 + s2 + s3 + s4 + s5}) s0 = get_class(DynamicSphere, "dynamic_sphere") s1 = get_methods(DynamicSphere, "dynamic_sphere") s2 = get_methods(RigidPrim, "dynamic_sphere") s3 = get_methods(VisualSphere, "dynamic_sphere") s4 = get_methods(GeometryPrim, "dynamic_sphere") s5 = get_methods(_SinglePrimWrapper, "dynamic_sphere") subsnippets.append({"title": "DynamicSphere", "snippets": [s0] + s1 + s2 + s3 + s4 + s5}) s0 = get_class(FixedCapsule, "fixed_capsule") s1 = get_methods(VisualCapsule, "fixed_capsule") s2 = get_methods(GeometryPrim, "fixed_capsule") s3 = get_methods(_SinglePrimWrapper, "fixed_capsule") subsnippets.append({"title": "FixedCapsule", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(FixedCone, "fixed_cone") s1 = get_methods(VisualCone, "fixed_cone") s2 = get_methods(GeometryPrim, "fixed_cone") s3 = get_methods(_SinglePrimWrapper, "fixed_cone") subsnippets.append({"title": "FixedCone", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(FixedCuboid, "fixed_cuboid") s1 = get_methods(VisualCuboid, "fixed_cuboid") s2 = get_methods(GeometryPrim, "fixed_cuboid") s3 = get_methods(_SinglePrimWrapper, "fixed_cuboid") subsnippets.append({"title": "FixedCuboid", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(FixedCylinder, "fixed_cylinder") s1 = get_methods(VisualCylinder, "fixed_cylinder") s2 = get_methods(GeometryPrim, "fixed_cylinder") s3 = get_methods(_SinglePrimWrapper, "fixed_cylinder") subsnippets.append({"title": "FixedCylinder", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(FixedSphere, "fixed_sphere") s1 = get_methods(VisualSphere, "fixed_sphere") s2 = get_methods(GeometryPrim, "fixed_sphere") s3 = get_methods(_SinglePrimWrapper, "fixed_sphere") subsnippets.append({"title": "FixedSphere", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(GroundPlane, "ground_plane") s1 = get_methods(GroundPlane, "ground_plane") subsnippets.append({"title": "GroundPlane", "snippets": [s0] + s1}) s0 = get_class(VisualCapsule, "visual_capsule") s1 = get_methods(VisualCapsule, "visual_capsule") s2 = get_methods(GeometryPrim, "visual_capsule") s3 = get_methods(_SinglePrimWrapper, "visual_capsule") subsnippets.append({"title": "VisualCapsule", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(VisualCone, "visual_cone") s1 = get_methods(VisualCone, "visual_cone") s2 = get_methods(GeometryPrim, "visual_cone") s3 = get_methods(_SinglePrimWrapper, "visual_cone") subsnippets.append({"title": "VisualCone", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(VisualCuboid, "visual_cuboid") s1 = get_methods(VisualCuboid, "visual_cuboid") s2 = get_methods(GeometryPrim, "visual_cuboid") s3 = get_methods(_SinglePrimWrapper, "visual_cuboid") subsnippets.append({"title": "VisualCuboid", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(VisualCylinder, "visual_cylinder") s1 = get_methods(VisualCylinder, "visual_cylinder") s2 = get_methods(GeometryPrim, "visual_cylinder") s3 = get_methods(_SinglePrimWrapper, "visual_cylinder") subsnippets.append({"title": "VisualCylinder", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(VisualSphere, "visual_sphere") s1 = get_methods(VisualSphere, "visual_sphere") s2 = get_methods(GeometryPrim, "visual_sphere") s3 = get_methods(_SinglePrimWrapper, "visual_sphere") subsnippets.append({"title": "VisualSphere", "snippets": [s0] + s1 + s2 + s3}) snippets.append({"title": "Objects", "snippets": subsnippets}) # physics_context s0 = get_class(PhysicsContext, "physics_context") s1 = get_methods(PhysicsContext, "physics_context") snippets.append({"title": "PhysicsContext", "snippets": [s0] + s1}) # prims subsnippets = [] s0 = get_class(BaseSensor, "base_sensor") s1 = get_methods(BaseSensor, "base_sensor") s2 = get_methods(_SinglePrimWrapper, "base_sensor") subsnippets.append({"title": "BaseSensor", "snippets": [s0] + s1 + s2}) s0 = get_class(ClothPrim, "cloth_prim") s1 = get_methods(ClothPrim, "cloth_prim") s2 = get_methods(_SinglePrimWrapper, "cloth_prim") subsnippets.append({"title": "ClothPrim", "snippets": [s0] + s1 + s2}) s0 = get_class(ClothPrimView, "cloth_prim_view") s1 = get_methods(ClothPrimView, "cloth_prim_view") s2 = get_methods(XFormPrimView, "cloth_prim_view") subsnippets.append({"title": "ClothPrimView", "snippets": [s0] + s1 + s2}) s0 = get_class(GeometryPrim, "geometry_prim") s1 = get_methods(GeometryPrim, "geometry_prim") s2 = get_methods(_SinglePrimWrapper, "geometry_prim") subsnippets.append({"title": "GeometryPrim", "snippets": [s0] + s1 + s2}) s0 = get_class(GeometryPrimView, "geometry_prim_view") s1 = get_methods(GeometryPrimView, "geometry_prim_view") s2 = get_methods(XFormPrimView, "geometry_prim_view") subsnippets.append({"title": "GeometryPrimView", "snippets": [s0] + s1 + s2}) s0 = get_class(ParticleSystem, "particle_system") s1 = get_methods(ParticleSystem, "particle_system") subsnippets.append({"title": "ParticleSystem", "snippets": [s0] + s1}) s0 = get_class(ParticleSystemView, "particle_system_view") s1 = get_methods(ParticleSystemView, "particle_system_view") subsnippets.append({"title": "ParticleSystemView", "snippets": [s0] + s1}) s0 = get_class(RigidContactView, "rigid_contact_view") s1 = get_methods(RigidContactView, "rigid_contact_view") subsnippets.append({"title": "RigidContactView", "snippets": [s0] + s1}) s0 = get_class(RigidPrim, "rigid_prim") s1 = get_methods(RigidPrim, "rigid_prim") s2 = get_methods(_SinglePrimWrapper, "rigid_prim") subsnippets.append({"title": "RigidPrim", "snippets": [s0] + s1 + s2}) s0 = get_class(RigidPrimView, "rigid_prim_view") s1 = get_methods(RigidPrimView, "rigid_prim_view") s2 = get_methods(XFormPrimView, "rigid_prim_view") subsnippets.append({"title": "RigidPrimView", "snippets": [s0] + s1 + s2}) s0 = get_class(XFormPrim, "xform_prim") s1 = get_methods(XFormPrim, "xform_prim") s2 = get_methods(_SinglePrimWrapper, "xform_prim") subsnippets.append({"title": "XFormPrim", "snippets": [s0] + s1 + s2}) s0 = get_class(XFormPrimView, "xform_prim_view") s1 = get_methods(XFormPrimView, "xform_prim_view") subsnippets.append({"title": "XFormPrimView", "snippets": [s0] + s1}) snippets.append({"title": "Prims", "snippets": subsnippets}) # robots subsnippets = [] s0 = get_class(Robot, "robot") s1 = get_methods(Robot, "robot") s2 = get_methods(Articulation, "robot") s3 = get_methods(_SinglePrimWrapper, "robot") subsnippets.append({"title": "Robot", "snippets": [s0] + s1 + s2 + s3}) s0 = get_class(RobotView, "robot_view") s1 = get_methods(RobotView, "robot_view") s2 = get_methods(ArticulationView, "robot_view") s3 = get_methods(XFormPrimView, "robot_view") subsnippets.append({"title": "RobotView", "snippets": [s0] + s1 + s2 + s3}) snippets.append({"title": "Robots", "snippets": subsnippets}) # scenes subsnippets = [] s0 = get_class(Scene, "scene") s1 = get_methods(Scene, "scene") subsnippets.append({"title": "Scene", "snippets": [s0] + s1}) s0 = get_class(SceneRegistry, "scene_registry") s1 = get_methods(SceneRegistry, "scene_registry") subsnippets.append({"title": "SceneRegistry", "snippets": [s0] + s1}) snippets.append({"title": "Scenes", "snippets": subsnippets}) # simulation_context s0 = get_class(SimulationContext, "simulation_context") s1 = get_methods(SimulationContext, "simulation_context") snippets.append({"title": "SimulationContext", "snippets": [s0] + s1}) # world s0 = get_class(World, "world") s1 = get_methods(World, "world") s2 = get_methods(SimulationContext, "world") snippets.append({"title": "World", "snippets": [s0] + s1 + s2}) # tasks subsnippets = [] s0 = get_class(BaseTask, "base_task") s1 = get_methods(BaseTask, "base_task") subsnippets.append({"title": "BaseTask", "snippets": [s0] + s1}) s0 = get_class(FollowTarget, "follow_target") s1 = get_methods(FollowTarget, "follow_target") s2 = get_methods(BaseTask, "follow_target") subsnippets.append({"title": "FollowTarget", "snippets": [s0] + s1 + s2}) s0 = get_class(PickPlace, "pick_place") s1 = get_methods(PickPlace, "pick_place") s2 = get_methods(BaseTask, "pick_place") subsnippets.append({"title": "PickPlace", "snippets": [s0] + s1 + s2}) s0 = get_class(Stacking, "stacking") s1 = get_methods(Stacking, "stacking") s2 = get_methods(BaseTask, "stacking") subsnippets.append({"title": "Stacking", "snippets": [s0] + s1 + s2}) snippets.append({"title": "Tasks", "snippets": subsnippets}) # core utils snippets_utils = [] s0 = get_functions(utils_bounds, "bounds_utils", exclude_functions=["get_prim_at_path"]) snippets_utils.append({"title": "Bounds", "snippets": s0}) s0 = get_functions(utils_carb, "carb_utils") snippets_utils.append({"title": "Carb", "snippets": s0}) s0 = get_functions(utils_collisions, "collisions_utils", exclude_functions=["get_current_stage"]) snippets_utils.append({"title": "Collisions", "snippets": s0}) s0 = get_functions(utils_constants, "constants_utils") snippets_utils.append({"title": "Constants", "snippets": [{"title": "AXES_INDICES", "description": "Mapping from axis name to axis ID", "snippet": "AXES_INDICES\n"}, {"title": "AXES_TOKEN", "description": "Mapping from axis name to axis USD token", "snippet": "AXES_TOKEN\n"}]}) s0 = get_functions(utils_distance_metrics, "distance_metrics_utils") snippets_utils.append({"title": "Distance Metrics", "snippets": s0}) s0 = get_functions(utils_extensions, "extensions_utils") snippets_utils.append({"title": "Extensions", "snippets": s0}) s0 = get_functions(utils_math, "math_utils") snippets_utils.append({"title": "Math", "snippets": s0}) s0 = get_functions(utils_mesh, "mesh_utils", exclude_functions=["get_stage_units", "get_relative_transform"]) snippets_utils.append({"title": "Mesh", "snippets": s0}) s0 = get_functions(utils_nucleus, "nucleus_utils", exclude_functions=["namedtuple", "urlparse", "get_version"]) snippets_utils.append({"title": "Nucleus", "snippets": s0}) s0 = get_functions(utils_numpy, "numpy_utils") snippets_utils.append({"title": "Numpy", "snippets": s0}) s0 = get_functions(utils_physics, "physics_utils", exclude_functions=["get_current_stage"]) snippets_utils.append({"title": "Physics", "snippets": s0}) s0 = get_functions(utils_prims, "prims_utils", exclude_functions=["add_reference_to_stage", "get_current_stage", "find_root_prim_path_from_regex", "add_update_semantics"]) snippets_utils.append({"title": "Prims", "snippets": s0}) s0 = get_functions(utils_random, "random_utils", exclude_functions=["get_world_pose_from_relative", "get_translation_from_target", "euler_angles_to_quat"]) snippets_utils.append({"title": "Random", "snippets": s0}) s0 = get_functions(utils_render_product, "render_product_utils", exclude_functions=["set_prim_hide_in_stage_window", "set_prim_no_delete", "get_current_stage"]) snippets_utils.append({"title": "Render Product", "snippets": s0}) s0 = get_functions(utils_rotations, "rotations_utils") snippets_utils.append({"title": "Rotations", "snippets": s0}) s0 = get_functions(utils_semantics, "semantics_utils") snippets_utils.append({"title": "Semantics", "snippets": s0}) s0 = get_functions(utils_stage, "stage_utils") snippets_utils.append({"title": "Stage", "snippets": s0}) s0 = get_functions(utils_string, "string_utils") snippets_utils.append({"title": "String", "snippets": s0}) s0 = get_functions(utils_transformations, "transformations_utils", exclude_functions=["gf_quat_to_np_array"]) snippets_utils.append({"title": "Transformations", "snippets": s0}) s0 = get_functions(utils_torch, "torch_utils") snippets_utils.append({"title": "Torch", "snippets": s0}) subsnippets = [] s0 = get_class(utils_types.ArticulationAction, "articulation_action") s1 = get_methods(utils_types.ArticulationAction, "articulation_action") subsnippets.append({"title": "ArticulationAction", "snippets": [s0] + s1}) s0 = get_class(utils_types.ArticulationActions, "articulation_actions") subsnippets.append(s0) s0 = get_class(utils_types.DataFrame, "data_frame") s1 = get_methods(utils_types.DataFrame, "data_frame") subsnippets.append({"title": "DataFrame", "snippets": [s0] + s1}) s0 = get_class(utils_types.DOFInfo, "dof_Info") subsnippets.append(s0) s0 = get_class(utils_types.DynamicState, "dynamic_state") subsnippets.append(s0) s0 = get_class(utils_types.DynamicsViewState, "dynamics_view_state") subsnippets.append(s0) s0 = get_class(utils_types.JointsState, "joints_state") subsnippets.append(s0) s0 = get_class(utils_types.XFormPrimState, "xform_prim_state") subsnippets.append(s0) s0 = get_class(utils_types.XFormPrimViewState, "xform_prim_view_state") subsnippets.append(s0) s0 = get_functions(utils_types, "types_utils") snippets_utils.append({"title": "Types", "snippets": subsnippets}) s0 = get_functions(utils_viewports, "viewports_utils", exclude_functions=["get_active_viewport", "get_current_stage", "set_prim_hide_in_stage_window", "set_prim_no_delete"]) snippets_utils.append({"title": "Viewports", "snippets": s0}) s0 = get_functions(utils_xforms, "xforms_utils") snippets_utils.append({"title": "XForms", "snippets": s0}) # ui utils snippets_ui_utils = [] s0 = get_functions(ui_utils, "ui_utils") snippets_ui_utils.append({"title": "UI Utils", "snippets": s0}) # SimulationApp snippets_simulation_app = [] s0 = get_class(SimulationApp, "simulation_app") s1 = get_methods(SimulationApp, "simulation_app") snippets_simulation_app.append({"title": "SimulationApp", "snippets": [s0] + s1}) with open("isaac-sim-snippets-core.json", "w") as f: json.dump(snippets, f, indent=0) with open("isaac-sim-snippets-utils.json", "w") as f: json.dump(snippets_utils, f, indent=0) with open("isaac-sim-snippets-ui-utils.json", "w") as f: json.dump(snippets_ui_utils, f, indent=0) with open("isaac-sim-snippets-simulation-app.json", "w") as f: json.dump(snippets_simulation_app, f, indent=0) print("DONE")
28,986
Python
39.037293
208
0.677706
Toni-SM/semu.misc.vscode/exts-vscode/embedded-vscode-for-nvidia-omniverse/snippets/generate_commands_app.py
import json import inspect import collections count = 0 snippets = [] snippets_by_extensions_depth = 2 snippets_by_extensions = collections.defaultdict(list) def class_fullname(c): try: module = c.__module__ if module == 'builtins': return c.__name__ return module + '.' + c.__name__ except: return str(c) from pxr import Sdf commands = omni.kit.commands.get_commands() for k, v in commands.items(): # count += 1 # print() # if count > 20: # break if v: command_class = list(v.values())[0] command_extension = list(v.keys())[0] spec = inspect.getfullargspec(command_class.__init__) signature = inspect.signature(command_class.__init__) command = command_class.__qualname__ command_args = [] command_annotations = [] for parameter in signature.parameters.values(): if parameter.name in ["self", "args", "kwargs"]: continue # arg if type(parameter.default) == type(inspect.Parameter.empty): command_args.append("{}={}".format(parameter.name, parameter.name)) else: default_value = parameter.default if type(parameter.default) is str: default_value = '"{}"'.format(parameter.default) elif type(parameter.default) is Sdf.Path: if parameter.default == Sdf.Path.emptyPath: default_value = "Sdf.Path.emptyPath" else: default_value = 'Sdf.Path("{}")'.format(parameter.default) elif inspect.isclass(parameter.default): default_value = class_fullname(parameter.default) command_args.append("{}={}".format(parameter.name, default_value)) # annotation if parameter.annotation == inspect.Parameter.empty: command_annotations.append("") else: command_annotations.append(class_fullname(parameter.annotation)) # build snippet arguments_as_string = '")' if command_args: arguments_as_string = '",\n' for i, arg, annotation in zip(range(len(command_args)), command_args, command_annotations): is_last = i >= len(command_args) - 1 if annotation: arguments_as_string += " " * 26 + "{}{}".format(arg, ") # {}".format(annotation) if is_last else ", # {}\n".format(annotation)) else: arguments_as_string += " " * 26 + "{}{}".format(arg, ")" if is_last else ",\n") title = command try: description = command_class.__doc__.replace("\n ", "\n").replace(" **Command**", "") if description.startswith("\n"): description = description[1:] if description.endswith("\n"): description = description[:-1] while " " in description: description = description.replace(" ", " ") description = "[{}]\n\n".format(command_extension) + description except Exception as e: description = None if not description: description = "[{}]".format(command_extension) snippet = 'omni.kit.commands.execute("{}{}'.format(command, arguments_as_string) + "\n" # storage snippet (all) snippets.append({"title": title, "description": description, "snippet": snippet}) # storage snippet (by extension) command_extension = ".".join(command_extension.split(".")[:snippets_by_extensions_depth]) snippets_by_extensions[command_extension].append({"title": title, "description": description, "snippet": snippet}) snippets = [] for title, snippets_by_extension in snippets_by_extensions.items(): snippets.append({"title": title, "snippets": snippets_by_extension}) with open("kit-commands.json", "w") as f: json.dump({"snippets": snippets}, f, indent=0) print("done")
4,069
Python
37.396226
145
0.561317
Toni-SM/semu.xr.openxr/README.md
## OpenXR compact binding for creating extended reality applications on NVIDIA Omniverse > This extension provides a compact python binding (on top of the open standard [OpenXR](https://www.khronos.org/openxr/) for augmented reality (AR) and virtual reality (VR)) to create extended reality applications taking advantage of NVIDIA Omniverse rendering capabilities. In addition to updating views (e.g., head-mounted display), it enables subscription to any input event (e.g., controller buttons and triggers) and execution of output actions (e.g., haptic vibration) through a simple and efficient API for accessing conformant devices such as HTC Vive, Oculus and others... <br> **Target applications:** Any NVIDIA Omniverse app with the `omni.syntheticdata` extension installed (e.g., Isaac Sim, Code, etc.) - *Tested in Ubuntu 18.04/20.04, STEAMVR beta 1.24.3, Omniverse Code 2022.1.3 and Isaac Sim 2022.1.1* **Supported OS:** Linux **Changelog:** [CHANGELOG.md](exts/semu.xr.openxr/docs/CHANGELOG.md) **Table of Contents:** - [Extension setup](#setup) - [Diagrams](#diagrams) - [Sample code](#sample) - [GUI launcher](#gui) - [Extension API](#api) - [Acquiring extension interface](#api-interface) - [API](#api-functions) - [```init```](#method-init) - [```is_session_running```](#method-is_session_running) - [```create_instance```](#method-create_instance) - [```get_system```](#method-get_system) - [```create_session```](#method-create_session) - [```poll_events```](#method-poll_events) - [```poll_actions```](#method-poll_actions) - [```render_views```](#method-render_views) - [```subscribe_action_event```](#method-subscribe_action_event) - [```apply_haptic_feedback```](#method-apply_haptic_feedback) - [```stop_haptic_feedback```](#method-stop_haptic_feedback) - [```setup_mono_view```](#method-setup_mono_view) - [```setup_stereo_view```](#method-setup_stereo_view) - [```get_recommended_resolutions```](#method-get_recommended_resolutions) - [```set_reference_system_pose```](#method-set_reference_system_pose) - [```set_stereo_rectification```](#method-set_stereo_rectification) - [```set_meters_per_unit```](#method-set_meters_per_unit) - [```set_frame_transformations```](#method-set_frame_transformations) - [```teleport_prim```](#method-teleport_prim) - [```subscribe_render_event```](#method-subscribe_render_event) - [```set_frames```](#method-set_frames) - [Available enumerations](#api-enumerations) - [Available constants](#api-constants) <br> ![showcase](exts/semu.xr.openxr/data/preview.png) <hr> <a name="setup"></a> ### Extension setup 1. Add the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Search Paths](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-search-paths) * Git url (git+https) as extension search path ``` git+https://github.com/Toni-SM/semu.xr.openxr.git?branch=main&dir=exts ``` * Compressed (.zip) file for import [semu.xr.openxr.zip](https://github.com/Toni-SM/semu.xr.openxr/releases) 2. Enable the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Enabling/Disabling](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-enabling-disabling) 3. Import the extension into any python code and use it... ```python from semu.xr.openxr import _openxr ``` 4. Or use the [GUI launcher](#gui) to directly dislpay the current stage in the HMD <hr> <a name="diagrams"></a> ### Diagrams High-level overview of extension usage, including the order of function calls, callbacks and the action and rendering loop <p align="center"> <img src="https://user-images.githubusercontent.com/22400377/190011524-27ae7023-6c49-4e00-986f-03e087bd9ac1.png" width="55%"> </p> Typical OpenXR application showing the grouping of the standard functions under the compact binding provided by the extension (adapted from [openxr-10-reference-guide.pdf](https://www.khronos.org/registry/OpenXR/specs/1.0/refguide/openxr-10-reference-guide.pdf)) ![openxr-application](https://user-images.githubusercontent.com/22400377/136704215-5507bbee-666a-42da-b692-cbf8c08a749b.png) <hr> <a name="sample"></a> ### Sample code The following sample code shows a typical workflow that configures and renders on a stereo headset the view generated in an Omniverse application. It configures and subscribes two input actions to the left controller to 1) mirror on a simulated sphere the pose of the controller and 2) change the dimensions of the sphere based on the position of the trigger. In addition, an output action, a haptic vibration, is configured and executed when the controller trigger reaches its maximum position A short video, after the code, shows a test of the OpenXR application from the Script Editor using an HTC Vive Pro ```python import omni from pxr import UsdGeom from semu.xr.openxr import _openxr # get stage unit stage = omni.usd.get_context().get_stage() meters_per_unit = UsdGeom.GetStageMetersPerUnit(stage) # create a sphere (1 centimeter radius) to mirror the controller's pose sphere_prim = omni.usd.get_context().get_stage().DefinePrim("/sphere", "Sphere") sphere_prim.GetAttribute("radius").Set(0.01 / meters_per_unit) # acquire interface xr = _openxr.acquire_openxr_interface() # setup OpenXR application using default parameters xr.init() xr.create_instance() xr.get_system() # action callback def on_action_event(path, value): # process controller's trigger if path == "/user/hand/left/input/trigger/value": # modify the sphere's radius (from 1 to 10 centimeters) according to the controller's trigger position sphere_prim.GetAttribute("radius").Set((value * 9 + 1) * 0.01 / meters_per_unit) # apply haptic vibration when the controller's trigger is fully depressed if value == 1: xr.apply_haptic_feedback("/user/hand/left/output/haptic", {"duration": _openxr.XR_MIN_HAPTIC_DURATION}) # mirror the controller's pose on the sphere (cartesian position and rotation as quaternion) elif path == "/user/hand/left/input/grip/pose": xr.teleport_prim(sphere_prim, value[0], value[1]) # subscribe controller actions (haptic actions don't require callbacks) xr.subscribe_action_event("/user/hand/left/input/grip/pose", callback=on_action_event, reference_space=_openxr.XR_REFERENCE_SPACE_TYPE_LOCAL) xr.subscribe_action_event("/user/hand/left/input/trigger/value", callback=on_action_event) xr.subscribe_action_event("/user/hand/left/output/haptic") # create session and define interaction profiles xr.create_session() # setup cameras and viewports and prepare rendering using the internal callback xr.set_meters_per_unit(meters_per_unit) xr.setup_stereo_view() xr.set_frame_transformations(flip=0) xr.set_stereo_rectification(y=0.05) # execute action and rendering loop on each simulation step def on_simulation_step(step): if xr.poll_events() and xr.is_session_running(): xr.poll_actions() xr.render_views(_openxr.XR_REFERENCE_SPACE_TYPE_LOCAL) physx_subs = omni.physx.get_physx_interface().subscribe_physics_step_events(on_simulation_step) ``` [Watch the sample video](https://user-images.githubusercontent.com/22400377/190255669-d1e05833-e7c0-4ec7-9bd8-956188fe7053.mp4) <hr> <a name="gui"></a> ### GUI launcher The extension also provides a graphical user interface that helps to launch a partially configurable OpenXR application form a window. This interface is located in the *Add-ons > OpenXR UI* menu The first four options (Graphics API, Form factor, Blend mode, View configuration type) cannot be modified once the OpenXR application is running. They are used to create and configure the OpenXR instance, system and session The other options (under the central separator) can be modified while the application is running. They help to modify the pose of the reference system, or to perform transformations on the images to be rendered, for example. <p align="center"> <img src="https://user-images.githubusercontent.com/22400377/190108800-c5b701cd-05ea-41d5-9e5d-726049021eb8.png" width="65%"> </p> <hr> <a name="api"></a> ### Extension API <a name="api-interface"></a> #### Acquiring extension interface * Acquire OpenXR interface ```python _openxr.acquire_openxr_interface() -> semu::xr::openxr::OpenXR ``` * Release OpenXR interface ```python _openxr.release_openxr_interface(xr: semu::xr::openxr::OpenXR) -> None ``` <a name="api-functions"></a> #### API The following functions are provided on the OpenXR interface: <a name="method-init"></a> - Init OpenXR application by loading the necessary libraries ```python init(graphics: str = "OpenGL", use_ctypes: bool = False) -> bool ``` Parameters: - graphics: ```str``` OpenXR graphics API supported by the runtime (OpenGL, OpenGLES, Vulkan, D3D11, D3D12). **Note:** At the moment only OpenGL is available - use_ctypes: ```bool```, optional If true, use ctypes as C/C++ interface instead of pybind11 (default) Returns: - ```bool``` ```True``` if initialization was successful, otherwise ```False``` <a name="method-is_session_running"></a> - Get OpenXR session's running status ```python is_session_running() -> bool ``` Returns: - ```bool``` Return ```True``` if the OpenXR session is running, ```False``` otherwise <a name="method-create_instance"></a> - Create an OpenXR instance to allow communication with an OpenXR runtime ```python create_instance(application_name: str = "Omniverse (XR)", engine_name: str = "", api_layers: list = [], extensions: list = []) -> bool ``` Parameters: - application_name: ```str```, optional Name of the OpenXR application (default: *Omniverse (XR)*) - engine_name: ```str```, optional Name of the engine (if any) used to create the application (empty by default) - api_layers: ```list``` of ```str```, optional [API layers](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#api-layers) to be inserted between the OpenXR application and the runtime implementation - extensions: ```list``` of ```str```, optional [Extensions](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#extensions) to be loaded. **Note:** The graphics API selected during initialization (init) is automatically included in the extensions to be loaded. At the moment only the graphic extensions are configured Returns: - ```bool``` ```True``` if the instance has been created successfully, otherwise ```False``` <a name="method-get_system"></a> - Obtain the system represented by a collection of related devices at runtime ```python get_system(form_factor: int = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, blend_mode: int = XR_ENVIRONMENT_BLEND_MODE_OPAQUE, view_configuration_type: int = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO) -> bool ``` Parameters: - form_factor: {```XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY```, ```XR_FORM_FACTOR_HANDHELD_DISPLAY```}, optional Desired [form factor](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#form_factor_description) from ```XrFormFactor``` enum (default: ```XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY```) - blend_mode: {```XR_ENVIRONMENT_BLEND_MODE_OPAQUE```, ```XR_ENVIRONMENT_BLEND_MODE_ADDITIVE```, ```XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND```}, optional Desired environment [blend mode](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#environment_blend_mode) from ```XrEnvironmentBlendMode``` enum (default: ```XR_ENVIRONMENT_BLEND_MODE_OPAQUE```) - view_configuration_type: {```XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO```, ```XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO```}, optional Primary [view configuration](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#view_configurations) type from ```XrViewConfigurationType``` enum (default: ```XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO```) Returns: - ```bool``` ```True``` if the system has been obtained successfully, otherwise ```False``` <a name="method-create_session"></a> - Create an OpenXR session that represents an application's intention to display XR content ```python create_session() -> bool ``` Returns: - ```bool``` ```True``` if the session has been created successfully, otherwise ```False``` <a name="method-poll_events"></a> - [Event polling](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#event-polling) and processing ```python poll_events() -> bool ``` Returns: - ```bool``` ```False``` if the running session needs to end (due to the user closing or switching the application, etc.), otherwise ```False``` <a name="method-poll_actions"></a> - [Action](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_action_overview) polling ```python poll_actions() -> bool ``` Returns: - ```bool``` ```True``` if there is no error during polling, otherwise ```False``` <a name="method-render_views"></a> - Present rendered images to the user's views according to the selected reference space ```python render_views(reference_space: int = XR_REFERENCE_SPACE_TYPE_LOCAL) -> bool ``` Parameters: - reference_space: {```XR_REFERENCE_SPACE_TYPE_VIEW```, ```XR_REFERENCE_SPACE_TYPE_LOCAL```, ```XR_REFERENCE_SPACE_TYPE_STAGE```}, optional Desired [reference space](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#reference-spaces) type from ```XrReferenceSpaceType``` enum used to render the images (default: ```XR_REFERENCE_SPACE_TYPE_LOCAL```) Returns: - ```bool``` ```True``` if there is no error during rendering, otherwise ```False``` <a name="method-subscribe_action_event"></a> - Create an action given a path and subscribe a callback function to the update event of this action ```python subscribe_action_event(path: str, callback: Union[Callable[[str, object], None], None] = None, action_type: Union[int, None] = None, reference_space: Union[int, None] = XR_REFERENCE_SPACE_TYPE_LOCAL) -> bool ``` If ```action_type``` is ```None``` the action type will be automatically defined by parsing the last segment of the path according to the following policy: | Action type (```XrActionType```) | Last segment of the path | |----------------------------------|--------------------------| | ```XR_ACTION_TYPE_BOOLEAN_INPUT``` | */click*, */touch* | | ```XR_ACTION_TYPE_FLOAT_INPUT``` | */value*, */force* | | ```XR_ACTION_TYPE_VECTOR2F_INPUT``` | */x*, */y* | | ```XR_ACTION_TYPE_POSE_INPUT``` | */pose* | | ```XR_ACTION_TYPE_VIBRATION_OUTPUT``` | */haptic*, */haptic_left*, */haptic_right*, */haptic_left_trigger*, */haptic_right_trigger* | The callback function (a callable object) should have only the following 2 parameters: - path: ```str``` The complete path (user path and subpath) of the action that invokes the callback - value: ```bool```, ```float```, ```tuple(float, float)```, ```tuple(pxr.Gf.Vec3d, pxr.Gf.Quatd)``` The current state of the action according to its type | Action type (```XrActionType```) | python type | |----------------------------------|-------------| | ```XR_ACTION_TYPE_BOOLEAN_INPUT``` | ```bool``` | | ```XR_ACTION_TYPE_FLOAT_INPUT``` | ```float``` | | ```XR_ACTION_TYPE_VECTOR2F_INPUT``` (x, y) | ```tuple(float, float)``` | | ```XR_ACTION_TYPE_POSE_INPUT``` (position (in stage unit), rotation as quaternion) | ```tuple(pxr.Gf.Vec3d, pxr.Gf.Quatd)``` | ```XR_ACTION_TYPE_VIBRATION_OUTPUT``` actions will not invoke their callback function. In this case the callback must be None ```XR_ACTION_TYPE_POSE_INPUT``` also specifies, through the definition of the reference_space parameter, the reference space used to retrieve the pose The collection of available paths corresponds to the following [interaction profiles](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-interaction-profiles): - [Khronos Simple Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_khronos_simple_controller_profile) - [Google Daydream Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_google_daydream_controller_profile) - [HTC Vive Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_htc_vive_controller_profile) - [HTC Vive Pro](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_htc_vive_pro_profile) - [Microsoft Mixed Reality Motion Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_microsoft_mixed_reality_motion_controller_profile) - [Microsoft Xbox Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_microsoft_xbox_controller_profile) - [Oculus Go Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_oculus_go_controller_profile) - [Oculus Touch Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_oculus_touch_controller_profile) - [Valve Index Controller](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_valve_index_controller_profile) Parameters: - path: ```str``` Complete [path](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved) (user path and subpath) referring to the action - callback: callable object (2 parameters) or ```None``` for ```XR_ACTION_TYPE_VIBRATION_OUTPUT``` Callback invoked when the state of the action changes - action_type: {```XR_ACTION_TYPE_BOOLEAN_INPUT```, ```XR_ACTION_TYPE_FLOAT_INPUT```, ```XR_ACTION_TYPE_VECTOR2F_INPUT```, ```XR_ACTION_TYPE_POSE_INPUT```, ```XR_ACTION_TYPE_VIBRATION_OUTPUT```} or ```None```, optional Action [type](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrActionType) from ```XrActionType``` enum (default: ```None```) - reference_space: {```XR_REFERENCE_SPACE_TYPE_VIEW```, ```XR_REFERENCE_SPACE_TYPE_LOCAL```, ```XR_REFERENCE_SPACE_TYPE_STAGE```}, optional Desired [reference space](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#reference-spaces) type from ```XrReferenceSpaceType``` enum used to retrieve the pose (default: ```XR_REFERENCE_SPACE_TYPE_LOCAL```) Returns - ```bool``` ```True``` if there is no error during action creation, otherwise ```False``` <a name="method-apply_haptic_feedback"></a> - Apply a [haptic feedback](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_output_actions_and_haptics) to a device defined by a path (user path and subpath) ```python apply_haptic_feedback(path: str, haptic_feedback: dict) -> bool ``` Parameters: - path: ```str``` Complete [path](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved) (user path and subpath) referring to the action - haptic_feedback: ```dict``` A python dictionary containing the field names and value of a ```XrHapticBaseHeader```-based structure. **Note:** At the moment the only haptics type supported is the unextended OpenXR [XrHapticVibration](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrHapticVibration) Returns: - ```bool``` ```True``` if there is no error during the haptic feedback application, otherwise ```False``` <a name="method-stop_haptic_feedback"></a> - Stop a [haptic feedback](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#_output_actions_and_haptics) applied to a device defined by a path (user path and subpath) ```python stop_haptic_feedback(path: str) -> bool ``` Parameters: - path: ```str``` Complete [path](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#semantic-path-reserved) (user path and subpath) referring to the action Returns: - ```bool``` ```True``` if there is no error during the haptic feedback stop, otherwise ```False``` <a name="method-setup_mono_view"></a> - Setup Omniverse viewport and camera for monoscopic rendering ```python setup_mono_view(camera: Union[str, pxr.Sdf.Path, pxr.Usd.Prim] = "/OpenXR/Cameras/camera", camera_properties: dict = {"focalLength": 10}) -> None ``` This method obtains the viewport window for the given camera. If the viewport window does not exist, a new one is created and the camera is set as active. If the given camera does not exist, a new camera is created with the same path and set to the recommended resolution of the display device Parameters: - camera: ```str```, ```pxr.Sdf.Path``` or ```pxr.Usd.Prim```, optional Omniverse camera prim or path (default: */OpenXR/Cameras/camera*) - camera_properties: ```dict``` Dictionary containing the [camera properties](https://docs.omniverse.nvidia.com/app_create/prod_materials-and-rendering/cameras.html#camera-properties) supported by the Omniverse kit to be set (default: ```{"focalLength": 10}```) <a name="method-setup_stereo_view"></a> - Setup Omniverse viewports and cameras for stereoscopic rendering ```python setup_stereo_view(left_camera: Union[str, pxr.Sdf.Path, pxr.Usd.Prim] = "/OpenXR/Cameras/left_camera", right_camera: Union[str, pxr.Sdf.Path, pxr.Usd.Prim, None] = "/OpenXR/Cameras/right_camera", camera_properties: dict = {"focalLength": 10}) -> None ``` This method obtains the viewport window for each camera. If the viewport window does not exist, a new one is created and the camera is set as active. If the given cameras do not exist, new cameras are created with the same path and set to the recommended resolution of the display device Parameters: - left_camera: ```str```, ```pxr.Sdf.Path``` or ```pxr.Usd.Prim```, optional Omniverse left camera prim or path (default: */OpenXR/Cameras/left_camera*) - right_camera: ```str```, ```pxr.Sdf.Path``` or ```pxr.Usd.Prim```, optional Omniverse right camera prim or path (default: */OpenXR/Cameras/right_camera*) - camera_properties: ```dict``` Dictionary containing the [camera properties](https://docs.omniverse.nvidia.com/app_create/prod_materials-and-rendering/cameras.html#camera-properties) supported by the Omniverse kit to be set (default: ```{"focalLength": 10}```) <a name="method-get_recommended_resolutions"></a> - Get the recommended resolution of the display device ```python get_recommended_resolutions() -> tuple ``` Returns: - ```tuple``` Tuple containing the recommended resolutions (width, height) of each device view. If the tuple length is 2, index 0 represents the left eye and index 1 represents the right eye <a name="method-set_reference_system_pose"></a> - Set the pose of the origin of the reference system ```python set_reference_system_pose(position: Union[pxr.Gf.Vec3d, None] = None, rotation: Union[pxr.Gf.Vec3d, None] = None) -> None ``` Parameters: - position: ```pxr.Gf.Vec3d``` or ```None```, optional Cartesian position (in stage unit) (default: ```None```) - rotation: ```pxr.Gf.Vec3d``` or ```None```, optional Rotation (in degress) on each axis (default: ```None```) <a name="method-set_stereo_rectification"></a> - Set the angle (in radians) of the rotation axes for stereoscopic view rectification ```python set_stereo_rectification(x: float = 0, y: float = 0, z: float = 0) -> None ``` Parameters: - x: ```float```, optional Angle (in radians) of the X-axis (default: 0) - y: ```float```, optional Angle (in radians) of the Y-axis (default: 0) - x: ```float```, optional Angle (in radians) of the Z-axis (default: 0) <a name="method-set_meters_per_unit"></a> - Specify the meters per unit to be applied to transformations (default: 1.0) ```python set_meters_per_unit(meters_per_unit: float) -> None ``` Parameters: - meters_per_unit: ```float``` Meters per unit. E.g.: 1 meter is 1.0, 1 centimeter is 0.01 <a name="method-set_frame_transformations"></a> - Specify the transformations to be applied to the rendered images ```python set_frame_transformations(fit: bool = False, flip: Union[int, tuple, None] = None) -> None ``` Parameters: - fit: ```bool```, optionl Adjust each rendered image to the recommended resolution of the display device by cropping and scaling the image from its center (default: ```False```). OpenCV ```resize``` method with ```INTER_LINEAR``` interpolation will be used to scale the image to the recommended resolution - flip: ```int```, ```tuple``` or ```None```, optionl Flip each image around vertical (0), horizontal (1), or both axes (0,1) (default: ```None```) <a name="method-teleport_prim"></a> - Teleport the prim specified by the given transformation (position and rotation) ```python teleport_prim(prim: pxr.Usd.Prim, position: pxr.Gf.Vec3d, rotation: pxr.Gf.Quatd, reference_position: Union[pxr.Gf.Vec3d, None] = None, reference_rotation: Union[pxr.Gf.Vec3d, None] = None) -> None ``` Parameters: - prim: ```pxr.Usd.Prim``` Target prim - position: ```pxr.Gf.Vec3d``` Cartesian position (in stage unit) used to transform the prim - rotation: ```pxr.Gf.Quatd``` Rotation (as quaternion) used to transform the prim - reference_position: ```pxr.Gf.Vec3d``` or ```None```, optional Cartesian position (in stage unit) used as reference system (default: ```None```) - reference_rotation: ```pxr.Gf.Vec3d``` or ```None```, optional Rotation (in degress) on each axis used as reference system (default: ```None```) <a name="method-subscribe_render_event"></a> - Subscribe a callback function to the render event ```python subscribe_render_event(callback=None) -> None ``` The callback function (a callable object) should have only the following 3 parameters: - num_views: ```int``` The number of views to render: mono (1), stereo (2) - views: ```tuple``` of ```XrView``` structure A [XrView](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrView) structure contains the view pose and projection state necessary to render a image. The length of the tuple corresponds to the number of views (if the tuple length is 2, index 0 represents the left eye and index 1 represents the right eye) - configuration_views: ```tuple``` of ```XrViewConfigurationView``` structure A [XrViewConfigurationView](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrViewConfigurationView) structure specifies properties related to rendering of a view (e.g. the optimal width and height to be used when rendering the view). The length of the tuple corresponds to the number of views (if the tuple length is 2, index 0 represents the left eye and index 1 represents the right eye) The callback function must call the ```set_frames``` function to pass to the selected graphics API the image or images to be rendered If the callback is None, an internal callback will be used to render the views. This internal callback updates the pose of the cameras according to the specified reference system, gets the images from the previously configured viewports and invokes the ```set_frames``` function to render the views Parameters: - callback: callable object (3 parameters) or ```None```, optional Callback invoked on each render event (default: ```None```) <a name="method-set_frames"></a> - Pass to the selected graphics API the images to be rendered in the views ```python set_frames(configuration_views: list, left: numpy.ndarray, right: numpy.ndarray = None) -> bool ``` In the case of stereoscopic devices, the parameters left and right represent the left eye and right eye respectively. To pass an image to the graphic API of monoscopic devices only the parameter left should be used (the parameter right must be ```None```) This function will apply to each image the transformations defined by the ```set_frame_transformations``` function if they were specified Parameters: - configuration_views: ```tuple``` of ```XrViewConfigurationView``` structure A [XrViewConfigurationView](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrViewConfigurationView) structure specifies properties related to rendering of a view (e.g. the optimal width and height to be used when rendering the view) - left: ```numpy.ndarray``` RGB or RGBA image (```numpy.uint8```) - right: ```numpy.ndarray``` or ```None``` RGB or RGBA image (```numpy.uint8```) Returns: - ```bool``` ```True``` if there is no error during the passing to the selected graphics API, otherwise ```False``` <a name="api-enumerations"></a> #### Available enumerations - Form factors supported by OpenXR runtimes ([```XrFormFactor```](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrFormFactor)) - ```XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY``` = 1 - ```XR_FORM_FACTOR_HANDHELD_DISPLAY``` = 2 - Environment blend mode ([```XrEnvironmentBlendMode```](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrEnvironmentBlendMode)) - ```XR_ENVIRONMENT_BLEND_MODE_OPAQUE``` = 1 - ```XR_ENVIRONMENT_BLEND_MODE_ADDITIVE``` = 2 - ```XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND``` = 3 - Primary view configuration type ([```XrViewConfigurationType```](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrViewConfigurationType)) - ```XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO``` = 1 - ```XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO``` = 2 - Reference spaces ([```XrReferenceSpaceType```](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrReferenceSpaceType)) - ```XR_REFERENCE_SPACE_TYPE_VIEW``` = 1 - ```XR_REFERENCE_SPACE_TYPE_LOCAL``` = 2 - ```XR_REFERENCE_SPACE_TYPE_STAGE``` = 3 - Action type ([```XrActionType```](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrActionType)) - ```XR_ACTION_TYPE_BOOLEAN_INPUT``` = 1 - ```XR_ACTION_TYPE_FLOAT_INPUT``` = 2 - ```XR_ACTION_TYPE_VECTOR2F_INPUT``` = 3 - ```XR_ACTION_TYPE_POSE_INPUT``` = 4 - ```XR_ACTION_TYPE_VIBRATION_OUTPUT``` = 100 <a name="api-constants"></a> #### Available constants - Graphics API extension names - ```XR_KHR_OPENGL_ENABLE_EXTENSION_NAME``` = "XR_KHR_opengl_enable" - ```XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME``` = "XR_KHR_opengl_es_enable" - ```XR_KHR_VULKAN_ENABLE_EXTENSION_NAME``` = "XR_KHR_vulkan_enable" - ```XR_KHR_D3D11_ENABLE_EXTENSION_NAME``` = "XR_KHR_D3D11_enable" - ```XR_KHR_D3D12_ENABLE_EXTENSION_NAME``` = "XR_KHR_D3D12_enable" - Useful constants for applying haptic feedback - ```XR_NO_DURATION``` = 0 - ```XR_INFINITE_DURATION``` = 0x7fffffffffffffff - ```XR_MIN_HAPTIC_DURATION``` = -1 - ```XR_FREQUENCY_UNSPECIFIED``` = 0
31,433
Markdown
42.658333
582
0.69777
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/BUILD.md
## Building from source ### Linux ```bash cd src/semu.xr.openxr bash compile_extension.bash ``` ## Removing old compiled files Get a fresh clone of the repository and follow the next steps ```bash # remove compiled files _openxr.cpython-37m-x86_64-linux-gnu.so git filter-repo --invert-paths --path exts/semu.xr.openxr/semu/xr/openxr/_openxr.cpython-37m-x86_64-linux-gnu.so # add origin git remote add origin [email protected]:Toni-SM/semu.xr.openxr.git # push changes git push origin --force --all git push origin --force --tags ``` ## Packaging the extension ```bash cd src/semu.xr.openxr bash package_extension.bash ```
628
Markdown
19.290322
112
0.737261
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/compile_extension.py
import os import sys from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext # OV python (kit\python\include) if sys.platform == 'win32': python_library_dir = os.path.join(os.path.dirname(sys.executable), "include") elif sys.platform == 'linux': python_library_dir = os.path.join(os.path.dirname(sys.executable), "..", "include") if not os.path.exists(python_library_dir): raise Exception("OV Python library directory not found: {}".format(python_library_dir)) ext_modules = [ Extension("_openxr", [os.path.join("semu", "xr", "openxr", "openxr.py")], library_dirs=[python_library_dir]), ] for ext in ext_modules: ext.cython_directives = {'language_level': "3"} setup( name = 'semu.xr.openxr', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
882
Python
27.48387
91
0.673469
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/pybind11_wrapper.cpp
#include <pybind11/pybind11.h> #include <pybind11/functional.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include "xr.cpp" namespace py = pybind11; namespace pybind11 { namespace detail { template <> struct type_caster<XrView>{ public: PYBIND11_TYPE_CASTER(XrView, _("XrView")); // conversion from C++ to Python static handle cast(XrView src, return_value_policy /* policy */, handle /* parent */){ PyObject * fov = PyDict_New(); PyDict_SetItemString(fov, "angleLeft", PyFloat_FromDouble(src.fov.angleLeft)); PyDict_SetItemString(fov, "angleRight", PyFloat_FromDouble(src.fov.angleRight)); PyDict_SetItemString(fov, "angleUp", PyFloat_FromDouble(src.fov.angleUp)); PyDict_SetItemString(fov, "angleDown", PyFloat_FromDouble(src.fov.angleDown)); PyObject * position = PyDict_New(); PyDict_SetItemString(position, "x", PyFloat_FromDouble(src.pose.position.x)); PyDict_SetItemString(position, "y", PyFloat_FromDouble(src.pose.position.y)); PyDict_SetItemString(position, "z", PyFloat_FromDouble(src.pose.position.z)); PyObject * orientation = PyDict_New(); PyDict_SetItemString(orientation, "x", PyFloat_FromDouble(src.pose.orientation.x)); PyDict_SetItemString(orientation, "y", PyFloat_FromDouble(src.pose.orientation.y)); PyDict_SetItemString(orientation, "z", PyFloat_FromDouble(src.pose.orientation.z)); PyDict_SetItemString(orientation, "w", PyFloat_FromDouble(src.pose.orientation.w)); PyObject * pose = PyDict_New(); PyDict_SetItemString(pose, "position", position); PyDict_SetItemString(pose, "orientation", orientation); PyObject * view = PyDict_New(); PyDict_SetItemString(view, "type", PyLong_FromLong(src.type)); PyDict_SetItemString(view, "next", Py_None); PyDict_SetItemString(view, "pose", pose); PyDict_SetItemString(view, "fov", fov); return view; } }; template <> struct type_caster<XrViewConfigurationView>{ public: PYBIND11_TYPE_CASTER(XrViewConfigurationView, _("XrViewConfigurationView")); // conversion from C++ to Python static handle cast(XrViewConfigurationView src, return_value_policy /* policy */, handle /* parent */){ PyObject * configurationView = PyDict_New(); PyDict_SetItemString(configurationView, "type", PyLong_FromLong(src.type)); PyDict_SetItemString(configurationView, "next", Py_None); PyDict_SetItemString(configurationView, "recommendedImageRectWidth", PyLong_FromLong(src.recommendedImageRectWidth)); PyDict_SetItemString(configurationView, "maxImageRectWidth", PyLong_FromLong(src.maxImageRectWidth)); PyDict_SetItemString(configurationView, "recommendedImageRectHeight", PyLong_FromLong(src.recommendedImageRectHeight)); PyDict_SetItemString(configurationView, "maxImageRectHeight", PyLong_FromLong(src.maxImageRectHeight)); PyDict_SetItemString(configurationView, "recommendedSwapchainSampleCount", PyLong_FromLong(src.recommendedSwapchainSampleCount)); PyDict_SetItemString(configurationView, "maxSwapchainSampleCount", PyLong_FromLong(src.maxSwapchainSampleCount)); return configurationView; } }; template <> struct type_caster<ActionState>{ public: PYBIND11_TYPE_CASTER(ActionState, _("ActionState")); // conversion from C++ to Python static handle cast(ActionState src, return_value_policy /* policy */, handle /* parent */){ PyObject * state = PyDict_New(); PyDict_SetItemString(state, "type", PyLong_FromLong(src.type)); PyDict_SetItemString(state, "path", PyUnicode_FromString(src.path)); PyDict_SetItemString(state, "isActive", PyBool_FromLong(src.isActive)); PyDict_SetItemString(state, "stateBool", PyBool_FromLong(src.stateBool)); PyDict_SetItemString(state, "stateFloat", PyFloat_FromDouble(src.stateFloat)); PyDict_SetItemString(state, "stateVectorX", PyFloat_FromDouble(src.stateVectorX)); PyDict_SetItemString(state, "stateVectorY", PyFloat_FromDouble(src.stateVectorY)); return state; } }; template <> struct type_caster<ActionPoseState>{ public: PYBIND11_TYPE_CASTER(ActionPoseState, _("ActionPoseState")); // conversion from C++ to Python static handle cast(ActionPoseState src, return_value_policy /* policy */, handle /* parent */){ PyObject * state = PyDict_New(); PyDict_SetItemString(state, "type", PyLong_FromLong(src.type)); PyDict_SetItemString(state, "path", PyUnicode_FromString(src.path)); PyDict_SetItemString(state, "isActive", PyBool_FromLong(src.isActive)); PyObject * position = PyDict_New(); PyDict_SetItemString(position, "x", PyFloat_FromDouble(src.pose.position.x)); PyDict_SetItemString(position, "y", PyFloat_FromDouble(src.pose.position.y)); PyDict_SetItemString(position, "z", PyFloat_FromDouble(src.pose.position.z)); PyObject * orientation = PyDict_New(); PyDict_SetItemString(orientation, "x", PyFloat_FromDouble(src.pose.orientation.x)); PyDict_SetItemString(orientation, "y", PyFloat_FromDouble(src.pose.orientation.y)); PyDict_SetItemString(orientation, "z", PyFloat_FromDouble(src.pose.orientation.z)); PyDict_SetItemString(orientation, "w", PyFloat_FromDouble(src.pose.orientation.w)); PyObject * pose = PyDict_New(); PyDict_SetItemString(pose, "position", position); PyDict_SetItemString(pose, "orientation", orientation); PyDict_SetItemString(state, "pose", pose); return state; } }; }} PYBIND11_MODULE(xrlib_p, m){ py::class_<OpenXrApplication>(m, "OpenXrApplication") .def(py::init<>()) // utils .def("destroy", &OpenXrApplication::destroy) .def("isSessionRunning", &OpenXrApplication::isSessionRunning) .def("getViewConfigurationViews", &OpenXrApplication::getViewConfigurationViews) .def("getViewConfigurationViewsSize", &OpenXrApplication::getViewConfigurationViewsSize) // setup app .def("createInstance", &OpenXrApplication::createInstance) .def("getSystem", [](OpenXrApplication &m, int formFactor, int blendMode, int configurationType){ return m.getSystem(XrFormFactor(formFactor), XrEnvironmentBlendMode(blendMode), XrViewConfigurationType(configurationType)); }) .def("createSession", &OpenXrApplication::createSession) // actions .def("addAction", [](OpenXrApplication &m, string stringPath, int actionType, int referenceSpaceType){ return m.addAction(stringPath, XrActionType(actionType), XrReferenceSpaceType(referenceSpaceType)); }) .def("applyHapticFeedback", [](OpenXrApplication &m, string stringPath, float amplitude, int64_t duration, float frequency){ XrHapticVibration vibration = {XR_TYPE_HAPTIC_VIBRATION}; vibration.amplitude = amplitude; vibration.duration = XrDuration(duration); vibration.frequency = frequency; return m.applyHapticFeedback(stringPath, (XrHapticBaseHeader*)&vibration); }) .def("stopHapticFeedback", &OpenXrApplication::stopHapticFeedback) // poll data .def("pollEvents", [](OpenXrApplication &m){ bool exitLoop = true; bool returnValue = m.pollEvents(&exitLoop); return std::make_tuple(returnValue, exitLoop); }) .def("pollActions", [](OpenXrApplication &m){ vector<ActionState> actionStates; bool returnValue = m.pollActions(actionStates); return std::make_tuple(returnValue, actionStates); }) // render .def("renderViews", [](OpenXrApplication &m, int referenceSpaceType){ vector<ActionPoseState> actionPoseState; bool returnValue = m.renderViews(XrReferenceSpaceType(referenceSpaceType), actionPoseState); return std::make_tuple(returnValue, actionPoseState); }) // render utilities .def("setRenderCallback", &OpenXrApplication::setRenderCallbackFromFunction) .def("setFrames", [](OpenXrApplication &m, py::array_t<uint8_t> left, py::array_t<uint8_t> right, bool rgba){ py::buffer_info leftInfo = left.request(); if(m.getViewConfigurationViewsSize() == 1) return m.setFrameByIndex(0, leftInfo.shape[1], leftInfo.shape[0], leftInfo.ptr, rgba); else if(m.getViewConfigurationViewsSize() == 2){ py::buffer_info rightInfo = right.request(); bool status = m.setFrameByIndex(0, leftInfo.shape[1], leftInfo.shape[0], leftInfo.ptr, rgba); return status && m.setFrameByIndex(1, rightInfo.shape[1], rightInfo.shape[0], rightInfo.ptr, rgba); } return false; }); }
9,822
C++
52.385869
145
0.620342
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/xr.cpp
#define XR_USE_PLATFORM_XLIB // #define XR_USE_GRAPHICS_API_VULKAN #define XR_USE_GRAPHICS_API_OPENGL // Vulkan libraries #ifdef XR_USE_GRAPHICS_API_VULKAN #define APP_USE_VULKAN2 #define STB_IMAGE_IMPLEMENTATION #include <vulkan/vulkan.h> #include "stb_image.h" #endif // OpenGL libraries #ifdef XR_USE_GRAPHICS_API_OPENGL #define GL_GLEXT_PROTOTYPES #define GL3_PROTOTYPES #include <GL/gl.h> #include <GL/glext.h> #include <GL/glx.h> #include <X11/Xlib.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #ifdef APPLICATION_IMAGE #include <SDL2/SDL_image.h> #endif #endif #include <vector> #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <functional> using namespace std; #include <openxr/openxr.h> #include <openxr/openxr_platform.h> #include <openxr/openxr_reflection.h> #ifndef _countof #define _countof(x) (sizeof(x)/sizeof((x)[0])) #endif // generate stringify functions for OpenXR enumerations #define ENUM_CASE_STR(name, val) case name: return #name; #define MAKE_TO_STRING_FUNC(enumType) \ inline const char* _enum_to_string(enumType e) { \ switch (e) { \ XR_LIST_ENUM_##enumType(ENUM_CASE_STR) \ default: return "Unknown " #enumType; \ } \ } MAKE_TO_STRING_FUNC(XrReferenceSpaceType); MAKE_TO_STRING_FUNC(XrViewConfigurationType); MAKE_TO_STRING_FUNC(XrEnvironmentBlendMode); MAKE_TO_STRING_FUNC(XrSessionState); MAKE_TO_STRING_FUNC(XrResult); MAKE_TO_STRING_FUNC(XrFormFactor); struct ActionState{ XrActionType type; const char * path; bool isActive; bool stateBool; // XR_TYPE_ACTION_STATE_BOOLEAN float stateFloat; // XR_TYPE_ACTION_STATE_FLOAT float stateVectorX; // XR_TYPE_ACTION_STATE_VECTOR2F float stateVectorY; // XR_TYPE_ACTION_STATE_VECTOR2F }; struct ActionPoseState{ XrActionType type; const char * path; bool isActive; XrPosef pose; // XR_TYPE_ACTION_STATE_POSE }; struct Action{ XrAction action; XrPath path; string stringPath; }; struct ActionPose{ XrReferenceSpaceType referenceSpaceType; XrSpace space; XrAction action; XrPath path; string stringPath; }; struct Actions{ vector<Action> aBoolean; vector<Action> aFloat; vector<Action> aVector2f; vector<ActionPose> aPose; vector<Action> aVibration; }; struct SwapchainHandler{ XrSwapchain handle; int32_t width; int32_t height; uint32_t length; #ifdef XR_USE_GRAPHICS_API_VULKAN vector<XrSwapchainImageVulkan2KHR> images; #endif #ifdef XR_USE_GRAPHICS_API_OPENGL vector<XrSwapchainImageOpenGLKHR> images; #endif }; vector<const char*> cast_to_vector_char_p(const vector<string> & input_list){ vector<const char*> output_list; for (size_t i = 0; i < input_list.size(); i++) output_list.push_back(input_list[i].data()); return output_list; } bool xrCheckResult(const XrInstance & xr_instance, const XrResult & xr_result, const string & message = ""){ if(XR_SUCCEEDED(xr_result)) return true; if(xr_instance != NULL){ char xr_result_as_string[XR_MAX_RESULT_STRING_SIZE]; xrResultToString(xr_instance, xr_result, xr_result_as_string); if(!message.empty()) std::cout << "[ERROR] " << message << " failed with code: " << xr_result << " (" << xr_result_as_string << "). " << message << std::endl; else std::cout << "[ERROR] code: " << xr_result << " (" << xr_result_as_string << ")" << std::endl; } else{ if(!message.empty()) std::cout << "[ERROR] " << message << " failed with code: " << xr_result << " (" << _enum_to_string(xr_result) << ")" << std::endl; else std::cout << "[ERROR] code: " << xr_result << " (" << _enum_to_string(xr_result) << ")" << std::endl; } return false; } // Vulkan graphics API #ifdef XR_USE_GRAPHICS_API_VULKAN class VulkanHandler{ private: XrResult xr_result; VkResult vk_result; VkInstance vk_instance; VkPhysicalDevice vk_physicalDevice = VK_NULL_HANDLE; VkDevice vk_logicalDevice; uint32_t vk_queueFamilyIndex; VkQueue vk_graphicsQueue; VkCommandPool vk_cmdPool; VkPipelineCache vk_pipelineCache; bool getRequirements(XrInstance xr_instance, XrSystemId xr_system_id); bool defineLayers(vector<const char*> requestedLayers, vector<const char*> & enabledLayers); bool defineExtensions(vector<const char*> requestedExtensions, vector<const char*> & enabledExtensions); public: VulkanHandler(); ~VulkanHandler(); void createInstance(XrInstance xr_instance, XrSystemId xr_system_id); void getPhysicalDevice(XrInstance xr_instance, XrSystemId xr_system_id); void createLogicalDevice(XrInstance xr_instance, XrSystemId xr_system_id); VkInstance getInstance(){ return vk_instance; } VkPhysicalDevice getPhysicalDevice(){ return vk_physicalDevice; } VkDevice getLogicalDevice(){ return vk_logicalDevice; } uint32_t getQueueFamilyIndex(){ return vk_queueFamilyIndex; } void renderView(const XrCompositionLayerProjectionView &, const XrSwapchainImageBaseHeader *, int64_t); uint32_t getSupportedSwapchainSampleCount(XrViewConfigurationView){ return VK_SAMPLE_COUNT_1_BIT; } void loadImageFromFile(); }; VulkanHandler::VulkanHandler(){ loadImageFromFile(); } VulkanHandler::~VulkanHandler(){ // vkDestroyInstance(vk_instance, nullptr); // vkDestroyDevice(vk_logicalDevice, nullptr); } void VulkanHandler::loadImageFromFile(){ int texWidth, texHeight, texChannels; stbi_uc* pixels = stbi_load("texture.jpg", &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); VkDeviceSize imageSize = texWidth * texHeight * 4; if (!pixels) { throw std::runtime_error("failed to load texture image!"); } } bool VulkanHandler::getRequirements(XrInstance xr_instance, XrSystemId xr_system_id){ #ifdef APP_USE_VULKAN2 PFN_xrGetVulkanGraphicsRequirements2KHR pfn_xrGetVulkanGraphicsRequirements2KHR = nullptr; xrGetInstanceProcAddr(xr_instance, "xrGetVulkanGraphicsRequirements2KHR", reinterpret_cast<PFN_xrVoidFunction*>(&pfn_xrGetVulkanGraphicsRequirements2KHR)); XrGraphicsRequirementsVulkan2KHR graphicsRequirement = {XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN2_KHR}; xr_result = pfn_xrGetVulkanGraphicsRequirements2KHR(xr_instance, xr_system_id, &graphicsRequirement); if(!xrCheckResult(NULL, xr_result, "PFN_xrGetVulkanGraphicsRequirementsKHR")) return false; std::cout << "Vulkan (Vulkan2) requirements" << std::endl; #else PFN_xrGetVulkanGraphicsRequirementsKHR pfn_xrGetVulkanGraphicsRequirementsKHR = nullptr; xrGetInstanceProcAddr(xr_instance, "xrGetVulkanGraphicsRequirementsKHR", reinterpret_cast<PFN_xrVoidFunction*>(&pfn_xrGetVulkanGraphicsRequirementsKHR)); XrGraphicsRequirementsVulkanKHR graphicsRequirement = {XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR}; xr_result = pfn_xrGetVulkanGraphicsRequirementsKHR(xr_instance, xr_system_id, &graphicsRequirement); if(!xrCheckResult(NULL, xr_result, "PFN_xrGetVulkanGraphicsRequirementsKHR")) return false; std::cout << "Vulkan (Vulkan) requirements" << std::endl; #endif std::cout << " |-- min API version: " << XR_VERSION_MAJOR(graphicsRequirement.minApiVersionSupported) << "." << XR_VERSION_MINOR(graphicsRequirement.minApiVersionSupported) << "." << XR_VERSION_PATCH(graphicsRequirement.minApiVersionSupported) << std::endl; std::cout << " |-- max API version: " << XR_VERSION_MAJOR(graphicsRequirement.maxApiVersionSupported) << "." << XR_VERSION_MINOR(graphicsRequirement.maxApiVersionSupported) << "." << XR_VERSION_PATCH(graphicsRequirement.maxApiVersionSupported) << std::endl; return true; } bool VulkanHandler::defineLayers(vector<const char*> requestedLayers, vector<const char*> & enabledLayers){ uint32_t propertyCount = 0; vkEnumerateInstanceLayerProperties(&propertyCount, nullptr); std::vector<VkLayerProperties> layerProperties(propertyCount); vkEnumerateInstanceLayerProperties(&propertyCount, layerProperties.data()); std::cout << "Vulkan layers available (" << layerProperties.size() << ")" << std::endl; for (size_t i = 0; i < layerProperties.size(); i++){ std::cout << " |-- " << layerProperties[i].layerName << std::endl; for (size_t j = 0; j < requestedLayers.size(); j++) if (strcmp(layerProperties[i].layerName, requestedLayers[j]) == 0){ enabledLayers.push_back(requestedLayers[j]); std::cout << " | (requested)" << std::endl; break; } } return true; } bool VulkanHandler::defineExtensions(vector<const char*> requestedExtensions, vector<const char*> & enabledExtensions){ uint32_t propertyCount = 0; vkEnumerateInstanceExtensionProperties(nullptr, &propertyCount, nullptr); vector<VkExtensionProperties> extensionsProperties(propertyCount); vkEnumerateInstanceExtensionProperties(nullptr, &propertyCount, extensionsProperties.data()); std::cout << "Vulkan extension properties (" << extensionsProperties.size() << ")" << std::endl; for (size_t i = 0; i < extensionsProperties.size(); i++){ std::cout << " |-- " << extensionsProperties[i].extensionName << std::endl; for (size_t j = 0; j < requestedExtensions.size(); j++) if (strcmp(extensionsProperties[i].extensionName, requestedExtensions[j]) == 0){ enabledExtensions.push_back(requestedExtensions[j]); std::cout << " | (requested)" << std::endl; break; } } return true; } void VulkanHandler::createInstance(XrInstance xr_instance, XrSystemId xr_system_id){ // requirements getRequirements(xr_instance, xr_system_id); // layers vector<const char*> enabledLayers; vector<const char*> requestedLayers = { "VK_LAYER_LUNARG_core_validation" }; // TODO: see why it crashes the application // defineLayers(requestedLayers, enabledLayers); // extensions vector<const char*> enabledExtensions; vector<const char*> requestedExtensions = { "VK_EXT_debug_report" }; defineExtensions(requestedExtensions, enabledExtensions); VkApplicationInfo appInfo = {VK_STRUCTURE_TYPE_APPLICATION_INFO}; appInfo.pApplicationName = "Isaac Sim (VR)"; appInfo.applicationVersion = 1; appInfo.pEngineName = "Isaac Sim (VR)"; appInfo.engineVersion = 1; appInfo.apiVersion = VK_API_VERSION_1_0; VkInstanceCreateInfo instanceInfo = {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; instanceInfo.pApplicationInfo = &appInfo; instanceInfo.enabledLayerCount = (uint32_t)enabledLayers.size(); instanceInfo.ppEnabledLayerNames = enabledLayers.empty() ? nullptr : enabledLayers.data(); instanceInfo.enabledExtensionCount = (uint32_t)enabledExtensions.size(); instanceInfo.ppEnabledExtensionNames = enabledExtensions.empty() ? nullptr : enabledExtensions.data(); XrVulkanInstanceCreateInfoKHR createInfo = {XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR}; createInfo.systemId = xr_system_id; createInfo.pfnGetInstanceProcAddr = vkGetInstanceProcAddr; createInfo.vulkanCreateInfo = &instanceInfo; createInfo.vulkanAllocator = nullptr; PFN_xrCreateVulkanInstanceKHR pfn_xrCreateVulkanInstanceKHR = nullptr; xr_result = xrGetInstanceProcAddr(xr_instance, "xrCreateVulkanInstanceKHR", reinterpret_cast<PFN_xrVoidFunction*>(&pfn_xrCreateVulkanInstanceKHR)); xr_result = pfn_xrCreateVulkanInstanceKHR(xr_instance, &createInfo, &vk_instance, &vk_result); } void VulkanHandler::getPhysicalDevice(XrInstance xr_instance, XrSystemId xr_system_id){ // enumerate device uint32_t propertyCount = 0; vkEnumeratePhysicalDevices(vk_instance, &propertyCount, nullptr); if(!propertyCount) throw std::runtime_error("Failed to find GPUs with Vulkan support"); vector<VkPhysicalDevice> devices(propertyCount); vkEnumeratePhysicalDevices(vk_instance, &propertyCount, devices.data()); // get physical device XrVulkanGraphicsDeviceGetInfoKHR deviceGetInfo = {XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR}; deviceGetInfo.systemId = xr_system_id; deviceGetInfo.vulkanInstance = vk_instance; deviceGetInfo.next = nullptr; PFN_xrGetVulkanGraphicsDevice2KHR pfn_xrGetVulkanGraphicsDevice2KHR = nullptr; xr_result = xrGetInstanceProcAddr(xr_instance, "xrGetVulkanGraphicsDevice2KHR", reinterpret_cast<PFN_xrVoidFunction*>(&pfn_xrGetVulkanGraphicsDevice2KHR)); xr_result = pfn_xrGetVulkanGraphicsDevice2KHR(xr_instance, &deviceGetInfo, &vk_physicalDevice); std::cout << "Vulkan physical devices (" << devices.size() << ")" << std::endl; for(const auto& device : devices){ if(device == vk_physicalDevice){ std::cout << " |-- handle: " << device << std::endl; std::cout << " | (selected)"<< std::endl; } else std::cout << " |-- handle: " << device << std::endl; } } void VulkanHandler::createLogicalDevice(XrInstance xr_instance, XrSystemId xr_system_id){ uint32_t propertyCount = 0; float queuePriorities = 0; VkDeviceQueueCreateInfo queueInfo = {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; queueInfo.queueCount = 1; queueInfo.pQueuePriorities = &queuePriorities; // queue families index vkGetPhysicalDeviceQueueFamilyProperties(vk_physicalDevice, &propertyCount, nullptr); vector<VkQueueFamilyProperties> queueFamilyProps(propertyCount); vkGetPhysicalDeviceQueueFamilyProperties(vk_physicalDevice, &propertyCount, &queueFamilyProps[0]); for (uint32_t i = 0; i < propertyCount; ++i) if ((queueFamilyProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0u){ queueInfo.queueFamilyIndex = i; vk_queueFamilyIndex = queueInfo.queueFamilyIndex; break; } vector<const char*> deviceExtensions; deviceExtensions.push_back("VK_KHR_external_memory"); deviceExtensions.push_back("VK_KHR_external_memory_fd"); deviceExtensions.push_back("VK_KHR_external_semaphore"); deviceExtensions.push_back("VK_KHR_external_semaphore_fd"); deviceExtensions.push_back("VK_KHR_get_memory_requirements2"); VkPhysicalDeviceFeatures features = {}; features.samplerAnisotropy = true; VkDeviceCreateInfo deviceInfo = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; deviceInfo.queueCreateInfoCount = 1; deviceInfo.pQueueCreateInfos = &queueInfo; deviceInfo.enabledLayerCount = 0; deviceInfo.ppEnabledLayerNames = nullptr; deviceInfo.enabledExtensionCount = (uint32_t)deviceExtensions.size(); deviceInfo.ppEnabledExtensionNames = deviceExtensions.empty() ? nullptr : deviceExtensions.data(); deviceInfo.pEnabledFeatures = &features; XrVulkanDeviceCreateInfoKHR createInfo = {XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR}; createInfo.systemId = xr_system_id; createInfo.pfnGetInstanceProcAddr = vkGetInstanceProcAddr; createInfo.vulkanCreateInfo = &deviceInfo; createInfo.vulkanPhysicalDevice = vk_physicalDevice; createInfo.vulkanAllocator = nullptr; createInfo.createFlags = 0; createInfo.next = nullptr; PFN_xrCreateVulkanDeviceKHR pfn_xrCreateVulkanDeviceKHR = nullptr; xr_result = xrGetInstanceProcAddr(xr_instance, "xrCreateVulkanDeviceKHR", reinterpret_cast<PFN_xrVoidFunction*>(&pfn_xrCreateVulkanDeviceKHR)); xr_result = pfn_xrCreateVulkanDeviceKHR(xr_instance, &createInfo, &vk_logicalDevice, &vk_result); // get queue vkGetDeviceQueue(vk_logicalDevice, vk_queueFamilyIndex, 0, &vk_graphicsQueue); // m_memAllocator.Init(m_vkPhysicalDevice, m_vkDevice); VkPipelineCacheCreateInfo info = {VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; vkCreatePipelineCache(vk_logicalDevice, &info, nullptr, &vk_pipelineCache); VkCommandPoolCreateInfo cmdPoolInfo = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cmdPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; cmdPoolInfo.queueFamilyIndex = vk_queueFamilyIndex; vk_result = vkCreateCommandPool(vk_logicalDevice, &cmdPoolInfo, nullptr, &vk_cmdPool); } void VulkanHandler::renderView(const XrCompositionLayerProjectionView & layerView, const XrSwapchainImageBaseHeader * swapchainImage, int64_t swapchainFormat){ std::cout << "layerView.subImage.imageArrayIndex: " << layerView.subImage.imageArrayIndex << std::endl; } #endif // OpenGL graphics API #ifdef XR_USE_GRAPHICS_API_OPENGL void GLAPIENTRY MessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam){ std::cout << "GL CALLBACK: " << (type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "") << " type = 0x" << type << ", severity = 0x" << severity << ", message = " << message << std::endl; } static const char* glslShaderVertex = R"_( #version 410 out vec2 v_tex; const vec2 pos[4]=vec2[4](vec2(-1.0, 1.0), vec2(-1.0,-1.0), vec2( 1.0, 1.0), vec2( 1.0,-1.0)); void main(){ v_tex=0.5*pos[gl_VertexID] + vec2(0.5); gl_Position=vec4(pos[gl_VertexID], 0.0, 1.0); } )_"; static const char* glslShaderFragment = R"_( #version 410 in vec2 v_tex; uniform sampler2D texSampler; out vec4 color; void main(){ color=texture(texSampler, v_tex); } )_"; class OpenGLHandler{ private: XrResult xr_result; SDL_Window * sdl_window; SDL_GLContext gl_context; PFNGLBLITNAMEDFRAMEBUFFERPROC _glBlitNamedFramebuffer; GLuint vao; GLuint program; GLuint texture; GLuint swapchainFramebuffer; bool checkShader(GLuint); bool checkProgram(GLuint); void loadTexture(string, GLuint *); public: OpenGLHandler(); ~OpenGLHandler(); bool getRequirements(XrInstance xr_instance, XrSystemId xr_system_id); bool initGraphicsBinding(Display** xDisplay, uint32_t* visualid, GLXFBConfig* glxFBConfig, GLXDrawable* glxDrawable, GLXContext* glxContext, int witdh, int height); bool initResources(XrInstance xr_instance, XrSystemId xr_system_id); void acquireContext(XrGraphicsBindingOpenGLXlibKHR, string); void renderView(const XrCompositionLayerProjectionView &, const XrSwapchainImageBaseHeader *, int64_t); void renderViewFromImage(const XrCompositionLayerProjectionView &, const XrSwapchainImageBaseHeader *, int64_t, int, int, void *, bool); uint32_t getSupportedSwapchainSampleCount(XrViewConfigurationView){ return 1; } }; OpenGLHandler::OpenGLHandler() { } OpenGLHandler::~OpenGLHandler() { } void OpenGLHandler::loadTexture(string path, GLuint * textureId){ #ifdef APPLICATION_IMAGE int mode = GL_RGB; SDL_Surface *tex = IMG_Load(path.c_str()); if(tex->format->BitsPerPixel >= 4) mode = GL_RGBA; else mode = GL_RGB; glGenTextures(1, textureId); glBindTexture(GL_TEXTURE_2D, *textureId); glTexImage2D(GL_TEXTURE_2D, 0, mode, tex->w, tex->h, 0, mode, GL_UNSIGNED_BYTE, tex->pixels); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); #endif } bool OpenGLHandler::checkShader(GLuint shader){ GLint r = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &r); if(r == GL_FALSE){ GLchar msg[4096] = {}; GLsizei length; glGetShaderInfoLog(shader, sizeof(msg), &length, msg); std::cout << "GL SHADER: " << msg << std::endl; return false; } return true; } bool OpenGLHandler::checkProgram(GLuint prog) { GLint r = 0; glGetProgramiv(prog, GL_LINK_STATUS, &r); if(r == GL_FALSE){ GLchar msg[4096] = {}; GLsizei length; glGetProgramInfoLog(prog, sizeof(msg), &length, msg); std::cout << "GL SHADER: " << msg << std::endl; return false; } return true; } void OpenGLHandler::acquireContext(XrGraphicsBindingOpenGLXlibKHR graphicsBinding, string message){ GLXContext context = glXGetCurrentContext(); if(context != graphicsBinding.glxContext){ // std::cout << "glxContext changed (" << context << " != " << graphicsBinding.glxContext << ") in "<< message << std::endl; glXMakeCurrent(graphicsBinding.xDisplay, graphicsBinding.glxDrawable, graphicsBinding.glxContext); } } bool OpenGLHandler::initGraphicsBinding(Display** xDisplay, uint32_t* visualid, GLXFBConfig* glxFBConfig, GLXDrawable* glxDrawable, GLXContext* glxContext, int witdh, int height){ if(SDL_Init(SDL_INIT_VIDEO) < 0){ std::cout << "Unable to initialize SDL" << std::endl; return false; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 0); // create our window centered at half the VR resolution sdl_window = SDL_CreateWindow("Omniverse (VR)", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, witdh / 2, height / 2, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); if (!sdl_window){ std::cout << "Unable to create SDL window" << std::endl; return false; } gl_context = SDL_GL_CreateContext(sdl_window); glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(MessageCallback, 0); SDL_GL_SetSwapInterval(0); _glBlitNamedFramebuffer = (PFNGLBLITNAMEDFRAMEBUFFERPROC)glXGetProcAddressARB((GLubyte*)"glBlitNamedFramebuffer"); *xDisplay = XOpenDisplay(NULL); *glxContext = glXGetCurrentContext(); *glxDrawable = glXGetCurrentDrawable(); SDL_HideWindow(sdl_window); return true; } bool OpenGLHandler::getRequirements(XrInstance xr_instance, XrSystemId xr_system_id){ PFN_xrGetOpenGLGraphicsRequirementsKHR pfn_xrGetOpenGLGraphicsRequirementsKHR = nullptr; xr_result = xrGetInstanceProcAddr(xr_instance, "xrGetOpenGLGraphicsRequirementsKHR", reinterpret_cast<PFN_xrVoidFunction*>(&pfn_xrGetOpenGLGraphicsRequirementsKHR)); if(!xrCheckResult(NULL, xr_result, "xrGetOpenGLGraphicsRequirementsKHR (xrGetInstanceProcAddr)")) return false; XrGraphicsRequirementsOpenGLKHR graphicsRequirement = {XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR}; xr_result = pfn_xrGetOpenGLGraphicsRequirementsKHR(xr_instance, xr_system_id, &graphicsRequirement); if(!xrCheckResult(NULL, xr_result, "xrGetOpenGLGraphicsRequirementsKHR")) return false; std::cout << "OpenGL requirements" << std::endl; std::cout << " |-- min API version: " << XR_VERSION_MAJOR(graphicsRequirement.minApiVersionSupported) << "." << XR_VERSION_MINOR(graphicsRequirement.minApiVersionSupported) << "." << XR_VERSION_PATCH(graphicsRequirement.minApiVersionSupported) << std::endl; std::cout << " |-- max API version: " << XR_VERSION_MAJOR(graphicsRequirement.maxApiVersionSupported) << "." << XR_VERSION_MINOR(graphicsRequirement.maxApiVersionSupported) << "." << XR_VERSION_PATCH(graphicsRequirement.maxApiVersionSupported) << std::endl; return true; } bool OpenGLHandler::initResources(XrInstance xr_instance, XrSystemId xr_system_id){ glGenTextures(1, &texture); glGenVertexArrays(1, &vao); glGenFramebuffers(1, &swapchainFramebuffer); GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &glslShaderVertex, nullptr); glCompileShader(vertexShader); if(!checkShader(vertexShader)) return false; GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &glslShaderFragment, nullptr); glCompileShader(fragmentShader); if(!checkShader(fragmentShader)) return false; program = glCreateProgram(); glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); glLinkProgram(program); if(!checkProgram(program)) return false; glDeleteShader(vertexShader); glDeleteShader(fragmentShader); return true; } void OpenGLHandler::renderView(const XrCompositionLayerProjectionView & layerView, const XrSwapchainImageBaseHeader * swapchainImage, int64_t swapchainFormat){ glBindFramebuffer(GL_FRAMEBUFFER, swapchainFramebuffer); const uint32_t colorTexture = reinterpret_cast<const XrSwapchainImageOpenGLKHR*>(swapchainImage)->image; glViewport(static_cast<GLint>(layerView.subImage.imageRect.offset.x), static_cast<GLint>(layerView.subImage.imageRect.offset.y), static_cast<GLsizei>(layerView.subImage.imageRect.extent.width), static_cast<GLsizei>(layerView.subImage.imageRect.extent.height)); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture, 0); glUseProgram(program); glBindTexture(GL_TEXTURE_2D, texture); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // render to window int width, height; SDL_GetWindowSize(sdl_window, &width, &height); glViewport(0, 0, width, height); glUseProgram(program); glBindTexture(GL_TEXTURE_2D, texture); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // swap window every other eye static int everyOther = 0; if((everyOther++ & 1) != 0) SDL_GL_SwapWindow(sdl_window); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); } void OpenGLHandler::renderViewFromImage(const XrCompositionLayerProjectionView & layerView, const XrSwapchainImageBaseHeader * swapchainImage, int64_t swapchainFormat, int frameWidth, int frameHeight, void * frameData, bool rgba){ // load texture glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, frameWidth, frameHeight, 0, rgba ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, frameData); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // render to hmd glBindFramebuffer(GL_FRAMEBUFFER, swapchainFramebuffer); const uint32_t colorTexture = reinterpret_cast<const XrSwapchainImageOpenGLKHR*>(swapchainImage)->image; glViewport(static_cast<GLint>(layerView.subImage.imageRect.offset.x), static_cast<GLint>(layerView.subImage.imageRect.offset.y), static_cast<GLsizei>(layerView.subImage.imageRect.extent.width), static_cast<GLsizei>(layerView.subImage.imageRect.extent.height)); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture, 0); glUseProgram(program); glBindTexture(GL_TEXTURE_2D, texture); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // // render to window // int width, height; // SDL_GetWindowSize(sdl_window, &width, &height); // glViewport(0, 0, width, height); // glUseProgram(program); // glBindTexture(GL_TEXTURE_2D, texture); // glBindVertexArray(vao); // glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // // swap window every other eye // static int everyOther = 0; // if((everyOther++ & 1) != 0) // SDL_GL_SwapWindow(sdl_window); // glBindTexture(GL_TEXTURE_2D, 0); // glUseProgram(0); } #endif class OpenXrApplication{ private: XrResult xr_result; XrInstance xr_instance = {}; XrSystemId xr_system_id = XR_NULL_SYSTEM_ID; XrSession xr_session = {}; XrSpace xr_space_view = {}; XrSpace xr_space_local = {}; XrSpace xr_space_stage = {}; // actions XrActionSet xr_action_set; Actions xr_actions; vector<SwapchainHandler> xr_swapchains_handlers; vector<XrViewConfigurationView> xr_view_configuration_views; bool xr_frames_is_rgba; vector<int> xr_frames_width; vector<int> xr_frames_height; vector<void*> xr_frames_data; void (*renderCallback)(int, XrView*, XrViewConfigurationView*); function<void(int, vector<XrView>, vector<XrViewConfigurationView>)> renderCallbackFunction; bool flagSessionRunning = false; // config XrEnvironmentBlendMode environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM; XrViewConfigurationType configViewConfigurationType = XR_VIEW_CONFIGURATION_TYPE_MAX_ENUM; #ifdef XR_USE_GRAPHICS_API_VULKAN XrGraphicsBindingVulkan2KHR xr_graphics_binding = {XR_TYPE_GRAPHICS_BINDING_VULKAN2_KHR}; VulkanHandler xr_graphics_handler; #endif #ifdef XR_USE_GRAPHICS_API_OPENGL XrGraphicsBindingOpenGLXlibKHR xr_graphics_binding = {XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR}; OpenGLHandler xr_graphics_handler; #endif bool defineLayers(const vector<string> &, vector<string> &); bool defineExtensions(const vector<string> &, vector<string> &); bool acquireInstanceProperties(); bool acquireSystemProperties(); bool acquireViewConfiguration(XrViewConfigurationType); bool acquireBlendModes(XrEnvironmentBlendMode); bool defineReferenceSpaces(); void defineInteractionProfileBindings(vector<XrActionSuggestedBinding> &, const vector<string> &); bool suggestInteractionProfileBindings(); bool defineSessionSpaces(); bool defineSwapchains(); void cleanFrames(){ // for(size_t i = 0; i < xr_frames_data.size(); i++){ // xr_frames_data[i] = nullptr; // xr_frames_width[i] = 0; // xr_frames_height[i] = 0; // } }; public: OpenXrApplication(); ~OpenXrApplication(); bool destroy(); bool createInstance(const string &, const string &, const vector<string> &, const vector<string> &); bool getSystem(XrFormFactor, XrEnvironmentBlendMode, XrViewConfigurationType); bool createSession(); bool pollEvents(bool *); bool pollActions(vector<ActionState> &); bool renderViews(XrReferenceSpaceType, vector<ActionPoseState> &); bool addAction(string, XrActionType, XrReferenceSpaceType); bool applyHapticFeedback(string, XrHapticBaseHeader *); bool stopHapticFeedback(string); bool setFrameByIndex(int, int, int, void *, bool); void setRenderCallbackFromPointer(void (*callback)(int, XrView*, XrViewConfigurationView*)){ renderCallback = callback; }; void setRenderCallbackFromFunction(function<void(int, vector<XrView>, vector<XrViewConfigurationView>)> &callback){ renderCallbackFunction = callback; }; bool isSessionRunning(){ return flagSessionRunning; } int getViewConfigurationViewsSize(){ return xr_view_configuration_views.size(); } vector<XrViewConfigurationView> getViewConfigurationViews(){ return xr_view_configuration_views; } }; OpenXrApplication::OpenXrApplication(){ renderCallback = nullptr; renderCallbackFunction = nullptr; } OpenXrApplication::~OpenXrApplication(){ destroy(); } bool OpenXrApplication::destroy(){ if(xr_instance != NULL){ std::cout << "Destroying OpenXR application" << std::endl; for(size_t i = 0; i < xr_actions.aPose.size(); i++) xrDestroySpace(xr_actions.aPose[i].space); xrDestroyActionSet(xr_action_set); for(size_t i = 0; i < xr_swapchains_handlers.size(); i++) xrDestroySwapchain(xr_swapchains_handlers[i].handle); xrDestroySpace(xr_space_view); xrDestroySpace(xr_space_local); xrDestroySpace(xr_space_stage); xrDestroySession(xr_session); xrDestroyInstance(xr_instance); xr_instance = {}; xr_system_id = XR_NULL_SYSTEM_ID; xr_session = {}; std::cout << "OpenXR application destroyed" << std::endl; } return true; } bool OpenXrApplication::defineLayers(const vector<string> & requestedApiLayers, vector<string> & enabledApiLayers){ uint32_t propertyCountOutput; xr_result = xrEnumerateApiLayerProperties(0, &propertyCountOutput, nullptr); if(!xrCheckResult(NULL, xr_result, "xrEnumerateApiLayerProperties")) return false; vector<XrApiLayerProperties> apiLayerProperties(propertyCountOutput, {XR_TYPE_API_LAYER_PROPERTIES}); xr_result = xrEnumerateApiLayerProperties(propertyCountOutput, &propertyCountOutput, apiLayerProperties.data()); if(!xrCheckResult(NULL, xr_result, "xrEnumerateApiLayerProperties")) return false; std::cout << "OpenXR API layers (" << apiLayerProperties.size() << ")" << std::endl; for(size_t i = 0; i < apiLayerProperties.size(); i++){ std::cout << " |-- " << apiLayerProperties[i].layerName << std::endl; for(size_t j = 0; j < requestedApiLayers.size(); j++) if(!requestedApiLayers[j].compare(apiLayerProperties[i].layerName)){ enabledApiLayers.push_back(requestedApiLayers[j]); std::cout << " | (requested)" << std::endl; break; } } // check for unavailable layers if(requestedApiLayers.size() != enabledApiLayers.size()){ bool used = false; std::cout << "Unavailable OpenXR API layers" << std::endl; for(size_t i = 0; i < requestedApiLayers.size(); i++){ used = false; for(size_t j = 0; j < enabledApiLayers.size(); j++) if(!requestedApiLayers[i].compare(enabledApiLayers[j])){ used = true; break; } if(!used) std::cout << " |-- " << requestedApiLayers[i] << std::endl; } return false; } return true; } bool OpenXrApplication::defineExtensions(const vector<string> & requestedExtensions, vector<string> & enabledExtensions){ uint32_t propertyCountOutput; xr_result = xrEnumerateInstanceExtensionProperties(nullptr, 0, &propertyCountOutput, nullptr); if(!xrCheckResult(NULL, xr_result, "xrEnumerateInstanceExtensionProperties")) return false; vector<XrExtensionProperties> extensionProperties(propertyCountOutput, {XR_TYPE_EXTENSION_PROPERTIES}); xr_result = xrEnumerateInstanceExtensionProperties(nullptr, propertyCountOutput, &propertyCountOutput, extensionProperties.data()); if(!xrCheckResult(NULL, xr_result, "xrEnumerateInstanceExtensionProperties")) return false; std::cout << "OpenXR extensions (" << extensionProperties.size() << ")" << std::endl; for(size_t i = 0; i < extensionProperties.size(); i++){ std::cout << " |-- " << extensionProperties[i].extensionName << std::endl; for(size_t j = 0; j < requestedExtensions.size(); j++) if(!requestedExtensions[j].compare(extensionProperties[i].extensionName)){ enabledExtensions.push_back(requestedExtensions[j]); std::cout << " | (requested)" << std::endl; break; } } // check for unavailable extensions if(requestedExtensions.size() != enabledExtensions.size()){ bool used = false; std::cout << "Unavailable OpenXR extensions" << std::endl; for(size_t i = 0; i < requestedExtensions.size(); i++){ used = false; for(size_t j = 0; j < enabledExtensions.size(); j++) if(!requestedExtensions[i].compare(enabledExtensions[j])){ used = true; break; } if(!used) std::cout << " |-- " << requestedExtensions[i] << std::endl; } return false; } return true; } bool OpenXrApplication::acquireInstanceProperties(){ XrInstanceProperties instanceProperties = {XR_TYPE_INSTANCE_PROPERTIES}; xr_result = xrGetInstanceProperties(xr_instance, &instanceProperties); if(!xrCheckResult(xr_instance, xr_result, "xrGetInstanceProperties")) return false; std::cout << "Runtime" << std::endl; std::cout << " |-- name: " << instanceProperties.runtimeName << std::endl; std::cout << " |-- version: " << XR_VERSION_MAJOR(instanceProperties.runtimeVersion) << "." << XR_VERSION_MINOR(instanceProperties.runtimeVersion) << "." << XR_VERSION_PATCH(instanceProperties.runtimeVersion) << std::endl; return true; } bool OpenXrApplication::acquireSystemProperties(){ XrSystemProperties systemProperties = {XR_TYPE_SYSTEM_PROPERTIES}; xr_result = xrGetSystemProperties(xr_instance, xr_system_id, &systemProperties); if(!xrCheckResult(xr_instance, xr_result, "xrGetSystemProperties")) return false; std::cout << "System" << std::endl; std::cout << " |-- system id: " << systemProperties.systemId << std::endl; std::cout << " |-- system name: " << systemProperties.systemName << std::endl; std::cout << " |-- vendor id: " << systemProperties.vendorId << std::endl; std::cout << " |-- max layers: " << systemProperties.graphicsProperties.maxLayerCount << std::endl; std::cout << " |-- max swapchain height: " << systemProperties.graphicsProperties.maxSwapchainImageHeight << std::endl; std::cout << " |-- max swapchain width: " << systemProperties.graphicsProperties.maxSwapchainImageWidth << std::endl; std::cout << " |-- orientation tracking: " << systemProperties.trackingProperties.orientationTracking << std::endl; std::cout << " |-- position tracking: " << systemProperties.trackingProperties.positionTracking << std::endl; return true; } bool OpenXrApplication::acquireViewConfiguration(XrViewConfigurationType configurationType){ uint32_t propertyCountOutput; xr_result = xrEnumerateViewConfigurations(xr_instance, xr_system_id, 0, &propertyCountOutput, nullptr); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateViewConfigurations")) return false; vector<XrViewConfigurationType> viewConfigurationTypes(propertyCountOutput); xr_result = xrEnumerateViewConfigurations(xr_instance, xr_system_id, propertyCountOutput, &propertyCountOutput, viewConfigurationTypes.data()); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateViewConfigurations")) return false; std::cout << "View configurations (" << viewConfigurationTypes.size() << ")" << std::endl; for(size_t i = 0; i < viewConfigurationTypes.size(); i++){ std::cout << " |-- type " << viewConfigurationTypes[i] << " (https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrViewConfigurationType)" << std::endl; if(viewConfigurationTypes[i] == configurationType){ std::cout << " | (requested)" << std::endl; configViewConfigurationType = configurationType; } } if(configViewConfigurationType == XR_VIEW_CONFIGURATION_TYPE_MAX_ENUM){ std::cout << "Unavailable view configuration type: " << configurationType << " (https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrViewConfigurationType)" << std::endl; return false; } // view configuration properties XrViewConfigurationProperties viewConfigurationProperties = {XR_TYPE_VIEW_CONFIGURATION_PROPERTIES}; xr_result = xrGetViewConfigurationProperties(xr_instance, xr_system_id, configViewConfigurationType, &viewConfigurationProperties); if(!xrCheckResult(xr_instance, xr_result, "xrGetViewConfigurationProperties")) return false; std::cout << "View configuration properties" << std::endl; std::cout << " |-- configuration type: " << viewConfigurationProperties.viewConfigurationType << " (https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrViewConfigurationType)" << std::endl; std::cout << " |-- fov mutable (bool): " << viewConfigurationProperties.fovMutable << std::endl; // view configuration views xr_result = xrEnumerateViewConfigurationViews(xr_instance, xr_system_id, configViewConfigurationType, 0, &propertyCountOutput, nullptr); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateViewConfigurationViews")) return false; xr_view_configuration_views.resize(propertyCountOutput, {XR_TYPE_VIEW_CONFIGURATION_VIEW}); xr_result = xrEnumerateViewConfigurationViews(xr_instance, xr_system_id, configViewConfigurationType, propertyCountOutput, &propertyCountOutput, xr_view_configuration_views.data()); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateViewConfigurationViews")) return false; std::cout << "View configuration views (" << xr_view_configuration_views.size() << ")" << std::endl; for(size_t i = 0; i < xr_view_configuration_views.size(); i++){ std::cout << " |-- view " << i << std::endl; std::cout << " | |-- recommended resolution: " << xr_view_configuration_views[i].recommendedImageRectWidth << " x " << xr_view_configuration_views[i].recommendedImageRectHeight << std::endl; std::cout << " | |-- max resolution: " << xr_view_configuration_views[i].maxImageRectWidth << " x " << xr_view_configuration_views[i].maxImageRectHeight << std::endl; std::cout << " | |-- recommended swapchain samples: " << xr_view_configuration_views[i].recommendedSwapchainSampleCount << std::endl; std::cout << " | |-- max swapchain samples: " << xr_view_configuration_views[i].maxSwapchainSampleCount << std::endl; } // resize frame buffers xr_frames_data.resize(xr_view_configuration_views.size()); xr_frames_width.resize(xr_view_configuration_views.size()); xr_frames_height.resize(xr_view_configuration_views.size()); cleanFrames(); return true; } bool OpenXrApplication::acquireBlendModes(XrEnvironmentBlendMode blendMode){ uint32_t propertyCountOutput; xr_result = xrEnumerateEnvironmentBlendModes(xr_instance, xr_system_id, configViewConfigurationType, 0, &propertyCountOutput, nullptr); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateEnvironmentBlendModes")) return false; vector<XrEnvironmentBlendMode> environmentBlendModes(propertyCountOutput); xr_result = xrEnumerateEnvironmentBlendModes(xr_instance, xr_system_id, configViewConfigurationType, propertyCountOutput, &propertyCountOutput, environmentBlendModes.data()); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateEnvironmentBlendModes")) return false; std::cout << "Environment blend modes (" << environmentBlendModes.size() << ")" << std::endl; for (size_t i = 0; i < environmentBlendModes.size(); i++){ std::cout << " |-- mode: " << environmentBlendModes[i] << " (https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrEnvironmentBlendMode)" << std::endl; if(environmentBlendModes[i] == blendMode){ std::cout << " | (requested)" << std::endl; environmentBlendMode = blendMode; } } if(environmentBlendMode == XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM){ std::cout << "Unavailable blend mode: " << blendMode << " (https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrEnvironmentBlendMode)" << std::endl; return false; } return true; } bool OpenXrApplication::defineReferenceSpaces(){ // get reference spaces uint32_t propertyCountOutput; xr_result = xrEnumerateReferenceSpaces(xr_session, 0, &propertyCountOutput, nullptr); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateReferenceSpaces")) return false; vector<XrReferenceSpaceType> referenceSpaces(propertyCountOutput); xr_result = xrEnumerateReferenceSpaces(xr_session, propertyCountOutput, &propertyCountOutput, referenceSpaces.data()); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateReferenceSpaces")) return false; // create reference space XrPosef pose; pose.orientation = { .x = 0, .y = 0, .z = 0, .w = 1.0 }; pose.position = { .x = 0, .y = 0, .z = 0 }; XrReferenceSpaceCreateInfo referenceSpaceCreateInfo = {XR_TYPE_REFERENCE_SPACE_CREATE_INFO}; referenceSpaceCreateInfo.poseInReferenceSpace = pose; XrExtent2Df spaceBounds; std::cout << "Reference spaces (" << referenceSpaces.size() << ")" << std::endl; for (size_t i = 0; i < referenceSpaces.size(); i++){ referenceSpaceCreateInfo.referenceSpaceType = referenceSpaces[i]; std::cout << " |-- type: " << referenceSpaces[i] << " (https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrReferenceSpaceType)" << std::endl; // view if(referenceSpaces[i] == XR_REFERENCE_SPACE_TYPE_VIEW){ xr_result = xrCreateReferenceSpace(xr_session, &referenceSpaceCreateInfo, &xr_space_view); if(!xrCheckResult(xr_instance, xr_result, "xrCreateReferenceSpace (XR_REFERENCE_SPACE_TYPE_VIEW)")) return false; // get bounds xr_result = xrGetReferenceSpaceBoundsRect(xr_session, XR_REFERENCE_SPACE_TYPE_VIEW, &spaceBounds); if(!xrCheckResult(xr_instance, xr_result, "xrGetReferenceSpaceBoundsRect (XR_REFERENCE_SPACE_TYPE_VIEW)")) return false; std::cout << " | |-- reference space bounds" << std::endl; std::cout << " | | |-- width: " << spaceBounds.width << std::endl; std::cout << " | | |-- height: " << spaceBounds.height << std::endl; } // local else if(referenceSpaces[i] == XR_REFERENCE_SPACE_TYPE_LOCAL){ xr_result = xrCreateReferenceSpace(xr_session, &referenceSpaceCreateInfo, &xr_space_local); if(!xrCheckResult(xr_instance, xr_result, "xrCreateReferenceSpace (XR_REFERENCE_SPACE_TYPE_LOCAL)")) return false; // get bounds xr_result = xrGetReferenceSpaceBoundsRect(xr_session, XR_REFERENCE_SPACE_TYPE_LOCAL, &spaceBounds); if(!xrCheckResult(xr_instance, xr_result, "xrGetReferenceSpaceBoundsRect (XR_REFERENCE_SPACE_TYPE_LOCAL)")) return false; std::cout << " | |-- reference space bounds" << std::endl; std::cout << " | | |-- width: " << spaceBounds.width << std::endl; std::cout << " | | |-- height: " << spaceBounds.height << std::endl; } // stage else if(referenceSpaces[i] == XR_REFERENCE_SPACE_TYPE_STAGE){ xr_result = xrCreateReferenceSpace(xr_session, &referenceSpaceCreateInfo, &xr_space_stage); if(!xrCheckResult(xr_instance, xr_result, "xrCreateReferenceSpace (XR_REFERENCE_SPACE_TYPE_STAGE)")) return false; // get bounds xr_result = xrGetReferenceSpaceBoundsRect(xr_session, XR_REFERENCE_SPACE_TYPE_STAGE, &spaceBounds); if(!xrCheckResult(xr_instance, xr_result, "xrGetReferenceSpaceBoundsRect (XR_REFERENCE_SPACE_TYPE_STAGE)")) return false; std::cout << " | |-- reference space bounds" << std::endl; std::cout << " | | |-- width: " << spaceBounds.width << std::endl; std::cout << " | | |-- height: " << spaceBounds.height << std::endl; } } return true; } void OpenXrApplication::defineInteractionProfileBindings(vector<XrActionSuggestedBinding> & bindings, const vector<string> & validPaths){ for(size_t i = 0; i < xr_actions.aBoolean.size(); i++) if(std::find(validPaths.begin(), validPaths.end(), xr_actions.aBoolean[i].stringPath) != validPaths.end()){ XrActionSuggestedBinding binding; binding.action = xr_actions.aBoolean[i].action; binding.binding = xr_actions.aBoolean[i].path; bindings.push_back(binding); } for(size_t i = 0; i < xr_actions.aFloat.size(); i++) if(std::find(validPaths.begin(), validPaths.end(), xr_actions.aFloat[i].stringPath) != validPaths.end()){ XrActionSuggestedBinding binding; binding.action = xr_actions.aFloat[i].action; binding.binding = xr_actions.aFloat[i].path; bindings.push_back(binding); } for(size_t i = 0; i < xr_actions.aVector2f.size(); i++) if(std::find(validPaths.begin(), validPaths.end(), xr_actions.aVector2f[i].stringPath) != validPaths.end()){ XrActionSuggestedBinding binding; binding.action = xr_actions.aVector2f[i].action; binding.binding = xr_actions.aVector2f[i].path; bindings.push_back(binding); } for(size_t i = 0; i < xr_actions.aPose.size(); i++) if(std::find(validPaths.begin(), validPaths.end(), xr_actions.aPose[i].stringPath) != validPaths.end()){ XrActionSuggestedBinding binding; binding.action = xr_actions.aPose[i].action; binding.binding = xr_actions.aPose[i].path; bindings.push_back(binding); } for(size_t i = 0; i < xr_actions.aVibration.size(); i++) if(std::find(validPaths.begin(), validPaths.end(), xr_actions.aVibration[i].stringPath) != validPaths.end()){ XrActionSuggestedBinding binding; binding.action = xr_actions.aVibration[i].action; binding.binding = xr_actions.aVibration[i].path; bindings.push_back(binding); } } bool OpenXrApplication::suggestInteractionProfileBindings(){ vector<string> validPathsKhronosSimpleController = {{"/user/hand/left/input/select/click"}, {"/user/hand/left/input/menu/click"}, {"/user/hand/left/input/grip/pose"}, {"/user/hand/left/input/aim/pose"}, {"/user/hand/left/output/haptic"}, {"/user/hand/right/input/select/click"}, {"/user/hand/right/input/menu/click"}, {"/user/hand/right/input/grip/pose"}, {"/user/hand/right/input/aim/pose"}, {"/user/hand/right/output/haptic"}}; vector<string> validPathsGoogleDaydreamController = {{"/user/hand/left/input/select/click"}, {"/user/hand/left/input/trackpad/x"}, {"/user/hand/left/input/trackpad/y"}, {"/user/hand/left/input/trackpad/click"}, {"/user/hand/left/input/trackpad/touch"}, {"/user/hand/left/input/grip/pose"}, {"/user/hand/left/input/aim/pose"}, {"/user/hand/right/input/select/click"}, {"/user/hand/right/input/trackpad/x"}, {"/user/hand/right/input/trackpad/y"}, {"/user/hand/right/input/trackpad/click"}, {"/user/hand/right/input/trackpad/touch"}, {"/user/hand/right/input/grip/pose"}, {"/user/hand/right/input/aim/pose"}}; vector<string> validPathsHTCViveController = {{"/user/hand/left/input/system/click"}, {"/user/hand/left/input/squeeze/click"}, {"/user/hand/left/input/menu/click"}, {"/user/hand/left/input/trigger/click"}, {"/user/hand/left/input/trigger/value"}, {"/user/hand/left/input/trackpad/x"}, {"/user/hand/left/input/trackpad/y"}, {"/user/hand/left/input/trackpad/click"}, {"/user/hand/left/input/trackpad/touch"}, {"/user/hand/left/input/grip/pose"}, {"/user/hand/left/input/aim/pose"}, {"/user/hand/left/output/haptic"}, {"/user/hand/right/input/system/click"}, {"/user/hand/right/input/squeeze/click"}, {"/user/hand/right/input/menu/click"}, {"/user/hand/right/input/trigger/click"}, {"/user/hand/right/input/trigger/value"}, {"/user/hand/right/input/trackpad/x"}, {"/user/hand/right/input/trackpad/y"}, {"/user/hand/right/input/trackpad/click"}, {"/user/hand/right/input/trackpad/touch"}, {"/user/hand/right/input/grip/pose"}, {"/user/hand/right/input/aim/pose"}, {"/user/hand/right/output/haptic"}}; vector<string> validPathsHTCVivePro = {{"/user/head/input/system/click"}, {"/user/head/input/volume_up/click"}, {"/user/head/input/volume_down/click"}, {"/user/head/input/mute_mic/click"}}; vector<string> validPathsMicrosoftMixedRealityMotionController = {{"/user/hand/left/input/menu/click"}, {"/user/hand/left/input/squeeze/click"}, {"/user/hand/left/input/trigger/value"}, {"/user/hand/left/input/thumbstick/x"}, {"/user/hand/left/input/thumbstick/y"}, {"/user/hand/left/input/thumbstick/click"}, {"/user/hand/left/input/trackpad/x"}, {"/user/hand/left/input/trackpad/y"}, {"/user/hand/left/input/trackpad/click"}, {"/user/hand/left/input/trackpad/touch"}, {"/user/hand/left/input/grip/pose"}, {"/user/hand/left/input/aim/pose"}, {"/user/hand/left/output/haptic"}, {"/user/hand/right/input/menu/click"}, {"/user/hand/right/input/squeeze/click"}, {"/user/hand/right/input/trigger/value"}, {"/user/hand/right/input/thumbstick/x"}, {"/user/hand/right/input/thumbstick/y"}, {"/user/hand/right/input/thumbstick/click"}, {"/user/hand/right/input/trackpad/x"}, {"/user/hand/right/input/trackpad/y"}, {"/user/hand/right/input/trackpad/click"}, {"/user/hand/right/input/trackpad/touch"}, {"/user/hand/right/input/grip/pose"}, {"/user/hand/right/input/aim/pose"}, {"/user/hand/right/output/haptic"}}; vector<string> validPathsMicrosoftXboxController = {{"/user/gamepad/input/menu/click"}, {"/user/gamepad/input/view/click"}, {"/user/gamepad/input/a/click"}, {"/user/gamepad/input/b/click"}, {"/user/gamepad/input/x/click"}, {"/user/gamepad/input/y/click"}, {"/user/gamepad/input/dpad_down/click"}, {"/user/gamepad/input/dpad_right/click"}, {"/user/gamepad/input/dpad_up/click"}, {"/user/gamepad/input/dpad_left/click"}, {"/user/gamepad/input/shoulder_left/click"}, {"/user/gamepad/input/shoulder_right/click"}, {"/user/gamepad/input/thumbstick_left/click"}, {"/user/gamepad/input/thumbstick_right/click"}, {"/user/gamepad/input/trigger_left/value"}, {"/user/gamepad/input/trigger_right/value"}, {"/user/gamepad/input/thumbstick_left/x"}, {"/user/gamepad/input/thumbstick_left/y"}, {"/user/gamepad/input/thumbstick_right/x"}, {"/user/gamepad/input/thumbstick_right/y"}, {"/user/gamepad/output/haptic_left"}, {"/user/gamepad/output/haptic_right"}, {"/user/gamepad/output/haptic_left_trigger"}, {"/user/gamepad/output/haptic_right_trigger"}}; vector<string> validPathsOculusGoController = {{"/user/hand/left/input/system/click"}, {"/user/hand/left/input/trigger/click"}, {"/user/hand/left/input/back/click"}, {"/user/hand/left/input/trackpad/x"}, {"/user/hand/left/input/trackpad/y"}, {"/user/hand/left/input/trackpad/click"}, {"/user/hand/left/input/trackpad/touch"}, {"/user/hand/left/input/grip/pose"}, {"/user/hand/left/input/aim/pose"}, {"/user/hand/right/input/system/click"}, {"/user/hand/right/input/trigger/click"}, {"/user/hand/right/input/back/click"}, {"/user/hand/right/input/trackpad/x"}, {"/user/hand/right/input/trackpad/y"}, {"/user/hand/right/input/trackpad/click"}, {"/user/hand/right/input/trackpad/touch"}, {"/user/hand/right/input/grip/pose"}, {"/user/hand/right/input/aim/pose"}}; vector<string> validPathsOculusTouchController = {{"/user/hand/left/input/squeeze/value"}, {"/user/hand/left/input/trigger/value"}, {"/user/hand/left/input/trigger/touch"}, {"/user/hand/left/input/thumbstick/x"}, {"/user/hand/left/input/thumbstick/y"}, {"/user/hand/left/input/thumbstick/click"}, {"/user/hand/left/input/thumbstick/touch"}, {"/user/hand/left/input/thumbrest/touch"}, {"/user/hand/left/input/grip/pose"}, {"/user/hand/left/input/aim/pose"}, {"/user/hand/left/output/haptic"}, {"/user/hand/left/input/x/click"}, {"/user/hand/left/input/x/touch"}, {"/user/hand/left/input/y/click"}, {"/user/hand/left/input/y/touch"}, {"/user/hand/left/input/menu/click"}, {"/user/hand/right/input/squeeze/value"}, {"/user/hand/right/input/trigger/value"}, {"/user/hand/right/input/trigger/touch"}, {"/user/hand/right/input/thumbstick/x"}, {"/user/hand/right/input/thumbstick/y"}, {"/user/hand/right/input/thumbstick/click"}, {"/user/hand/right/input/thumbstick/touch"}, {"/user/hand/right/input/thumbrest/touch"}, {"/user/hand/right/input/grip/pose"}, {"/user/hand/right/input/aim/pose"}, {"/user/hand/right/output/haptic"}, {"/user/hand/right/input/a/click"}, {"/user/hand/right/input/a/touch"}, {"/user/hand/right/input/b/click"}, {"/user/hand/right/input/b/touch"}, {"/user/hand/right/input/system/click"}}; vector<string> validPathsValveIndexController = {{"/user/hand/left/input/system/click"}, {"/user/hand/left/input/system/touch"}, {"/user/hand/left/input/a/click"}, {"/user/hand/left/input/a/touch"}, {"/user/hand/left/input/b/click"}, {"/user/hand/left/input/b/touch"}, {"/user/hand/left/input/squeeze/value"}, {"/user/hand/left/input/squeeze/force"}, {"/user/hand/left/input/trigger/click"}, {"/user/hand/left/input/trigger/value"}, {"/user/hand/left/input/trigger/touch"}, {"/user/hand/left/input/thumbstick/x"}, {"/user/hand/left/input/thumbstick/y"}, {"/user/hand/left/input/thumbstick/click"}, {"/user/hand/left/input/thumbstick/touch"}, {"/user/hand/left/input/trackpad/x"}, {"/user/hand/left/input/trackpad/y"}, {"/user/hand/left/input/trackpad/force"}, {"/user/hand/left/input/trackpad/touch"}, {"/user/hand/left/input/grip/pose"}, {"/user/hand/left/input/aim/pose"}, {"/user/hand/left/output/haptic"}, {"/user/hand/right/input/system/click"}, {"/user/hand/right/input/system/touch"}, {"/user/hand/right/input/a/click"}, {"/user/hand/right/input/a/touch"}, {"/user/hand/right/input/b/click"}, {"/user/hand/right/input/b/touch"}, {"/user/hand/right/input/squeeze/value"}, {"/user/hand/right/input/squeeze/force"}, {"/user/hand/right/input/trigger/click"}, {"/user/hand/right/input/trigger/value"}, {"/user/hand/right/input/trigger/touch"}, {"/user/hand/right/input/thumbstick/x"}, {"/user/hand/right/input/thumbstick/y"}, {"/user/hand/right/input/thumbstick/click"}, {"/user/hand/right/input/thumbstick/touch"}, {"/user/hand/right/input/trackpad/x"}, {"/user/hand/right/input/trackpad/y"}, {"/user/hand/right/input/trackpad/force"}, {"/user/hand/right/input/trackpad/touch"}, {"/user/hand/right/input/grip/pose"}, {"/user/hand/right/input/aim/pose"}, {"/user/hand/right/output/haptic"}}; XrPath interactionProfilePath; vector<XrActionSuggestedBinding> bindings; XrInteractionProfileSuggestedBinding suggestedBindings = {XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING}; std::cout << "Suggested interaction bindings by profiles" << std::endl; // Khronos Simple Controller bindings.clear(); xrStringToPath(xr_instance, "/interaction_profiles/khr/simple_controller", &interactionProfilePath); defineInteractionProfileBindings(bindings, validPathsKhronosSimpleController); if(bindings.size()){ suggestedBindings.interactionProfile = interactionProfilePath; suggestedBindings.suggestedBindings = bindings.data(); suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size(); xr_result = xrSuggestInteractionProfileBindings(xr_instance, &suggestedBindings); if(!xrCheckResult(xr_instance, xr_result, "xrSuggestInteractionProfileBindings /interaction_profiles/khr/simple_controller")) return false; } std::cout << " |-- /interaction_profiles/khr/simple_controller (" << bindings.size() << ")" << std::endl; // Google Daydream Controller bindings.clear(); xrStringToPath(xr_instance, "/interaction_profiles/google/daydream_controller", &interactionProfilePath); defineInteractionProfileBindings(bindings, validPathsGoogleDaydreamController); if(bindings.size()){ suggestedBindings.interactionProfile = interactionProfilePath; suggestedBindings.suggestedBindings = bindings.data(); suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size(); xr_result = xrSuggestInteractionProfileBindings(xr_instance, &suggestedBindings); if(!xrCheckResult(xr_instance, xr_result, "xrSuggestInteractionProfileBindings /interaction_profiles/google/daydream_controller")) return false; } std::cout << " |-- /interaction_profiles/google/daydream_controller (" << bindings.size() << ")" << std::endl; // HTC Vive Controller bindings.clear(); xrStringToPath(xr_instance, "/interaction_profiles/htc/vive_controller", &interactionProfilePath); defineInteractionProfileBindings(bindings, validPathsHTCViveController); if(bindings.size()){ suggestedBindings.interactionProfile = interactionProfilePath; suggestedBindings.suggestedBindings = bindings.data(); suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size(); xr_result = xrSuggestInteractionProfileBindings(xr_instance, &suggestedBindings); if(!xrCheckResult(xr_instance, xr_result, "xrSuggestInteractionProfileBindings /interaction_profiles/htc/vive_controller")) return false; } std::cout << " |-- /interaction_profiles/htc/vive_controller (" << bindings.size() << ")" << std::endl; // HTC Vive Pro bindings.clear(); xrStringToPath(xr_instance, "/interaction_profiles/htc/vive_pro", &interactionProfilePath); defineInteractionProfileBindings(bindings, validPathsHTCVivePro); if(bindings.size()){ suggestedBindings.interactionProfile = interactionProfilePath; suggestedBindings.suggestedBindings = bindings.data(); suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size(); xr_result = xrSuggestInteractionProfileBindings(xr_instance, &suggestedBindings); if(!xrCheckResult(xr_instance, xr_result, "xrSuggestInteractionProfileBindings /interaction_profiles/htc/vive_pro")) return false; } std::cout << " |-- /interaction_profiles/htc/vive_pro (" << bindings.size() << ")" << std::endl; // Microsoft Mixed Reality Motion Controller bindings.clear(); xrStringToPath(xr_instance, "/interaction_profiles/microsoft/motion_controller", &interactionProfilePath); defineInteractionProfileBindings(bindings, validPathsMicrosoftMixedRealityMotionController); if(bindings.size()){ suggestedBindings.interactionProfile = interactionProfilePath; suggestedBindings.suggestedBindings = bindings.data(); suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size(); xr_result = xrSuggestInteractionProfileBindings(xr_instance, &suggestedBindings); if(!xrCheckResult(xr_instance, xr_result, "xrSuggestInteractionProfileBindings /interaction_profiles/microsoft/motion_controller")) return false; } std::cout << " |-- /interaction_profiles/microsoft/motion_controller (" << bindings.size() << ")" << std::endl; // Microsoft Xbox Controller bindings.clear(); xrStringToPath(xr_instance, "/interaction_profiles/microsoft/xbox_controller", &interactionProfilePath); defineInteractionProfileBindings(bindings, validPathsMicrosoftXboxController); if(bindings.size()){ suggestedBindings.interactionProfile = interactionProfilePath; suggestedBindings.suggestedBindings = bindings.data(); suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size(); xr_result = xrSuggestInteractionProfileBindings(xr_instance, &suggestedBindings); if(!xrCheckResult(xr_instance, xr_result, "xrSuggestInteractionProfileBindings /interaction_profiles/microsoft/xbox_controller")) return false; } std::cout << " |-- /interaction_profiles/microsoft/xbox_controller (" << bindings.size() << ")" << std::endl; // Oculus Go Controller bindings.clear(); xrStringToPath(xr_instance, "/interaction_profiles/oculus/go_controller", &interactionProfilePath); defineInteractionProfileBindings(bindings, validPathsOculusGoController); if(bindings.size()){ suggestedBindings.interactionProfile = interactionProfilePath; suggestedBindings.suggestedBindings = bindings.data(); suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size(); xr_result = xrSuggestInteractionProfileBindings(xr_instance, &suggestedBindings); if(!xrCheckResult(xr_instance, xr_result, "xrSuggestInteractionProfileBindings /interaction_profiles/oculus/go_controller")) return false; } std::cout << " |-- /interaction_profiles/oculus/go_controller (" << bindings.size() << ")" << std::endl; // Oculus Touch Controller bindings.clear(); xrStringToPath(xr_instance, "/interaction_profiles/oculus/touch_controller", &interactionProfilePath); defineInteractionProfileBindings(bindings, validPathsOculusTouchController); if(bindings.size()){ suggestedBindings.interactionProfile = interactionProfilePath; suggestedBindings.suggestedBindings = bindings.data(); suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size(); xr_result = xrSuggestInteractionProfileBindings(xr_instance, &suggestedBindings); if(!xrCheckResult(xr_instance, xr_result, "xrSuggestInteractionProfileBindings /interaction_profiles/oculus/touch_controller")) return false; } std::cout << " |-- /interaction_profiles/oculus/touch_controller (" << bindings.size() << ")" << std::endl; // Valve Index Controller bindings.clear(); xrStringToPath(xr_instance, "/interaction_profiles/valve/index_controller", &interactionProfilePath); defineInteractionProfileBindings(bindings, validPathsValveIndexController); if(bindings.size()){ suggestedBindings.interactionProfile = interactionProfilePath; suggestedBindings.suggestedBindings = bindings.data(); suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size(); xr_result = xrSuggestInteractionProfileBindings(xr_instance, &suggestedBindings); if(!xrCheckResult(xr_instance, xr_result, "xrSuggestInteractionProfileBindings /interaction_profiles/valve/index_controller")) return false; } std::cout << " |-- /interaction_profiles/valve/index_controller (" << bindings.size() << ")" << std::endl; return true; } bool OpenXrApplication::defineSessionSpaces(){ XrSessionActionSetsAttachInfo attachInfo{XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO}; attachInfo.countActionSets = 1; attachInfo.actionSets = &xr_action_set; xr_result = xrAttachSessionActionSets(xr_session, &attachInfo); if(!xrCheckResult(xr_instance, xr_result, "xrAttachSessionActionSets")) return false; XrActionSpaceCreateInfo actionSpaceInfo = {XR_TYPE_ACTION_SPACE_CREATE_INFO}; actionSpaceInfo.poseInActionSpace.orientation.w = 1.f; actionSpaceInfo.subactionPath = XR_NULL_PATH; for(size_t i = 0; i < xr_actions.aPose.size(); i++){ XrSpace space; actionSpaceInfo.action = xr_actions.aPose[i].action; xr_result = xrCreateActionSpace(xr_session, &actionSpaceInfo, &space); if(!xrCheckResult(xr_instance, xr_result, "xrCreateActionSpace")) return false; xr_actions.aPose[i].space = space; } return true; } bool OpenXrApplication::defineSwapchains(){ // get swapchain Formats uint32_t propertyCountOutput; xr_result = xrEnumerateSwapchainFormats(xr_session, 0, &propertyCountOutput, nullptr); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateSwapchainFormats")) return false; vector<int64_t> swapchainFormats(propertyCountOutput); xr_result = xrEnumerateSwapchainFormats(xr_session, propertyCountOutput, &propertyCountOutput, swapchainFormats.data()); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateSwapchainFormats")) return false; // select swapchain format #ifdef XR_USE_GRAPHICS_API_VULKAN int64_t supportedSwapchainFormats[] = {VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}; #endif #ifdef XR_USE_GRAPHICS_API_OPENGL int64_t supportedSwapchainFormats[] = {GL_RGB10_A2, GL_RGBA16F, GL_RGBA8, GL_RGBA8_SNORM}; #endif int64_t selectedSwapchainFormats = -1; for(size_t i = 0; i < swapchainFormats.size(); i++){ for (size_t j = 0; j < _countof(supportedSwapchainFormats); j++) if(swapchainFormats[i] == supportedSwapchainFormats[j]){ selectedSwapchainFormats = swapchainFormats[i]; break; } if(selectedSwapchainFormats != -1) break; } if((selectedSwapchainFormats == -1) && swapchainFormats.size()) selectedSwapchainFormats = swapchainFormats[0]; std::cout << "Swapchain formats (" << swapchainFormats.size() << ")" << std::endl; for (size_t i = 0; i < swapchainFormats.size(); i++){ std::cout << " |-- format: " << swapchainFormats[i] << std::endl; if (swapchainFormats[i] == selectedSwapchainFormats) std::cout << " | (selected)" << std::endl; } // create swapchain per view std::cout << "Created swapchain (" << xr_view_configuration_views.size() << ")" << std::endl; for(uint32_t i = 0; i < xr_view_configuration_views.size(); i++){ XrSwapchainCreateInfo swapchainCreateInfo = {XR_TYPE_SWAPCHAIN_CREATE_INFO}; swapchainCreateInfo.arraySize = 1; swapchainCreateInfo.format = selectedSwapchainFormats; swapchainCreateInfo.width = xr_view_configuration_views[i].recommendedImageRectWidth; swapchainCreateInfo.height = xr_view_configuration_views[i].recommendedImageRectHeight; swapchainCreateInfo.mipCount = 1; swapchainCreateInfo.faceCount = 1; swapchainCreateInfo.sampleCount = xr_graphics_handler.getSupportedSwapchainSampleCount(xr_view_configuration_views[i]); swapchainCreateInfo.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT; SwapchainHandler swapchain; xr_result = xrCreateSwapchain(xr_session, &swapchainCreateInfo, &swapchain.handle); if(!xrCheckResult(xr_instance, xr_result, "xrCreateSwapchain")) return false; swapchain.width = swapchainCreateInfo.width; swapchain.height = swapchainCreateInfo.height; std::cout << " |-- swapchain: " << i << std::endl; std::cout << " | |-- width: " << swapchainCreateInfo.width << std::endl; std::cout << " | |-- height: " << swapchainCreateInfo.height << std::endl; std::cout << " | |-- sample count: " << swapchainCreateInfo.sampleCount << std::endl; // enumerate swapchain images xr_result = xrEnumerateSwapchainImages(swapchain.handle, 0, &propertyCountOutput, nullptr); if(!xrCheckResult(xr_instance, xr_result, "xrEnumerateSwapchainImages")) return false; swapchain.length = propertyCountOutput; #ifdef XR_USE_GRAPHICS_API_VULKAN swapchain.images.resize(propertyCountOutput, {XR_TYPE_SWAPCHAIN_IMAGE_VULKAN2_KHR}); #endif #ifdef XR_USE_GRAPHICS_API_OPENGL swapchain.images.resize(propertyCountOutput, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR}); #endif xrEnumerateSwapchainImages(swapchain.handle, propertyCountOutput, &propertyCountOutput, (XrSwapchainImageBaseHeader*)swapchain.images.data()); std::cout << " | |-- swapchain images: " << propertyCountOutput << std::endl; xr_swapchains_handlers.push_back(swapchain); } #ifdef XR_USE_GRAPHICS_API_OPENGL // acquire GL context glXMakeCurrent(xr_graphics_binding.xDisplay, xr_graphics_binding.glxDrawable, xr_graphics_binding.glxContext); #endif return true; } bool OpenXrApplication::createInstance(const string & applicationName, const string & engineName, const vector<string> & requestedApiLayers, const vector<string> & requestedExtensions){ vector<string> enabledApiLayers; vector<string> enabledExtensions; // layers if(!defineLayers(requestedApiLayers, enabledApiLayers)) return false; // extensions if(!defineExtensions(requestedExtensions, enabledExtensions)) return false; vector<const char*> enabledApiLayerNames = cast_to_vector_char_p(enabledApiLayers); vector<const char*> enabledExtensionNames = cast_to_vector_char_p(enabledExtensions); // initialize OpenXR (create instance) with the enabled extensions and layers XrInstanceCreateInfo createInfo = {XR_TYPE_INSTANCE_CREATE_INFO}; createInfo.next = NULL; createInfo.createFlags = 0; createInfo.enabledApiLayerCount = enabledApiLayers.size(); createInfo.enabledApiLayerNames = enabledApiLayerNames.data(); createInfo.enabledExtensionCount = enabledExtensions.size(); createInfo.enabledExtensionNames = enabledExtensionNames.data(); createInfo.applicationInfo.apiVersion = XR_CURRENT_API_VERSION; createInfo.applicationInfo.applicationVersion = 1; createInfo.applicationInfo.engineVersion = 1; strncpy(createInfo.applicationInfo.applicationName, applicationName.c_str(), XR_MAX_APPLICATION_NAME_SIZE); strncpy(createInfo.applicationInfo.engineName, engineName.c_str(), XR_MAX_ENGINE_NAME_SIZE); xr_result = xrCreateInstance(&createInfo, &xr_instance); if(!xrCheckResult(NULL, xr_result, "xrCreateInstance")) return false; return true; } bool OpenXrApplication::getSystem(XrFormFactor formFactor, XrEnvironmentBlendMode blendMode, XrViewConfigurationType configurationType){ XrSystemGetInfo systemInfo = {XR_TYPE_SYSTEM_GET_INFO}; systemInfo.formFactor = formFactor; xr_result = xrGetSystem(xr_instance, &systemInfo, &xr_system_id); if(!xrCheckResult(xr_instance, xr_result, "xrGetSystem")) return false; if(!acquireInstanceProperties()) return false; if(!acquireSystemProperties()) return false; if(!acquireViewConfiguration(configurationType)) return false; if(!acquireBlendModes(blendMode)) return false; // create action set XrActionSetCreateInfo actionSetInfo = {XR_TYPE_ACTION_SET_CREATE_INFO}; strcpy(actionSetInfo.actionSetName, "actionset"); strcpy(actionSetInfo.localizedActionSetName, "localized_actionset"); actionSetInfo.priority = 0; xr_result = xrCreateActionSet(xr_instance, &actionSetInfo, &xr_action_set); if(!xrCheckResult(xr_instance, xr_result, "xrCreateActionSet")) return false; return true; } bool OpenXrApplication::createSession(){ #ifdef XR_USE_GRAPHICS_API_VULKAN xr_graphics_handler.createInstance(xr_instance, xr_system_id); xr_graphics_handler.getPhysicalDevice(xr_instance, xr_system_id); xr_graphics_handler.createLogicalDevice(xr_instance, xr_system_id); xr_graphics_binding.instance = xr_graphics_handler.getInstance(); xr_graphics_binding.physicalDevice = xr_graphics_handler.getPhysicalDevice(); xr_graphics_binding.device = xr_graphics_handler.getLogicalDevice(); xr_graphics_binding.queueFamilyIndex = xr_graphics_handler.getQueueFamilyIndex(); xr_graphics_binding.queueIndex = 0; std::cout << "Graphics binding: Vulkan" << std::endl; std::cout << " |-- instance: " << xr_graphics_binding.instance << std::endl; std::cout << " |-- physical device: " << xr_graphics_binding.physicalDevice << std::endl; std::cout << " |-- device: " << xr_graphics_binding.device << std::endl; std::cout << " |-- queue family index: " << xr_graphics_binding.queueFamilyIndex << std::endl; std::cout << " |-- queue index: " << xr_graphics_binding.queueIndex << std::endl; #endif #ifdef XR_USE_GRAPHICS_API_OPENGL if(!xr_graphics_handler.getRequirements(xr_instance, xr_system_id)) return false; if(!xr_graphics_handler.initGraphicsBinding(&xr_graphics_binding.xDisplay, &xr_graphics_binding.visualid, &xr_graphics_binding.glxFBConfig, &xr_graphics_binding.glxDrawable, &xr_graphics_binding.glxContext, xr_view_configuration_views[0].recommendedImageRectWidth, xr_view_configuration_views[0].recommendedImageRectHeight)) return false; if(!xr_graphics_handler.initResources(xr_instance, xr_system_id)) return false; std::cout << "Graphics binding: OpenGL" << std::endl; std::cout << " |-- xDisplay: " << xr_graphics_binding.xDisplay << std::endl; std::cout << " |-- visualid: " << xr_graphics_binding.visualid << std::endl; std::cout << " |-- glxFBConfig: " << xr_graphics_binding.glxFBConfig << std::endl; std::cout << " |-- glxDrawable: " << xr_graphics_binding.glxDrawable << std::endl; std::cout << " |-- glxContext: " << xr_graphics_binding.glxContext << std::endl; #endif // create session XrSessionCreateInfo sessionInfo = {XR_TYPE_SESSION_CREATE_INFO}; sessionInfo.next = &xr_graphics_binding; sessionInfo.systemId = xr_system_id; xr_result = xrCreateSession(xr_instance, &sessionInfo, &xr_session); if(!xrCheckResult(xr_instance, xr_result, "xrCreateSession")) return false; // reference spaces if(!defineReferenceSpaces()) return false; // suggest interaction profile bindings if(!suggestInteractionProfileBindings()) return false; // action spaces / attach session action sets if(!defineSessionSpaces()) return false; // swapchains if(!defineSwapchains()) return false; return true; } bool OpenXrApplication::pollEvents(bool * exitLoop){ *exitLoop = false; XrEventDataBuffer event; while(true){ // pool events event.type = XR_TYPE_EVENT_DATA_BUFFER; event.next = nullptr; xr_result = xrPollEvent(xr_instance, &event); if(!xrCheckResult(xr_instance, xr_result, "xrPollEvent")) return false; // process messages switch(event.type){ case XR_EVENT_UNAVAILABLE: { return true; break; } case XR_TYPE_EVENT_DATA_BUFFER: { return true; break; } // event queue overflowed (some events were removed) case XR_TYPE_EVENT_DATA_EVENTS_LOST: { const XrEventDataEventsLost & eventsLost = *reinterpret_cast<XrEventDataEventsLost*>(&event); std::cout << "Event queue has overflowed (" << eventsLost.lostEventCount << " overflowed event(s))" << std::endl; break; } // session state changed case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: { const XrEventDataSessionStateChanged & sessionStateChangedEvent = *reinterpret_cast<XrEventDataSessionStateChanged*>(&event); std::cout << "XrEventDataSessionStateChanged to " << _enum_to_string(sessionStateChangedEvent.state) << " (" << sessionStateChangedEvent.state << ")" << std::endl; // check session if((sessionStateChangedEvent.session != XR_NULL_HANDLE) && (sessionStateChangedEvent.session != xr_session)){ std::cout << "XrEventDataSessionStateChanged for unknown session " << sessionStateChangedEvent.session << std::endl; return false; } // handle session state switch(sessionStateChangedEvent.state){ case XR_SESSION_STATE_READY: { XrSessionBeginInfo sessionBeginInfo = {XR_TYPE_SESSION_BEGIN_INFO}; sessionBeginInfo.primaryViewConfigurationType = configViewConfigurationType; xr_result = xrBeginSession(xr_session, &sessionBeginInfo); if(!xrCheckResult(xr_instance, xr_result, "xrBeginSession")) return false; flagSessionRunning = true; std::cout << "Event: XR_SESSION_STATE_READY (xrBeginSession)" << std::endl; break; } case XR_SESSION_STATE_STOPPING: { xr_result = xrEndSession(xr_session); if(!xrCheckResult(xr_instance, xr_result, "xrEndSession")) return false; flagSessionRunning = false; std::cout << "Event: XR_SESSION_STATE_STOPPING (xrEndSession)" << std::endl; break; } case XR_SESSION_STATE_EXITING: { *exitLoop = true; std::cout << "Event: XR_SESSION_STATE_EXITING" << std::endl; break; } case XR_SESSION_STATE_LOSS_PENDING: { *exitLoop = true; std::cout << "Event: XR_SESSION_STATE_LOSS_PENDING" << std::endl; break; } default: break; } break; } // application is about to lose the XrInstance case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: { const XrEventDataInstanceLossPending & instanceLossPending = *reinterpret_cast<XrEventDataInstanceLossPending*>(&event); *exitLoop = true; std::cout << "XrEventDataInstanceLossPending by " << instanceLossPending.lossTime << std::endl; return true; break; } case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: { // TODO: implement std::cout << "XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED" << std::endl; break; } // reference space is changing case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: { const XrEventDataReferenceSpaceChangePending & referenceSpaceChangePending = *reinterpret_cast<XrEventDataReferenceSpaceChangePending*>(&event); std::cout << "XrEventDataReferenceSpaceChangePending for " << _enum_to_string(referenceSpaceChangePending.referenceSpaceType) << std::endl; break; } default: break; } } return true; } bool OpenXrApplication::pollActions(vector<ActionState> & actionStates){ // sync actions XrActiveActionSet activeActionSet = {xr_action_set, XR_NULL_PATH}; XrActionsSyncInfo syncInfo = {XR_TYPE_ACTIONS_SYNC_INFO}; syncInfo.countActiveActionSets = 1; syncInfo.activeActionSets = &activeActionSet; xr_result = xrSyncActions(xr_session, &syncInfo); if(!xrCheckResult(xr_instance, xr_result, "xrSyncActions")) return false; XrActionStateGetInfo getInfo = {XR_TYPE_ACTION_STATE_GET_INFO}; getInfo.next = nullptr; getInfo.subactionPath = XR_NULL_PATH; // boolean XrActionStateBoolean actionStateBoolean = {XR_TYPE_ACTION_STATE_BOOLEAN}; for(size_t i = 0; i < xr_actions.aBoolean.size(); i++){ getInfo.action = xr_actions.aBoolean[i].action; xr_result = xrGetActionStateBoolean(xr_session, &getInfo, &actionStateBoolean); if(!xrCheckResult(xr_instance, xr_result, "xrGetActionStateBoolean")) return false; if(actionStateBoolean.isActive && actionStateBoolean.changedSinceLastSync){ ActionState state; state.type = XR_ACTION_TYPE_BOOLEAN_INPUT; state.path = xr_actions.aBoolean[i].stringPath.c_str(); state.isActive = actionStateBoolean.isActive; state.stateBool = (bool)actionStateBoolean.currentState; actionStates.push_back(state); } } // float XrActionStateFloat actionStateFloat = {XR_TYPE_ACTION_STATE_FLOAT}; for(size_t i = 0; i < xr_actions.aFloat.size(); i++){ getInfo.action = xr_actions.aFloat[i].action; xr_result = xrGetActionStateFloat(xr_session, &getInfo, &actionStateFloat); if(!xrCheckResult(xr_instance, xr_result, "xrGetActionStateFloat")) return false; if(actionStateFloat.isActive && actionStateFloat.changedSinceLastSync){ ActionState state; state.type = XR_ACTION_TYPE_FLOAT_INPUT; state.path = xr_actions.aFloat[i].stringPath.c_str(); state.isActive = actionStateFloat.isActive; state.stateFloat = actionStateFloat.currentState; actionStates.push_back(state); } } // vector2f XrActionStateVector2f actionStateVector2f = {XR_TYPE_ACTION_STATE_VECTOR2F}; for(size_t i = 0; i < xr_actions.aVector2f.size(); i++){ getInfo.action = xr_actions.aVector2f[i].action; xr_result = xrGetActionStateVector2f(xr_session, &getInfo, &actionStateVector2f); if(!xrCheckResult(xr_instance, xr_result, "xrGetActionStateVector2f")) return false; if(actionStateVector2f.isActive && actionStateVector2f.changedSinceLastSync){ ActionState state; state.type = XR_ACTION_TYPE_VECTOR2F_INPUT; state.path = xr_actions.aVector2f[i].stringPath.c_str(); state.isActive = actionStateVector2f.isActive; state.stateVectorX = actionStateVector2f.currentState.x; state.stateVectorY = actionStateVector2f.currentState.y; actionStates.push_back(state); } } // pose XrActionStatePose actionStatePose = {XR_TYPE_ACTION_STATE_POSE}; for(size_t i = 0; i < xr_actions.aPose.size(); i++){ getInfo.action = xr_actions.aPose[i].action; xr_result = xrGetActionStatePose(xr_session, &getInfo, &actionStatePose); if(!xrCheckResult(xr_instance, xr_result, "xrGetActionStatePose")) return false; if(actionStatePose.isActive){ ActionState state; state.type = XR_ACTION_TYPE_POSE_INPUT; state.path = xr_actions.aPose[i].stringPath.c_str(); state.isActive = actionStatePose.isActive; actionStates.push_back(state); } } return true; } bool OpenXrApplication::renderViews(XrReferenceSpaceType referenceSpaceType, vector<ActionPoseState> & actionPoseStates){ xr_graphics_handler.acquireContext(xr_graphics_binding, "xrWaitFrame"); XrFrameWaitInfo frameWaitInfo = {XR_TYPE_FRAME_WAIT_INFO}; XrFrameState frameState = {XR_TYPE_FRAME_STATE}; xr_result = xrWaitFrame(xr_session, &frameWaitInfo, &frameState); if(!xrCheckResult(xr_instance, xr_result, "xrWaitFrame")) return false; XrFrameBeginInfo frameBeginInfo = {XR_TYPE_FRAME_BEGIN_INFO}; xr_result = xrBeginFrame(xr_session, &frameBeginInfo); if(!xrCheckResult(xr_instance, xr_result, "xrBeginFrame")) return false; // locate actions XrSpaceLocation spaceLocation = {XR_TYPE_SPACE_LOCATION}; for(size_t i = 0; i < xr_actions.aPose.size(); i++){ XrSpace actionPoseSpace; if(xr_actions.aPose[i].referenceSpaceType == XR_REFERENCE_SPACE_TYPE_VIEW) actionPoseSpace = xr_space_view; else if(xr_actions.aPose[i].referenceSpaceType == XR_REFERENCE_SPACE_TYPE_LOCAL) actionPoseSpace = xr_space_local; else if(xr_actions.aPose[i].referenceSpaceType == XR_REFERENCE_SPACE_TYPE_STAGE) actionPoseSpace = xr_space_stage; else{ std::cout << "[WARNING] Invalid reference space (" << xr_actions.aPose[i].referenceSpaceType << ") for " << xr_actions.aPose[i].stringPath << std::endl; continue; } xr_result = xrLocateSpace(xr_actions.aPose[i].space, actionPoseSpace, frameState.predictedDisplayTime, &spaceLocation); if(!xrCheckResult(xr_instance, xr_result, "xrLocateSpace")) return false; ActionPoseState state; state.type = XR_ACTION_TYPE_POSE_INPUT; state.path = xr_actions.aPose[i].stringPath.c_str(); state.isActive = false; if((spaceLocation.locationFlags & XR_VIEW_STATE_POSITION_VALID_BIT) != 0 || (spaceLocation.locationFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) != 0){ state.isActive = true; state.pose = spaceLocation.pose; } actionPoseStates.push_back(state); } vector<XrCompositionLayerBaseHeader*> layers; XrCompositionLayerProjection layer = {XR_TYPE_COMPOSITION_LAYER_PROJECTION}; vector<XrCompositionLayerProjectionView> projectionLayerViews; if(frameState.shouldRender == XR_TRUE){ // locate views vector<XrView> views(xr_view_configuration_views.size(), {XR_TYPE_VIEW}); XrViewState viewState = {XR_TYPE_VIEW_STATE}; uint32_t viewCountOutput; XrViewLocateInfo viewLocateInfo = {XR_TYPE_VIEW_LOCATE_INFO}; viewLocateInfo.viewConfigurationType = configViewConfigurationType; viewLocateInfo.displayTime = frameState.predictedDisplayTime; if(referenceSpaceType == XR_REFERENCE_SPACE_TYPE_VIEW){ viewLocateInfo.space = xr_space_view; xr_result = xrLocateViews(xr_session, &viewLocateInfo, &viewState, (uint32_t)views.size(), &viewCountOutput, views.data()); if(!xrCheckResult(xr_instance, xr_result, "xrLocateViews (XR_REFERENCE_SPACE_TYPE_VIEW)")) return false; if((viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0 || (viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0) std::cout << "Invalid location view for XR_REFERENCE_SPACE_TYPE_VIEW" << std::endl; } else if(referenceSpaceType == XR_REFERENCE_SPACE_TYPE_LOCAL){ viewLocateInfo.space = xr_space_local; xr_result = xrLocateViews(xr_session, &viewLocateInfo, &viewState, (uint32_t)views.size(), &viewCountOutput, views.data()); if(!xrCheckResult(xr_instance, xr_result, "xrLocateViews (XR_REFERENCE_SPACE_TYPE_LOCAL)")) return false; if((viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0 || (viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0) std::cout << "Invalid location view for XR_REFERENCE_SPACE_TYPE_LOCAL" << std::endl; } else if(referenceSpaceType == XR_REFERENCE_SPACE_TYPE_STAGE){ viewLocateInfo.space = xr_space_stage; xr_result = xrLocateViews(xr_session, &viewLocateInfo, &viewState, (uint32_t)views.size(), &viewCountOutput, views.data()); if(!xrCheckResult(xr_instance, xr_result, "xrLocateViews (XR_REFERENCE_SPACE_TYPE_STAGE)")) return false; if((viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0 || (viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0) std::cout << "Invalid location view for XR_REFERENCE_SPACE_TYPE_STAGE" << std::endl; } else{ std::cout << "Invalid reference space type (" << referenceSpaceType << ")" << std::endl; return false; } // call render callback to get frames if(renderCallback) renderCallback(views.size(), views.data(), xr_view_configuration_views.data()); else if(renderCallbackFunction) renderCallbackFunction(views.size(), views, xr_view_configuration_views); // TODO: render if there are images // render view to the appropriate part of the swapchain image projectionLayerViews.resize(viewCountOutput); for(uint32_t i = 0; i < viewCountOutput; i++){ // Each view has a separate swapchain which is acquired, rendered to, and released const SwapchainHandler viewSwapchain = xr_swapchains_handlers[i]; XrSwapchainImageAcquireInfo acquireInfo{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO}; uint32_t swapchainImageIndex; xr_result = xrAcquireSwapchainImage(viewSwapchain.handle, &acquireInfo, &swapchainImageIndex); if(!xrCheckResult(xr_instance, xr_result, "xrAcquireSwapchainImage")) return false; xr_graphics_handler.acquireContext(xr_graphics_binding, "xrAcquireSwapchainImage"); XrSwapchainImageWaitInfo waitInfo = {XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; waitInfo.timeout = XR_INFINITE_DURATION; xr_result = xrWaitSwapchainImage(viewSwapchain.handle, &waitInfo); if(!xrCheckResult(xr_instance, xr_result, "xrWaitSwapchainImage")) return false; xr_graphics_handler.acquireContext(xr_graphics_binding, "xrWaitSwapchainImage"); projectionLayerViews[i] = {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}; projectionLayerViews[i].pose = views[i].pose; projectionLayerViews[i].fov = views[i].fov; projectionLayerViews[i].subImage.swapchain = viewSwapchain.handle; projectionLayerViews[i].subImage.imageRect.offset = {0, 0}; projectionLayerViews[i].subImage.imageRect.extent = {viewSwapchain.width, viewSwapchain.height}; // render frame if((renderCallback || renderCallbackFunction) && (xr_frames_width[i] && xr_frames_height[i])){ const XrSwapchainImageBaseHeader* const swapchainImage = (XrSwapchainImageBaseHeader*)&viewSwapchain.images[swapchainImageIndex]; // FIXME: use format (vulkan: 43, opengl: 34842) // xr_graphics_handler.renderView(projectionLayerViews[i], swapchainImage, 43); xr_graphics_handler.renderViewFromImage(projectionLayerViews[i], swapchainImage, 43, xr_frames_width[i], xr_frames_height[i], xr_frames_data[i], xr_frames_is_rgba); cleanFrames(); } XrSwapchainImageReleaseInfo releaseInfo{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO}; xr_result = xrReleaseSwapchainImage(viewSwapchain.handle, &releaseInfo); if(!xrCheckResult(xr_instance, xr_result, "xrReleaseSwapchainImage")) return false; } if(referenceSpaceType == XR_REFERENCE_SPACE_TYPE_VIEW) layer.space = xr_space_view; else if(referenceSpaceType == XR_REFERENCE_SPACE_TYPE_LOCAL) layer.space = xr_space_local; else if(referenceSpaceType == XR_REFERENCE_SPACE_TYPE_STAGE) layer.space = xr_space_stage; layer.viewCount = (uint32_t)projectionLayerViews.size(); layer.views = projectionLayerViews.data(); layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(&layer)); } // end frame XrFrameEndInfo frameEndInfo{XR_TYPE_FRAME_END_INFO}; frameEndInfo.displayTime = frameState.predictedDisplayTime; frameEndInfo.environmentBlendMode = environmentBlendMode; frameEndInfo.layerCount = (uint32_t)layers.size(); frameEndInfo.layers = layers.data(); xr_result = xrEndFrame(xr_session, &frameEndInfo); if(!xrCheckResult(xr_instance, xr_result, "xrEndFrame")) return false; return true; } bool OpenXrApplication::addAction(string stringPath, XrActionType actionType, XrReferenceSpaceType referenceSpaceType){ XrPath path; XrAction action; xrStringToPath(xr_instance, stringPath.c_str(), &path); string actionName = ""; string localizedActionName = ""; if(actionType == XR_ACTION_TYPE_BOOLEAN_INPUT) actionName = "action_boolean_" + std::to_string(xr_actions.aBoolean.size()); else if(actionType == XR_ACTION_TYPE_FLOAT_INPUT) actionName = "action_float_" + std::to_string(xr_actions.aFloat.size()); else if(actionType == XR_ACTION_TYPE_VECTOR2F_INPUT) actionName = "action_vector2f_" + std::to_string(xr_actions.aVector2f.size()); else if(actionType == XR_ACTION_TYPE_POSE_INPUT) actionName = "action_pose_" + std::to_string(xr_actions.aPose.size()); else if(actionType == XR_ACTION_TYPE_VIBRATION_OUTPUT) actionName = "action_vibration_" + std::to_string(xr_actions.aVibration.size()); localizedActionName = "localized_" + actionName; XrActionCreateInfo actionInfo = {XR_TYPE_ACTION_CREATE_INFO}; actionInfo.actionType = actionType; strcpy(actionInfo.actionName, actionName.c_str()); strcpy(actionInfo.localizedActionName, localizedActionName.c_str()); actionInfo.countSubactionPaths = 0; actionInfo.subactionPaths = nullptr; xr_result = xrCreateAction(xr_action_set, &actionInfo, &action); if(!xrCheckResult(xr_instance, xr_result, "xrCreateAction")) return false; if(actionType == XR_ACTION_TYPE_BOOLEAN_INPUT){ Action actionPackage; actionPackage.action = action; actionPackage.path = path; actionPackage.stringPath = stringPath; xr_actions.aBoolean.push_back(actionPackage); } else if(actionType == XR_ACTION_TYPE_FLOAT_INPUT){ Action actionPackage; actionPackage.action = action; actionPackage.path = path; actionPackage.stringPath = stringPath; xr_actions.aFloat.push_back(actionPackage); } else if(actionType == XR_ACTION_TYPE_VECTOR2F_INPUT){ Action actionPackage; actionPackage.action = action; actionPackage.path = path; actionPackage.stringPath = stringPath; xr_actions.aVector2f.push_back(actionPackage); } else if(actionType == XR_ACTION_TYPE_POSE_INPUT){ ActionPose actionPackage; actionPackage.action = action; actionPackage.path = path; actionPackage.stringPath = stringPath; actionPackage.referenceSpaceType = referenceSpaceType; xr_actions.aPose.push_back(actionPackage); } else if(actionType == XR_ACTION_TYPE_VIBRATION_OUTPUT){ Action actionPackage; actionPackage.action = action; actionPackage.path = path; actionPackage.stringPath = stringPath; xr_actions.aVibration.push_back(actionPackage); } return true; } bool OpenXrApplication::applyHapticFeedback(string stringPath, XrHapticBaseHeader * hapticFeedback){ for(size_t i = 0; i < xr_actions.aVibration.size(); i++) if(!xr_actions.aVibration[i].stringPath.compare(stringPath)){ XrHapticActionInfo hapticActionInfo = {XR_TYPE_HAPTIC_ACTION_INFO}; hapticActionInfo.action = xr_actions.aVibration[i].action; hapticActionInfo.subactionPath = XR_NULL_PATH; xr_result = xrApplyHapticFeedback(xr_session, &hapticActionInfo, hapticFeedback); if(!xrCheckResult(xr_instance, xr_result, "xrApplyHapticFeedback")) return false; return true; } return false; } bool OpenXrApplication::stopHapticFeedback(string stringPath){ for(size_t i = 0; i < xr_actions.aVibration.size(); i++) if(!xr_actions.aVibration[i].stringPath.compare(stringPath)){ XrHapticActionInfo hapticActionInfo = {XR_TYPE_HAPTIC_ACTION_INFO}; hapticActionInfo.action = xr_actions.aVibration[i].action; hapticActionInfo.subactionPath = XR_NULL_PATH; xr_result = xrStopHapticFeedback(xr_session, &hapticActionInfo); if(!xrCheckResult(xr_instance, xr_result, "xrStopHapticFeedback")) return false; return true; } return false; } bool OpenXrApplication::setFrameByIndex(int index, int width, int height, void * frame, bool rgba){ if(index < 0 || (size_t)index >= xr_frames_data.size()) return false; xr_frames_width[index] = width; xr_frames_height[index] = height; xr_frames_data[index] = frame; xr_frames_is_rgba = rgba; return true; } #ifdef APPLICATION int main(){ OpenXrApplication * app = new OpenXrApplication(); vector<ActionPoseState> requestedActionPoseStates; // create instance string applicationName = "Omniverse (VR)"; string engineName = "OpenXR Engine"; vector<string> requestedApiLayers = { "XR_APILAYER_LUNARG_core_validation" }; vector<string> requestedExtensions = { #ifdef XR_USE_GRAPHICS_API_VULKAN #ifdef APP_USE_VULKAN2 XR_KHR_VULKAN_ENABLE2_EXTENSION_NAME, #else XR_KHR_VULKAN_ENABLE_EXTENSION_NAME, #endif #endif #ifdef XR_USE_GRAPHICS_API_OPENGL XR_KHR_OPENGL_ENABLE_EXTENSION_NAME, #endif }; app->createInstance(applicationName, engineName, requestedApiLayers, requestedExtensions); app->getSystem(XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, XR_ENVIRONMENT_BLEND_MODE_OPAQUE, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO); app->createSession(); bool exitRenderLoop = false; #ifdef XR_USE_GRAPHICS_API_OPENGL SDL_Event sdl_event; #endif while(true){ #ifdef XR_USE_GRAPHICS_API_OPENGL while(SDL_PollEvent(&sdl_event)) if (sdl_event.type == SDL_QUIT || (sdl_event.type == SDL_KEYDOWN && sdl_event.key.keysym.sym == SDLK_ESCAPE)) return 0; #endif app->pollEvents(&exitRenderLoop); if(exitRenderLoop) break; if(app->isSessionRunning()){ vector<ActionState> requestedActionStates; app->pollActions(requestedActionStates); app->renderViews(XR_REFERENCE_SPACE_TYPE_LOCAL, requestedActionPoseStates); } else{ // Throttle loop since xrWaitFrame won't be called. // std::this_thread::sleep_for(std::chrono::milliseconds(250)); } } return 0; } #endif #ifdef CTYPES extern "C" { OpenXrApplication * openXrApplication(){ return new OpenXrApplication(); } bool destroy(OpenXrApplication * app){ return app->destroy(); } // utils bool isSessionRunning(OpenXrApplication * app){ return app->isSessionRunning(); } bool getViewConfigurationViews(OpenXrApplication * app, XrViewConfigurationView * views, int viewsLength){ if((size_t)viewsLength != app->getViewConfigurationViewsSize()) return false; vector<XrViewConfigurationView> viewConfigurationView = app->getViewConfigurationViews(); for(size_t i = 0; i < viewConfigurationView.size(); i++) views[i] = viewConfigurationView[i]; return true; } int getViewConfigurationViewsSize(OpenXrApplication * app){ return app->getViewConfigurationViewsSize(); } // setup app bool createInstance(OpenXrApplication * app, const char * applicationName, const char * engineName, const char ** apiLayers, int apiLayersLength, const char ** extensions, int extensionsLength){ vector<string> requestedApiLayers; for(int i = 0; i < apiLayersLength; i++) requestedApiLayers.push_back(apiLayers[i]); vector<string> requestedExtensions; for(int i = 0; i < extensionsLength; i++) requestedExtensions.push_back(extensions[i]); return app->createInstance(applicationName, engineName, requestedApiLayers, requestedExtensions); } bool getSystem(OpenXrApplication * app, int formFactor, int blendMode, int configurationType){ return app->getSystem(XrFormFactor(formFactor), XrEnvironmentBlendMode(blendMode), XrViewConfigurationType(configurationType)); } bool createSession(OpenXrApplication * app){ return app->createSession(); } // actions bool addAction(OpenXrApplication * app, const char * stringPath, int actionType, int referenceSpaceType){ return app->addAction(stringPath, XrActionType(actionType), XrReferenceSpaceType(referenceSpaceType)); } bool applyHapticFeedback(OpenXrApplication * app, const char * stringPath, float amplitude, int64_t duration, float frequency){ XrHapticVibration vibration = {XR_TYPE_HAPTIC_VIBRATION}; vibration.amplitude = amplitude; vibration.duration = XrDuration(duration); vibration.frequency = frequency; return app->applyHapticFeedback(stringPath, (XrHapticBaseHeader*)&vibration); } bool stopHapticFeedback(OpenXrApplication * app, const char * stringPath){ return app->stopHapticFeedback(stringPath); } // poll data bool pollEvents(OpenXrApplication * app, bool * exitLoop){ return app->pollEvents(exitLoop); } bool pollActions(OpenXrApplication * app, ActionState * actionStates, int actionStatesLength){ vector<ActionState> requestedActionStates; bool status = app->pollActions(requestedActionStates); if(requestedActionStates.size() <= actionStatesLength) for(size_t i = 0; i < requestedActionStates.size(); i++) actionStates[i] = requestedActionStates[i]; return status; } // render bool renderViews(OpenXrApplication * app, int referenceSpaceType, ActionPoseState * actionPoseStates, int actionPoseStatesLength){ vector<ActionPoseState> requestedActionPoseStates; bool status = app->renderViews(XrReferenceSpaceType(referenceSpaceType), requestedActionPoseStates); if(requestedActionPoseStates.size() <= actionPoseStatesLength) for(size_t i = 0; i < requestedActionPoseStates.size(); i++) actionPoseStates[i] = requestedActionPoseStates[i]; return status; } // render utilities void setRenderCallback(OpenXrApplication * app, void (*callback)(int, XrView*, XrViewConfigurationView*)){ app->setRenderCallbackFromPointer(callback); } bool setFrames(OpenXrApplication * app, int leftWidth, int leftHeight, void * leftData, int rightWidth, int rightHeight, void * rightData, bool rgba){ if(app->getViewConfigurationViewsSize() == 1) return app->setFrameByIndex(0, leftWidth, leftHeight, leftData, rgba); else if(app->getViewConfigurationViewsSize() == 2){ bool status = app->setFrameByIndex(0, leftWidth, leftHeight, leftData, rgba); return status && app->setFrameByIndex(1, rightWidth, rightHeight, rightData, rgba); } return false; } } #endif
100,211
C++
41.426757
259
0.716967
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/pybind11_ext.py
import os import sys from distutils.core import setup from pybind11.setup_helpers import Pybind11Extension, build_ext # OV python (kit\python\include) if sys.platform == 'win32': python_library_dir = os.path.join(os.path.dirname(sys.executable), "include") elif sys.platform == 'linux': python_library_dir = os.path.join(os.path.dirname(sys.executable), "..", "lib") if not os.path.exists(python_library_dir): raise Exception("OV Python library directory not found: {}".format(python_library_dir)) ext_modules = [ Pybind11Extension("xrlib_p", ["pybind11_wrapper.cpp"], include_dirs=[os.path.join(os.getcwd(), "thirdparty", "openxr", "include"), os.path.join(os.getcwd(), "thirdparty", "opengl", "include"), os.path.join(os.getcwd(), "thirdparty", "sdl2")], library_dirs=[os.path.join(os.getcwd(), "thirdparty", "openxr", "lib"), os.path.join(os.getcwd(), "thirdparty", "opengl", "lib"), os.path.join(os.getcwd(), "thirdparty", "sdl2", "lib"), python_library_dir], libraries=["openxr_loader", "GL", "SDL2"], extra_link_args=["-Wl,-rpath=./bin"], undef_macros=["CTYPES", "APPLICATION"]), ] setup( name = 'openxr-lib', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
1,527
Python
40.297296
97
0.542895
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/BUILD.md
## Building from source ### Linux Install the following packages or dependencies ```bash sudo apt install libx11-dev ``` Setup a python environment. Change the `OV_APP` variable to the name of the Omniverse app you want to build for ```bash cd src/semu.xr.openxr/sources ~/.local/share/ov/pkg/OV_APP/kit/python/bin/python3 -m venv env # source the env source env/bin/activate # install required packages python -m pip install --upgrade pip python -m pip install pybind11 python -m pip install Cython ``` #### Build CTYPES-based library ```bash cd src/semu.xr.openxr/sources bash compile_ctypes.bash ``` #### Build PYBIND11-based library ```bash cd src/semu.xr.openxr/sources bash compile_pybind11.bash ```
717
Markdown
17.410256
111
0.74198
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/openxr/include/openxr/openxr_platform.h
#ifndef OPENXR_PLATFORM_H_ #define OPENXR_PLATFORM_H_ 1 /* ** Copyright (c) 2017-2021, The Khronos Group Inc. ** ** SPDX-License-Identifier: Apache-2.0 OR MIT */ /* ** This header is generated from the Khronos OpenXR XML API Registry. ** */ #include "openxr.h" #ifdef __cplusplus extern "C" { #endif #ifdef XR_USE_PLATFORM_ANDROID #define XR_KHR_android_thread_settings 1 #define XR_KHR_android_thread_settings_SPEC_VERSION 5 #define XR_KHR_ANDROID_THREAD_SETTINGS_EXTENSION_NAME "XR_KHR_android_thread_settings" typedef enum XrAndroidThreadTypeKHR { XR_ANDROID_THREAD_TYPE_APPLICATION_MAIN_KHR = 1, XR_ANDROID_THREAD_TYPE_APPLICATION_WORKER_KHR = 2, XR_ANDROID_THREAD_TYPE_RENDERER_MAIN_KHR = 3, XR_ANDROID_THREAD_TYPE_RENDERER_WORKER_KHR = 4, XR_ANDROID_THREAD_TYPE_MAX_ENUM_KHR = 0x7FFFFFFF } XrAndroidThreadTypeKHR; typedef XrResult (XRAPI_PTR *PFN_xrSetAndroidApplicationThreadKHR)(XrSession session, XrAndroidThreadTypeKHR threadType, uint32_t threadId); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrSetAndroidApplicationThreadKHR( XrSession session, XrAndroidThreadTypeKHR threadType, uint32_t threadId); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_PLATFORM_ANDROID */ #ifdef XR_USE_PLATFORM_ANDROID #define XR_KHR_android_surface_swapchain 1 #define XR_KHR_android_surface_swapchain_SPEC_VERSION 4 #define XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME "XR_KHR_android_surface_swapchain" typedef XrResult (XRAPI_PTR *PFN_xrCreateSwapchainAndroidSurfaceKHR)(XrSession session, const XrSwapchainCreateInfo* info, XrSwapchain* swapchain, jobject* surface); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreateSwapchainAndroidSurfaceKHR( XrSession session, const XrSwapchainCreateInfo* info, XrSwapchain* swapchain, jobject* surface); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_PLATFORM_ANDROID */ #ifdef XR_USE_PLATFORM_ANDROID #define XR_KHR_android_create_instance 1 #define XR_KHR_android_create_instance_SPEC_VERSION 3 #define XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME "XR_KHR_android_create_instance" // XrInstanceCreateInfoAndroidKHR extends XrInstanceCreateInfo typedef struct XrInstanceCreateInfoAndroidKHR { XrStructureType type; const void* XR_MAY_ALIAS next; void* XR_MAY_ALIAS applicationVM; void* XR_MAY_ALIAS applicationActivity; } XrInstanceCreateInfoAndroidKHR; #endif /* XR_USE_PLATFORM_ANDROID */ #ifdef XR_USE_GRAPHICS_API_VULKAN #define XR_KHR_vulkan_swapchain_format_list 1 #define XR_KHR_vulkan_swapchain_format_list_SPEC_VERSION 4 #define XR_KHR_VULKAN_SWAPCHAIN_FORMAT_LIST_EXTENSION_NAME "XR_KHR_vulkan_swapchain_format_list" typedef struct XrVulkanSwapchainFormatListCreateInfoKHR { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t viewFormatCount; const VkFormat* viewFormats; } XrVulkanSwapchainFormatListCreateInfoKHR; #endif /* XR_USE_GRAPHICS_API_VULKAN */ #ifdef XR_USE_GRAPHICS_API_OPENGL #define XR_KHR_opengl_enable 1 #define XR_KHR_opengl_enable_SPEC_VERSION 10 #define XR_KHR_OPENGL_ENABLE_EXTENSION_NAME "XR_KHR_opengl_enable" #ifdef XR_USE_PLATFORM_WIN32 // XrGraphicsBindingOpenGLWin32KHR extends XrSessionCreateInfo typedef struct XrGraphicsBindingOpenGLWin32KHR { XrStructureType type; const void* XR_MAY_ALIAS next; HDC hDC; HGLRC hGLRC; } XrGraphicsBindingOpenGLWin32KHR; #endif // XR_USE_PLATFORM_WIN32 #ifdef XR_USE_PLATFORM_XLIB // XrGraphicsBindingOpenGLXlibKHR extends XrSessionCreateInfo typedef struct XrGraphicsBindingOpenGLXlibKHR { XrStructureType type; const void* XR_MAY_ALIAS next; Display* xDisplay; uint32_t visualid; GLXFBConfig glxFBConfig; GLXDrawable glxDrawable; GLXContext glxContext; } XrGraphicsBindingOpenGLXlibKHR; #endif // XR_USE_PLATFORM_XLIB #ifdef XR_USE_PLATFORM_XCB // XrGraphicsBindingOpenGLXcbKHR extends XrSessionCreateInfo typedef struct XrGraphicsBindingOpenGLXcbKHR { XrStructureType type; const void* XR_MAY_ALIAS next; xcb_connection_t* connection; uint32_t screenNumber; xcb_glx_fbconfig_t fbconfigid; xcb_visualid_t visualid; xcb_glx_drawable_t glxDrawable; xcb_glx_context_t glxContext; } XrGraphicsBindingOpenGLXcbKHR; #endif // XR_USE_PLATFORM_XCB #ifdef XR_USE_PLATFORM_WAYLAND // XrGraphicsBindingOpenGLWaylandKHR extends XrSessionCreateInfo typedef struct XrGraphicsBindingOpenGLWaylandKHR { XrStructureType type; const void* XR_MAY_ALIAS next; struct wl_display* display; } XrGraphicsBindingOpenGLWaylandKHR; #endif // XR_USE_PLATFORM_WAYLAND typedef struct XrSwapchainImageOpenGLKHR { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t image; } XrSwapchainImageOpenGLKHR; typedef struct XrGraphicsRequirementsOpenGLKHR { XrStructureType type; void* XR_MAY_ALIAS next; XrVersion minApiVersionSupported; XrVersion maxApiVersionSupported; } XrGraphicsRequirementsOpenGLKHR; typedef XrResult (XRAPI_PTR *PFN_xrGetOpenGLGraphicsRequirementsKHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsOpenGLKHR* graphicsRequirements); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrGetOpenGLGraphicsRequirementsKHR( XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsOpenGLKHR* graphicsRequirements); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_GRAPHICS_API_OPENGL */ #ifdef XR_USE_GRAPHICS_API_OPENGL_ES #define XR_KHR_opengl_es_enable 1 #define XR_KHR_opengl_es_enable_SPEC_VERSION 8 #define XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME "XR_KHR_opengl_es_enable" #ifdef XR_USE_PLATFORM_ANDROID // XrGraphicsBindingOpenGLESAndroidKHR extends XrSessionCreateInfo typedef struct XrGraphicsBindingOpenGLESAndroidKHR { XrStructureType type; const void* XR_MAY_ALIAS next; EGLDisplay display; EGLConfig config; EGLContext context; } XrGraphicsBindingOpenGLESAndroidKHR; #endif // XR_USE_PLATFORM_ANDROID typedef struct XrSwapchainImageOpenGLESKHR { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t image; } XrSwapchainImageOpenGLESKHR; typedef struct XrGraphicsRequirementsOpenGLESKHR { XrStructureType type; void* XR_MAY_ALIAS next; XrVersion minApiVersionSupported; XrVersion maxApiVersionSupported; } XrGraphicsRequirementsOpenGLESKHR; typedef XrResult (XRAPI_PTR *PFN_xrGetOpenGLESGraphicsRequirementsKHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsOpenGLESKHR* graphicsRequirements); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrGetOpenGLESGraphicsRequirementsKHR( XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsOpenGLESKHR* graphicsRequirements); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_GRAPHICS_API_OPENGL_ES */ #ifdef XR_USE_GRAPHICS_API_VULKAN #define XR_KHR_vulkan_enable 1 #define XR_KHR_vulkan_enable_SPEC_VERSION 8 #define XR_KHR_VULKAN_ENABLE_EXTENSION_NAME "XR_KHR_vulkan_enable" // XrGraphicsBindingVulkanKHR extends XrSessionCreateInfo typedef struct XrGraphicsBindingVulkanKHR { XrStructureType type; const void* XR_MAY_ALIAS next; VkInstance instance; VkPhysicalDevice physicalDevice; VkDevice device; uint32_t queueFamilyIndex; uint32_t queueIndex; } XrGraphicsBindingVulkanKHR; typedef struct XrSwapchainImageVulkanKHR { XrStructureType type; void* XR_MAY_ALIAS next; VkImage image; } XrSwapchainImageVulkanKHR; typedef struct XrGraphicsRequirementsVulkanKHR { XrStructureType type; void* XR_MAY_ALIAS next; XrVersion minApiVersionSupported; XrVersion maxApiVersionSupported; } XrGraphicsRequirementsVulkanKHR; typedef XrResult (XRAPI_PTR *PFN_xrGetVulkanInstanceExtensionsKHR)(XrInstance instance, XrSystemId systemId, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, char* buffer); typedef XrResult (XRAPI_PTR *PFN_xrGetVulkanDeviceExtensionsKHR)(XrInstance instance, XrSystemId systemId, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, char* buffer); typedef XrResult (XRAPI_PTR *PFN_xrGetVulkanGraphicsDeviceKHR)(XrInstance instance, XrSystemId systemId, VkInstance vkInstance, VkPhysicalDevice* vkPhysicalDevice); typedef XrResult (XRAPI_PTR *PFN_xrGetVulkanGraphicsRequirementsKHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsVulkanKHR* graphicsRequirements); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrGetVulkanInstanceExtensionsKHR( XrInstance instance, XrSystemId systemId, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, char* buffer); XRAPI_ATTR XrResult XRAPI_CALL xrGetVulkanDeviceExtensionsKHR( XrInstance instance, XrSystemId systemId, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, char* buffer); XRAPI_ATTR XrResult XRAPI_CALL xrGetVulkanGraphicsDeviceKHR( XrInstance instance, XrSystemId systemId, VkInstance vkInstance, VkPhysicalDevice* vkPhysicalDevice); XRAPI_ATTR XrResult XRAPI_CALL xrGetVulkanGraphicsRequirementsKHR( XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsVulkanKHR* graphicsRequirements); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_GRAPHICS_API_VULKAN */ #ifdef XR_USE_GRAPHICS_API_D3D11 #define XR_KHR_D3D11_enable 1 #define XR_KHR_D3D11_enable_SPEC_VERSION 8 #define XR_KHR_D3D11_ENABLE_EXTENSION_NAME "XR_KHR_D3D11_enable" // XrGraphicsBindingD3D11KHR extends XrSessionCreateInfo typedef struct XrGraphicsBindingD3D11KHR { XrStructureType type; const void* XR_MAY_ALIAS next; ID3D11Device* device; } XrGraphicsBindingD3D11KHR; typedef struct XrSwapchainImageD3D11KHR { XrStructureType type; void* XR_MAY_ALIAS next; ID3D11Texture2D* texture; } XrSwapchainImageD3D11KHR; typedef struct XrGraphicsRequirementsD3D11KHR { XrStructureType type; void* XR_MAY_ALIAS next; LUID adapterLuid; D3D_FEATURE_LEVEL minFeatureLevel; } XrGraphicsRequirementsD3D11KHR; typedef XrResult (XRAPI_PTR *PFN_xrGetD3D11GraphicsRequirementsKHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsD3D11KHR* graphicsRequirements); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrGetD3D11GraphicsRequirementsKHR( XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsD3D11KHR* graphicsRequirements); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_GRAPHICS_API_D3D11 */ #ifdef XR_USE_GRAPHICS_API_D3D12 #define XR_KHR_D3D12_enable 1 #define XR_KHR_D3D12_enable_SPEC_VERSION 8 #define XR_KHR_D3D12_ENABLE_EXTENSION_NAME "XR_KHR_D3D12_enable" // XrGraphicsBindingD3D12KHR extends XrSessionCreateInfo typedef struct XrGraphicsBindingD3D12KHR { XrStructureType type; const void* XR_MAY_ALIAS next; ID3D12Device* device; ID3D12CommandQueue* queue; } XrGraphicsBindingD3D12KHR; typedef struct XrSwapchainImageD3D12KHR { XrStructureType type; void* XR_MAY_ALIAS next; ID3D12Resource* texture; } XrSwapchainImageD3D12KHR; typedef struct XrGraphicsRequirementsD3D12KHR { XrStructureType type; void* XR_MAY_ALIAS next; LUID adapterLuid; D3D_FEATURE_LEVEL minFeatureLevel; } XrGraphicsRequirementsD3D12KHR; typedef XrResult (XRAPI_PTR *PFN_xrGetD3D12GraphicsRequirementsKHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsD3D12KHR* graphicsRequirements); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrGetD3D12GraphicsRequirementsKHR( XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsD3D12KHR* graphicsRequirements); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_GRAPHICS_API_D3D12 */ #ifdef XR_USE_PLATFORM_WIN32 #define XR_KHR_win32_convert_performance_counter_time 1 #define XR_KHR_win32_convert_performance_counter_time_SPEC_VERSION 1 #define XR_KHR_WIN32_CONVERT_PERFORMANCE_COUNTER_TIME_EXTENSION_NAME "XR_KHR_win32_convert_performance_counter_time" typedef XrResult (XRAPI_PTR *PFN_xrConvertWin32PerformanceCounterToTimeKHR)(XrInstance instance, const LARGE_INTEGER* performanceCounter, XrTime* time); typedef XrResult (XRAPI_PTR *PFN_xrConvertTimeToWin32PerformanceCounterKHR)(XrInstance instance, XrTime time, LARGE_INTEGER* performanceCounter); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrConvertWin32PerformanceCounterToTimeKHR( XrInstance instance, const LARGE_INTEGER* performanceCounter, XrTime* time); XRAPI_ATTR XrResult XRAPI_CALL xrConvertTimeToWin32PerformanceCounterKHR( XrInstance instance, XrTime time, LARGE_INTEGER* performanceCounter); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_PLATFORM_WIN32 */ #ifdef XR_USE_TIMESPEC #define XR_KHR_convert_timespec_time 1 #define XR_KHR_convert_timespec_time_SPEC_VERSION 1 #define XR_KHR_CONVERT_TIMESPEC_TIME_EXTENSION_NAME "XR_KHR_convert_timespec_time" typedef XrResult (XRAPI_PTR *PFN_xrConvertTimespecTimeToTimeKHR)(XrInstance instance, const struct timespec* timespecTime, XrTime* time); typedef XrResult (XRAPI_PTR *PFN_xrConvertTimeToTimespecTimeKHR)(XrInstance instance, XrTime time, struct timespec* timespecTime); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrConvertTimespecTimeToTimeKHR( XrInstance instance, const struct timespec* timespecTime, XrTime* time); XRAPI_ATTR XrResult XRAPI_CALL xrConvertTimeToTimespecTimeKHR( XrInstance instance, XrTime time, struct timespec* timespecTime); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_TIMESPEC */ #ifdef XR_USE_PLATFORM_ANDROID #define XR_KHR_loader_init_android 1 #define XR_KHR_loader_init_android_SPEC_VERSION 1 #define XR_KHR_LOADER_INIT_ANDROID_EXTENSION_NAME "XR_KHR_loader_init_android" typedef struct XrLoaderInitInfoAndroidKHR { XrStructureType type; const void* XR_MAY_ALIAS next; void* XR_MAY_ALIAS applicationVM; void* XR_MAY_ALIAS applicationContext; } XrLoaderInitInfoAndroidKHR; #endif /* XR_USE_PLATFORM_ANDROID */ #ifdef XR_USE_GRAPHICS_API_VULKAN #define XR_KHR_vulkan_enable2 1 #define XR_KHR_vulkan_enable2_SPEC_VERSION 2 #define XR_KHR_VULKAN_ENABLE2_EXTENSION_NAME "XR_KHR_vulkan_enable2" typedef XrFlags64 XrVulkanInstanceCreateFlagsKHR; // Flag bits for XrVulkanInstanceCreateFlagsKHR typedef XrFlags64 XrVulkanDeviceCreateFlagsKHR; // Flag bits for XrVulkanDeviceCreateFlagsKHR typedef struct XrVulkanInstanceCreateInfoKHR { XrStructureType type; const void* XR_MAY_ALIAS next; XrSystemId systemId; XrVulkanInstanceCreateFlagsKHR createFlags; PFN_vkGetInstanceProcAddr pfnGetInstanceProcAddr; const VkInstanceCreateInfo* vulkanCreateInfo; const VkAllocationCallbacks* vulkanAllocator; } XrVulkanInstanceCreateInfoKHR; typedef struct XrVulkanDeviceCreateInfoKHR { XrStructureType type; const void* XR_MAY_ALIAS next; XrSystemId systemId; XrVulkanDeviceCreateFlagsKHR createFlags; PFN_vkGetInstanceProcAddr pfnGetInstanceProcAddr; VkPhysicalDevice vulkanPhysicalDevice; const VkDeviceCreateInfo* vulkanCreateInfo; const VkAllocationCallbacks* vulkanAllocator; } XrVulkanDeviceCreateInfoKHR; typedef XrGraphicsBindingVulkanKHR XrGraphicsBindingVulkan2KHR; typedef struct XrVulkanGraphicsDeviceGetInfoKHR { XrStructureType type; const void* XR_MAY_ALIAS next; XrSystemId systemId; VkInstance vulkanInstance; } XrVulkanGraphicsDeviceGetInfoKHR; typedef XrSwapchainImageVulkanKHR XrSwapchainImageVulkan2KHR; typedef XrGraphicsRequirementsVulkanKHR XrGraphicsRequirementsVulkan2KHR; typedef XrResult (XRAPI_PTR *PFN_xrCreateVulkanInstanceKHR)(XrInstance instance, const XrVulkanInstanceCreateInfoKHR* createInfo, VkInstance* vulkanInstance, VkResult* vulkanResult); typedef XrResult (XRAPI_PTR *PFN_xrCreateVulkanDeviceKHR)(XrInstance instance, const XrVulkanDeviceCreateInfoKHR* createInfo, VkDevice* vulkanDevice, VkResult* vulkanResult); typedef XrResult (XRAPI_PTR *PFN_xrGetVulkanGraphicsDevice2KHR)(XrInstance instance, const XrVulkanGraphicsDeviceGetInfoKHR* getInfo, VkPhysicalDevice* vulkanPhysicalDevice); typedef XrResult (XRAPI_PTR *PFN_xrGetVulkanGraphicsRequirements2KHR)(XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsVulkanKHR* graphicsRequirements); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreateVulkanInstanceKHR( XrInstance instance, const XrVulkanInstanceCreateInfoKHR* createInfo, VkInstance* vulkanInstance, VkResult* vulkanResult); XRAPI_ATTR XrResult XRAPI_CALL xrCreateVulkanDeviceKHR( XrInstance instance, const XrVulkanDeviceCreateInfoKHR* createInfo, VkDevice* vulkanDevice, VkResult* vulkanResult); XRAPI_ATTR XrResult XRAPI_CALL xrGetVulkanGraphicsDevice2KHR( XrInstance instance, const XrVulkanGraphicsDeviceGetInfoKHR* getInfo, VkPhysicalDevice* vulkanPhysicalDevice); XRAPI_ATTR XrResult XRAPI_CALL xrGetVulkanGraphicsRequirements2KHR( XrInstance instance, XrSystemId systemId, XrGraphicsRequirementsVulkanKHR* graphicsRequirements); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_GRAPHICS_API_VULKAN */ #ifdef XR_USE_PLATFORM_EGL #define XR_MNDX_egl_enable 1 #define XR_MNDX_egl_enable_SPEC_VERSION 1 #define XR_MNDX_EGL_ENABLE_EXTENSION_NAME "XR_MNDX_egl_enable" // XrGraphicsBindingEGLMNDX extends XrSessionCreateInfo typedef struct XrGraphicsBindingEGLMNDX { XrStructureType type; const void* XR_MAY_ALIAS next; PFNEGLGETPROCADDRESSPROC getProcAddress; EGLDisplay display; EGLConfig config; EGLContext context; } XrGraphicsBindingEGLMNDX; #endif /* XR_USE_PLATFORM_EGL */ #ifdef XR_USE_PLATFORM_WIN32 #define XR_MSFT_perception_anchor_interop 1 #define XR_MSFT_perception_anchor_interop_SPEC_VERSION 1 #define XR_MSFT_PERCEPTION_ANCHOR_INTEROP_EXTENSION_NAME "XR_MSFT_perception_anchor_interop" typedef XrResult (XRAPI_PTR *PFN_xrCreateSpatialAnchorFromPerceptionAnchorMSFT)(XrSession session, IUnknown* perceptionAnchor, XrSpatialAnchorMSFT* anchor); typedef XrResult (XRAPI_PTR *PFN_xrTryGetPerceptionAnchorFromSpatialAnchorMSFT)(XrSession session, XrSpatialAnchorMSFT anchor, IUnknown** perceptionAnchor); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreateSpatialAnchorFromPerceptionAnchorMSFT( XrSession session, IUnknown* perceptionAnchor, XrSpatialAnchorMSFT* anchor); XRAPI_ATTR XrResult XRAPI_CALL xrTryGetPerceptionAnchorFromSpatialAnchorMSFT( XrSession session, XrSpatialAnchorMSFT anchor, IUnknown** perceptionAnchor); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_PLATFORM_WIN32 */ #ifdef XR_USE_PLATFORM_WIN32 #define XR_MSFT_holographic_window_attachment 1 #define XR_MSFT_holographic_window_attachment_SPEC_VERSION 1 #define XR_MSFT_HOLOGRAPHIC_WINDOW_ATTACHMENT_EXTENSION_NAME "XR_MSFT_holographic_window_attachment" #ifdef XR_USE_PLATFORM_WIN32 // XrHolographicWindowAttachmentMSFT extends XrSessionCreateInfo typedef struct XrHolographicWindowAttachmentMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; IUnknown* holographicSpace; IUnknown* coreWindow; } XrHolographicWindowAttachmentMSFT; #endif // XR_USE_PLATFORM_WIN32 #endif /* XR_USE_PLATFORM_WIN32 */ #ifdef XR_USE_PLATFORM_ANDROID #define XR_FB_android_surface_swapchain_create 1 #define XR_FB_android_surface_swapchain_create_SPEC_VERSION 1 #define XR_FB_ANDROID_SURFACE_SWAPCHAIN_CREATE_EXTENSION_NAME "XR_FB_android_surface_swapchain_create" typedef XrFlags64 XrAndroidSurfaceSwapchainFlagsFB; // Flag bits for XrAndroidSurfaceSwapchainFlagsFB static const XrAndroidSurfaceSwapchainFlagsFB XR_ANDROID_SURFACE_SWAPCHAIN_SYNCHRONOUS_BIT_FB = 0x00000001; static const XrAndroidSurfaceSwapchainFlagsFB XR_ANDROID_SURFACE_SWAPCHAIN_USE_TIMESTAMPS_BIT_FB = 0x00000002; #ifdef XR_USE_PLATFORM_ANDROID // XrAndroidSurfaceSwapchainCreateInfoFB extends XrSwapchainCreateInfo typedef struct XrAndroidSurfaceSwapchainCreateInfoFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrAndroidSurfaceSwapchainFlagsFB createFlags; } XrAndroidSurfaceSwapchainCreateInfoFB; #endif // XR_USE_PLATFORM_ANDROID #endif /* XR_USE_PLATFORM_ANDROID */ #ifdef XR_USE_PLATFORM_WIN32 #define XR_OCULUS_audio_device_guid 1 #define XR_OCULUS_audio_device_guid_SPEC_VERSION 1 #define XR_OCULUS_AUDIO_DEVICE_GUID_EXTENSION_NAME "XR_OCULUS_audio_device_guid" #define XR_MAX_AUDIO_DEVICE_STR_SIZE_OCULUS 128 typedef XrResult (XRAPI_PTR *PFN_xrGetAudioOutputDeviceGuidOculus)(XrInstance instance, wchar_t buffer[XR_MAX_AUDIO_DEVICE_STR_SIZE_OCULUS]); typedef XrResult (XRAPI_PTR *PFN_xrGetAudioInputDeviceGuidOculus)(XrInstance instance, wchar_t buffer[XR_MAX_AUDIO_DEVICE_STR_SIZE_OCULUS]); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrGetAudioOutputDeviceGuidOculus( XrInstance instance, wchar_t buffer[XR_MAX_AUDIO_DEVICE_STR_SIZE_OCULUS]); XRAPI_ATTR XrResult XRAPI_CALL xrGetAudioInputDeviceGuidOculus( XrInstance instance, wchar_t buffer[XR_MAX_AUDIO_DEVICE_STR_SIZE_OCULUS]); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #endif /* XR_USE_PLATFORM_WIN32 */ #ifdef XR_USE_GRAPHICS_API_VULKAN #define XR_FB_foveation_vulkan 1 #define XR_FB_foveation_vulkan_SPEC_VERSION 1 #define XR_FB_FOVEATION_VULKAN_EXTENSION_NAME "XR_FB_foveation_vulkan" // XrSwapchainImageFoveationVulkanFB extends XrSwapchainImageVulkanKHR typedef struct XrSwapchainImageFoveationVulkanFB { XrStructureType type; void* XR_MAY_ALIAS next; VkImage image; uint32_t width; uint32_t height; } XrSwapchainImageFoveationVulkanFB; #endif /* XR_USE_GRAPHICS_API_VULKAN */ #ifdef XR_USE_PLATFORM_ANDROID #define XR_FB_swapchain_update_state_android_surface 1 #define XR_FB_swapchain_update_state_android_surface_SPEC_VERSION 1 #define XR_FB_SWAPCHAIN_UPDATE_STATE_ANDROID_SURFACE_EXTENSION_NAME "XR_FB_swapchain_update_state_android_surface" #ifdef XR_USE_PLATFORM_ANDROID typedef struct XrSwapchainStateAndroidSurfaceDimensionsFB { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t width; uint32_t height; } XrSwapchainStateAndroidSurfaceDimensionsFB; #endif // XR_USE_PLATFORM_ANDROID #endif /* XR_USE_PLATFORM_ANDROID */ #ifdef XR_USE_GRAPHICS_API_OPENGL_ES #define XR_FB_swapchain_update_state_opengl_es 1 #define XR_FB_swapchain_update_state_opengl_es_SPEC_VERSION 1 #define XR_FB_SWAPCHAIN_UPDATE_STATE_OPENGL_ES_EXTENSION_NAME "XR_FB_swapchain_update_state_opengl_es" #ifdef XR_USE_GRAPHICS_API_OPENGL_ES typedef struct XrSwapchainStateSamplerOpenGLESFB { XrStructureType type; void* XR_MAY_ALIAS next; EGLenum minFilter; EGLenum magFilter; EGLenum wrapModeS; EGLenum wrapModeT; EGLenum swizzleRed; EGLenum swizzleGreen; EGLenum swizzleBlue; EGLenum swizzleAlpha; float maxAnisotropy; XrColor4f borderColor; } XrSwapchainStateSamplerOpenGLESFB; #endif // XR_USE_GRAPHICS_API_OPENGL_ES #endif /* XR_USE_GRAPHICS_API_OPENGL_ES */ #ifdef XR_USE_GRAPHICS_API_VULKAN #define XR_FB_swapchain_update_state_vulkan 1 #define XR_FB_swapchain_update_state_vulkan_SPEC_VERSION 1 #define XR_FB_SWAPCHAIN_UPDATE_STATE_VULKAN_EXTENSION_NAME "XR_FB_swapchain_update_state_vulkan" #ifdef XR_USE_GRAPHICS_API_VULKAN typedef struct XrSwapchainStateSamplerVulkanFB { XrStructureType type; void* XR_MAY_ALIAS next; VkFilter minFilter; VkFilter magFilter; VkSamplerMipmapMode mipmapMode; VkSamplerAddressMode wrapModeS; VkSamplerAddressMode wrapModeT; VkComponentSwizzle swizzleRed; VkComponentSwizzle swizzleGreen; VkComponentSwizzle swizzleBlue; VkComponentSwizzle swizzleAlpha; float maxAnisotropy; XrColor4f borderColor; } XrSwapchainStateSamplerVulkanFB; #endif // XR_USE_GRAPHICS_API_VULKAN #endif /* XR_USE_GRAPHICS_API_VULKAN */ #ifdef __cplusplus } #endif #endif
28,343
C
40.928994
260
0.686236
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/openxr/include/openxr/openxr_platform_defines.h
/* ** Copyright (c) 2017-2021, The Khronos Group Inc. ** ** SPDX-License-Identifier: Apache-2.0 OR MIT */ #ifndef OPENXR_PLATFORM_DEFINES_H_ #define OPENXR_PLATFORM_DEFINES_H_ 1 #ifdef __cplusplus extern "C" { #endif /* Platform-specific calling convention macros. * * Platforms should define these so that OpenXR clients call OpenXR functions * with the same calling conventions that the OpenXR implementation expects. * * XRAPI_ATTR - Placed before the return type in function declarations. * Useful for C++11 and GCC/Clang-style function attribute syntax. * XRAPI_CALL - Placed after the return type in function declarations. * Useful for MSVC-style calling convention syntax. * XRAPI_PTR - Placed between the '(' and '*' in function pointer types. * * Function declaration: XRAPI_ATTR void XRAPI_CALL xrFunction(void); * Function pointer type: typedef void (XRAPI_PTR *PFN_xrFunction)(void); */ #if defined(_WIN32) #define XRAPI_ATTR // On Windows, functions use the stdcall convention #define XRAPI_CALL __stdcall #define XRAPI_PTR XRAPI_CALL #elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH < 7 #error "API not supported for the 'armeabi' NDK ABI" #elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7 && defined(__ARM_32BIT_STATE) // On Android 32-bit ARM targets, functions use the "hardfloat" // calling convention, i.e. float parameters are passed in registers. This // is true even if the rest of the application passes floats on the stack, // as it does by default when compiling for the armeabi-v7a NDK ABI. #define XRAPI_ATTR __attribute__((pcs("aapcs-vfp"))) #define XRAPI_CALL #define XRAPI_PTR XRAPI_ATTR #else // On other platforms, use the default calling convention #define XRAPI_ATTR #define XRAPI_CALL #define XRAPI_PTR #endif #include <stddef.h> #if !defined(XR_NO_STDINT_H) #if defined(_MSC_VER) && (_MSC_VER < 1600) typedef signed __int8 int8_t; typedef unsigned __int8 uint8_t; typedef signed __int16 int16_t; typedef unsigned __int16 uint16_t; typedef signed __int32 int32_t; typedef unsigned __int32 uint32_t; typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif #endif // !defined( XR_NO_STDINT_H ) // XR_PTR_SIZE (in bytes) #if (defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)) #define XR_PTR_SIZE 8 #else #define XR_PTR_SIZE 4 #endif // Needed so we can use clang __has_feature portably. #if !defined(XR_COMPILER_HAS_FEATURE) #if defined(__clang__) #define XR_COMPILER_HAS_FEATURE(x) __has_feature(x) #else #define XR_COMPILER_HAS_FEATURE(x) 0 #endif #endif // Identifies if the current compiler has C++11 support enabled. // Does not by itself identify if any given C++11 feature is present. #if !defined(XR_CPP11_ENABLED) && defined(__cplusplus) #if defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__) #define XR_CPP11_ENABLED 1 #elif defined(_MSC_VER) && (_MSC_VER >= 1600) #define XR_CPP11_ENABLED 1 #elif (__cplusplus >= 201103L) // 201103 is the first C++11 version. #define XR_CPP11_ENABLED 1 #endif #endif // Identifies if the current compiler supports C++11 nullptr. #if !defined(XR_CPP_NULLPTR_SUPPORTED) #if defined(XR_CPP11_ENABLED) && \ ((defined(__clang__) && XR_COMPILER_HAS_FEATURE(cxx_nullptr)) || \ (defined(__GNUC__) && (((__GNUC__ * 1000) + __GNUC_MINOR__) >= 4006)) || \ (defined(_MSC_VER) && (_MSC_VER >= 1600)) || \ (defined(__EDG_VERSION__) && (__EDG_VERSION__ >= 403))) #define XR_CPP_NULLPTR_SUPPORTED 1 #endif #endif #ifdef __cplusplus } #endif #endif
3,793
C
33.18018
200
0.679146
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/openxr/include/openxr/openxr.h
#ifndef OPENXR_H_ #define OPENXR_H_ 1 /* ** Copyright (c) 2017-2021, The Khronos Group Inc. ** ** SPDX-License-Identifier: Apache-2.0 OR MIT */ /* ** This header is generated from the Khronos OpenXR XML API Registry. ** */ #ifdef __cplusplus extern "C" { #endif #define XR_VERSION_1_0 1 #include "openxr_platform_defines.h" #define XR_MAKE_VERSION(major, minor, patch) \ ((((major) & 0xffffULL) << 48) | (((minor) & 0xffffULL) << 32) | ((patch) & 0xffffffffULL)) // OpenXR current version number. #define XR_CURRENT_API_VERSION XR_MAKE_VERSION(1, 0, 20) #define XR_VERSION_MAJOR(version) (uint16_t)(((uint64_t)(version) >> 48)& 0xffffULL) #define XR_VERSION_MINOR(version) (uint16_t)(((uint64_t)(version) >> 32) & 0xffffULL) #define XR_VERSION_PATCH(version) (uint32_t)((uint64_t)(version) & 0xffffffffULL) #if !defined(XR_NULL_HANDLE) #if (XR_PTR_SIZE == 8) && XR_CPP_NULLPTR_SUPPORTED #define XR_NULL_HANDLE nullptr #else #define XR_NULL_HANDLE 0 #endif #endif #define XR_NULL_SYSTEM_ID 0 #define XR_NULL_PATH 0 #define XR_SUCCEEDED(result) ((result) >= 0) #define XR_FAILED(result) ((result) < 0) #define XR_UNQUALIFIED_SUCCESS(result) ((result) == 0) #define XR_NO_DURATION 0 #define XR_INFINITE_DURATION 0x7fffffffffffffffLL #define XR_MIN_HAPTIC_DURATION -1 #define XR_FREQUENCY_UNSPECIFIED 0 #define XR_MAX_EVENT_DATA_SIZE sizeof(XrEventDataBuffer) #if !defined(XR_MAY_ALIAS) #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4)) #define XR_MAY_ALIAS __attribute__((__may_alias__)) #else #define XR_MAY_ALIAS #endif #endif #if !defined(XR_DEFINE_HANDLE) #if (XR_PTR_SIZE == 8) #define XR_DEFINE_HANDLE(object) typedef struct object##_T* object; #else #define XR_DEFINE_HANDLE(object) typedef uint64_t object; #endif #endif #if !defined(XR_DEFINE_ATOM) #define XR_DEFINE_ATOM(object) typedef uint64_t object; #endif typedef uint64_t XrVersion; typedef uint64_t XrFlags64; XR_DEFINE_ATOM(XrSystemId) typedef uint32_t XrBool32; XR_DEFINE_ATOM(XrPath) typedef int64_t XrTime; typedef int64_t XrDuration; XR_DEFINE_HANDLE(XrInstance) XR_DEFINE_HANDLE(XrSession) XR_DEFINE_HANDLE(XrSpace) XR_DEFINE_HANDLE(XrAction) XR_DEFINE_HANDLE(XrSwapchain) XR_DEFINE_HANDLE(XrActionSet) #define XR_TRUE 1 #define XR_FALSE 0 #define XR_MAX_EXTENSION_NAME_SIZE 128 #define XR_MAX_API_LAYER_NAME_SIZE 256 #define XR_MAX_API_LAYER_DESCRIPTION_SIZE 256 #define XR_MAX_SYSTEM_NAME_SIZE 256 #define XR_MAX_APPLICATION_NAME_SIZE 128 #define XR_MAX_ENGINE_NAME_SIZE 128 #define XR_MAX_RUNTIME_NAME_SIZE 128 #define XR_MAX_PATH_LENGTH 256 #define XR_MAX_STRUCTURE_NAME_SIZE 64 #define XR_MAX_RESULT_STRING_SIZE 64 #define XR_MIN_COMPOSITION_LAYERS_SUPPORTED 16 #define XR_MAX_ACTION_SET_NAME_SIZE 64 #define XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE 128 #define XR_MAX_ACTION_NAME_SIZE 64 #define XR_MAX_LOCALIZED_ACTION_NAME_SIZE 128 typedef enum XrResult { XR_SUCCESS = 0, XR_TIMEOUT_EXPIRED = 1, XR_SESSION_LOSS_PENDING = 3, XR_EVENT_UNAVAILABLE = 4, XR_SPACE_BOUNDS_UNAVAILABLE = 7, XR_SESSION_NOT_FOCUSED = 8, XR_FRAME_DISCARDED = 9, XR_ERROR_VALIDATION_FAILURE = -1, XR_ERROR_RUNTIME_FAILURE = -2, XR_ERROR_OUT_OF_MEMORY = -3, XR_ERROR_API_VERSION_UNSUPPORTED = -4, XR_ERROR_INITIALIZATION_FAILED = -6, XR_ERROR_FUNCTION_UNSUPPORTED = -7, XR_ERROR_FEATURE_UNSUPPORTED = -8, XR_ERROR_EXTENSION_NOT_PRESENT = -9, XR_ERROR_LIMIT_REACHED = -10, XR_ERROR_SIZE_INSUFFICIENT = -11, XR_ERROR_HANDLE_INVALID = -12, XR_ERROR_INSTANCE_LOST = -13, XR_ERROR_SESSION_RUNNING = -14, XR_ERROR_SESSION_NOT_RUNNING = -16, XR_ERROR_SESSION_LOST = -17, XR_ERROR_SYSTEM_INVALID = -18, XR_ERROR_PATH_INVALID = -19, XR_ERROR_PATH_COUNT_EXCEEDED = -20, XR_ERROR_PATH_FORMAT_INVALID = -21, XR_ERROR_PATH_UNSUPPORTED = -22, XR_ERROR_LAYER_INVALID = -23, XR_ERROR_LAYER_LIMIT_EXCEEDED = -24, XR_ERROR_SWAPCHAIN_RECT_INVALID = -25, XR_ERROR_SWAPCHAIN_FORMAT_UNSUPPORTED = -26, XR_ERROR_ACTION_TYPE_MISMATCH = -27, XR_ERROR_SESSION_NOT_READY = -28, XR_ERROR_SESSION_NOT_STOPPING = -29, XR_ERROR_TIME_INVALID = -30, XR_ERROR_REFERENCE_SPACE_UNSUPPORTED = -31, XR_ERROR_FILE_ACCESS_ERROR = -32, XR_ERROR_FILE_CONTENTS_INVALID = -33, XR_ERROR_FORM_FACTOR_UNSUPPORTED = -34, XR_ERROR_FORM_FACTOR_UNAVAILABLE = -35, XR_ERROR_API_LAYER_NOT_PRESENT = -36, XR_ERROR_CALL_ORDER_INVALID = -37, XR_ERROR_GRAPHICS_DEVICE_INVALID = -38, XR_ERROR_POSE_INVALID = -39, XR_ERROR_INDEX_OUT_OF_RANGE = -40, XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED = -41, XR_ERROR_ENVIRONMENT_BLEND_MODE_UNSUPPORTED = -42, XR_ERROR_NAME_DUPLICATED = -44, XR_ERROR_NAME_INVALID = -45, XR_ERROR_ACTIONSET_NOT_ATTACHED = -46, XR_ERROR_ACTIONSETS_ALREADY_ATTACHED = -47, XR_ERROR_LOCALIZED_NAME_DUPLICATED = -48, XR_ERROR_LOCALIZED_NAME_INVALID = -49, XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING = -50, XR_ERROR_RUNTIME_UNAVAILABLE = -51, XR_ERROR_ANDROID_THREAD_SETTINGS_ID_INVALID_KHR = -1000003000, XR_ERROR_ANDROID_THREAD_SETTINGS_FAILURE_KHR = -1000003001, XR_ERROR_CREATE_SPATIAL_ANCHOR_FAILED_MSFT = -1000039001, XR_ERROR_SECONDARY_VIEW_CONFIGURATION_TYPE_NOT_ENABLED_MSFT = -1000053000, XR_ERROR_CONTROLLER_MODEL_KEY_INVALID_MSFT = -1000055000, XR_ERROR_REPROJECTION_MODE_UNSUPPORTED_MSFT = -1000066000, XR_ERROR_COMPUTE_NEW_SCENE_NOT_COMPLETED_MSFT = -1000097000, XR_ERROR_SCENE_COMPONENT_ID_INVALID_MSFT = -1000097001, XR_ERROR_SCENE_COMPONENT_TYPE_MISMATCH_MSFT = -1000097002, XR_ERROR_SCENE_MESH_BUFFER_ID_INVALID_MSFT = -1000097003, XR_ERROR_SCENE_COMPUTE_FEATURE_INCOMPATIBLE_MSFT = -1000097004, XR_ERROR_SCENE_COMPUTE_CONSISTENCY_MISMATCH_MSFT = -1000097005, XR_ERROR_DISPLAY_REFRESH_RATE_UNSUPPORTED_FB = -1000101000, XR_ERROR_COLOR_SPACE_UNSUPPORTED_FB = -1000108000, XR_ERROR_UNEXPECTED_STATE_PASSTHROUGH_FB = -1000118000, XR_ERROR_FEATURE_ALREADY_CREATED_PASSTHROUGH_FB = -1000118001, XR_ERROR_FEATURE_REQUIRED_PASSTHROUGH_FB = -1000118002, XR_ERROR_NOT_PERMITTED_PASSTHROUGH_FB = -1000118003, XR_ERROR_INSUFFICIENT_RESOURCES_PASSTHROUGH_FB = -1000118004, XR_ERROR_UNKNOWN_PASSTHROUGH_FB = -1000118050, XR_ERROR_MARKER_NOT_TRACKED_VARJO = -1000124000, XR_ERROR_MARKER_ID_INVALID_VARJO = -1000124001, XR_ERROR_SPATIAL_ANCHOR_NAME_NOT_FOUND_MSFT = -1000142001, XR_ERROR_SPATIAL_ANCHOR_NAME_INVALID_MSFT = -1000142002, XR_RESULT_MAX_ENUM = 0x7FFFFFFF } XrResult; typedef enum XrStructureType { XR_TYPE_UNKNOWN = 0, XR_TYPE_API_LAYER_PROPERTIES = 1, XR_TYPE_EXTENSION_PROPERTIES = 2, XR_TYPE_INSTANCE_CREATE_INFO = 3, XR_TYPE_SYSTEM_GET_INFO = 4, XR_TYPE_SYSTEM_PROPERTIES = 5, XR_TYPE_VIEW_LOCATE_INFO = 6, XR_TYPE_VIEW = 7, XR_TYPE_SESSION_CREATE_INFO = 8, XR_TYPE_SWAPCHAIN_CREATE_INFO = 9, XR_TYPE_SESSION_BEGIN_INFO = 10, XR_TYPE_VIEW_STATE = 11, XR_TYPE_FRAME_END_INFO = 12, XR_TYPE_HAPTIC_VIBRATION = 13, XR_TYPE_EVENT_DATA_BUFFER = 16, XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING = 17, XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED = 18, XR_TYPE_ACTION_STATE_BOOLEAN = 23, XR_TYPE_ACTION_STATE_FLOAT = 24, XR_TYPE_ACTION_STATE_VECTOR2F = 25, XR_TYPE_ACTION_STATE_POSE = 27, XR_TYPE_ACTION_SET_CREATE_INFO = 28, XR_TYPE_ACTION_CREATE_INFO = 29, XR_TYPE_INSTANCE_PROPERTIES = 32, XR_TYPE_FRAME_WAIT_INFO = 33, XR_TYPE_COMPOSITION_LAYER_PROJECTION = 35, XR_TYPE_COMPOSITION_LAYER_QUAD = 36, XR_TYPE_REFERENCE_SPACE_CREATE_INFO = 37, XR_TYPE_ACTION_SPACE_CREATE_INFO = 38, XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING = 40, XR_TYPE_VIEW_CONFIGURATION_VIEW = 41, XR_TYPE_SPACE_LOCATION = 42, XR_TYPE_SPACE_VELOCITY = 43, XR_TYPE_FRAME_STATE = 44, XR_TYPE_VIEW_CONFIGURATION_PROPERTIES = 45, XR_TYPE_FRAME_BEGIN_INFO = 46, XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW = 48, XR_TYPE_EVENT_DATA_EVENTS_LOST = 49, XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING = 51, XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED = 52, XR_TYPE_INTERACTION_PROFILE_STATE = 53, XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO = 55, XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO = 56, XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO = 57, XR_TYPE_ACTION_STATE_GET_INFO = 58, XR_TYPE_HAPTIC_ACTION_INFO = 59, XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO = 60, XR_TYPE_ACTIONS_SYNC_INFO = 61, XR_TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO = 62, XR_TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO = 63, XR_TYPE_COMPOSITION_LAYER_CUBE_KHR = 1000006000, XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR = 1000008000, XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR = 1000010000, XR_TYPE_VULKAN_SWAPCHAIN_FORMAT_LIST_CREATE_INFO_KHR = 1000014000, XR_TYPE_EVENT_DATA_PERF_SETTINGS_EXT = 1000015000, XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR = 1000017000, XR_TYPE_COMPOSITION_LAYER_EQUIRECT_KHR = 1000018000, XR_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT = 1000019000, XR_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT = 1000019001, XR_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT = 1000019002, XR_TYPE_DEBUG_UTILS_LABEL_EXT = 1000019003, XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR = 1000023000, XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR = 1000023001, XR_TYPE_GRAPHICS_BINDING_OPENGL_XCB_KHR = 1000023002, XR_TYPE_GRAPHICS_BINDING_OPENGL_WAYLAND_KHR = 1000023003, XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR = 1000023004, XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR = 1000023005, XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR = 1000024001, XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR = 1000024002, XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR = 1000024003, XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR = 1000025000, XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR = 1000025001, XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR = 1000025002, XR_TYPE_GRAPHICS_BINDING_D3D11_KHR = 1000027000, XR_TYPE_SWAPCHAIN_IMAGE_D3D11_KHR = 1000027001, XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR = 1000027002, XR_TYPE_GRAPHICS_BINDING_D3D12_KHR = 1000028000, XR_TYPE_SWAPCHAIN_IMAGE_D3D12_KHR = 1000028001, XR_TYPE_GRAPHICS_REQUIREMENTS_D3D12_KHR = 1000028002, XR_TYPE_SYSTEM_EYE_GAZE_INTERACTION_PROPERTIES_EXT = 1000030000, XR_TYPE_EYE_GAZE_SAMPLE_TIME_EXT = 1000030001, XR_TYPE_VISIBILITY_MASK_KHR = 1000031000, XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR = 1000031001, XR_TYPE_SESSION_CREATE_INFO_OVERLAY_EXTX = 1000033000, XR_TYPE_EVENT_DATA_MAIN_SESSION_VISIBILITY_CHANGED_EXTX = 1000033003, XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR = 1000034000, XR_TYPE_SPATIAL_ANCHOR_CREATE_INFO_MSFT = 1000039000, XR_TYPE_SPATIAL_ANCHOR_SPACE_CREATE_INFO_MSFT = 1000039001, XR_TYPE_COMPOSITION_LAYER_IMAGE_LAYOUT_FB = 1000040000, XR_TYPE_COMPOSITION_LAYER_ALPHA_BLEND_FB = 1000041001, XR_TYPE_VIEW_CONFIGURATION_DEPTH_RANGE_EXT = 1000046000, XR_TYPE_GRAPHICS_BINDING_EGL_MNDX = 1000048004, XR_TYPE_SPATIAL_GRAPH_NODE_SPACE_CREATE_INFO_MSFT = 1000049000, XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT = 1000051000, XR_TYPE_HAND_TRACKER_CREATE_INFO_EXT = 1000051001, XR_TYPE_HAND_JOINTS_LOCATE_INFO_EXT = 1000051002, XR_TYPE_HAND_JOINT_LOCATIONS_EXT = 1000051003, XR_TYPE_HAND_JOINT_VELOCITIES_EXT = 1000051004, XR_TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT = 1000052000, XR_TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT = 1000052001, XR_TYPE_HAND_MESH_UPDATE_INFO_MSFT = 1000052002, XR_TYPE_HAND_MESH_MSFT = 1000052003, XR_TYPE_HAND_POSE_TYPE_INFO_MSFT = 1000052004, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_SESSION_BEGIN_INFO_MSFT = 1000053000, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_STATE_MSFT = 1000053001, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_FRAME_STATE_MSFT = 1000053002, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_FRAME_END_INFO_MSFT = 1000053003, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_LAYER_INFO_MSFT = 1000053004, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_SWAPCHAIN_CREATE_INFO_MSFT = 1000053005, XR_TYPE_CONTROLLER_MODEL_KEY_STATE_MSFT = 1000055000, XR_TYPE_CONTROLLER_MODEL_NODE_PROPERTIES_MSFT = 1000055001, XR_TYPE_CONTROLLER_MODEL_PROPERTIES_MSFT = 1000055002, XR_TYPE_CONTROLLER_MODEL_NODE_STATE_MSFT = 1000055003, XR_TYPE_CONTROLLER_MODEL_STATE_MSFT = 1000055004, XR_TYPE_VIEW_CONFIGURATION_VIEW_FOV_EPIC = 1000059000, XR_TYPE_HOLOGRAPHIC_WINDOW_ATTACHMENT_MSFT = 1000063000, XR_TYPE_COMPOSITION_LAYER_REPROJECTION_INFO_MSFT = 1000066000, XR_TYPE_COMPOSITION_LAYER_REPROJECTION_PLANE_OVERRIDE_MSFT = 1000066001, XR_TYPE_ANDROID_SURFACE_SWAPCHAIN_CREATE_INFO_FB = 1000070000, XR_TYPE_COMPOSITION_LAYER_SECURE_CONTENT_FB = 1000072000, XR_TYPE_INTERACTION_PROFILE_ANALOG_THRESHOLD_VALVE = 1000079000, XR_TYPE_HAND_JOINTS_MOTION_RANGE_INFO_EXT = 1000080000, XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR = 1000089000, XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR = 1000090000, XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR = 1000090001, XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR = 1000090003, XR_TYPE_COMPOSITION_LAYER_EQUIRECT2_KHR = 1000091000, XR_TYPE_SCENE_OBSERVER_CREATE_INFO_MSFT = 1000097000, XR_TYPE_SCENE_CREATE_INFO_MSFT = 1000097001, XR_TYPE_NEW_SCENE_COMPUTE_INFO_MSFT = 1000097002, XR_TYPE_VISUAL_MESH_COMPUTE_LOD_INFO_MSFT = 1000097003, XR_TYPE_SCENE_COMPONENTS_MSFT = 1000097004, XR_TYPE_SCENE_COMPONENTS_GET_INFO_MSFT = 1000097005, XR_TYPE_SCENE_COMPONENT_LOCATIONS_MSFT = 1000097006, XR_TYPE_SCENE_COMPONENTS_LOCATE_INFO_MSFT = 1000097007, XR_TYPE_SCENE_OBJECTS_MSFT = 1000097008, XR_TYPE_SCENE_COMPONENT_PARENT_FILTER_INFO_MSFT = 1000097009, XR_TYPE_SCENE_OBJECT_TYPES_FILTER_INFO_MSFT = 1000097010, XR_TYPE_SCENE_PLANES_MSFT = 1000097011, XR_TYPE_SCENE_PLANE_ALIGNMENT_FILTER_INFO_MSFT = 1000097012, XR_TYPE_SCENE_MESHES_MSFT = 1000097013, XR_TYPE_SCENE_MESH_BUFFERS_GET_INFO_MSFT = 1000097014, XR_TYPE_SCENE_MESH_BUFFERS_MSFT = 1000097015, XR_TYPE_SCENE_MESH_VERTEX_BUFFER_MSFT = 1000097016, XR_TYPE_SCENE_MESH_INDICES_UINT32_MSFT = 1000097017, XR_TYPE_SCENE_MESH_INDICES_UINT16_MSFT = 1000097018, XR_TYPE_SERIALIZED_SCENE_FRAGMENT_DATA_GET_INFO_MSFT = 1000098000, XR_TYPE_SCENE_DESERIALIZE_INFO_MSFT = 1000098001, XR_TYPE_EVENT_DATA_DISPLAY_REFRESH_RATE_CHANGED_FB = 1000101000, XR_TYPE_VIVE_TRACKER_PATHS_HTCX = 1000103000, XR_TYPE_EVENT_DATA_VIVE_TRACKER_CONNECTED_HTCX = 1000103001, XR_TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB = 1000108000, XR_TYPE_HAND_TRACKING_MESH_FB = 1000110001, XR_TYPE_HAND_TRACKING_SCALE_FB = 1000110003, XR_TYPE_HAND_TRACKING_AIM_STATE_FB = 1000111001, XR_TYPE_HAND_TRACKING_CAPSULES_STATE_FB = 1000112000, XR_TYPE_FOVEATION_PROFILE_CREATE_INFO_FB = 1000114000, XR_TYPE_SWAPCHAIN_CREATE_INFO_FOVEATION_FB = 1000114001, XR_TYPE_SWAPCHAIN_STATE_FOVEATION_FB = 1000114002, XR_TYPE_FOVEATION_LEVEL_PROFILE_CREATE_INFO_FB = 1000115000, XR_TYPE_TRIANGLE_MESH_CREATE_INFO_FB = 1000117001, XR_TYPE_SYSTEM_PASSTHROUGH_PROPERTIES_FB = 1000118000, XR_TYPE_PASSTHROUGH_CREATE_INFO_FB = 1000118001, XR_TYPE_PASSTHROUGH_LAYER_CREATE_INFO_FB = 1000118002, XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_FB = 1000118003, XR_TYPE_GEOMETRY_INSTANCE_CREATE_INFO_FB = 1000118004, XR_TYPE_GEOMETRY_INSTANCE_TRANSFORM_FB = 1000118005, XR_TYPE_PASSTHROUGH_STYLE_FB = 1000118020, XR_TYPE_PASSTHROUGH_COLOR_MAP_MONO_TO_RGBA_FB = 1000118021, XR_TYPE_PASSTHROUGH_COLOR_MAP_MONO_TO_MONO_FB = 1000118022, XR_TYPE_EVENT_DATA_PASSTHROUGH_STATE_CHANGED_FB = 1000118030, XR_TYPE_BINDING_MODIFICATIONS_KHR = 1000120000, XR_TYPE_VIEW_LOCATE_FOVEATED_RENDERING_VARJO = 1000121000, XR_TYPE_FOVEATED_VIEW_CONFIGURATION_VIEW_VARJO = 1000121001, XR_TYPE_SYSTEM_FOVEATED_RENDERING_PROPERTIES_VARJO = 1000121002, XR_TYPE_COMPOSITION_LAYER_DEPTH_TEST_VARJO = 1000122000, XR_TYPE_SYSTEM_MARKER_TRACKING_PROPERTIES_VARJO = 1000124000, XR_TYPE_EVENT_DATA_MARKER_TRACKING_UPDATE_VARJO = 1000124001, XR_TYPE_MARKER_SPACE_CREATE_INFO_VARJO = 1000124002, XR_TYPE_SPATIAL_ANCHOR_PERSISTENCE_INFO_MSFT = 1000142000, XR_TYPE_SPATIAL_ANCHOR_FROM_PERSISTED_ANCHOR_CREATE_INFO_MSFT = 1000142001, XR_TYPE_SWAPCHAIN_IMAGE_FOVEATION_VULKAN_FB = 1000160000, XR_TYPE_SWAPCHAIN_STATE_ANDROID_SURFACE_DIMENSIONS_FB = 1000161000, XR_TYPE_SWAPCHAIN_STATE_SAMPLER_OPENGL_ES_FB = 1000162000, XR_TYPE_SWAPCHAIN_STATE_SAMPLER_VULKAN_FB = 1000163000, XR_TYPE_COMPOSITION_LAYER_SPACE_WARP_INFO_FB = 1000171000, XR_TYPE_SYSTEM_SPACE_WARP_PROPERTIES_FB = 1000171001, XR_TYPE_GRAPHICS_BINDING_VULKAN2_KHR = XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR, XR_TYPE_SWAPCHAIN_IMAGE_VULKAN2_KHR = XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR, XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN2_KHR = XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR, XR_STRUCTURE_TYPE_MAX_ENUM = 0x7FFFFFFF } XrStructureType; typedef enum XrFormFactor { XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY = 1, XR_FORM_FACTOR_HANDHELD_DISPLAY = 2, XR_FORM_FACTOR_MAX_ENUM = 0x7FFFFFFF } XrFormFactor; typedef enum XrViewConfigurationType { XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO = 1, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO = 2, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO = 1000037000, XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT = 1000054000, XR_VIEW_CONFIGURATION_TYPE_MAX_ENUM = 0x7FFFFFFF } XrViewConfigurationType; typedef enum XrEnvironmentBlendMode { XR_ENVIRONMENT_BLEND_MODE_OPAQUE = 1, XR_ENVIRONMENT_BLEND_MODE_ADDITIVE = 2, XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND = 3, XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM = 0x7FFFFFFF } XrEnvironmentBlendMode; typedef enum XrReferenceSpaceType { XR_REFERENCE_SPACE_TYPE_VIEW = 1, XR_REFERENCE_SPACE_TYPE_LOCAL = 2, XR_REFERENCE_SPACE_TYPE_STAGE = 3, XR_REFERENCE_SPACE_TYPE_UNBOUNDED_MSFT = 1000038000, XR_REFERENCE_SPACE_TYPE_COMBINED_EYE_VARJO = 1000121000, XR_REFERENCE_SPACE_TYPE_MAX_ENUM = 0x7FFFFFFF } XrReferenceSpaceType; typedef enum XrActionType { XR_ACTION_TYPE_BOOLEAN_INPUT = 1, XR_ACTION_TYPE_FLOAT_INPUT = 2, XR_ACTION_TYPE_VECTOR2F_INPUT = 3, XR_ACTION_TYPE_POSE_INPUT = 4, XR_ACTION_TYPE_VIBRATION_OUTPUT = 100, XR_ACTION_TYPE_MAX_ENUM = 0x7FFFFFFF } XrActionType; typedef enum XrEyeVisibility { XR_EYE_VISIBILITY_BOTH = 0, XR_EYE_VISIBILITY_LEFT = 1, XR_EYE_VISIBILITY_RIGHT = 2, XR_EYE_VISIBILITY_MAX_ENUM = 0x7FFFFFFF } XrEyeVisibility; typedef enum XrSessionState { XR_SESSION_STATE_UNKNOWN = 0, XR_SESSION_STATE_IDLE = 1, XR_SESSION_STATE_READY = 2, XR_SESSION_STATE_SYNCHRONIZED = 3, XR_SESSION_STATE_VISIBLE = 4, XR_SESSION_STATE_FOCUSED = 5, XR_SESSION_STATE_STOPPING = 6, XR_SESSION_STATE_LOSS_PENDING = 7, XR_SESSION_STATE_EXITING = 8, XR_SESSION_STATE_MAX_ENUM = 0x7FFFFFFF } XrSessionState; typedef enum XrObjectType { XR_OBJECT_TYPE_UNKNOWN = 0, XR_OBJECT_TYPE_INSTANCE = 1, XR_OBJECT_TYPE_SESSION = 2, XR_OBJECT_TYPE_SWAPCHAIN = 3, XR_OBJECT_TYPE_SPACE = 4, XR_OBJECT_TYPE_ACTION_SET = 5, XR_OBJECT_TYPE_ACTION = 6, XR_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT = 1000019000, XR_OBJECT_TYPE_SPATIAL_ANCHOR_MSFT = 1000039000, XR_OBJECT_TYPE_HAND_TRACKER_EXT = 1000051000, XR_OBJECT_TYPE_SCENE_OBSERVER_MSFT = 1000097000, XR_OBJECT_TYPE_SCENE_MSFT = 1000097001, XR_OBJECT_TYPE_FOVEATION_PROFILE_FB = 1000114000, XR_OBJECT_TYPE_TRIANGLE_MESH_FB = 1000117000, XR_OBJECT_TYPE_PASSTHROUGH_FB = 1000118000, XR_OBJECT_TYPE_PASSTHROUGH_LAYER_FB = 1000118002, XR_OBJECT_TYPE_GEOMETRY_INSTANCE_FB = 1000118004, XR_OBJECT_TYPE_SPATIAL_ANCHOR_STORE_CONNECTION_MSFT = 1000142000, XR_OBJECT_TYPE_MAX_ENUM = 0x7FFFFFFF } XrObjectType; typedef XrFlags64 XrInstanceCreateFlags; // Flag bits for XrInstanceCreateFlags typedef XrFlags64 XrSessionCreateFlags; // Flag bits for XrSessionCreateFlags typedef XrFlags64 XrSpaceVelocityFlags; // Flag bits for XrSpaceVelocityFlags static const XrSpaceVelocityFlags XR_SPACE_VELOCITY_LINEAR_VALID_BIT = 0x00000001; static const XrSpaceVelocityFlags XR_SPACE_VELOCITY_ANGULAR_VALID_BIT = 0x00000002; typedef XrFlags64 XrSpaceLocationFlags; // Flag bits for XrSpaceLocationFlags static const XrSpaceLocationFlags XR_SPACE_LOCATION_ORIENTATION_VALID_BIT = 0x00000001; static const XrSpaceLocationFlags XR_SPACE_LOCATION_POSITION_VALID_BIT = 0x00000002; static const XrSpaceLocationFlags XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT = 0x00000004; static const XrSpaceLocationFlags XR_SPACE_LOCATION_POSITION_TRACKED_BIT = 0x00000008; typedef XrFlags64 XrSwapchainCreateFlags; // Flag bits for XrSwapchainCreateFlags static const XrSwapchainCreateFlags XR_SWAPCHAIN_CREATE_PROTECTED_CONTENT_BIT = 0x00000001; static const XrSwapchainCreateFlags XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT = 0x00000002; typedef XrFlags64 XrSwapchainUsageFlags; // Flag bits for XrSwapchainUsageFlags static const XrSwapchainUsageFlags XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT = 0x00000001; static const XrSwapchainUsageFlags XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT = 0x00000002; static const XrSwapchainUsageFlags XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT = 0x00000004; static const XrSwapchainUsageFlags XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT = 0x00000008; static const XrSwapchainUsageFlags XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT = 0x00000010; static const XrSwapchainUsageFlags XR_SWAPCHAIN_USAGE_SAMPLED_BIT = 0x00000020; static const XrSwapchainUsageFlags XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT = 0x00000040; static const XrSwapchainUsageFlags XR_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT_MND = 0x00000080; static const XrSwapchainUsageFlags XR_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT_KHR = 0x00000080; // alias of XR_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT_MND typedef XrFlags64 XrCompositionLayerFlags; // Flag bits for XrCompositionLayerFlags static const XrCompositionLayerFlags XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT = 0x00000001; static const XrCompositionLayerFlags XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT = 0x00000002; static const XrCompositionLayerFlags XR_COMPOSITION_LAYER_UNPREMULTIPLIED_ALPHA_BIT = 0x00000004; typedef XrFlags64 XrViewStateFlags; // Flag bits for XrViewStateFlags static const XrViewStateFlags XR_VIEW_STATE_ORIENTATION_VALID_BIT = 0x00000001; static const XrViewStateFlags XR_VIEW_STATE_POSITION_VALID_BIT = 0x00000002; static const XrViewStateFlags XR_VIEW_STATE_ORIENTATION_TRACKED_BIT = 0x00000004; static const XrViewStateFlags XR_VIEW_STATE_POSITION_TRACKED_BIT = 0x00000008; typedef XrFlags64 XrInputSourceLocalizedNameFlags; // Flag bits for XrInputSourceLocalizedNameFlags static const XrInputSourceLocalizedNameFlags XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT = 0x00000001; static const XrInputSourceLocalizedNameFlags XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT = 0x00000002; static const XrInputSourceLocalizedNameFlags XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT = 0x00000004; typedef void (XRAPI_PTR *PFN_xrVoidFunction)(void); typedef struct XrApiLayerProperties { XrStructureType type; void* XR_MAY_ALIAS next; char layerName[XR_MAX_API_LAYER_NAME_SIZE]; XrVersion specVersion; uint32_t layerVersion; char description[XR_MAX_API_LAYER_DESCRIPTION_SIZE]; } XrApiLayerProperties; typedef struct XrExtensionProperties { XrStructureType type; void* XR_MAY_ALIAS next; char extensionName[XR_MAX_EXTENSION_NAME_SIZE]; uint32_t extensionVersion; } XrExtensionProperties; typedef struct XrApplicationInfo { char applicationName[XR_MAX_APPLICATION_NAME_SIZE]; uint32_t applicationVersion; char engineName[XR_MAX_ENGINE_NAME_SIZE]; uint32_t engineVersion; XrVersion apiVersion; } XrApplicationInfo; typedef struct XrInstanceCreateInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrInstanceCreateFlags createFlags; XrApplicationInfo applicationInfo; uint32_t enabledApiLayerCount; const char* const* enabledApiLayerNames; uint32_t enabledExtensionCount; const char* const* enabledExtensionNames; } XrInstanceCreateInfo; typedef struct XrInstanceProperties { XrStructureType type; void* XR_MAY_ALIAS next; XrVersion runtimeVersion; char runtimeName[XR_MAX_RUNTIME_NAME_SIZE]; } XrInstanceProperties; typedef struct XrEventDataBuffer { XrStructureType type; const void* XR_MAY_ALIAS next; uint8_t varying[4000]; } XrEventDataBuffer; typedef struct XrSystemGetInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrFormFactor formFactor; } XrSystemGetInfo; typedef struct XrSystemGraphicsProperties { uint32_t maxSwapchainImageHeight; uint32_t maxSwapchainImageWidth; uint32_t maxLayerCount; } XrSystemGraphicsProperties; typedef struct XrSystemTrackingProperties { XrBool32 orientationTracking; XrBool32 positionTracking; } XrSystemTrackingProperties; typedef struct XrSystemProperties { XrStructureType type; void* XR_MAY_ALIAS next; XrSystemId systemId; uint32_t vendorId; char systemName[XR_MAX_SYSTEM_NAME_SIZE]; XrSystemGraphicsProperties graphicsProperties; XrSystemTrackingProperties trackingProperties; } XrSystemProperties; typedef struct XrSessionCreateInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrSessionCreateFlags createFlags; XrSystemId systemId; } XrSessionCreateInfo; typedef struct XrVector3f { float x; float y; float z; } XrVector3f; // XrSpaceVelocity extends XrSpaceLocation typedef struct XrSpaceVelocity { XrStructureType type; void* XR_MAY_ALIAS next; XrSpaceVelocityFlags velocityFlags; XrVector3f linearVelocity; XrVector3f angularVelocity; } XrSpaceVelocity; typedef struct XrQuaternionf { float x; float y; float z; float w; } XrQuaternionf; typedef struct XrPosef { XrQuaternionf orientation; XrVector3f position; } XrPosef; typedef struct XrReferenceSpaceCreateInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrReferenceSpaceType referenceSpaceType; XrPosef poseInReferenceSpace; } XrReferenceSpaceCreateInfo; typedef struct XrExtent2Df { float width; float height; } XrExtent2Df; typedef struct XrActionSpaceCreateInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrAction action; XrPath subactionPath; XrPosef poseInActionSpace; } XrActionSpaceCreateInfo; typedef struct XrSpaceLocation { XrStructureType type; void* XR_MAY_ALIAS next; XrSpaceLocationFlags locationFlags; XrPosef pose; } XrSpaceLocation; typedef struct XrViewConfigurationProperties { XrStructureType type; void* XR_MAY_ALIAS next; XrViewConfigurationType viewConfigurationType; XrBool32 fovMutable; } XrViewConfigurationProperties; typedef struct XrViewConfigurationView { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t recommendedImageRectWidth; uint32_t maxImageRectWidth; uint32_t recommendedImageRectHeight; uint32_t maxImageRectHeight; uint32_t recommendedSwapchainSampleCount; uint32_t maxSwapchainSampleCount; } XrViewConfigurationView; typedef struct XrSwapchainCreateInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrSwapchainCreateFlags createFlags; XrSwapchainUsageFlags usageFlags; int64_t format; uint32_t sampleCount; uint32_t width; uint32_t height; uint32_t faceCount; uint32_t arraySize; uint32_t mipCount; } XrSwapchainCreateInfo; typedef struct XR_MAY_ALIAS XrSwapchainImageBaseHeader { XrStructureType type; void* XR_MAY_ALIAS next; } XrSwapchainImageBaseHeader; typedef struct XrSwapchainImageAcquireInfo { XrStructureType type; const void* XR_MAY_ALIAS next; } XrSwapchainImageAcquireInfo; typedef struct XrSwapchainImageWaitInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrDuration timeout; } XrSwapchainImageWaitInfo; typedef struct XrSwapchainImageReleaseInfo { XrStructureType type; const void* XR_MAY_ALIAS next; } XrSwapchainImageReleaseInfo; typedef struct XrSessionBeginInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrViewConfigurationType primaryViewConfigurationType; } XrSessionBeginInfo; typedef struct XrFrameWaitInfo { XrStructureType type; const void* XR_MAY_ALIAS next; } XrFrameWaitInfo; typedef struct XrFrameState { XrStructureType type; void* XR_MAY_ALIAS next; XrTime predictedDisplayTime; XrDuration predictedDisplayPeriod; XrBool32 shouldRender; } XrFrameState; typedef struct XrFrameBeginInfo { XrStructureType type; const void* XR_MAY_ALIAS next; } XrFrameBeginInfo; typedef struct XR_MAY_ALIAS XrCompositionLayerBaseHeader { XrStructureType type; const void* XR_MAY_ALIAS next; XrCompositionLayerFlags layerFlags; XrSpace space; } XrCompositionLayerBaseHeader; typedef struct XrFrameEndInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrTime displayTime; XrEnvironmentBlendMode environmentBlendMode; uint32_t layerCount; const XrCompositionLayerBaseHeader* const* layers; } XrFrameEndInfo; typedef struct XrViewLocateInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrViewConfigurationType viewConfigurationType; XrTime displayTime; XrSpace space; } XrViewLocateInfo; typedef struct XrViewState { XrStructureType type; void* XR_MAY_ALIAS next; XrViewStateFlags viewStateFlags; } XrViewState; typedef struct XrFovf { float angleLeft; float angleRight; float angleUp; float angleDown; } XrFovf; typedef struct XrView { XrStructureType type; void* XR_MAY_ALIAS next; XrPosef pose; XrFovf fov; } XrView; typedef struct XrActionSetCreateInfo { XrStructureType type; const void* XR_MAY_ALIAS next; char actionSetName[XR_MAX_ACTION_SET_NAME_SIZE]; char localizedActionSetName[XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE]; uint32_t priority; } XrActionSetCreateInfo; typedef struct XrActionCreateInfo { XrStructureType type; const void* XR_MAY_ALIAS next; char actionName[XR_MAX_ACTION_NAME_SIZE]; XrActionType actionType; uint32_t countSubactionPaths; const XrPath* subactionPaths; char localizedActionName[XR_MAX_LOCALIZED_ACTION_NAME_SIZE]; } XrActionCreateInfo; typedef struct XrActionSuggestedBinding { XrAction action; XrPath binding; } XrActionSuggestedBinding; typedef struct XrInteractionProfileSuggestedBinding { XrStructureType type; const void* XR_MAY_ALIAS next; XrPath interactionProfile; uint32_t countSuggestedBindings; const XrActionSuggestedBinding* suggestedBindings; } XrInteractionProfileSuggestedBinding; typedef struct XrSessionActionSetsAttachInfo { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t countActionSets; const XrActionSet* actionSets; } XrSessionActionSetsAttachInfo; typedef struct XrInteractionProfileState { XrStructureType type; void* XR_MAY_ALIAS next; XrPath interactionProfile; } XrInteractionProfileState; typedef struct XrActionStateGetInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrAction action; XrPath subactionPath; } XrActionStateGetInfo; typedef struct XrActionStateBoolean { XrStructureType type; void* XR_MAY_ALIAS next; XrBool32 currentState; XrBool32 changedSinceLastSync; XrTime lastChangeTime; XrBool32 isActive; } XrActionStateBoolean; typedef struct XrActionStateFloat { XrStructureType type; void* XR_MAY_ALIAS next; float currentState; XrBool32 changedSinceLastSync; XrTime lastChangeTime; XrBool32 isActive; } XrActionStateFloat; typedef struct XrVector2f { float x; float y; } XrVector2f; typedef struct XrActionStateVector2f { XrStructureType type; void* XR_MAY_ALIAS next; XrVector2f currentState; XrBool32 changedSinceLastSync; XrTime lastChangeTime; XrBool32 isActive; } XrActionStateVector2f; typedef struct XrActionStatePose { XrStructureType type; void* XR_MAY_ALIAS next; XrBool32 isActive; } XrActionStatePose; typedef struct XrActiveActionSet { XrActionSet actionSet; XrPath subactionPath; } XrActiveActionSet; typedef struct XrActionsSyncInfo { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t countActiveActionSets; const XrActiveActionSet* activeActionSets; } XrActionsSyncInfo; typedef struct XrBoundSourcesForActionEnumerateInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrAction action; } XrBoundSourcesForActionEnumerateInfo; typedef struct XrInputSourceLocalizedNameGetInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrPath sourcePath; XrInputSourceLocalizedNameFlags whichComponents; } XrInputSourceLocalizedNameGetInfo; typedef struct XrHapticActionInfo { XrStructureType type; const void* XR_MAY_ALIAS next; XrAction action; XrPath subactionPath; } XrHapticActionInfo; typedef struct XR_MAY_ALIAS XrHapticBaseHeader { XrStructureType type; const void* XR_MAY_ALIAS next; } XrHapticBaseHeader; typedef struct XR_MAY_ALIAS XrBaseInStructure { XrStructureType type; const struct XrBaseInStructure* next; } XrBaseInStructure; typedef struct XR_MAY_ALIAS XrBaseOutStructure { XrStructureType type; struct XrBaseOutStructure* next; } XrBaseOutStructure; typedef struct XrOffset2Di { int32_t x; int32_t y; } XrOffset2Di; typedef struct XrExtent2Di { int32_t width; int32_t height; } XrExtent2Di; typedef struct XrRect2Di { XrOffset2Di offset; XrExtent2Di extent; } XrRect2Di; typedef struct XrSwapchainSubImage { XrSwapchain swapchain; XrRect2Di imageRect; uint32_t imageArrayIndex; } XrSwapchainSubImage; typedef struct XrCompositionLayerProjectionView { XrStructureType type; const void* XR_MAY_ALIAS next; XrPosef pose; XrFovf fov; XrSwapchainSubImage subImage; } XrCompositionLayerProjectionView; typedef struct XrCompositionLayerProjection { XrStructureType type; const void* XR_MAY_ALIAS next; XrCompositionLayerFlags layerFlags; XrSpace space; uint32_t viewCount; const XrCompositionLayerProjectionView* views; } XrCompositionLayerProjection; typedef struct XrCompositionLayerQuad { XrStructureType type; const void* XR_MAY_ALIAS next; XrCompositionLayerFlags layerFlags; XrSpace space; XrEyeVisibility eyeVisibility; XrSwapchainSubImage subImage; XrPosef pose; XrExtent2Df size; } XrCompositionLayerQuad; typedef struct XR_MAY_ALIAS XrEventDataBaseHeader { XrStructureType type; const void* XR_MAY_ALIAS next; } XrEventDataBaseHeader; typedef struct XrEventDataEventsLost { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t lostEventCount; } XrEventDataEventsLost; typedef struct XrEventDataInstanceLossPending { XrStructureType type; const void* XR_MAY_ALIAS next; XrTime lossTime; } XrEventDataInstanceLossPending; typedef struct XrEventDataSessionStateChanged { XrStructureType type; const void* XR_MAY_ALIAS next; XrSession session; XrSessionState state; XrTime time; } XrEventDataSessionStateChanged; typedef struct XrEventDataReferenceSpaceChangePending { XrStructureType type; const void* XR_MAY_ALIAS next; XrSession session; XrReferenceSpaceType referenceSpaceType; XrTime changeTime; XrBool32 poseValid; XrPosef poseInPreviousSpace; } XrEventDataReferenceSpaceChangePending; typedef struct XrEventDataInteractionProfileChanged { XrStructureType type; const void* XR_MAY_ALIAS next; XrSession session; } XrEventDataInteractionProfileChanged; typedef struct XrHapticVibration { XrStructureType type; const void* XR_MAY_ALIAS next; XrDuration duration; float frequency; float amplitude; } XrHapticVibration; typedef struct XrOffset2Df { float x; float y; } XrOffset2Df; typedef struct XrRect2Df { XrOffset2Df offset; XrExtent2Df extent; } XrRect2Df; typedef struct XrVector4f { float x; float y; float z; float w; } XrVector4f; typedef struct XrColor4f { float r; float g; float b; float a; } XrColor4f; typedef XrResult (XRAPI_PTR *PFN_xrGetInstanceProcAddr)(XrInstance instance, const char* name, PFN_xrVoidFunction* function); typedef XrResult (XRAPI_PTR *PFN_xrEnumerateApiLayerProperties)(uint32_t propertyCapacityInput, uint32_t* propertyCountOutput, XrApiLayerProperties* properties); typedef XrResult (XRAPI_PTR *PFN_xrEnumerateInstanceExtensionProperties)(const char* layerName, uint32_t propertyCapacityInput, uint32_t* propertyCountOutput, XrExtensionProperties* properties); typedef XrResult (XRAPI_PTR *PFN_xrCreateInstance)(const XrInstanceCreateInfo* createInfo, XrInstance* instance); typedef XrResult (XRAPI_PTR *PFN_xrDestroyInstance)(XrInstance instance); typedef XrResult (XRAPI_PTR *PFN_xrGetInstanceProperties)(XrInstance instance, XrInstanceProperties* instanceProperties); typedef XrResult (XRAPI_PTR *PFN_xrPollEvent)(XrInstance instance, XrEventDataBuffer* eventData); typedef XrResult (XRAPI_PTR *PFN_xrResultToString)(XrInstance instance, XrResult value, char buffer[XR_MAX_RESULT_STRING_SIZE]); typedef XrResult (XRAPI_PTR *PFN_xrStructureTypeToString)(XrInstance instance, XrStructureType value, char buffer[XR_MAX_STRUCTURE_NAME_SIZE]); typedef XrResult (XRAPI_PTR *PFN_xrGetSystem)(XrInstance instance, const XrSystemGetInfo* getInfo, XrSystemId* systemId); typedef XrResult (XRAPI_PTR *PFN_xrGetSystemProperties)(XrInstance instance, XrSystemId systemId, XrSystemProperties* properties); typedef XrResult (XRAPI_PTR *PFN_xrEnumerateEnvironmentBlendModes)(XrInstance instance, XrSystemId systemId, XrViewConfigurationType viewConfigurationType, uint32_t environmentBlendModeCapacityInput, uint32_t* environmentBlendModeCountOutput, XrEnvironmentBlendMode* environmentBlendModes); typedef XrResult (XRAPI_PTR *PFN_xrCreateSession)(XrInstance instance, const XrSessionCreateInfo* createInfo, XrSession* session); typedef XrResult (XRAPI_PTR *PFN_xrDestroySession)(XrSession session); typedef XrResult (XRAPI_PTR *PFN_xrEnumerateReferenceSpaces)(XrSession session, uint32_t spaceCapacityInput, uint32_t* spaceCountOutput, XrReferenceSpaceType* spaces); typedef XrResult (XRAPI_PTR *PFN_xrCreateReferenceSpace)(XrSession session, const XrReferenceSpaceCreateInfo* createInfo, XrSpace* space); typedef XrResult (XRAPI_PTR *PFN_xrGetReferenceSpaceBoundsRect)(XrSession session, XrReferenceSpaceType referenceSpaceType, XrExtent2Df* bounds); typedef XrResult (XRAPI_PTR *PFN_xrCreateActionSpace)(XrSession session, const XrActionSpaceCreateInfo* createInfo, XrSpace* space); typedef XrResult (XRAPI_PTR *PFN_xrLocateSpace)(XrSpace space, XrSpace baseSpace, XrTime time, XrSpaceLocation* location); typedef XrResult (XRAPI_PTR *PFN_xrDestroySpace)(XrSpace space); typedef XrResult (XRAPI_PTR *PFN_xrEnumerateViewConfigurations)(XrInstance instance, XrSystemId systemId, uint32_t viewConfigurationTypeCapacityInput, uint32_t* viewConfigurationTypeCountOutput, XrViewConfigurationType* viewConfigurationTypes); typedef XrResult (XRAPI_PTR *PFN_xrGetViewConfigurationProperties)(XrInstance instance, XrSystemId systemId, XrViewConfigurationType viewConfigurationType, XrViewConfigurationProperties* configurationProperties); typedef XrResult (XRAPI_PTR *PFN_xrEnumerateViewConfigurationViews)(XrInstance instance, XrSystemId systemId, XrViewConfigurationType viewConfigurationType, uint32_t viewCapacityInput, uint32_t* viewCountOutput, XrViewConfigurationView* views); typedef XrResult (XRAPI_PTR *PFN_xrEnumerateSwapchainFormats)(XrSession session, uint32_t formatCapacityInput, uint32_t* formatCountOutput, int64_t* formats); typedef XrResult (XRAPI_PTR *PFN_xrCreateSwapchain)(XrSession session, const XrSwapchainCreateInfo* createInfo, XrSwapchain* swapchain); typedef XrResult (XRAPI_PTR *PFN_xrDestroySwapchain)(XrSwapchain swapchain); typedef XrResult (XRAPI_PTR *PFN_xrEnumerateSwapchainImages)(XrSwapchain swapchain, uint32_t imageCapacityInput, uint32_t* imageCountOutput, XrSwapchainImageBaseHeader* images); typedef XrResult (XRAPI_PTR *PFN_xrAcquireSwapchainImage)(XrSwapchain swapchain, const XrSwapchainImageAcquireInfo* acquireInfo, uint32_t* index); typedef XrResult (XRAPI_PTR *PFN_xrWaitSwapchainImage)(XrSwapchain swapchain, const XrSwapchainImageWaitInfo* waitInfo); typedef XrResult (XRAPI_PTR *PFN_xrReleaseSwapchainImage)(XrSwapchain swapchain, const XrSwapchainImageReleaseInfo* releaseInfo); typedef XrResult (XRAPI_PTR *PFN_xrBeginSession)(XrSession session, const XrSessionBeginInfo* beginInfo); typedef XrResult (XRAPI_PTR *PFN_xrEndSession)(XrSession session); typedef XrResult (XRAPI_PTR *PFN_xrRequestExitSession)(XrSession session); typedef XrResult (XRAPI_PTR *PFN_xrWaitFrame)(XrSession session, const XrFrameWaitInfo* frameWaitInfo, XrFrameState* frameState); typedef XrResult (XRAPI_PTR *PFN_xrBeginFrame)(XrSession session, const XrFrameBeginInfo* frameBeginInfo); typedef XrResult (XRAPI_PTR *PFN_xrEndFrame)(XrSession session, const XrFrameEndInfo* frameEndInfo); typedef XrResult (XRAPI_PTR *PFN_xrLocateViews)(XrSession session, const XrViewLocateInfo* viewLocateInfo, XrViewState* viewState, uint32_t viewCapacityInput, uint32_t* viewCountOutput, XrView* views); typedef XrResult (XRAPI_PTR *PFN_xrStringToPath)(XrInstance instance, const char* pathString, XrPath* path); typedef XrResult (XRAPI_PTR *PFN_xrPathToString)(XrInstance instance, XrPath path, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, char* buffer); typedef XrResult (XRAPI_PTR *PFN_xrCreateActionSet)(XrInstance instance, const XrActionSetCreateInfo* createInfo, XrActionSet* actionSet); typedef XrResult (XRAPI_PTR *PFN_xrDestroyActionSet)(XrActionSet actionSet); typedef XrResult (XRAPI_PTR *PFN_xrCreateAction)(XrActionSet actionSet, const XrActionCreateInfo* createInfo, XrAction* action); typedef XrResult (XRAPI_PTR *PFN_xrDestroyAction)(XrAction action); typedef XrResult (XRAPI_PTR *PFN_xrSuggestInteractionProfileBindings)(XrInstance instance, const XrInteractionProfileSuggestedBinding* suggestedBindings); typedef XrResult (XRAPI_PTR *PFN_xrAttachSessionActionSets)(XrSession session, const XrSessionActionSetsAttachInfo* attachInfo); typedef XrResult (XRAPI_PTR *PFN_xrGetCurrentInteractionProfile)(XrSession session, XrPath topLevelUserPath, XrInteractionProfileState* interactionProfile); typedef XrResult (XRAPI_PTR *PFN_xrGetActionStateBoolean)(XrSession session, const XrActionStateGetInfo* getInfo, XrActionStateBoolean* state); typedef XrResult (XRAPI_PTR *PFN_xrGetActionStateFloat)(XrSession session, const XrActionStateGetInfo* getInfo, XrActionStateFloat* state); typedef XrResult (XRAPI_PTR *PFN_xrGetActionStateVector2f)(XrSession session, const XrActionStateGetInfo* getInfo, XrActionStateVector2f* state); typedef XrResult (XRAPI_PTR *PFN_xrGetActionStatePose)(XrSession session, const XrActionStateGetInfo* getInfo, XrActionStatePose* state); typedef XrResult (XRAPI_PTR *PFN_xrSyncActions)(XrSession session, const XrActionsSyncInfo* syncInfo); typedef XrResult (XRAPI_PTR *PFN_xrEnumerateBoundSourcesForAction)(XrSession session, const XrBoundSourcesForActionEnumerateInfo* enumerateInfo, uint32_t sourceCapacityInput, uint32_t* sourceCountOutput, XrPath* sources); typedef XrResult (XRAPI_PTR *PFN_xrGetInputSourceLocalizedName)(XrSession session, const XrInputSourceLocalizedNameGetInfo* getInfo, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, char* buffer); typedef XrResult (XRAPI_PTR *PFN_xrApplyHapticFeedback)(XrSession session, const XrHapticActionInfo* hapticActionInfo, const XrHapticBaseHeader* hapticFeedback); typedef XrResult (XRAPI_PTR *PFN_xrStopHapticFeedback)(XrSession session, const XrHapticActionInfo* hapticActionInfo); #ifndef XR_NO_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrGetInstanceProcAddr( XrInstance instance, const char* name, PFN_xrVoidFunction* function); XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateApiLayerProperties( uint32_t propertyCapacityInput, uint32_t* propertyCountOutput, XrApiLayerProperties* properties); XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateInstanceExtensionProperties( const char* layerName, uint32_t propertyCapacityInput, uint32_t* propertyCountOutput, XrExtensionProperties* properties); XRAPI_ATTR XrResult XRAPI_CALL xrCreateInstance( const XrInstanceCreateInfo* createInfo, XrInstance* instance); XRAPI_ATTR XrResult XRAPI_CALL xrDestroyInstance( XrInstance instance); XRAPI_ATTR XrResult XRAPI_CALL xrGetInstanceProperties( XrInstance instance, XrInstanceProperties* instanceProperties); XRAPI_ATTR XrResult XRAPI_CALL xrPollEvent( XrInstance instance, XrEventDataBuffer* eventData); XRAPI_ATTR XrResult XRAPI_CALL xrResultToString( XrInstance instance, XrResult value, char buffer[XR_MAX_RESULT_STRING_SIZE]); XRAPI_ATTR XrResult XRAPI_CALL xrStructureTypeToString( XrInstance instance, XrStructureType value, char buffer[XR_MAX_STRUCTURE_NAME_SIZE]); XRAPI_ATTR XrResult XRAPI_CALL xrGetSystem( XrInstance instance, const XrSystemGetInfo* getInfo, XrSystemId* systemId); XRAPI_ATTR XrResult XRAPI_CALL xrGetSystemProperties( XrInstance instance, XrSystemId systemId, XrSystemProperties* properties); XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateEnvironmentBlendModes( XrInstance instance, XrSystemId systemId, XrViewConfigurationType viewConfigurationType, uint32_t environmentBlendModeCapacityInput, uint32_t* environmentBlendModeCountOutput, XrEnvironmentBlendMode* environmentBlendModes); XRAPI_ATTR XrResult XRAPI_CALL xrCreateSession( XrInstance instance, const XrSessionCreateInfo* createInfo, XrSession* session); XRAPI_ATTR XrResult XRAPI_CALL xrDestroySession( XrSession session); XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateReferenceSpaces( XrSession session, uint32_t spaceCapacityInput, uint32_t* spaceCountOutput, XrReferenceSpaceType* spaces); XRAPI_ATTR XrResult XRAPI_CALL xrCreateReferenceSpace( XrSession session, const XrReferenceSpaceCreateInfo* createInfo, XrSpace* space); XRAPI_ATTR XrResult XRAPI_CALL xrGetReferenceSpaceBoundsRect( XrSession session, XrReferenceSpaceType referenceSpaceType, XrExtent2Df* bounds); XRAPI_ATTR XrResult XRAPI_CALL xrCreateActionSpace( XrSession session, const XrActionSpaceCreateInfo* createInfo, XrSpace* space); XRAPI_ATTR XrResult XRAPI_CALL xrLocateSpace( XrSpace space, XrSpace baseSpace, XrTime time, XrSpaceLocation* location); XRAPI_ATTR XrResult XRAPI_CALL xrDestroySpace( XrSpace space); XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateViewConfigurations( XrInstance instance, XrSystemId systemId, uint32_t viewConfigurationTypeCapacityInput, uint32_t* viewConfigurationTypeCountOutput, XrViewConfigurationType* viewConfigurationTypes); XRAPI_ATTR XrResult XRAPI_CALL xrGetViewConfigurationProperties( XrInstance instance, XrSystemId systemId, XrViewConfigurationType viewConfigurationType, XrViewConfigurationProperties* configurationProperties); XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateViewConfigurationViews( XrInstance instance, XrSystemId systemId, XrViewConfigurationType viewConfigurationType, uint32_t viewCapacityInput, uint32_t* viewCountOutput, XrViewConfigurationView* views); XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateSwapchainFormats( XrSession session, uint32_t formatCapacityInput, uint32_t* formatCountOutput, int64_t* formats); XRAPI_ATTR XrResult XRAPI_CALL xrCreateSwapchain( XrSession session, const XrSwapchainCreateInfo* createInfo, XrSwapchain* swapchain); XRAPI_ATTR XrResult XRAPI_CALL xrDestroySwapchain( XrSwapchain swapchain); XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateSwapchainImages( XrSwapchain swapchain, uint32_t imageCapacityInput, uint32_t* imageCountOutput, XrSwapchainImageBaseHeader* images); XRAPI_ATTR XrResult XRAPI_CALL xrAcquireSwapchainImage( XrSwapchain swapchain, const XrSwapchainImageAcquireInfo* acquireInfo, uint32_t* index); XRAPI_ATTR XrResult XRAPI_CALL xrWaitSwapchainImage( XrSwapchain swapchain, const XrSwapchainImageWaitInfo* waitInfo); XRAPI_ATTR XrResult XRAPI_CALL xrReleaseSwapchainImage( XrSwapchain swapchain, const XrSwapchainImageReleaseInfo* releaseInfo); XRAPI_ATTR XrResult XRAPI_CALL xrBeginSession( XrSession session, const XrSessionBeginInfo* beginInfo); XRAPI_ATTR XrResult XRAPI_CALL xrEndSession( XrSession session); XRAPI_ATTR XrResult XRAPI_CALL xrRequestExitSession( XrSession session); XRAPI_ATTR XrResult XRAPI_CALL xrWaitFrame( XrSession session, const XrFrameWaitInfo* frameWaitInfo, XrFrameState* frameState); XRAPI_ATTR XrResult XRAPI_CALL xrBeginFrame( XrSession session, const XrFrameBeginInfo* frameBeginInfo); XRAPI_ATTR XrResult XRAPI_CALL xrEndFrame( XrSession session, const XrFrameEndInfo* frameEndInfo); XRAPI_ATTR XrResult XRAPI_CALL xrLocateViews( XrSession session, const XrViewLocateInfo* viewLocateInfo, XrViewState* viewState, uint32_t viewCapacityInput, uint32_t* viewCountOutput, XrView* views); XRAPI_ATTR XrResult XRAPI_CALL xrStringToPath( XrInstance instance, const char* pathString, XrPath* path); XRAPI_ATTR XrResult XRAPI_CALL xrPathToString( XrInstance instance, XrPath path, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, char* buffer); XRAPI_ATTR XrResult XRAPI_CALL xrCreateActionSet( XrInstance instance, const XrActionSetCreateInfo* createInfo, XrActionSet* actionSet); XRAPI_ATTR XrResult XRAPI_CALL xrDestroyActionSet( XrActionSet actionSet); XRAPI_ATTR XrResult XRAPI_CALL xrCreateAction( XrActionSet actionSet, const XrActionCreateInfo* createInfo, XrAction* action); XRAPI_ATTR XrResult XRAPI_CALL xrDestroyAction( XrAction action); XRAPI_ATTR XrResult XRAPI_CALL xrSuggestInteractionProfileBindings( XrInstance instance, const XrInteractionProfileSuggestedBinding* suggestedBindings); XRAPI_ATTR XrResult XRAPI_CALL xrAttachSessionActionSets( XrSession session, const XrSessionActionSetsAttachInfo* attachInfo); XRAPI_ATTR XrResult XRAPI_CALL xrGetCurrentInteractionProfile( XrSession session, XrPath topLevelUserPath, XrInteractionProfileState* interactionProfile); XRAPI_ATTR XrResult XRAPI_CALL xrGetActionStateBoolean( XrSession session, const XrActionStateGetInfo* getInfo, XrActionStateBoolean* state); XRAPI_ATTR XrResult XRAPI_CALL xrGetActionStateFloat( XrSession session, const XrActionStateGetInfo* getInfo, XrActionStateFloat* state); XRAPI_ATTR XrResult XRAPI_CALL xrGetActionStateVector2f( XrSession session, const XrActionStateGetInfo* getInfo, XrActionStateVector2f* state); XRAPI_ATTR XrResult XRAPI_CALL xrGetActionStatePose( XrSession session, const XrActionStateGetInfo* getInfo, XrActionStatePose* state); XRAPI_ATTR XrResult XRAPI_CALL xrSyncActions( XrSession session, const XrActionsSyncInfo* syncInfo); XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateBoundSourcesForAction( XrSession session, const XrBoundSourcesForActionEnumerateInfo* enumerateInfo, uint32_t sourceCapacityInput, uint32_t* sourceCountOutput, XrPath* sources); XRAPI_ATTR XrResult XRAPI_CALL xrGetInputSourceLocalizedName( XrSession session, const XrInputSourceLocalizedNameGetInfo* getInfo, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, char* buffer); XRAPI_ATTR XrResult XRAPI_CALL xrApplyHapticFeedback( XrSession session, const XrHapticActionInfo* hapticActionInfo, const XrHapticBaseHeader* hapticFeedback); XRAPI_ATTR XrResult XRAPI_CALL xrStopHapticFeedback( XrSession session, const XrHapticActionInfo* hapticActionInfo); #endif /* !XR_NO_PROTOTYPES */ #define XR_KHR_composition_layer_cube 1 #define XR_KHR_composition_layer_cube_SPEC_VERSION 8 #define XR_KHR_COMPOSITION_LAYER_CUBE_EXTENSION_NAME "XR_KHR_composition_layer_cube" typedef struct XrCompositionLayerCubeKHR { XrStructureType type; const void* XR_MAY_ALIAS next; XrCompositionLayerFlags layerFlags; XrSpace space; XrEyeVisibility eyeVisibility; XrSwapchain swapchain; uint32_t imageArrayIndex; XrQuaternionf orientation; } XrCompositionLayerCubeKHR; #define XR_KHR_composition_layer_depth 1 #define XR_KHR_composition_layer_depth_SPEC_VERSION 5 #define XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME "XR_KHR_composition_layer_depth" // XrCompositionLayerDepthInfoKHR extends XrCompositionLayerProjectionView typedef struct XrCompositionLayerDepthInfoKHR { XrStructureType type; const void* XR_MAY_ALIAS next; XrSwapchainSubImage subImage; float minDepth; float maxDepth; float nearZ; float farZ; } XrCompositionLayerDepthInfoKHR; #define XR_KHR_composition_layer_cylinder 1 #define XR_KHR_composition_layer_cylinder_SPEC_VERSION 4 #define XR_KHR_COMPOSITION_LAYER_CYLINDER_EXTENSION_NAME "XR_KHR_composition_layer_cylinder" typedef struct XrCompositionLayerCylinderKHR { XrStructureType type; const void* XR_MAY_ALIAS next; XrCompositionLayerFlags layerFlags; XrSpace space; XrEyeVisibility eyeVisibility; XrSwapchainSubImage subImage; XrPosef pose; float radius; float centralAngle; float aspectRatio; } XrCompositionLayerCylinderKHR; #define XR_KHR_composition_layer_equirect 1 #define XR_KHR_composition_layer_equirect_SPEC_VERSION 3 #define XR_KHR_COMPOSITION_LAYER_EQUIRECT_EXTENSION_NAME "XR_KHR_composition_layer_equirect" typedef struct XrCompositionLayerEquirectKHR { XrStructureType type; const void* XR_MAY_ALIAS next; XrCompositionLayerFlags layerFlags; XrSpace space; XrEyeVisibility eyeVisibility; XrSwapchainSubImage subImage; XrPosef pose; float radius; XrVector2f scale; XrVector2f bias; } XrCompositionLayerEquirectKHR; #define XR_KHR_visibility_mask 1 #define XR_KHR_visibility_mask_SPEC_VERSION 2 #define XR_KHR_VISIBILITY_MASK_EXTENSION_NAME "XR_KHR_visibility_mask" typedef enum XrVisibilityMaskTypeKHR { XR_VISIBILITY_MASK_TYPE_HIDDEN_TRIANGLE_MESH_KHR = 1, XR_VISIBILITY_MASK_TYPE_VISIBLE_TRIANGLE_MESH_KHR = 2, XR_VISIBILITY_MASK_TYPE_LINE_LOOP_KHR = 3, XR_VISIBILITY_MASK_TYPE_MAX_ENUM_KHR = 0x7FFFFFFF } XrVisibilityMaskTypeKHR; typedef struct XrVisibilityMaskKHR { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t vertexCapacityInput; uint32_t vertexCountOutput; XrVector2f* vertices; uint32_t indexCapacityInput; uint32_t indexCountOutput; uint32_t* indices; } XrVisibilityMaskKHR; typedef struct XrEventDataVisibilityMaskChangedKHR { XrStructureType type; const void* XR_MAY_ALIAS next; XrSession session; XrViewConfigurationType viewConfigurationType; uint32_t viewIndex; } XrEventDataVisibilityMaskChangedKHR; typedef XrResult (XRAPI_PTR *PFN_xrGetVisibilityMaskKHR)(XrSession session, XrViewConfigurationType viewConfigurationType, uint32_t viewIndex, XrVisibilityMaskTypeKHR visibilityMaskType, XrVisibilityMaskKHR* visibilityMask); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrGetVisibilityMaskKHR( XrSession session, XrViewConfigurationType viewConfigurationType, uint32_t viewIndex, XrVisibilityMaskTypeKHR visibilityMaskType, XrVisibilityMaskKHR* visibilityMask); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_KHR_composition_layer_color_scale_bias 1 #define XR_KHR_composition_layer_color_scale_bias_SPEC_VERSION 5 #define XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME "XR_KHR_composition_layer_color_scale_bias" // XrCompositionLayerColorScaleBiasKHR extends XrCompositionLayerBaseHeader typedef struct XrCompositionLayerColorScaleBiasKHR { XrStructureType type; const void* XR_MAY_ALIAS next; XrColor4f colorScale; XrColor4f colorBias; } XrCompositionLayerColorScaleBiasKHR; #define XR_KHR_loader_init 1 #define XR_KHR_loader_init_SPEC_VERSION 1 #define XR_KHR_LOADER_INIT_EXTENSION_NAME "XR_KHR_loader_init" typedef struct XR_MAY_ALIAS XrLoaderInitInfoBaseHeaderKHR { XrStructureType type; const void* XR_MAY_ALIAS next; } XrLoaderInitInfoBaseHeaderKHR; typedef XrResult (XRAPI_PTR *PFN_xrInitializeLoaderKHR)(const XrLoaderInitInfoBaseHeaderKHR* loaderInitInfo); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrInitializeLoaderKHR( const XrLoaderInitInfoBaseHeaderKHR* loaderInitInfo); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_KHR_composition_layer_equirect2 1 #define XR_KHR_composition_layer_equirect2_SPEC_VERSION 1 #define XR_KHR_COMPOSITION_LAYER_EQUIRECT2_EXTENSION_NAME "XR_KHR_composition_layer_equirect2" typedef struct XrCompositionLayerEquirect2KHR { XrStructureType type; const void* XR_MAY_ALIAS next; XrCompositionLayerFlags layerFlags; XrSpace space; XrEyeVisibility eyeVisibility; XrSwapchainSubImage subImage; XrPosef pose; float radius; float centralHorizontalAngle; float upperVerticalAngle; float lowerVerticalAngle; } XrCompositionLayerEquirect2KHR; #define XR_KHR_binding_modification 1 #define XR_KHR_binding_modification_SPEC_VERSION 1 #define XR_KHR_BINDING_MODIFICATION_EXTENSION_NAME "XR_KHR_binding_modification" typedef struct XR_MAY_ALIAS XrBindingModificationBaseHeaderKHR { XrStructureType type; const void* XR_MAY_ALIAS next; } XrBindingModificationBaseHeaderKHR; // XrBindingModificationsKHR extends XrInteractionProfileSuggestedBinding typedef struct XrBindingModificationsKHR { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t bindingModificationCount; const XrBindingModificationBaseHeaderKHR* const* bindingModifications; } XrBindingModificationsKHR; #define XR_KHR_swapchain_usage_input_attachment_bit 1 #define XR_KHR_swapchain_usage_input_attachment_bit_SPEC_VERSION 3 #define XR_KHR_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT_EXTENSION_NAME "XR_KHR_swapchain_usage_input_attachment_bit" #define XR_EXT_performance_settings 1 #define XR_EXT_performance_settings_SPEC_VERSION 3 #define XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME "XR_EXT_performance_settings" typedef enum XrPerfSettingsDomainEXT { XR_PERF_SETTINGS_DOMAIN_CPU_EXT = 1, XR_PERF_SETTINGS_DOMAIN_GPU_EXT = 2, XR_PERF_SETTINGS_DOMAIN_MAX_ENUM_EXT = 0x7FFFFFFF } XrPerfSettingsDomainEXT; typedef enum XrPerfSettingsSubDomainEXT { XR_PERF_SETTINGS_SUB_DOMAIN_COMPOSITING_EXT = 1, XR_PERF_SETTINGS_SUB_DOMAIN_RENDERING_EXT = 2, XR_PERF_SETTINGS_SUB_DOMAIN_THERMAL_EXT = 3, XR_PERF_SETTINGS_SUB_DOMAIN_MAX_ENUM_EXT = 0x7FFFFFFF } XrPerfSettingsSubDomainEXT; typedef enum XrPerfSettingsLevelEXT { XR_PERF_SETTINGS_LEVEL_POWER_SAVINGS_EXT = 0, XR_PERF_SETTINGS_LEVEL_SUSTAINED_LOW_EXT = 25, XR_PERF_SETTINGS_LEVEL_SUSTAINED_HIGH_EXT = 50, XR_PERF_SETTINGS_LEVEL_BOOST_EXT = 75, XR_PERF_SETTINGS_LEVEL_MAX_ENUM_EXT = 0x7FFFFFFF } XrPerfSettingsLevelEXT; typedef enum XrPerfSettingsNotificationLevelEXT { XR_PERF_SETTINGS_NOTIF_LEVEL_NORMAL_EXT = 0, XR_PERF_SETTINGS_NOTIF_LEVEL_WARNING_EXT = 25, XR_PERF_SETTINGS_NOTIF_LEVEL_IMPAIRED_EXT = 75, XR_PERF_SETTINGS_NOTIFICATION_LEVEL_MAX_ENUM_EXT = 0x7FFFFFFF } XrPerfSettingsNotificationLevelEXT; typedef struct XrEventDataPerfSettingsEXT { XrStructureType type; const void* XR_MAY_ALIAS next; XrPerfSettingsDomainEXT domain; XrPerfSettingsSubDomainEXT subDomain; XrPerfSettingsNotificationLevelEXT fromLevel; XrPerfSettingsNotificationLevelEXT toLevel; } XrEventDataPerfSettingsEXT; typedef XrResult (XRAPI_PTR *PFN_xrPerfSettingsSetPerformanceLevelEXT)(XrSession session, XrPerfSettingsDomainEXT domain, XrPerfSettingsLevelEXT level); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrPerfSettingsSetPerformanceLevelEXT( XrSession session, XrPerfSettingsDomainEXT domain, XrPerfSettingsLevelEXT level); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_EXT_thermal_query 1 #define XR_EXT_thermal_query_SPEC_VERSION 2 #define XR_EXT_THERMAL_QUERY_EXTENSION_NAME "XR_EXT_thermal_query" typedef XrResult (XRAPI_PTR *PFN_xrThermalGetTemperatureTrendEXT)(XrSession session, XrPerfSettingsDomainEXT domain, XrPerfSettingsNotificationLevelEXT* notificationLevel, float* tempHeadroom, float* tempSlope); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrThermalGetTemperatureTrendEXT( XrSession session, XrPerfSettingsDomainEXT domain, XrPerfSettingsNotificationLevelEXT* notificationLevel, float* tempHeadroom, float* tempSlope); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_EXT_debug_utils 1 XR_DEFINE_HANDLE(XrDebugUtilsMessengerEXT) #define XR_EXT_debug_utils_SPEC_VERSION 4 #define XR_EXT_DEBUG_UTILS_EXTENSION_NAME "XR_EXT_debug_utils" typedef XrFlags64 XrDebugUtilsMessageSeverityFlagsEXT; // Flag bits for XrDebugUtilsMessageSeverityFlagsEXT static const XrDebugUtilsMessageSeverityFlagsEXT XR_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT = 0x00000001; static const XrDebugUtilsMessageSeverityFlagsEXT XR_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT = 0x00000010; static const XrDebugUtilsMessageSeverityFlagsEXT XR_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT = 0x00000100; static const XrDebugUtilsMessageSeverityFlagsEXT XR_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT = 0x00001000; typedef XrFlags64 XrDebugUtilsMessageTypeFlagsEXT; // Flag bits for XrDebugUtilsMessageTypeFlagsEXT static const XrDebugUtilsMessageTypeFlagsEXT XR_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT = 0x00000001; static const XrDebugUtilsMessageTypeFlagsEXT XR_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT = 0x00000002; static const XrDebugUtilsMessageTypeFlagsEXT XR_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT = 0x00000004; static const XrDebugUtilsMessageTypeFlagsEXT XR_DEBUG_UTILS_MESSAGE_TYPE_CONFORMANCE_BIT_EXT = 0x00000008; typedef struct XrDebugUtilsObjectNameInfoEXT { XrStructureType type; const void* XR_MAY_ALIAS next; XrObjectType objectType; uint64_t objectHandle; const char* objectName; } XrDebugUtilsObjectNameInfoEXT; typedef struct XrDebugUtilsLabelEXT { XrStructureType type; const void* XR_MAY_ALIAS next; const char* labelName; } XrDebugUtilsLabelEXT; typedef struct XrDebugUtilsMessengerCallbackDataEXT { XrStructureType type; const void* XR_MAY_ALIAS next; const char* messageId; const char* functionName; const char* message; uint32_t objectCount; XrDebugUtilsObjectNameInfoEXT* objects; uint32_t sessionLabelCount; XrDebugUtilsLabelEXT* sessionLabels; } XrDebugUtilsMessengerCallbackDataEXT; typedef XrBool32 (XRAPI_PTR *PFN_xrDebugUtilsMessengerCallbackEXT)( XrDebugUtilsMessageSeverityFlagsEXT messageSeverity, XrDebugUtilsMessageTypeFlagsEXT messageTypes, const XrDebugUtilsMessengerCallbackDataEXT* callbackData, void* userData); // XrDebugUtilsMessengerCreateInfoEXT extends XrInstanceCreateInfo typedef struct XrDebugUtilsMessengerCreateInfoEXT { XrStructureType type; const void* XR_MAY_ALIAS next; XrDebugUtilsMessageSeverityFlagsEXT messageSeverities; XrDebugUtilsMessageTypeFlagsEXT messageTypes; PFN_xrDebugUtilsMessengerCallbackEXT userCallback; void* XR_MAY_ALIAS userData; } XrDebugUtilsMessengerCreateInfoEXT; typedef XrResult (XRAPI_PTR *PFN_xrSetDebugUtilsObjectNameEXT)(XrInstance instance, const XrDebugUtilsObjectNameInfoEXT* nameInfo); typedef XrResult (XRAPI_PTR *PFN_xrCreateDebugUtilsMessengerEXT)(XrInstance instance, const XrDebugUtilsMessengerCreateInfoEXT* createInfo, XrDebugUtilsMessengerEXT* messenger); typedef XrResult (XRAPI_PTR *PFN_xrDestroyDebugUtilsMessengerEXT)(XrDebugUtilsMessengerEXT messenger); typedef XrResult (XRAPI_PTR *PFN_xrSubmitDebugUtilsMessageEXT)(XrInstance instance, XrDebugUtilsMessageSeverityFlagsEXT messageSeverity, XrDebugUtilsMessageTypeFlagsEXT messageTypes, const XrDebugUtilsMessengerCallbackDataEXT* callbackData); typedef XrResult (XRAPI_PTR *PFN_xrSessionBeginDebugUtilsLabelRegionEXT)(XrSession session, const XrDebugUtilsLabelEXT* labelInfo); typedef XrResult (XRAPI_PTR *PFN_xrSessionEndDebugUtilsLabelRegionEXT)(XrSession session); typedef XrResult (XRAPI_PTR *PFN_xrSessionInsertDebugUtilsLabelEXT)(XrSession session, const XrDebugUtilsLabelEXT* labelInfo); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrSetDebugUtilsObjectNameEXT( XrInstance instance, const XrDebugUtilsObjectNameInfoEXT* nameInfo); XRAPI_ATTR XrResult XRAPI_CALL xrCreateDebugUtilsMessengerEXT( XrInstance instance, const XrDebugUtilsMessengerCreateInfoEXT* createInfo, XrDebugUtilsMessengerEXT* messenger); XRAPI_ATTR XrResult XRAPI_CALL xrDestroyDebugUtilsMessengerEXT( XrDebugUtilsMessengerEXT messenger); XRAPI_ATTR XrResult XRAPI_CALL xrSubmitDebugUtilsMessageEXT( XrInstance instance, XrDebugUtilsMessageSeverityFlagsEXT messageSeverity, XrDebugUtilsMessageTypeFlagsEXT messageTypes, const XrDebugUtilsMessengerCallbackDataEXT* callbackData); XRAPI_ATTR XrResult XRAPI_CALL xrSessionBeginDebugUtilsLabelRegionEXT( XrSession session, const XrDebugUtilsLabelEXT* labelInfo); XRAPI_ATTR XrResult XRAPI_CALL xrSessionEndDebugUtilsLabelRegionEXT( XrSession session); XRAPI_ATTR XrResult XRAPI_CALL xrSessionInsertDebugUtilsLabelEXT( XrSession session, const XrDebugUtilsLabelEXT* labelInfo); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_EXT_eye_gaze_interaction 1 #define XR_EXT_eye_gaze_interaction_SPEC_VERSION 1 #define XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME "XR_EXT_eye_gaze_interaction" // XrSystemEyeGazeInteractionPropertiesEXT extends XrSystemProperties typedef struct XrSystemEyeGazeInteractionPropertiesEXT { XrStructureType type; void* XR_MAY_ALIAS next; XrBool32 supportsEyeGazeInteraction; } XrSystemEyeGazeInteractionPropertiesEXT; // XrEyeGazeSampleTimeEXT extends XrSpaceLocation typedef struct XrEyeGazeSampleTimeEXT { XrStructureType type; void* XR_MAY_ALIAS next; XrTime time; } XrEyeGazeSampleTimeEXT; #define XR_EXTX_overlay 1 #define XR_EXTX_overlay_SPEC_VERSION 5 #define XR_EXTX_OVERLAY_EXTENSION_NAME "XR_EXTX_overlay" typedef XrFlags64 XrOverlaySessionCreateFlagsEXTX; // Flag bits for XrOverlaySessionCreateFlagsEXTX typedef XrFlags64 XrOverlayMainSessionFlagsEXTX; // Flag bits for XrOverlayMainSessionFlagsEXTX static const XrOverlayMainSessionFlagsEXTX XR_OVERLAY_MAIN_SESSION_ENABLED_COMPOSITION_LAYER_INFO_DEPTH_BIT_EXTX = 0x00000001; // XrSessionCreateInfoOverlayEXTX extends XrSessionCreateInfo typedef struct XrSessionCreateInfoOverlayEXTX { XrStructureType type; const void* XR_MAY_ALIAS next; XrOverlaySessionCreateFlagsEXTX createFlags; uint32_t sessionLayersPlacement; } XrSessionCreateInfoOverlayEXTX; typedef struct XrEventDataMainSessionVisibilityChangedEXTX { XrStructureType type; const void* XR_MAY_ALIAS next; XrBool32 visible; XrOverlayMainSessionFlagsEXTX flags; } XrEventDataMainSessionVisibilityChangedEXTX; #define XR_VARJO_quad_views 1 #define XR_VARJO_quad_views_SPEC_VERSION 1 #define XR_VARJO_QUAD_VIEWS_EXTENSION_NAME "XR_VARJO_quad_views" #define XR_MSFT_unbounded_reference_space 1 #define XR_MSFT_unbounded_reference_space_SPEC_VERSION 1 #define XR_MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME "XR_MSFT_unbounded_reference_space" #define XR_MSFT_spatial_anchor 1 XR_DEFINE_HANDLE(XrSpatialAnchorMSFT) #define XR_MSFT_spatial_anchor_SPEC_VERSION 2 #define XR_MSFT_SPATIAL_ANCHOR_EXTENSION_NAME "XR_MSFT_spatial_anchor" typedef struct XrSpatialAnchorCreateInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrSpace space; XrPosef pose; XrTime time; } XrSpatialAnchorCreateInfoMSFT; typedef struct XrSpatialAnchorSpaceCreateInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrSpatialAnchorMSFT anchor; XrPosef poseInAnchorSpace; } XrSpatialAnchorSpaceCreateInfoMSFT; typedef XrResult (XRAPI_PTR *PFN_xrCreateSpatialAnchorMSFT)(XrSession session, const XrSpatialAnchorCreateInfoMSFT* createInfo, XrSpatialAnchorMSFT* anchor); typedef XrResult (XRAPI_PTR *PFN_xrCreateSpatialAnchorSpaceMSFT)(XrSession session, const XrSpatialAnchorSpaceCreateInfoMSFT* createInfo, XrSpace* space); typedef XrResult (XRAPI_PTR *PFN_xrDestroySpatialAnchorMSFT)(XrSpatialAnchorMSFT anchor); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreateSpatialAnchorMSFT( XrSession session, const XrSpatialAnchorCreateInfoMSFT* createInfo, XrSpatialAnchorMSFT* anchor); XRAPI_ATTR XrResult XRAPI_CALL xrCreateSpatialAnchorSpaceMSFT( XrSession session, const XrSpatialAnchorSpaceCreateInfoMSFT* createInfo, XrSpace* space); XRAPI_ATTR XrResult XRAPI_CALL xrDestroySpatialAnchorMSFT( XrSpatialAnchorMSFT anchor); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_FB_composition_layer_image_layout 1 #define XR_FB_composition_layer_image_layout_SPEC_VERSION 1 #define XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME "XR_FB_composition_layer_image_layout" typedef XrFlags64 XrCompositionLayerImageLayoutFlagsFB; // Flag bits for XrCompositionLayerImageLayoutFlagsFB static const XrCompositionLayerImageLayoutFlagsFB XR_COMPOSITION_LAYER_IMAGE_LAYOUT_VERTICAL_FLIP_BIT_FB = 0x00000001; // XrCompositionLayerImageLayoutFB extends XrCompositionLayerBaseHeader typedef struct XrCompositionLayerImageLayoutFB { XrStructureType type; void* XR_MAY_ALIAS next; XrCompositionLayerImageLayoutFlagsFB flags; } XrCompositionLayerImageLayoutFB; #define XR_FB_composition_layer_alpha_blend 1 #define XR_FB_composition_layer_alpha_blend_SPEC_VERSION 2 #define XR_FB_COMPOSITION_LAYER_ALPHA_BLEND_EXTENSION_NAME "XR_FB_composition_layer_alpha_blend" typedef enum XrBlendFactorFB { XR_BLEND_FACTOR_ZERO_FB = 0, XR_BLEND_FACTOR_ONE_FB = 1, XR_BLEND_FACTOR_SRC_ALPHA_FB = 2, XR_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA_FB = 3, XR_BLEND_FACTOR_DST_ALPHA_FB = 4, XR_BLEND_FACTOR_ONE_MINUS_DST_ALPHA_FB = 5, XR_BLEND_FACTOR_MAX_ENUM_FB = 0x7FFFFFFF } XrBlendFactorFB; // XrCompositionLayerAlphaBlendFB extends XrCompositionLayerBaseHeader typedef struct XrCompositionLayerAlphaBlendFB { XrStructureType type; void* XR_MAY_ALIAS next; XrBlendFactorFB srcFactorColor; XrBlendFactorFB dstFactorColor; XrBlendFactorFB srcFactorAlpha; XrBlendFactorFB dstFactorAlpha; } XrCompositionLayerAlphaBlendFB; #define XR_MND_headless 1 #define XR_MND_headless_SPEC_VERSION 2 #define XR_MND_HEADLESS_EXTENSION_NAME "XR_MND_headless" #define XR_OCULUS_android_session_state_enable 1 #define XR_OCULUS_android_session_state_enable_SPEC_VERSION 1 #define XR_OCULUS_ANDROID_SESSION_STATE_ENABLE_EXTENSION_NAME "XR_OCULUS_android_session_state_enable" #define XR_EXT_view_configuration_depth_range 1 #define XR_EXT_view_configuration_depth_range_SPEC_VERSION 1 #define XR_EXT_VIEW_CONFIGURATION_DEPTH_RANGE_EXTENSION_NAME "XR_EXT_view_configuration_depth_range" // XrViewConfigurationDepthRangeEXT extends XrViewConfigurationView typedef struct XrViewConfigurationDepthRangeEXT { XrStructureType type; void* XR_MAY_ALIAS next; float recommendedNearZ; float minNearZ; float recommendedFarZ; float maxFarZ; } XrViewConfigurationDepthRangeEXT; #define XR_EXT_conformance_automation 1 #define XR_EXT_conformance_automation_SPEC_VERSION 3 #define XR_EXT_CONFORMANCE_AUTOMATION_EXTENSION_NAME "XR_EXT_conformance_automation" typedef XrResult (XRAPI_PTR *PFN_xrSetInputDeviceActiveEXT)(XrSession session, XrPath interactionProfile, XrPath topLevelPath, XrBool32 isActive); typedef XrResult (XRAPI_PTR *PFN_xrSetInputDeviceStateBoolEXT)(XrSession session, XrPath topLevelPath, XrPath inputSourcePath, XrBool32 state); typedef XrResult (XRAPI_PTR *PFN_xrSetInputDeviceStateFloatEXT)(XrSession session, XrPath topLevelPath, XrPath inputSourcePath, float state); typedef XrResult (XRAPI_PTR *PFN_xrSetInputDeviceStateVector2fEXT)(XrSession session, XrPath topLevelPath, XrPath inputSourcePath, XrVector2f state); typedef XrResult (XRAPI_PTR *PFN_xrSetInputDeviceLocationEXT)(XrSession session, XrPath topLevelPath, XrPath inputSourcePath, XrSpace space, XrPosef pose); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrSetInputDeviceActiveEXT( XrSession session, XrPath interactionProfile, XrPath topLevelPath, XrBool32 isActive); XRAPI_ATTR XrResult XRAPI_CALL xrSetInputDeviceStateBoolEXT( XrSession session, XrPath topLevelPath, XrPath inputSourcePath, XrBool32 state); XRAPI_ATTR XrResult XRAPI_CALL xrSetInputDeviceStateFloatEXT( XrSession session, XrPath topLevelPath, XrPath inputSourcePath, float state); XRAPI_ATTR XrResult XRAPI_CALL xrSetInputDeviceStateVector2fEXT( XrSession session, XrPath topLevelPath, XrPath inputSourcePath, XrVector2f state); XRAPI_ATTR XrResult XRAPI_CALL xrSetInputDeviceLocationEXT( XrSession session, XrPath topLevelPath, XrPath inputSourcePath, XrSpace space, XrPosef pose); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_MSFT_spatial_graph_bridge 1 #define XR_MSFT_spatial_graph_bridge_SPEC_VERSION 1 #define XR_MSFT_SPATIAL_GRAPH_BRIDGE_EXTENSION_NAME "XR_MSFT_spatial_graph_bridge" typedef enum XrSpatialGraphNodeTypeMSFT { XR_SPATIAL_GRAPH_NODE_TYPE_STATIC_MSFT = 1, XR_SPATIAL_GRAPH_NODE_TYPE_DYNAMIC_MSFT = 2, XR_SPATIAL_GRAPH_NODE_TYPE_MAX_ENUM_MSFT = 0x7FFFFFFF } XrSpatialGraphNodeTypeMSFT; typedef struct XrSpatialGraphNodeSpaceCreateInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrSpatialGraphNodeTypeMSFT nodeType; uint8_t nodeId[16]; XrPosef pose; } XrSpatialGraphNodeSpaceCreateInfoMSFT; typedef XrResult (XRAPI_PTR *PFN_xrCreateSpatialGraphNodeSpaceMSFT)(XrSession session, const XrSpatialGraphNodeSpaceCreateInfoMSFT* createInfo, XrSpace* space); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreateSpatialGraphNodeSpaceMSFT( XrSession session, const XrSpatialGraphNodeSpaceCreateInfoMSFT* createInfo, XrSpace* space); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_MSFT_hand_interaction 1 #define XR_MSFT_hand_interaction_SPEC_VERSION 1 #define XR_MSFT_HAND_INTERACTION_EXTENSION_NAME "XR_MSFT_hand_interaction" #define XR_EXT_hand_tracking 1 #define XR_HAND_JOINT_COUNT_EXT 26 XR_DEFINE_HANDLE(XrHandTrackerEXT) #define XR_EXT_hand_tracking_SPEC_VERSION 4 #define XR_EXT_HAND_TRACKING_EXTENSION_NAME "XR_EXT_hand_tracking" typedef enum XrHandEXT { XR_HAND_LEFT_EXT = 1, XR_HAND_RIGHT_EXT = 2, XR_HAND_MAX_ENUM_EXT = 0x7FFFFFFF } XrHandEXT; typedef enum XrHandJointEXT { XR_HAND_JOINT_PALM_EXT = 0, XR_HAND_JOINT_WRIST_EXT = 1, XR_HAND_JOINT_THUMB_METACARPAL_EXT = 2, XR_HAND_JOINT_THUMB_PROXIMAL_EXT = 3, XR_HAND_JOINT_THUMB_DISTAL_EXT = 4, XR_HAND_JOINT_THUMB_TIP_EXT = 5, XR_HAND_JOINT_INDEX_METACARPAL_EXT = 6, XR_HAND_JOINT_INDEX_PROXIMAL_EXT = 7, XR_HAND_JOINT_INDEX_INTERMEDIATE_EXT = 8, XR_HAND_JOINT_INDEX_DISTAL_EXT = 9, XR_HAND_JOINT_INDEX_TIP_EXT = 10, XR_HAND_JOINT_MIDDLE_METACARPAL_EXT = 11, XR_HAND_JOINT_MIDDLE_PROXIMAL_EXT = 12, XR_HAND_JOINT_MIDDLE_INTERMEDIATE_EXT = 13, XR_HAND_JOINT_MIDDLE_DISTAL_EXT = 14, XR_HAND_JOINT_MIDDLE_TIP_EXT = 15, XR_HAND_JOINT_RING_METACARPAL_EXT = 16, XR_HAND_JOINT_RING_PROXIMAL_EXT = 17, XR_HAND_JOINT_RING_INTERMEDIATE_EXT = 18, XR_HAND_JOINT_RING_DISTAL_EXT = 19, XR_HAND_JOINT_RING_TIP_EXT = 20, XR_HAND_JOINT_LITTLE_METACARPAL_EXT = 21, XR_HAND_JOINT_LITTLE_PROXIMAL_EXT = 22, XR_HAND_JOINT_LITTLE_INTERMEDIATE_EXT = 23, XR_HAND_JOINT_LITTLE_DISTAL_EXT = 24, XR_HAND_JOINT_LITTLE_TIP_EXT = 25, XR_HAND_JOINT_MAX_ENUM_EXT = 0x7FFFFFFF } XrHandJointEXT; typedef enum XrHandJointSetEXT { XR_HAND_JOINT_SET_DEFAULT_EXT = 0, XR_HAND_JOINT_SET_MAX_ENUM_EXT = 0x7FFFFFFF } XrHandJointSetEXT; // XrSystemHandTrackingPropertiesEXT extends XrSystemProperties typedef struct XrSystemHandTrackingPropertiesEXT { XrStructureType type; void* XR_MAY_ALIAS next; XrBool32 supportsHandTracking; } XrSystemHandTrackingPropertiesEXT; typedef struct XrHandTrackerCreateInfoEXT { XrStructureType type; const void* XR_MAY_ALIAS next; XrHandEXT hand; XrHandJointSetEXT handJointSet; } XrHandTrackerCreateInfoEXT; typedef struct XrHandJointsLocateInfoEXT { XrStructureType type; const void* XR_MAY_ALIAS next; XrSpace baseSpace; XrTime time; } XrHandJointsLocateInfoEXT; typedef struct XrHandJointLocationEXT { XrSpaceLocationFlags locationFlags; XrPosef pose; float radius; } XrHandJointLocationEXT; typedef struct XrHandJointVelocityEXT { XrSpaceVelocityFlags velocityFlags; XrVector3f linearVelocity; XrVector3f angularVelocity; } XrHandJointVelocityEXT; typedef struct XrHandJointLocationsEXT { XrStructureType type; void* XR_MAY_ALIAS next; XrBool32 isActive; uint32_t jointCount; XrHandJointLocationEXT* jointLocations; } XrHandJointLocationsEXT; // XrHandJointVelocitiesEXT extends XrHandJointLocationsEXT typedef struct XrHandJointVelocitiesEXT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t jointCount; XrHandJointVelocityEXT* jointVelocities; } XrHandJointVelocitiesEXT; typedef XrResult (XRAPI_PTR *PFN_xrCreateHandTrackerEXT)(XrSession session, const XrHandTrackerCreateInfoEXT* createInfo, XrHandTrackerEXT* handTracker); typedef XrResult (XRAPI_PTR *PFN_xrDestroyHandTrackerEXT)(XrHandTrackerEXT handTracker); typedef XrResult (XRAPI_PTR *PFN_xrLocateHandJointsEXT)(XrHandTrackerEXT handTracker, const XrHandJointsLocateInfoEXT* locateInfo, XrHandJointLocationsEXT* locations); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreateHandTrackerEXT( XrSession session, const XrHandTrackerCreateInfoEXT* createInfo, XrHandTrackerEXT* handTracker); XRAPI_ATTR XrResult XRAPI_CALL xrDestroyHandTrackerEXT( XrHandTrackerEXT handTracker); XRAPI_ATTR XrResult XRAPI_CALL xrLocateHandJointsEXT( XrHandTrackerEXT handTracker, const XrHandJointsLocateInfoEXT* locateInfo, XrHandJointLocationsEXT* locations); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_MSFT_hand_tracking_mesh 1 #define XR_MSFT_hand_tracking_mesh_SPEC_VERSION 3 #define XR_MSFT_HAND_TRACKING_MESH_EXTENSION_NAME "XR_MSFT_hand_tracking_mesh" typedef enum XrHandPoseTypeMSFT { XR_HAND_POSE_TYPE_TRACKED_MSFT = 0, XR_HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT = 1, XR_HAND_POSE_TYPE_MAX_ENUM_MSFT = 0x7FFFFFFF } XrHandPoseTypeMSFT; // XrSystemHandTrackingMeshPropertiesMSFT extends XrSystemProperties typedef struct XrSystemHandTrackingMeshPropertiesMSFT { XrStructureType type; void* XR_MAY_ALIAS next; XrBool32 supportsHandTrackingMesh; uint32_t maxHandMeshIndexCount; uint32_t maxHandMeshVertexCount; } XrSystemHandTrackingMeshPropertiesMSFT; typedef struct XrHandMeshSpaceCreateInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrHandPoseTypeMSFT handPoseType; XrPosef poseInHandMeshSpace; } XrHandMeshSpaceCreateInfoMSFT; typedef struct XrHandMeshUpdateInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrTime time; XrHandPoseTypeMSFT handPoseType; } XrHandMeshUpdateInfoMSFT; typedef struct XrHandMeshIndexBufferMSFT { uint32_t indexBufferKey; uint32_t indexCapacityInput; uint32_t indexCountOutput; uint32_t* indices; } XrHandMeshIndexBufferMSFT; typedef struct XrHandMeshVertexMSFT { XrVector3f position; XrVector3f normal; } XrHandMeshVertexMSFT; typedef struct XrHandMeshVertexBufferMSFT { XrTime vertexUpdateTime; uint32_t vertexCapacityInput; uint32_t vertexCountOutput; XrHandMeshVertexMSFT* vertices; } XrHandMeshVertexBufferMSFT; typedef struct XrHandMeshMSFT { XrStructureType type; void* XR_MAY_ALIAS next; XrBool32 isActive; XrBool32 indexBufferChanged; XrBool32 vertexBufferChanged; XrHandMeshIndexBufferMSFT indexBuffer; XrHandMeshVertexBufferMSFT vertexBuffer; } XrHandMeshMSFT; // XrHandPoseTypeInfoMSFT extends XrHandTrackerCreateInfoEXT typedef struct XrHandPoseTypeInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrHandPoseTypeMSFT handPoseType; } XrHandPoseTypeInfoMSFT; typedef XrResult (XRAPI_PTR *PFN_xrCreateHandMeshSpaceMSFT)(XrHandTrackerEXT handTracker, const XrHandMeshSpaceCreateInfoMSFT* createInfo, XrSpace* space); typedef XrResult (XRAPI_PTR *PFN_xrUpdateHandMeshMSFT)(XrHandTrackerEXT handTracker, const XrHandMeshUpdateInfoMSFT* updateInfo, XrHandMeshMSFT* handMesh); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreateHandMeshSpaceMSFT( XrHandTrackerEXT handTracker, const XrHandMeshSpaceCreateInfoMSFT* createInfo, XrSpace* space); XRAPI_ATTR XrResult XRAPI_CALL xrUpdateHandMeshMSFT( XrHandTrackerEXT handTracker, const XrHandMeshUpdateInfoMSFT* updateInfo, XrHandMeshMSFT* handMesh); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_MSFT_secondary_view_configuration 1 #define XR_MSFT_secondary_view_configuration_SPEC_VERSION 1 #define XR_MSFT_SECONDARY_VIEW_CONFIGURATION_EXTENSION_NAME "XR_MSFT_secondary_view_configuration" // XrSecondaryViewConfigurationSessionBeginInfoMSFT extends XrSessionBeginInfo typedef struct XrSecondaryViewConfigurationSessionBeginInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t viewConfigurationCount; const XrViewConfigurationType* enabledViewConfigurationTypes; } XrSecondaryViewConfigurationSessionBeginInfoMSFT; typedef struct XrSecondaryViewConfigurationStateMSFT { XrStructureType type; void* XR_MAY_ALIAS next; XrViewConfigurationType viewConfigurationType; XrBool32 active; } XrSecondaryViewConfigurationStateMSFT; // XrSecondaryViewConfigurationFrameStateMSFT extends XrFrameState typedef struct XrSecondaryViewConfigurationFrameStateMSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t viewConfigurationCount; XrSecondaryViewConfigurationStateMSFT* viewConfigurationStates; } XrSecondaryViewConfigurationFrameStateMSFT; typedef struct XrSecondaryViewConfigurationLayerInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrViewConfigurationType viewConfigurationType; XrEnvironmentBlendMode environmentBlendMode; uint32_t layerCount; const XrCompositionLayerBaseHeader* const* layers; } XrSecondaryViewConfigurationLayerInfoMSFT; // XrSecondaryViewConfigurationFrameEndInfoMSFT extends XrFrameEndInfo typedef struct XrSecondaryViewConfigurationFrameEndInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t viewConfigurationCount; const XrSecondaryViewConfigurationLayerInfoMSFT* viewConfigurationLayersInfo; } XrSecondaryViewConfigurationFrameEndInfoMSFT; // XrSecondaryViewConfigurationSwapchainCreateInfoMSFT extends XrSwapchainCreateInfo typedef struct XrSecondaryViewConfigurationSwapchainCreateInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrViewConfigurationType viewConfigurationType; } XrSecondaryViewConfigurationSwapchainCreateInfoMSFT; #define XR_MSFT_first_person_observer 1 #define XR_MSFT_first_person_observer_SPEC_VERSION 1 #define XR_MSFT_FIRST_PERSON_OBSERVER_EXTENSION_NAME "XR_MSFT_first_person_observer" #define XR_MSFT_controller_model 1 #define XR_NULL_CONTROLLER_MODEL_KEY_MSFT 0 XR_DEFINE_ATOM(XrControllerModelKeyMSFT) #define XR_MSFT_controller_model_SPEC_VERSION 2 #define XR_MSFT_CONTROLLER_MODEL_EXTENSION_NAME "XR_MSFT_controller_model" #define XR_MAX_CONTROLLER_MODEL_NODE_NAME_SIZE_MSFT 64 typedef struct XrControllerModelKeyStateMSFT { XrStructureType type; void* XR_MAY_ALIAS next; XrControllerModelKeyMSFT modelKey; } XrControllerModelKeyStateMSFT; typedef struct XrControllerModelNodePropertiesMSFT { XrStructureType type; void* XR_MAY_ALIAS next; char parentNodeName[XR_MAX_CONTROLLER_MODEL_NODE_NAME_SIZE_MSFT]; char nodeName[XR_MAX_CONTROLLER_MODEL_NODE_NAME_SIZE_MSFT]; } XrControllerModelNodePropertiesMSFT; typedef struct XrControllerModelPropertiesMSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t nodeCapacityInput; uint32_t nodeCountOutput; XrControllerModelNodePropertiesMSFT* nodeProperties; } XrControllerModelPropertiesMSFT; typedef struct XrControllerModelNodeStateMSFT { XrStructureType type; void* XR_MAY_ALIAS next; XrPosef nodePose; } XrControllerModelNodeStateMSFT; typedef struct XrControllerModelStateMSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t nodeCapacityInput; uint32_t nodeCountOutput; XrControllerModelNodeStateMSFT* nodeStates; } XrControllerModelStateMSFT; typedef XrResult (XRAPI_PTR *PFN_xrGetControllerModelKeyMSFT)(XrSession session, XrPath topLevelUserPath, XrControllerModelKeyStateMSFT* controllerModelKeyState); typedef XrResult (XRAPI_PTR *PFN_xrLoadControllerModelMSFT)(XrSession session, XrControllerModelKeyMSFT modelKey, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, uint8_t* buffer); typedef XrResult (XRAPI_PTR *PFN_xrGetControllerModelPropertiesMSFT)(XrSession session, XrControllerModelKeyMSFT modelKey, XrControllerModelPropertiesMSFT* properties); typedef XrResult (XRAPI_PTR *PFN_xrGetControllerModelStateMSFT)(XrSession session, XrControllerModelKeyMSFT modelKey, XrControllerModelStateMSFT* state); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrGetControllerModelKeyMSFT( XrSession session, XrPath topLevelUserPath, XrControllerModelKeyStateMSFT* controllerModelKeyState); XRAPI_ATTR XrResult XRAPI_CALL xrLoadControllerModelMSFT( XrSession session, XrControllerModelKeyMSFT modelKey, uint32_t bufferCapacityInput, uint32_t* bufferCountOutput, uint8_t* buffer); XRAPI_ATTR XrResult XRAPI_CALL xrGetControllerModelPropertiesMSFT( XrSession session, XrControllerModelKeyMSFT modelKey, XrControllerModelPropertiesMSFT* properties); XRAPI_ATTR XrResult XRAPI_CALL xrGetControllerModelStateMSFT( XrSession session, XrControllerModelKeyMSFT modelKey, XrControllerModelStateMSFT* state); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_EXT_win32_appcontainer_compatible 1 #define XR_EXT_win32_appcontainer_compatible_SPEC_VERSION 1 #define XR_EXT_WIN32_APPCONTAINER_COMPATIBLE_EXTENSION_NAME "XR_EXT_win32_appcontainer_compatible" #define XR_EPIC_view_configuration_fov 1 #define XR_EPIC_view_configuration_fov_SPEC_VERSION 2 #define XR_EPIC_VIEW_CONFIGURATION_FOV_EXTENSION_NAME "XR_EPIC_view_configuration_fov" // XrViewConfigurationViewFovEPIC extends XrViewConfigurationView typedef struct XrViewConfigurationViewFovEPIC { XrStructureType type; const void* XR_MAY_ALIAS next; XrFovf recommendedFov; XrFovf maxMutableFov; } XrViewConfigurationViewFovEPIC; #define XR_MSFT_composition_layer_reprojection 1 #define XR_MSFT_composition_layer_reprojection_SPEC_VERSION 1 #define XR_MSFT_COMPOSITION_LAYER_REPROJECTION_EXTENSION_NAME "XR_MSFT_composition_layer_reprojection" typedef enum XrReprojectionModeMSFT { XR_REPROJECTION_MODE_DEPTH_MSFT = 1, XR_REPROJECTION_MODE_PLANAR_FROM_DEPTH_MSFT = 2, XR_REPROJECTION_MODE_PLANAR_MANUAL_MSFT = 3, XR_REPROJECTION_MODE_ORIENTATION_ONLY_MSFT = 4, XR_REPROJECTION_MODE_MAX_ENUM_MSFT = 0x7FFFFFFF } XrReprojectionModeMSFT; // XrCompositionLayerReprojectionInfoMSFT extends XrCompositionLayerProjection typedef struct XrCompositionLayerReprojectionInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrReprojectionModeMSFT reprojectionMode; } XrCompositionLayerReprojectionInfoMSFT; // XrCompositionLayerReprojectionPlaneOverrideMSFT extends XrCompositionLayerProjection typedef struct XrCompositionLayerReprojectionPlaneOverrideMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrVector3f position; XrVector3f normal; XrVector3f velocity; } XrCompositionLayerReprojectionPlaneOverrideMSFT; typedef XrResult (XRAPI_PTR *PFN_xrEnumerateReprojectionModesMSFT)(XrInstance instance, XrSystemId systemId, XrViewConfigurationType viewConfigurationType, uint32_t modeCapacityInput, uint32_t* modeCountOutput, XrReprojectionModeMSFT* modes); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateReprojectionModesMSFT( XrInstance instance, XrSystemId systemId, XrViewConfigurationType viewConfigurationType, uint32_t modeCapacityInput, uint32_t* modeCountOutput, XrReprojectionModeMSFT* modes); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_HUAWEI_controller_interaction 1 #define XR_HUAWEI_controller_interaction_SPEC_VERSION 1 #define XR_HUAWEI_CONTROLLER_INTERACTION_EXTENSION_NAME "XR_HUAWEI_controller_interaction" #define XR_FB_swapchain_update_state 1 #define XR_FB_swapchain_update_state_SPEC_VERSION 3 #define XR_FB_SWAPCHAIN_UPDATE_STATE_EXTENSION_NAME "XR_FB_swapchain_update_state" typedef struct XR_MAY_ALIAS XrSwapchainStateBaseHeaderFB { XrStructureType type; void* XR_MAY_ALIAS next; } XrSwapchainStateBaseHeaderFB; typedef XrResult (XRAPI_PTR *PFN_xrUpdateSwapchainFB)(XrSwapchain swapchain, const XrSwapchainStateBaseHeaderFB* state); typedef XrResult (XRAPI_PTR *PFN_xrGetSwapchainStateFB)(XrSwapchain swapchain, XrSwapchainStateBaseHeaderFB* state); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrUpdateSwapchainFB( XrSwapchain swapchain, const XrSwapchainStateBaseHeaderFB* state); XRAPI_ATTR XrResult XRAPI_CALL xrGetSwapchainStateFB( XrSwapchain swapchain, XrSwapchainStateBaseHeaderFB* state); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_FB_composition_layer_secure_content 1 #define XR_FB_composition_layer_secure_content_SPEC_VERSION 1 #define XR_FB_COMPOSITION_LAYER_SECURE_CONTENT_EXTENSION_NAME "XR_FB_composition_layer_secure_content" typedef XrFlags64 XrCompositionLayerSecureContentFlagsFB; // Flag bits for XrCompositionLayerSecureContentFlagsFB static const XrCompositionLayerSecureContentFlagsFB XR_COMPOSITION_LAYER_SECURE_CONTENT_EXCLUDE_LAYER_BIT_FB = 0x00000001; static const XrCompositionLayerSecureContentFlagsFB XR_COMPOSITION_LAYER_SECURE_CONTENT_REPLACE_LAYER_BIT_FB = 0x00000002; // XrCompositionLayerSecureContentFB extends XrCompositionLayerBaseHeader typedef struct XrCompositionLayerSecureContentFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrCompositionLayerSecureContentFlagsFB flags; } XrCompositionLayerSecureContentFB; #define XR_VALVE_analog_threshold 1 #define XR_VALVE_analog_threshold_SPEC_VERSION 2 #define XR_VALVE_ANALOG_THRESHOLD_EXTENSION_NAME "XR_VALVE_analog_threshold" typedef struct XrInteractionProfileAnalogThresholdVALVE { XrStructureType type; const void* XR_MAY_ALIAS next; XrAction action; XrPath binding; float onThreshold; float offThreshold; const XrHapticBaseHeader* onHaptic; const XrHapticBaseHeader* offHaptic; } XrInteractionProfileAnalogThresholdVALVE; #define XR_EXT_hand_joints_motion_range 1 #define XR_EXT_hand_joints_motion_range_SPEC_VERSION 1 #define XR_EXT_HAND_JOINTS_MOTION_RANGE_EXTENSION_NAME "XR_EXT_hand_joints_motion_range" typedef enum XrHandJointsMotionRangeEXT { XR_HAND_JOINTS_MOTION_RANGE_UNOBSTRUCTED_EXT = 1, XR_HAND_JOINTS_MOTION_RANGE_CONFORMING_TO_CONTROLLER_EXT = 2, XR_HAND_JOINTS_MOTION_RANGE_MAX_ENUM_EXT = 0x7FFFFFFF } XrHandJointsMotionRangeEXT; // XrHandJointsMotionRangeInfoEXT extends XrHandJointsLocateInfoEXT typedef struct XrHandJointsMotionRangeInfoEXT { XrStructureType type; const void* XR_MAY_ALIAS next; XrHandJointsMotionRangeEXT handJointsMotionRange; } XrHandJointsMotionRangeInfoEXT; #define XR_EXT_samsung_odyssey_controller 1 #define XR_EXT_samsung_odyssey_controller_SPEC_VERSION 1 #define XR_EXT_SAMSUNG_ODYSSEY_CONTROLLER_EXTENSION_NAME "XR_EXT_samsung_odyssey_controller" #define XR_EXT_hp_mixed_reality_controller 1 #define XR_EXT_hp_mixed_reality_controller_SPEC_VERSION 1 #define XR_EXT_HP_MIXED_REALITY_CONTROLLER_EXTENSION_NAME "XR_EXT_hp_mixed_reality_controller" #define XR_MND_swapchain_usage_input_attachment_bit 1 #define XR_MND_swapchain_usage_input_attachment_bit_SPEC_VERSION 2 #define XR_MND_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT_EXTENSION_NAME "XR_MND_swapchain_usage_input_attachment_bit" #define XR_MSFT_scene_understanding 1 XR_DEFINE_HANDLE(XrSceneObserverMSFT) XR_DEFINE_HANDLE(XrSceneMSFT) #define XR_MSFT_scene_understanding_SPEC_VERSION 1 #define XR_MSFT_SCENE_UNDERSTANDING_EXTENSION_NAME "XR_MSFT_scene_understanding" typedef enum XrSceneComputeFeatureMSFT { XR_SCENE_COMPUTE_FEATURE_PLANE_MSFT = 1, XR_SCENE_COMPUTE_FEATURE_PLANE_MESH_MSFT = 2, XR_SCENE_COMPUTE_FEATURE_VISUAL_MESH_MSFT = 3, XR_SCENE_COMPUTE_FEATURE_COLLIDER_MESH_MSFT = 4, XR_SCENE_COMPUTE_FEATURE_SERIALIZE_SCENE_MSFT = 1000098000, XR_SCENE_COMPUTE_FEATURE_MAX_ENUM_MSFT = 0x7FFFFFFF } XrSceneComputeFeatureMSFT; typedef enum XrSceneComputeConsistencyMSFT { XR_SCENE_COMPUTE_CONSISTENCY_SNAPSHOT_COMPLETE_MSFT = 1, XR_SCENE_COMPUTE_CONSISTENCY_SNAPSHOT_INCOMPLETE_FAST_MSFT = 2, XR_SCENE_COMPUTE_CONSISTENCY_OCCLUSION_OPTIMIZED_MSFT = 3, XR_SCENE_COMPUTE_CONSISTENCY_MAX_ENUM_MSFT = 0x7FFFFFFF } XrSceneComputeConsistencyMSFT; typedef enum XrMeshComputeLodMSFT { XR_MESH_COMPUTE_LOD_COARSE_MSFT = 1, XR_MESH_COMPUTE_LOD_MEDIUM_MSFT = 2, XR_MESH_COMPUTE_LOD_FINE_MSFT = 3, XR_MESH_COMPUTE_LOD_UNLIMITED_MSFT = 4, XR_MESH_COMPUTE_LOD_MAX_ENUM_MSFT = 0x7FFFFFFF } XrMeshComputeLodMSFT; typedef enum XrSceneComponentTypeMSFT { XR_SCENE_COMPONENT_TYPE_INVALID_MSFT = -1, XR_SCENE_COMPONENT_TYPE_OBJECT_MSFT = 1, XR_SCENE_COMPONENT_TYPE_PLANE_MSFT = 2, XR_SCENE_COMPONENT_TYPE_VISUAL_MESH_MSFT = 3, XR_SCENE_COMPONENT_TYPE_COLLIDER_MESH_MSFT = 4, XR_SCENE_COMPONENT_TYPE_SERIALIZED_SCENE_FRAGMENT_MSFT = 1000098000, XR_SCENE_COMPONENT_TYPE_MAX_ENUM_MSFT = 0x7FFFFFFF } XrSceneComponentTypeMSFT; typedef enum XrSceneObjectTypeMSFT { XR_SCENE_OBJECT_TYPE_UNCATEGORIZED_MSFT = -1, XR_SCENE_OBJECT_TYPE_BACKGROUND_MSFT = 1, XR_SCENE_OBJECT_TYPE_WALL_MSFT = 2, XR_SCENE_OBJECT_TYPE_FLOOR_MSFT = 3, XR_SCENE_OBJECT_TYPE_CEILING_MSFT = 4, XR_SCENE_OBJECT_TYPE_PLATFORM_MSFT = 5, XR_SCENE_OBJECT_TYPE_INFERRED_MSFT = 6, XR_SCENE_OBJECT_TYPE_MAX_ENUM_MSFT = 0x7FFFFFFF } XrSceneObjectTypeMSFT; typedef enum XrScenePlaneAlignmentTypeMSFT { XR_SCENE_PLANE_ALIGNMENT_TYPE_NON_ORTHOGONAL_MSFT = 0, XR_SCENE_PLANE_ALIGNMENT_TYPE_HORIZONTAL_MSFT = 1, XR_SCENE_PLANE_ALIGNMENT_TYPE_VERTICAL_MSFT = 2, XR_SCENE_PLANE_ALIGNMENT_TYPE_MAX_ENUM_MSFT = 0x7FFFFFFF } XrScenePlaneAlignmentTypeMSFT; typedef enum XrSceneComputeStateMSFT { XR_SCENE_COMPUTE_STATE_NONE_MSFT = 0, XR_SCENE_COMPUTE_STATE_UPDATING_MSFT = 1, XR_SCENE_COMPUTE_STATE_COMPLETED_MSFT = 2, XR_SCENE_COMPUTE_STATE_COMPLETED_WITH_ERROR_MSFT = 3, XR_SCENE_COMPUTE_STATE_MAX_ENUM_MSFT = 0x7FFFFFFF } XrSceneComputeStateMSFT; typedef struct XrUuidMSFT { uint8_t bytes[16]; } XrUuidMSFT; typedef struct XrSceneObserverCreateInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; } XrSceneObserverCreateInfoMSFT; typedef struct XrSceneCreateInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; } XrSceneCreateInfoMSFT; typedef struct XrSceneSphereBoundMSFT { XrVector3f center; float radius; } XrSceneSphereBoundMSFT; typedef struct XrSceneOrientedBoxBoundMSFT { XrPosef pose; XrVector3f extents; } XrSceneOrientedBoxBoundMSFT; typedef struct XrSceneFrustumBoundMSFT { XrPosef pose; XrFovf fov; float farDistance; } XrSceneFrustumBoundMSFT; typedef struct XrSceneBoundsMSFT { XrSpace space; XrTime time; uint32_t sphereCount; const XrSceneSphereBoundMSFT* spheres; uint32_t boxCount; const XrSceneOrientedBoxBoundMSFT* boxes; uint32_t frustumCount; const XrSceneFrustumBoundMSFT* frustums; } XrSceneBoundsMSFT; typedef struct XrNewSceneComputeInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t requestedFeatureCount; const XrSceneComputeFeatureMSFT* requestedFeatures; XrSceneComputeConsistencyMSFT consistency; XrSceneBoundsMSFT bounds; } XrNewSceneComputeInfoMSFT; // XrVisualMeshComputeLodInfoMSFT extends XrNewSceneComputeInfoMSFT typedef struct XrVisualMeshComputeLodInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrMeshComputeLodMSFT lod; } XrVisualMeshComputeLodInfoMSFT; typedef struct XrSceneComponentMSFT { XrSceneComponentTypeMSFT componentType; XrUuidMSFT id; XrUuidMSFT parentId; XrTime updateTime; } XrSceneComponentMSFT; typedef struct XrSceneComponentsMSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t componentCapacityInput; uint32_t componentCountOutput; XrSceneComponentMSFT* components; } XrSceneComponentsMSFT; typedef struct XrSceneComponentsGetInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrSceneComponentTypeMSFT componentType; } XrSceneComponentsGetInfoMSFT; typedef struct XrSceneComponentLocationMSFT { XrSpaceLocationFlags flags; XrPosef pose; } XrSceneComponentLocationMSFT; typedef struct XrSceneComponentLocationsMSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t locationCount; XrSceneComponentLocationMSFT* locations; } XrSceneComponentLocationsMSFT; typedef struct XrSceneComponentsLocateInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrSpace baseSpace; XrTime time; uint32_t componentIdCount; const XrUuidMSFT* componentIds; } XrSceneComponentsLocateInfoMSFT; typedef struct XrSceneObjectMSFT { XrSceneObjectTypeMSFT objectType; } XrSceneObjectMSFT; // XrSceneObjectsMSFT extends XrSceneComponentsMSFT typedef struct XrSceneObjectsMSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t sceneObjectCount; XrSceneObjectMSFT* sceneObjects; } XrSceneObjectsMSFT; // XrSceneComponentParentFilterInfoMSFT extends XrSceneComponentsGetInfoMSFT typedef struct XrSceneComponentParentFilterInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrUuidMSFT parentId; } XrSceneComponentParentFilterInfoMSFT; // XrSceneObjectTypesFilterInfoMSFT extends XrSceneComponentsGetInfoMSFT typedef struct XrSceneObjectTypesFilterInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t objectTypeCount; const XrSceneObjectTypeMSFT* objectTypes; } XrSceneObjectTypesFilterInfoMSFT; typedef struct XrScenePlaneMSFT { XrScenePlaneAlignmentTypeMSFT alignment; XrExtent2Df size; uint64_t meshBufferId; XrBool32 supportsIndicesUint16; } XrScenePlaneMSFT; // XrScenePlanesMSFT extends XrSceneComponentsMSFT typedef struct XrScenePlanesMSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t scenePlaneCount; XrScenePlaneMSFT* scenePlanes; } XrScenePlanesMSFT; // XrScenePlaneAlignmentFilterInfoMSFT extends XrSceneComponentsGetInfoMSFT typedef struct XrScenePlaneAlignmentFilterInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t alignmentCount; const XrScenePlaneAlignmentTypeMSFT* alignments; } XrScenePlaneAlignmentFilterInfoMSFT; typedef struct XrSceneMeshMSFT { uint64_t meshBufferId; XrBool32 supportsIndicesUint16; } XrSceneMeshMSFT; // XrSceneMeshesMSFT extends XrSceneComponentsMSFT typedef struct XrSceneMeshesMSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t sceneMeshCount; XrSceneMeshMSFT* sceneMeshes; } XrSceneMeshesMSFT; typedef struct XrSceneMeshBuffersGetInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; uint64_t meshBufferId; } XrSceneMeshBuffersGetInfoMSFT; typedef struct XrSceneMeshBuffersMSFT { XrStructureType type; void* XR_MAY_ALIAS next; } XrSceneMeshBuffersMSFT; typedef struct XrSceneMeshVertexBufferMSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t vertexCapacityInput; uint32_t vertexCountOutput; XrVector3f* vertices; } XrSceneMeshVertexBufferMSFT; typedef struct XrSceneMeshIndicesUint32MSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t indexCapacityInput; uint32_t indexCountOutput; uint32_t* indices; } XrSceneMeshIndicesUint32MSFT; typedef struct XrSceneMeshIndicesUint16MSFT { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t indexCapacityInput; uint32_t indexCountOutput; uint16_t* indices; } XrSceneMeshIndicesUint16MSFT; typedef XrResult (XRAPI_PTR *PFN_xrEnumerateSceneComputeFeaturesMSFT)(XrInstance instance, XrSystemId systemId, uint32_t featureCapacityInput, uint32_t* featureCountOutput, XrSceneComputeFeatureMSFT* features); typedef XrResult (XRAPI_PTR *PFN_xrCreateSceneObserverMSFT)(XrSession session, const XrSceneObserverCreateInfoMSFT* createInfo, XrSceneObserverMSFT* sceneObserver); typedef XrResult (XRAPI_PTR *PFN_xrDestroySceneObserverMSFT)(XrSceneObserverMSFT sceneObserver); typedef XrResult (XRAPI_PTR *PFN_xrCreateSceneMSFT)(XrSceneObserverMSFT sceneObserver, const XrSceneCreateInfoMSFT* createInfo, XrSceneMSFT* scene); typedef XrResult (XRAPI_PTR *PFN_xrDestroySceneMSFT)(XrSceneMSFT scene); typedef XrResult (XRAPI_PTR *PFN_xrComputeNewSceneMSFT)(XrSceneObserverMSFT sceneObserver, const XrNewSceneComputeInfoMSFT* computeInfo); typedef XrResult (XRAPI_PTR *PFN_xrGetSceneComputeStateMSFT)(XrSceneObserverMSFT sceneObserver, XrSceneComputeStateMSFT* state); typedef XrResult (XRAPI_PTR *PFN_xrGetSceneComponentsMSFT)(XrSceneMSFT scene, const XrSceneComponentsGetInfoMSFT* getInfo, XrSceneComponentsMSFT* components); typedef XrResult (XRAPI_PTR *PFN_xrLocateSceneComponentsMSFT)(XrSceneMSFT scene, const XrSceneComponentsLocateInfoMSFT* locateInfo, XrSceneComponentLocationsMSFT* locations); typedef XrResult (XRAPI_PTR *PFN_xrGetSceneMeshBuffersMSFT)(XrSceneMSFT scene, const XrSceneMeshBuffersGetInfoMSFT* getInfo, XrSceneMeshBuffersMSFT* buffers); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateSceneComputeFeaturesMSFT( XrInstance instance, XrSystemId systemId, uint32_t featureCapacityInput, uint32_t* featureCountOutput, XrSceneComputeFeatureMSFT* features); XRAPI_ATTR XrResult XRAPI_CALL xrCreateSceneObserverMSFT( XrSession session, const XrSceneObserverCreateInfoMSFT* createInfo, XrSceneObserverMSFT* sceneObserver); XRAPI_ATTR XrResult XRAPI_CALL xrDestroySceneObserverMSFT( XrSceneObserverMSFT sceneObserver); XRAPI_ATTR XrResult XRAPI_CALL xrCreateSceneMSFT( XrSceneObserverMSFT sceneObserver, const XrSceneCreateInfoMSFT* createInfo, XrSceneMSFT* scene); XRAPI_ATTR XrResult XRAPI_CALL xrDestroySceneMSFT( XrSceneMSFT scene); XRAPI_ATTR XrResult XRAPI_CALL xrComputeNewSceneMSFT( XrSceneObserverMSFT sceneObserver, const XrNewSceneComputeInfoMSFT* computeInfo); XRAPI_ATTR XrResult XRAPI_CALL xrGetSceneComputeStateMSFT( XrSceneObserverMSFT sceneObserver, XrSceneComputeStateMSFT* state); XRAPI_ATTR XrResult XRAPI_CALL xrGetSceneComponentsMSFT( XrSceneMSFT scene, const XrSceneComponentsGetInfoMSFT* getInfo, XrSceneComponentsMSFT* components); XRAPI_ATTR XrResult XRAPI_CALL xrLocateSceneComponentsMSFT( XrSceneMSFT scene, const XrSceneComponentsLocateInfoMSFT* locateInfo, XrSceneComponentLocationsMSFT* locations); XRAPI_ATTR XrResult XRAPI_CALL xrGetSceneMeshBuffersMSFT( XrSceneMSFT scene, const XrSceneMeshBuffersGetInfoMSFT* getInfo, XrSceneMeshBuffersMSFT* buffers); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_MSFT_scene_understanding_serialization 1 #define XR_MSFT_scene_understanding_serialization_SPEC_VERSION 1 #define XR_MSFT_SCENE_UNDERSTANDING_SERIALIZATION_EXTENSION_NAME "XR_MSFT_scene_understanding_serialization" typedef struct XrSerializedSceneFragmentDataGetInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrUuidMSFT sceneFragmentId; } XrSerializedSceneFragmentDataGetInfoMSFT; typedef struct XrDeserializeSceneFragmentMSFT { uint32_t bufferSize; const uint8_t* buffer; } XrDeserializeSceneFragmentMSFT; typedef struct XrSceneDeserializeInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; uint32_t fragmentCount; const XrDeserializeSceneFragmentMSFT* fragments; } XrSceneDeserializeInfoMSFT; typedef XrResult (XRAPI_PTR *PFN_xrDeserializeSceneMSFT)(XrSceneObserverMSFT sceneObserver, const XrSceneDeserializeInfoMSFT* deserializeInfo); typedef XrResult (XRAPI_PTR *PFN_xrGetSerializedSceneFragmentDataMSFT)(XrSceneMSFT scene, const XrSerializedSceneFragmentDataGetInfoMSFT* getInfo, uint32_t countInput, uint32_t* readOutput, uint8_t* buffer); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrDeserializeSceneMSFT( XrSceneObserverMSFT sceneObserver, const XrSceneDeserializeInfoMSFT* deserializeInfo); XRAPI_ATTR XrResult XRAPI_CALL xrGetSerializedSceneFragmentDataMSFT( XrSceneMSFT scene, const XrSerializedSceneFragmentDataGetInfoMSFT* getInfo, uint32_t countInput, uint32_t* readOutput, uint8_t* buffer); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_FB_display_refresh_rate 1 #define XR_FB_display_refresh_rate_SPEC_VERSION 1 #define XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME "XR_FB_display_refresh_rate" typedef struct XrEventDataDisplayRefreshRateChangedFB { XrStructureType type; const void* XR_MAY_ALIAS next; float fromDisplayRefreshRate; float toDisplayRefreshRate; } XrEventDataDisplayRefreshRateChangedFB; typedef XrResult (XRAPI_PTR *PFN_xrEnumerateDisplayRefreshRatesFB)(XrSession session, uint32_t displayRefreshRateCapacityInput, uint32_t* displayRefreshRateCountOutput, float* displayRefreshRates); typedef XrResult (XRAPI_PTR *PFN_xrGetDisplayRefreshRateFB)(XrSession session, float* displayRefreshRate); typedef XrResult (XRAPI_PTR *PFN_xrRequestDisplayRefreshRateFB)(XrSession session, float displayRefreshRate); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateDisplayRefreshRatesFB( XrSession session, uint32_t displayRefreshRateCapacityInput, uint32_t* displayRefreshRateCountOutput, float* displayRefreshRates); XRAPI_ATTR XrResult XRAPI_CALL xrGetDisplayRefreshRateFB( XrSession session, float* displayRefreshRate); XRAPI_ATTR XrResult XRAPI_CALL xrRequestDisplayRefreshRateFB( XrSession session, float displayRefreshRate); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_HTC_vive_cosmos_controller_interaction 1 #define XR_HTC_vive_cosmos_controller_interaction_SPEC_VERSION 1 #define XR_HTC_VIVE_COSMOS_CONTROLLER_INTERACTION_EXTENSION_NAME "XR_HTC_vive_cosmos_controller_interaction" #define XR_HTCX_vive_tracker_interaction 1 #define XR_HTCX_vive_tracker_interaction_SPEC_VERSION 1 #define XR_HTCX_VIVE_TRACKER_INTERACTION_EXTENSION_NAME "XR_HTCX_vive_tracker_interaction" typedef struct XrViveTrackerPathsHTCX { XrStructureType type; void* XR_MAY_ALIAS next; XrPath persistentPath; XrPath rolePath; } XrViveTrackerPathsHTCX; typedef struct XrEventDataViveTrackerConnectedHTCX { XrStructureType type; const void* XR_MAY_ALIAS next; XrViveTrackerPathsHTCX* paths; } XrEventDataViveTrackerConnectedHTCX; typedef XrResult (XRAPI_PTR *PFN_xrEnumerateViveTrackerPathsHTCX)(XrInstance instance, uint32_t pathCapacityInput, uint32_t* pathCountOutput, XrViveTrackerPathsHTCX* paths); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateViveTrackerPathsHTCX( XrInstance instance, uint32_t pathCapacityInput, uint32_t* pathCountOutput, XrViveTrackerPathsHTCX* paths); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_FB_color_space 1 #define XR_FB_color_space_SPEC_VERSION 2 #define XR_FB_COLOR_SPACE_EXTENSION_NAME "XR_FB_color_space" typedef enum XrColorSpaceFB { XR_COLOR_SPACE_UNMANAGED_FB = 0, XR_COLOR_SPACE_REC2020_FB = 1, XR_COLOR_SPACE_REC709_FB = 2, XR_COLOR_SPACE_RIFT_CV1_FB = 3, XR_COLOR_SPACE_RIFT_S_FB = 4, XR_COLOR_SPACE_QUEST_FB = 5, XR_COLOR_SPACE_P3_FB = 6, XR_COLOR_SPACE_ADOBE_RGB_FB = 7, XR_COLOR_SPACE_MAX_ENUM_FB = 0x7FFFFFFF } XrColorSpaceFB; // XrSystemColorSpacePropertiesFB extends XrSystemProperties typedef struct XrSystemColorSpacePropertiesFB { XrStructureType type; void* XR_MAY_ALIAS next; XrColorSpaceFB colorSpace; } XrSystemColorSpacePropertiesFB; typedef XrResult (XRAPI_PTR *PFN_xrEnumerateColorSpacesFB)(XrSession session, uint32_t colorSpaceCapacityInput, uint32_t* colorSpaceCountOutput, XrColorSpaceFB* colorSpaces); typedef XrResult (XRAPI_PTR *PFN_xrSetColorSpaceFB)(XrSession session, const XrColorSpaceFB colorspace); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateColorSpacesFB( XrSession session, uint32_t colorSpaceCapacityInput, uint32_t* colorSpaceCountOutput, XrColorSpaceFB* colorSpaces); XRAPI_ATTR XrResult XRAPI_CALL xrSetColorSpaceFB( XrSession session, const XrColorSpaceFB colorspace); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_FB_hand_tracking_mesh 1 #define XR_FB_hand_tracking_mesh_SPEC_VERSION 1 #define XR_FB_HAND_TRACKING_MESH_EXTENSION_NAME "XR_FB_hand_tracking_mesh" typedef struct XrVector4sFB { int16_t x; int16_t y; int16_t z; int16_t w; } XrVector4sFB; typedef struct XrHandTrackingMeshFB { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t jointCapacityInput; uint32_t jointCountOutput; XrPosef* jointBindPoses; float* jointRadii; XrHandJointEXT* jointParents; uint32_t vertexCapacityInput; uint32_t vertexCountOutput; XrVector3f* vertexPositions; XrVector3f* vertexNormals; XrVector2f* vertexUVs; XrVector4sFB* vertexBlendIndices; XrVector4f* vertexBlendWeights; uint32_t indexCapacityInput; uint32_t indexCountOutput; int16_t* indices; } XrHandTrackingMeshFB; // XrHandTrackingScaleFB extends XrHandJointsLocateInfoEXT typedef struct XrHandTrackingScaleFB { XrStructureType type; void* XR_MAY_ALIAS next; float sensorOutput; float currentOutput; XrBool32 overrideHandScale; float overrideValueInput; } XrHandTrackingScaleFB; typedef XrResult (XRAPI_PTR *PFN_xrGetHandMeshFB)(XrHandTrackerEXT handTracker, XrHandTrackingMeshFB* mesh); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrGetHandMeshFB( XrHandTrackerEXT handTracker, XrHandTrackingMeshFB* mesh); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_FB_hand_tracking_aim 1 #define XR_FB_hand_tracking_aim_SPEC_VERSION 1 #define XR_FB_HAND_TRACKING_AIM_EXTENSION_NAME "XR_FB_hand_tracking_aim" typedef XrFlags64 XrHandTrackingAimFlagsFB; // Flag bits for XrHandTrackingAimFlagsFB static const XrHandTrackingAimFlagsFB XR_HAND_TRACKING_AIM_COMPUTED_BIT_FB = 0x00000001; static const XrHandTrackingAimFlagsFB XR_HAND_TRACKING_AIM_VALID_BIT_FB = 0x00000002; static const XrHandTrackingAimFlagsFB XR_HAND_TRACKING_AIM_INDEX_PINCHING_BIT_FB = 0x00000004; static const XrHandTrackingAimFlagsFB XR_HAND_TRACKING_AIM_MIDDLE_PINCHING_BIT_FB = 0x00000008; static const XrHandTrackingAimFlagsFB XR_HAND_TRACKING_AIM_RING_PINCHING_BIT_FB = 0x00000010; static const XrHandTrackingAimFlagsFB XR_HAND_TRACKING_AIM_LITTLE_PINCHING_BIT_FB = 0x00000020; static const XrHandTrackingAimFlagsFB XR_HAND_TRACKING_AIM_SYSTEM_GESTURE_BIT_FB = 0x00000040; static const XrHandTrackingAimFlagsFB XR_HAND_TRACKING_AIM_DOMINANT_HAND_BIT_FB = 0x00000080; static const XrHandTrackingAimFlagsFB XR_HAND_TRACKING_AIM_MENU_PRESSED_BIT_FB = 0x00000100; // XrHandTrackingAimStateFB extends XrHandJointsLocateInfoEXT typedef struct XrHandTrackingAimStateFB { XrStructureType type; void* XR_MAY_ALIAS next; XrHandTrackingAimFlagsFB status; XrPosef aimPose; float pinchStrengthIndex; float pinchStrengthMiddle; float pinchStrengthRing; float pinchStrengthLittle; } XrHandTrackingAimStateFB; #define XR_FB_hand_tracking_capsules 1 #define XR_FB_HAND_TRACKING_CAPSULE_POINT_COUNT 2 #define XR_FB_HAND_TRACKING_CAPSULE_COUNT 19 #define XR_FB_hand_tracking_capsules_SPEC_VERSION 1 #define XR_FB_HAND_TRACKING_CAPSULES_EXTENSION_NAME "XR_FB_hand_tracking_capsules" typedef struct XrHandCapsuleFB { XrVector3f points[XR_FB_HAND_TRACKING_CAPSULE_POINT_COUNT]; float radius; XrHandJointEXT joint; } XrHandCapsuleFB; // XrHandTrackingCapsulesStateFB extends XrHandJointsLocateInfoEXT typedef struct XrHandTrackingCapsulesStateFB { XrStructureType type; void* XR_MAY_ALIAS next; XrHandCapsuleFB capsules[XR_FB_HAND_TRACKING_CAPSULE_COUNT]; } XrHandTrackingCapsulesStateFB; #define XR_FB_foveation 1 XR_DEFINE_HANDLE(XrFoveationProfileFB) #define XR_FB_foveation_SPEC_VERSION 1 #define XR_FB_FOVEATION_EXTENSION_NAME "XR_FB_foveation" typedef XrFlags64 XrSwapchainCreateFoveationFlagsFB; // Flag bits for XrSwapchainCreateFoveationFlagsFB static const XrSwapchainCreateFoveationFlagsFB XR_SWAPCHAIN_CREATE_FOVEATION_SCALED_BIN_BIT_FB = 0x00000001; static const XrSwapchainCreateFoveationFlagsFB XR_SWAPCHAIN_CREATE_FOVEATION_FRAGMENT_DENSITY_MAP_BIT_FB = 0x00000002; typedef XrFlags64 XrSwapchainStateFoveationFlagsFB; // Flag bits for XrSwapchainStateFoveationFlagsFB typedef struct XrFoveationProfileCreateInfoFB { XrStructureType type; void* XR_MAY_ALIAS next; } XrFoveationProfileCreateInfoFB; // XrSwapchainCreateInfoFoveationFB extends XrSwapchainCreateInfo typedef struct XrSwapchainCreateInfoFoveationFB { XrStructureType type; void* XR_MAY_ALIAS next; XrSwapchainCreateFoveationFlagsFB flags; } XrSwapchainCreateInfoFoveationFB; typedef struct XrSwapchainStateFoveationFB { XrStructureType type; void* XR_MAY_ALIAS next; XrSwapchainStateFoveationFlagsFB flags; XrFoveationProfileFB profile; } XrSwapchainStateFoveationFB; typedef XrResult (XRAPI_PTR *PFN_xrCreateFoveationProfileFB)(XrSession session, const XrFoveationProfileCreateInfoFB* createInfo, XrFoveationProfileFB* profile); typedef XrResult (XRAPI_PTR *PFN_xrDestroyFoveationProfileFB)(XrFoveationProfileFB profile); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreateFoveationProfileFB( XrSession session, const XrFoveationProfileCreateInfoFB* createInfo, XrFoveationProfileFB* profile); XRAPI_ATTR XrResult XRAPI_CALL xrDestroyFoveationProfileFB( XrFoveationProfileFB profile); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_FB_foveation_configuration 1 #define XR_FB_foveation_configuration_SPEC_VERSION 1 #define XR_FB_FOVEATION_CONFIGURATION_EXTENSION_NAME "XR_FB_foveation_configuration" typedef enum XrFoveationLevelFB { XR_FOVEATION_LEVEL_NONE_FB = 0, XR_FOVEATION_LEVEL_LOW_FB = 1, XR_FOVEATION_LEVEL_MEDIUM_FB = 2, XR_FOVEATION_LEVEL_HIGH_FB = 3, XR_FOVEATION_LEVEL_MAX_ENUM_FB = 0x7FFFFFFF } XrFoveationLevelFB; typedef enum XrFoveationDynamicFB { XR_FOVEATION_DYNAMIC_DISABLED_FB = 0, XR_FOVEATION_DYNAMIC_LEVEL_ENABLED_FB = 1, XR_FOVEATION_DYNAMIC_MAX_ENUM_FB = 0x7FFFFFFF } XrFoveationDynamicFB; // XrFoveationLevelProfileCreateInfoFB extends XrFoveationProfileCreateInfoFB typedef struct XrFoveationLevelProfileCreateInfoFB { XrStructureType type; void* XR_MAY_ALIAS next; XrFoveationLevelFB level; float verticalOffset; XrFoveationDynamicFB dynamic; } XrFoveationLevelProfileCreateInfoFB; #define XR_FB_triangle_mesh 1 XR_DEFINE_HANDLE(XrTriangleMeshFB) #define XR_FB_triangle_mesh_SPEC_VERSION 1 #define XR_FB_TRIANGLE_MESH_EXTENSION_NAME "XR_FB_triangle_mesh" typedef enum XrWindingOrderFB { XR_WINDING_ORDER_UNKNOWN_FB = 0, XR_WINDING_ORDER_CW_FB = 1, XR_WINDING_ORDER_CCW_FB = 2, XR_WINDING_ORDER_MAX_ENUM_FB = 0x7FFFFFFF } XrWindingOrderFB; typedef XrFlags64 XrTriangleMeshFlagsFB; // Flag bits for XrTriangleMeshFlagsFB static const XrTriangleMeshFlagsFB XR_TRIANGLE_MESH_MUTABLE_BIT_FB = 0x00000001; typedef struct XrTriangleMeshCreateInfoFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrTriangleMeshFlagsFB flags; XrWindingOrderFB windingOrder; uint32_t vertexCount; const XrVector3f* vertexBuffer; uint32_t triangleCount; const uint32_t* indexBuffer; } XrTriangleMeshCreateInfoFB; typedef XrResult (XRAPI_PTR *PFN_xrCreateTriangleMeshFB)(XrSession session, const XrTriangleMeshCreateInfoFB* createInfo, XrTriangleMeshFB* outTriangleMesh); typedef XrResult (XRAPI_PTR *PFN_xrDestroyTriangleMeshFB)(XrTriangleMeshFB mesh); typedef XrResult (XRAPI_PTR *PFN_xrTriangleMeshGetVertexBufferFB)(XrTriangleMeshFB mesh, XrVector3f** outVertexBuffer); typedef XrResult (XRAPI_PTR *PFN_xrTriangleMeshGetIndexBufferFB)(XrTriangleMeshFB mesh, uint32_t** outIndexBuffer); typedef XrResult (XRAPI_PTR *PFN_xrTriangleMeshBeginUpdateFB)(XrTriangleMeshFB mesh); typedef XrResult (XRAPI_PTR *PFN_xrTriangleMeshEndUpdateFB)(XrTriangleMeshFB mesh, uint32_t vertexCount, uint32_t triangleCount); typedef XrResult (XRAPI_PTR *PFN_xrTriangleMeshBeginVertexBufferUpdateFB)(XrTriangleMeshFB mesh, uint32_t* outVertexCount); typedef XrResult (XRAPI_PTR *PFN_xrTriangleMeshEndVertexBufferUpdateFB)(XrTriangleMeshFB mesh); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreateTriangleMeshFB( XrSession session, const XrTriangleMeshCreateInfoFB* createInfo, XrTriangleMeshFB* outTriangleMesh); XRAPI_ATTR XrResult XRAPI_CALL xrDestroyTriangleMeshFB( XrTriangleMeshFB mesh); XRAPI_ATTR XrResult XRAPI_CALL xrTriangleMeshGetVertexBufferFB( XrTriangleMeshFB mesh, XrVector3f** outVertexBuffer); XRAPI_ATTR XrResult XRAPI_CALL xrTriangleMeshGetIndexBufferFB( XrTriangleMeshFB mesh, uint32_t** outIndexBuffer); XRAPI_ATTR XrResult XRAPI_CALL xrTriangleMeshBeginUpdateFB( XrTriangleMeshFB mesh); XRAPI_ATTR XrResult XRAPI_CALL xrTriangleMeshEndUpdateFB( XrTriangleMeshFB mesh, uint32_t vertexCount, uint32_t triangleCount); XRAPI_ATTR XrResult XRAPI_CALL xrTriangleMeshBeginVertexBufferUpdateFB( XrTriangleMeshFB mesh, uint32_t* outVertexCount); XRAPI_ATTR XrResult XRAPI_CALL xrTriangleMeshEndVertexBufferUpdateFB( XrTriangleMeshFB mesh); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_FB_passthrough 1 XR_DEFINE_HANDLE(XrPassthroughFB) XR_DEFINE_HANDLE(XrPassthroughLayerFB) XR_DEFINE_HANDLE(XrGeometryInstanceFB) #define XR_FB_passthrough_SPEC_VERSION 1 #define XR_FB_PASSTHROUGH_EXTENSION_NAME "XR_FB_passthrough" #define XR_PASSTHROUGH_COLOR_MAP_MONO_SIZE_FB 256 typedef enum XrPassthroughLayerPurposeFB { XR_PASSTHROUGH_LAYER_PURPOSE_RECONSTRUCTION_FB = 0, XR_PASSTHROUGH_LAYER_PURPOSE_PROJECTED_FB = 1, XR_PASSTHROUGH_LAYER_PURPOSE_MAX_ENUM_FB = 0x7FFFFFFF } XrPassthroughLayerPurposeFB; typedef XrFlags64 XrPassthroughFlagsFB; // Flag bits for XrPassthroughFlagsFB static const XrPassthroughFlagsFB XR_PASSTHROUGH_IS_RUNNING_AT_CREATION_BIT_FB = 0x00000001; typedef XrFlags64 XrPassthroughStateChangedFlagsFB; // Flag bits for XrPassthroughStateChangedFlagsFB static const XrPassthroughStateChangedFlagsFB XR_PASSTHROUGH_STATE_CHANGED_REINIT_REQUIRED_BIT_FB = 0x00000001; static const XrPassthroughStateChangedFlagsFB XR_PASSTHROUGH_STATE_CHANGED_NON_RECOVERABLE_ERROR_BIT_FB = 0x00000002; static const XrPassthroughStateChangedFlagsFB XR_PASSTHROUGH_STATE_CHANGED_RECOVERABLE_ERROR_BIT_FB = 0x00000004; static const XrPassthroughStateChangedFlagsFB XR_PASSTHROUGH_STATE_CHANGED_RESTORED_ERROR_BIT_FB = 0x00000008; // XrSystemPassthroughPropertiesFB extends XrSystemProperties typedef struct XrSystemPassthroughPropertiesFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrBool32 supportsPassthrough; } XrSystemPassthroughPropertiesFB; typedef struct XrPassthroughCreateInfoFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrPassthroughFlagsFB flags; } XrPassthroughCreateInfoFB; typedef struct XrPassthroughLayerCreateInfoFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrPassthroughFB passthrough; XrPassthroughFlagsFB flags; XrPassthroughLayerPurposeFB purpose; } XrPassthroughLayerCreateInfoFB; // XrCompositionLayerPassthroughFB extends XrCompositionLayerBaseHeader typedef struct XrCompositionLayerPassthroughFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrCompositionLayerFlags flags; XrSpace space; XrPassthroughLayerFB layerHandle; } XrCompositionLayerPassthroughFB; typedef struct XrGeometryInstanceCreateInfoFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrPassthroughLayerFB layer; XrTriangleMeshFB mesh; XrSpace baseSpace; XrPosef pose; XrVector3f scale; } XrGeometryInstanceCreateInfoFB; typedef struct XrGeometryInstanceTransformFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrSpace baseSpace; XrTime time; XrPosef pose; XrVector3f scale; } XrGeometryInstanceTransformFB; typedef struct XrPassthroughStyleFB { XrStructureType type; const void* XR_MAY_ALIAS next; float textureOpacityFactor; XrColor4f edgeColor; } XrPassthroughStyleFB; typedef struct XrPassthroughColorMapMonoToRgbaFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrColor4f textureColorMap[XR_PASSTHROUGH_COLOR_MAP_MONO_SIZE_FB]; } XrPassthroughColorMapMonoToRgbaFB; typedef struct XrPassthroughColorMapMonoToMonoFB { XrStructureType type; const void* XR_MAY_ALIAS next; uint8_t textureColorMap[XR_PASSTHROUGH_COLOR_MAP_MONO_SIZE_FB]; } XrPassthroughColorMapMonoToMonoFB; typedef struct XrEventDataPassthroughStateChangedFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrPassthroughStateChangedFlagsFB flags; } XrEventDataPassthroughStateChangedFB; typedef XrResult (XRAPI_PTR *PFN_xrCreatePassthroughFB)(XrSession session, const XrPassthroughCreateInfoFB* createInfo, XrPassthroughFB* outPassthrough); typedef XrResult (XRAPI_PTR *PFN_xrDestroyPassthroughFB)(XrPassthroughFB passthrough); typedef XrResult (XRAPI_PTR *PFN_xrPassthroughStartFB)(XrPassthroughFB passthrough); typedef XrResult (XRAPI_PTR *PFN_xrPassthroughPauseFB)(XrPassthroughFB passthrough); typedef XrResult (XRAPI_PTR *PFN_xrCreatePassthroughLayerFB)(XrSession session, const XrPassthroughLayerCreateInfoFB* createInfo, XrPassthroughLayerFB* outLayer); typedef XrResult (XRAPI_PTR *PFN_xrDestroyPassthroughLayerFB)(XrPassthroughLayerFB layer); typedef XrResult (XRAPI_PTR *PFN_xrPassthroughLayerPauseFB)(XrPassthroughLayerFB layer); typedef XrResult (XRAPI_PTR *PFN_xrPassthroughLayerResumeFB)(XrPassthroughLayerFB layer); typedef XrResult (XRAPI_PTR *PFN_xrPassthroughLayerSetStyleFB)(XrPassthroughLayerFB layer, const XrPassthroughStyleFB* style); typedef XrResult (XRAPI_PTR *PFN_xrCreateGeometryInstanceFB)(XrSession session, const XrGeometryInstanceCreateInfoFB* createInfo, XrGeometryInstanceFB* outGeometryInstance); typedef XrResult (XRAPI_PTR *PFN_xrDestroyGeometryInstanceFB)(XrGeometryInstanceFB instance); typedef XrResult (XRAPI_PTR *PFN_xrGeometryInstanceSetTransformFB)(XrGeometryInstanceFB instance, const XrGeometryInstanceTransformFB* transformation); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreatePassthroughFB( XrSession session, const XrPassthroughCreateInfoFB* createInfo, XrPassthroughFB* outPassthrough); XRAPI_ATTR XrResult XRAPI_CALL xrDestroyPassthroughFB( XrPassthroughFB passthrough); XRAPI_ATTR XrResult XRAPI_CALL xrPassthroughStartFB( XrPassthroughFB passthrough); XRAPI_ATTR XrResult XRAPI_CALL xrPassthroughPauseFB( XrPassthroughFB passthrough); XRAPI_ATTR XrResult XRAPI_CALL xrCreatePassthroughLayerFB( XrSession session, const XrPassthroughLayerCreateInfoFB* createInfo, XrPassthroughLayerFB* outLayer); XRAPI_ATTR XrResult XRAPI_CALL xrDestroyPassthroughLayerFB( XrPassthroughLayerFB layer); XRAPI_ATTR XrResult XRAPI_CALL xrPassthroughLayerPauseFB( XrPassthroughLayerFB layer); XRAPI_ATTR XrResult XRAPI_CALL xrPassthroughLayerResumeFB( XrPassthroughLayerFB layer); XRAPI_ATTR XrResult XRAPI_CALL xrPassthroughLayerSetStyleFB( XrPassthroughLayerFB layer, const XrPassthroughStyleFB* style); XRAPI_ATTR XrResult XRAPI_CALL xrCreateGeometryInstanceFB( XrSession session, const XrGeometryInstanceCreateInfoFB* createInfo, XrGeometryInstanceFB* outGeometryInstance); XRAPI_ATTR XrResult XRAPI_CALL xrDestroyGeometryInstanceFB( XrGeometryInstanceFB instance); XRAPI_ATTR XrResult XRAPI_CALL xrGeometryInstanceSetTransformFB( XrGeometryInstanceFB instance, const XrGeometryInstanceTransformFB* transformation); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_VARJO_foveated_rendering 1 #define XR_VARJO_foveated_rendering_SPEC_VERSION 2 #define XR_VARJO_FOVEATED_RENDERING_EXTENSION_NAME "XR_VARJO_foveated_rendering" // XrViewLocateFoveatedRenderingVARJO extends XrViewLocateInfo typedef struct XrViewLocateFoveatedRenderingVARJO { XrStructureType type; const void* XR_MAY_ALIAS next; XrBool32 foveatedRenderingActive; } XrViewLocateFoveatedRenderingVARJO; // XrFoveatedViewConfigurationViewVARJO extends XrViewConfigurationView typedef struct XrFoveatedViewConfigurationViewVARJO { XrStructureType type; void* XR_MAY_ALIAS next; XrBool32 foveatedRenderingActive; } XrFoveatedViewConfigurationViewVARJO; // XrSystemFoveatedRenderingPropertiesVARJO extends XrSystemProperties typedef struct XrSystemFoveatedRenderingPropertiesVARJO { XrStructureType type; void* XR_MAY_ALIAS next; XrBool32 supportsFoveatedRendering; } XrSystemFoveatedRenderingPropertiesVARJO; #define XR_VARJO_composition_layer_depth_test 1 #define XR_VARJO_composition_layer_depth_test_SPEC_VERSION 2 #define XR_VARJO_COMPOSITION_LAYER_DEPTH_TEST_EXTENSION_NAME "XR_VARJO_composition_layer_depth_test" // XrCompositionLayerDepthTestVARJO extends XrCompositionLayerProjection typedef struct XrCompositionLayerDepthTestVARJO { XrStructureType type; const void* XR_MAY_ALIAS next; float depthTestRangeNearZ; float depthTestRangeFarZ; } XrCompositionLayerDepthTestVARJO; #define XR_VARJO_environment_depth_estimation 1 #define XR_VARJO_environment_depth_estimation_SPEC_VERSION 1 #define XR_VARJO_ENVIRONMENT_DEPTH_ESTIMATION_EXTENSION_NAME "XR_VARJO_environment_depth_estimation" typedef XrResult (XRAPI_PTR *PFN_xrSetEnvironmentDepthEstimationVARJO)(XrSession session, XrBool32 enabled); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrSetEnvironmentDepthEstimationVARJO( XrSession session, XrBool32 enabled); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_VARJO_marker_tracking 1 #define XR_VARJO_marker_tracking_SPEC_VERSION 1 #define XR_VARJO_MARKER_TRACKING_EXTENSION_NAME "XR_VARJO_marker_tracking" // XrSystemMarkerTrackingPropertiesVARJO extends XrSystemProperties typedef struct XrSystemMarkerTrackingPropertiesVARJO { XrStructureType type; void* XR_MAY_ALIAS next; XrBool32 supportsMarkerTracking; } XrSystemMarkerTrackingPropertiesVARJO; typedef struct XrEventDataMarkerTrackingUpdateVARJO { XrStructureType type; const void* XR_MAY_ALIAS next; uint64_t markerId; XrBool32 isActive; XrBool32 isPredicted; XrTime time; } XrEventDataMarkerTrackingUpdateVARJO; typedef struct XrMarkerSpaceCreateInfoVARJO { XrStructureType type; const void* XR_MAY_ALIAS next; uint64_t markerId; XrPosef poseInMarkerSpace; } XrMarkerSpaceCreateInfoVARJO; typedef XrResult (XRAPI_PTR *PFN_xrSetMarkerTrackingVARJO)(XrSession session, XrBool32 enabled); typedef XrResult (XRAPI_PTR *PFN_xrSetMarkerTrackingTimeoutVARJO)(XrSession session, uint64_t markerId, XrDuration timeout); typedef XrResult (XRAPI_PTR *PFN_xrSetMarkerTrackingPredictionVARJO)(XrSession session, uint64_t markerId, XrBool32 enabled); typedef XrResult (XRAPI_PTR *PFN_xrGetMarkerSizeVARJO)(XrSession session, uint64_t markerId, XrExtent2Df* size); typedef XrResult (XRAPI_PTR *PFN_xrCreateMarkerSpaceVARJO)(XrSession session, const XrMarkerSpaceCreateInfoVARJO* createInfo, XrSpace* space); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrSetMarkerTrackingVARJO( XrSession session, XrBool32 enabled); XRAPI_ATTR XrResult XRAPI_CALL xrSetMarkerTrackingTimeoutVARJO( XrSession session, uint64_t markerId, XrDuration timeout); XRAPI_ATTR XrResult XRAPI_CALL xrSetMarkerTrackingPredictionVARJO( XrSession session, uint64_t markerId, XrBool32 enabled); XRAPI_ATTR XrResult XRAPI_CALL xrGetMarkerSizeVARJO( XrSession session, uint64_t markerId, XrExtent2Df* size); XRAPI_ATTR XrResult XRAPI_CALL xrCreateMarkerSpaceVARJO( XrSession session, const XrMarkerSpaceCreateInfoVARJO* createInfo, XrSpace* space); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_MSFT_spatial_anchor_persistence 1 XR_DEFINE_HANDLE(XrSpatialAnchorStoreConnectionMSFT) #define XR_MAX_SPATIAL_ANCHOR_NAME_SIZE_MSFT 256 #define XR_MSFT_spatial_anchor_persistence_SPEC_VERSION 2 #define XR_MSFT_SPATIAL_ANCHOR_PERSISTENCE_EXTENSION_NAME "XR_MSFT_spatial_anchor_persistence" typedef struct XrSpatialAnchorPersistenceNameMSFT { char name[XR_MAX_SPATIAL_ANCHOR_NAME_SIZE_MSFT]; } XrSpatialAnchorPersistenceNameMSFT; typedef struct XrSpatialAnchorPersistenceInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrSpatialAnchorPersistenceNameMSFT spatialAnchorPersistenceName; XrSpatialAnchorMSFT spatialAnchor; } XrSpatialAnchorPersistenceInfoMSFT; typedef struct XrSpatialAnchorFromPersistedAnchorCreateInfoMSFT { XrStructureType type; const void* XR_MAY_ALIAS next; XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore; XrSpatialAnchorPersistenceNameMSFT spatialAnchorPersistenceName; } XrSpatialAnchorFromPersistedAnchorCreateInfoMSFT; typedef XrResult (XRAPI_PTR *PFN_xrCreateSpatialAnchorStoreConnectionMSFT)(XrSession session, XrSpatialAnchorStoreConnectionMSFT* spatialAnchorStore); typedef XrResult (XRAPI_PTR *PFN_xrDestroySpatialAnchorStoreConnectionMSFT)(XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore); typedef XrResult (XRAPI_PTR *PFN_xrPersistSpatialAnchorMSFT)(XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore, const XrSpatialAnchorPersistenceInfoMSFT* spatialAnchorPersistenceInfo); typedef XrResult (XRAPI_PTR *PFN_xrEnumeratePersistedSpatialAnchorNamesMSFT)(XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore, uint32_t spatialAnchorNamesCapacityInput, uint32_t* spatialAnchorNamesCountOutput, XrSpatialAnchorPersistenceNameMSFT* persistedAnchorNames); typedef XrResult (XRAPI_PTR *PFN_xrCreateSpatialAnchorFromPersistedNameMSFT)(XrSession session, const XrSpatialAnchorFromPersistedAnchorCreateInfoMSFT* spatialAnchorCreateInfo, XrSpatialAnchorMSFT* spatialAnchor); typedef XrResult (XRAPI_PTR *PFN_xrUnpersistSpatialAnchorMSFT)(XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore, const XrSpatialAnchorPersistenceNameMSFT* spatialAnchorPersistenceName); typedef XrResult (XRAPI_PTR *PFN_xrClearSpatialAnchorStoreMSFT)(XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore); #ifndef XR_NO_PROTOTYPES #ifdef XR_EXTENSION_PROTOTYPES XRAPI_ATTR XrResult XRAPI_CALL xrCreateSpatialAnchorStoreConnectionMSFT( XrSession session, XrSpatialAnchorStoreConnectionMSFT* spatialAnchorStore); XRAPI_ATTR XrResult XRAPI_CALL xrDestroySpatialAnchorStoreConnectionMSFT( XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore); XRAPI_ATTR XrResult XRAPI_CALL xrPersistSpatialAnchorMSFT( XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore, const XrSpatialAnchorPersistenceInfoMSFT* spatialAnchorPersistenceInfo); XRAPI_ATTR XrResult XRAPI_CALL xrEnumeratePersistedSpatialAnchorNamesMSFT( XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore, uint32_t spatialAnchorNamesCapacityInput, uint32_t* spatialAnchorNamesCountOutput, XrSpatialAnchorPersistenceNameMSFT* persistedAnchorNames); XRAPI_ATTR XrResult XRAPI_CALL xrCreateSpatialAnchorFromPersistedNameMSFT( XrSession session, const XrSpatialAnchorFromPersistedAnchorCreateInfoMSFT* spatialAnchorCreateInfo, XrSpatialAnchorMSFT* spatialAnchor); XRAPI_ATTR XrResult XRAPI_CALL xrUnpersistSpatialAnchorMSFT( XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore, const XrSpatialAnchorPersistenceNameMSFT* spatialAnchorPersistenceName); XRAPI_ATTR XrResult XRAPI_CALL xrClearSpatialAnchorStoreMSFT( XrSpatialAnchorStoreConnectionMSFT spatialAnchorStore); #endif /* XR_EXTENSION_PROTOTYPES */ #endif /* !XR_NO_PROTOTYPES */ #define XR_FB_space_warp 1 #define XR_FB_space_warp_SPEC_VERSION 1 #define XR_FB_SPACE_WARP_EXTENSION_NAME "XR_FB_space_warp" typedef XrFlags64 XrCompositionLayerSpaceWarpInfoFlagsFB; // Flag bits for XrCompositionLayerSpaceWarpInfoFlagsFB // XrCompositionLayerSpaceWarpInfoFB extends XrCompositionLayerProjectionView typedef struct XrCompositionLayerSpaceWarpInfoFB { XrStructureType type; const void* XR_MAY_ALIAS next; XrCompositionLayerSpaceWarpInfoFlagsFB layerFlags; XrSwapchainSubImage motionVectorSubImage; XrPosef appSpaceDeltaPose; XrSwapchainSubImage depthSubImage; float minDepth; float maxDepth; float nearZ; float farZ; } XrCompositionLayerSpaceWarpInfoFB; // XrSystemSpaceWarpPropertiesFB extends XrSystemProperties typedef struct XrSystemSpaceWarpPropertiesFB { XrStructureType type; void* XR_MAY_ALIAS next; uint32_t recommendedMotionVectorImageRectWidth; uint32_t recommendedMotionVectorImageRectHeight; } XrSystemSpaceWarpPropertiesFB; #ifdef __cplusplus } #endif #endif
156,676
C
42.630465
329
0.686717
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/openxr/include/openxr/openxr_reflection.h
#ifndef OPENXR_REFLECTION_H_ #define OPENXR_REFLECTION_H_ 1 /* ** Copyright (c) 2017-2021, The Khronos Group Inc. ** ** SPDX-License-Identifier: Apache-2.0 OR MIT */ /* ** This header is generated from the Khronos OpenXR XML API Registry. ** */ #include "openxr.h" /* This file contains expansion macros (X Macros) for OpenXR enumerations and structures. Example of how to use expansion macros to make an enum-to-string function: #define XR_ENUM_CASE_STR(name, val) case name: return #name; #define XR_ENUM_STR(enumType) \ constexpr const char* XrEnumStr(enumType e) { \ switch (e) { \ XR_LIST_ENUM_##enumType(XR_ENUM_CASE_STR) \ default: return "Unknown"; \ } \ } \ XR_ENUM_STR(XrResult); */ #define XR_LIST_ENUM_XrResult(_) \ _(XR_SUCCESS, 0) \ _(XR_TIMEOUT_EXPIRED, 1) \ _(XR_SESSION_LOSS_PENDING, 3) \ _(XR_EVENT_UNAVAILABLE, 4) \ _(XR_SPACE_BOUNDS_UNAVAILABLE, 7) \ _(XR_SESSION_NOT_FOCUSED, 8) \ _(XR_FRAME_DISCARDED, 9) \ _(XR_ERROR_VALIDATION_FAILURE, -1) \ _(XR_ERROR_RUNTIME_FAILURE, -2) \ _(XR_ERROR_OUT_OF_MEMORY, -3) \ _(XR_ERROR_API_VERSION_UNSUPPORTED, -4) \ _(XR_ERROR_INITIALIZATION_FAILED, -6) \ _(XR_ERROR_FUNCTION_UNSUPPORTED, -7) \ _(XR_ERROR_FEATURE_UNSUPPORTED, -8) \ _(XR_ERROR_EXTENSION_NOT_PRESENT, -9) \ _(XR_ERROR_LIMIT_REACHED, -10) \ _(XR_ERROR_SIZE_INSUFFICIENT, -11) \ _(XR_ERROR_HANDLE_INVALID, -12) \ _(XR_ERROR_INSTANCE_LOST, -13) \ _(XR_ERROR_SESSION_RUNNING, -14) \ _(XR_ERROR_SESSION_NOT_RUNNING, -16) \ _(XR_ERROR_SESSION_LOST, -17) \ _(XR_ERROR_SYSTEM_INVALID, -18) \ _(XR_ERROR_PATH_INVALID, -19) \ _(XR_ERROR_PATH_COUNT_EXCEEDED, -20) \ _(XR_ERROR_PATH_FORMAT_INVALID, -21) \ _(XR_ERROR_PATH_UNSUPPORTED, -22) \ _(XR_ERROR_LAYER_INVALID, -23) \ _(XR_ERROR_LAYER_LIMIT_EXCEEDED, -24) \ _(XR_ERROR_SWAPCHAIN_RECT_INVALID, -25) \ _(XR_ERROR_SWAPCHAIN_FORMAT_UNSUPPORTED, -26) \ _(XR_ERROR_ACTION_TYPE_MISMATCH, -27) \ _(XR_ERROR_SESSION_NOT_READY, -28) \ _(XR_ERROR_SESSION_NOT_STOPPING, -29) \ _(XR_ERROR_TIME_INVALID, -30) \ _(XR_ERROR_REFERENCE_SPACE_UNSUPPORTED, -31) \ _(XR_ERROR_FILE_ACCESS_ERROR, -32) \ _(XR_ERROR_FILE_CONTENTS_INVALID, -33) \ _(XR_ERROR_FORM_FACTOR_UNSUPPORTED, -34) \ _(XR_ERROR_FORM_FACTOR_UNAVAILABLE, -35) \ _(XR_ERROR_API_LAYER_NOT_PRESENT, -36) \ _(XR_ERROR_CALL_ORDER_INVALID, -37) \ _(XR_ERROR_GRAPHICS_DEVICE_INVALID, -38) \ _(XR_ERROR_POSE_INVALID, -39) \ _(XR_ERROR_INDEX_OUT_OF_RANGE, -40) \ _(XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED, -41) \ _(XR_ERROR_ENVIRONMENT_BLEND_MODE_UNSUPPORTED, -42) \ _(XR_ERROR_NAME_DUPLICATED, -44) \ _(XR_ERROR_NAME_INVALID, -45) \ _(XR_ERROR_ACTIONSET_NOT_ATTACHED, -46) \ _(XR_ERROR_ACTIONSETS_ALREADY_ATTACHED, -47) \ _(XR_ERROR_LOCALIZED_NAME_DUPLICATED, -48) \ _(XR_ERROR_LOCALIZED_NAME_INVALID, -49) \ _(XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING, -50) \ _(XR_ERROR_RUNTIME_UNAVAILABLE, -51) \ _(XR_ERROR_ANDROID_THREAD_SETTINGS_ID_INVALID_KHR, -1000003000) \ _(XR_ERROR_ANDROID_THREAD_SETTINGS_FAILURE_KHR, -1000003001) \ _(XR_ERROR_CREATE_SPATIAL_ANCHOR_FAILED_MSFT, -1000039001) \ _(XR_ERROR_SECONDARY_VIEW_CONFIGURATION_TYPE_NOT_ENABLED_MSFT, -1000053000) \ _(XR_ERROR_CONTROLLER_MODEL_KEY_INVALID_MSFT, -1000055000) \ _(XR_ERROR_REPROJECTION_MODE_UNSUPPORTED_MSFT, -1000066000) \ _(XR_ERROR_COMPUTE_NEW_SCENE_NOT_COMPLETED_MSFT, -1000097000) \ _(XR_ERROR_SCENE_COMPONENT_ID_INVALID_MSFT, -1000097001) \ _(XR_ERROR_SCENE_COMPONENT_TYPE_MISMATCH_MSFT, -1000097002) \ _(XR_ERROR_SCENE_MESH_BUFFER_ID_INVALID_MSFT, -1000097003) \ _(XR_ERROR_SCENE_COMPUTE_FEATURE_INCOMPATIBLE_MSFT, -1000097004) \ _(XR_ERROR_SCENE_COMPUTE_CONSISTENCY_MISMATCH_MSFT, -1000097005) \ _(XR_ERROR_DISPLAY_REFRESH_RATE_UNSUPPORTED_FB, -1000101000) \ _(XR_ERROR_COLOR_SPACE_UNSUPPORTED_FB, -1000108000) \ _(XR_ERROR_UNEXPECTED_STATE_PASSTHROUGH_FB, -1000118000) \ _(XR_ERROR_FEATURE_ALREADY_CREATED_PASSTHROUGH_FB, -1000118001) \ _(XR_ERROR_FEATURE_REQUIRED_PASSTHROUGH_FB, -1000118002) \ _(XR_ERROR_NOT_PERMITTED_PASSTHROUGH_FB, -1000118003) \ _(XR_ERROR_INSUFFICIENT_RESOURCES_PASSTHROUGH_FB, -1000118004) \ _(XR_ERROR_UNKNOWN_PASSTHROUGH_FB, -1000118050) \ _(XR_ERROR_MARKER_NOT_TRACKED_VARJO, -1000124000) \ _(XR_ERROR_MARKER_ID_INVALID_VARJO, -1000124001) \ _(XR_ERROR_SPATIAL_ANCHOR_NAME_NOT_FOUND_MSFT, -1000142001) \ _(XR_ERROR_SPATIAL_ANCHOR_NAME_INVALID_MSFT, -1000142002) \ _(XR_RESULT_MAX_ENUM, 0x7FFFFFFF) #define XR_LIST_ENUM_XrStructureType(_) \ _(XR_TYPE_UNKNOWN, 0) \ _(XR_TYPE_API_LAYER_PROPERTIES, 1) \ _(XR_TYPE_EXTENSION_PROPERTIES, 2) \ _(XR_TYPE_INSTANCE_CREATE_INFO, 3) \ _(XR_TYPE_SYSTEM_GET_INFO, 4) \ _(XR_TYPE_SYSTEM_PROPERTIES, 5) \ _(XR_TYPE_VIEW_LOCATE_INFO, 6) \ _(XR_TYPE_VIEW, 7) \ _(XR_TYPE_SESSION_CREATE_INFO, 8) \ _(XR_TYPE_SWAPCHAIN_CREATE_INFO, 9) \ _(XR_TYPE_SESSION_BEGIN_INFO, 10) \ _(XR_TYPE_VIEW_STATE, 11) \ _(XR_TYPE_FRAME_END_INFO, 12) \ _(XR_TYPE_HAPTIC_VIBRATION, 13) \ _(XR_TYPE_EVENT_DATA_BUFFER, 16) \ _(XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING, 17) \ _(XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED, 18) \ _(XR_TYPE_ACTION_STATE_BOOLEAN, 23) \ _(XR_TYPE_ACTION_STATE_FLOAT, 24) \ _(XR_TYPE_ACTION_STATE_VECTOR2F, 25) \ _(XR_TYPE_ACTION_STATE_POSE, 27) \ _(XR_TYPE_ACTION_SET_CREATE_INFO, 28) \ _(XR_TYPE_ACTION_CREATE_INFO, 29) \ _(XR_TYPE_INSTANCE_PROPERTIES, 32) \ _(XR_TYPE_FRAME_WAIT_INFO, 33) \ _(XR_TYPE_COMPOSITION_LAYER_PROJECTION, 35) \ _(XR_TYPE_COMPOSITION_LAYER_QUAD, 36) \ _(XR_TYPE_REFERENCE_SPACE_CREATE_INFO, 37) \ _(XR_TYPE_ACTION_SPACE_CREATE_INFO, 38) \ _(XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING, 40) \ _(XR_TYPE_VIEW_CONFIGURATION_VIEW, 41) \ _(XR_TYPE_SPACE_LOCATION, 42) \ _(XR_TYPE_SPACE_VELOCITY, 43) \ _(XR_TYPE_FRAME_STATE, 44) \ _(XR_TYPE_VIEW_CONFIGURATION_PROPERTIES, 45) \ _(XR_TYPE_FRAME_BEGIN_INFO, 46) \ _(XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW, 48) \ _(XR_TYPE_EVENT_DATA_EVENTS_LOST, 49) \ _(XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, 51) \ _(XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED, 52) \ _(XR_TYPE_INTERACTION_PROFILE_STATE, 53) \ _(XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, 55) \ _(XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, 56) \ _(XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, 57) \ _(XR_TYPE_ACTION_STATE_GET_INFO, 58) \ _(XR_TYPE_HAPTIC_ACTION_INFO, 59) \ _(XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, 60) \ _(XR_TYPE_ACTIONS_SYNC_INFO, 61) \ _(XR_TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO, 62) \ _(XR_TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO, 63) \ _(XR_TYPE_COMPOSITION_LAYER_CUBE_KHR, 1000006000) \ _(XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR, 1000008000) \ _(XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR, 1000010000) \ _(XR_TYPE_VULKAN_SWAPCHAIN_FORMAT_LIST_CREATE_INFO_KHR, 1000014000) \ _(XR_TYPE_EVENT_DATA_PERF_SETTINGS_EXT, 1000015000) \ _(XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR, 1000017000) \ _(XR_TYPE_COMPOSITION_LAYER_EQUIRECT_KHR, 1000018000) \ _(XR_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT, 1000019000) \ _(XR_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT, 1000019001) \ _(XR_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, 1000019002) \ _(XR_TYPE_DEBUG_UTILS_LABEL_EXT, 1000019003) \ _(XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR, 1000023000) \ _(XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR, 1000023001) \ _(XR_TYPE_GRAPHICS_BINDING_OPENGL_XCB_KHR, 1000023002) \ _(XR_TYPE_GRAPHICS_BINDING_OPENGL_WAYLAND_KHR, 1000023003) \ _(XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR, 1000023004) \ _(XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR, 1000023005) \ _(XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR, 1000024001) \ _(XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR, 1000024002) \ _(XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR, 1000024003) \ _(XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR, 1000025000) \ _(XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR, 1000025001) \ _(XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR, 1000025002) \ _(XR_TYPE_GRAPHICS_BINDING_D3D11_KHR, 1000027000) \ _(XR_TYPE_SWAPCHAIN_IMAGE_D3D11_KHR, 1000027001) \ _(XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR, 1000027002) \ _(XR_TYPE_GRAPHICS_BINDING_D3D12_KHR, 1000028000) \ _(XR_TYPE_SWAPCHAIN_IMAGE_D3D12_KHR, 1000028001) \ _(XR_TYPE_GRAPHICS_REQUIREMENTS_D3D12_KHR, 1000028002) \ _(XR_TYPE_SYSTEM_EYE_GAZE_INTERACTION_PROPERTIES_EXT, 1000030000) \ _(XR_TYPE_EYE_GAZE_SAMPLE_TIME_EXT, 1000030001) \ _(XR_TYPE_VISIBILITY_MASK_KHR, 1000031000) \ _(XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR, 1000031001) \ _(XR_TYPE_SESSION_CREATE_INFO_OVERLAY_EXTX, 1000033000) \ _(XR_TYPE_EVENT_DATA_MAIN_SESSION_VISIBILITY_CHANGED_EXTX, 1000033003) \ _(XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR, 1000034000) \ _(XR_TYPE_SPATIAL_ANCHOR_CREATE_INFO_MSFT, 1000039000) \ _(XR_TYPE_SPATIAL_ANCHOR_SPACE_CREATE_INFO_MSFT, 1000039001) \ _(XR_TYPE_COMPOSITION_LAYER_IMAGE_LAYOUT_FB, 1000040000) \ _(XR_TYPE_COMPOSITION_LAYER_ALPHA_BLEND_FB, 1000041001) \ _(XR_TYPE_VIEW_CONFIGURATION_DEPTH_RANGE_EXT, 1000046000) \ _(XR_TYPE_GRAPHICS_BINDING_EGL_MNDX, 1000048004) \ _(XR_TYPE_SPATIAL_GRAPH_NODE_SPACE_CREATE_INFO_MSFT, 1000049000) \ _(XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT, 1000051000) \ _(XR_TYPE_HAND_TRACKER_CREATE_INFO_EXT, 1000051001) \ _(XR_TYPE_HAND_JOINTS_LOCATE_INFO_EXT, 1000051002) \ _(XR_TYPE_HAND_JOINT_LOCATIONS_EXT, 1000051003) \ _(XR_TYPE_HAND_JOINT_VELOCITIES_EXT, 1000051004) \ _(XR_TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT, 1000052000) \ _(XR_TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT, 1000052001) \ _(XR_TYPE_HAND_MESH_UPDATE_INFO_MSFT, 1000052002) \ _(XR_TYPE_HAND_MESH_MSFT, 1000052003) \ _(XR_TYPE_HAND_POSE_TYPE_INFO_MSFT, 1000052004) \ _(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_SESSION_BEGIN_INFO_MSFT, 1000053000) \ _(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_STATE_MSFT, 1000053001) \ _(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_FRAME_STATE_MSFT, 1000053002) \ _(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_FRAME_END_INFO_MSFT, 1000053003) \ _(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_LAYER_INFO_MSFT, 1000053004) \ _(XR_TYPE_SECONDARY_VIEW_CONFIGURATION_SWAPCHAIN_CREATE_INFO_MSFT, 1000053005) \ _(XR_TYPE_CONTROLLER_MODEL_KEY_STATE_MSFT, 1000055000) \ _(XR_TYPE_CONTROLLER_MODEL_NODE_PROPERTIES_MSFT, 1000055001) \ _(XR_TYPE_CONTROLLER_MODEL_PROPERTIES_MSFT, 1000055002) \ _(XR_TYPE_CONTROLLER_MODEL_NODE_STATE_MSFT, 1000055003) \ _(XR_TYPE_CONTROLLER_MODEL_STATE_MSFT, 1000055004) \ _(XR_TYPE_VIEW_CONFIGURATION_VIEW_FOV_EPIC, 1000059000) \ _(XR_TYPE_HOLOGRAPHIC_WINDOW_ATTACHMENT_MSFT, 1000063000) \ _(XR_TYPE_COMPOSITION_LAYER_REPROJECTION_INFO_MSFT, 1000066000) \ _(XR_TYPE_COMPOSITION_LAYER_REPROJECTION_PLANE_OVERRIDE_MSFT, 1000066001) \ _(XR_TYPE_ANDROID_SURFACE_SWAPCHAIN_CREATE_INFO_FB, 1000070000) \ _(XR_TYPE_COMPOSITION_LAYER_SECURE_CONTENT_FB, 1000072000) \ _(XR_TYPE_INTERACTION_PROFILE_ANALOG_THRESHOLD_VALVE, 1000079000) \ _(XR_TYPE_HAND_JOINTS_MOTION_RANGE_INFO_EXT, 1000080000) \ _(XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR, 1000089000) \ _(XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR, 1000090000) \ _(XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR, 1000090001) \ _(XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR, 1000090003) \ _(XR_TYPE_COMPOSITION_LAYER_EQUIRECT2_KHR, 1000091000) \ _(XR_TYPE_SCENE_OBSERVER_CREATE_INFO_MSFT, 1000097000) \ _(XR_TYPE_SCENE_CREATE_INFO_MSFT, 1000097001) \ _(XR_TYPE_NEW_SCENE_COMPUTE_INFO_MSFT, 1000097002) \ _(XR_TYPE_VISUAL_MESH_COMPUTE_LOD_INFO_MSFT, 1000097003) \ _(XR_TYPE_SCENE_COMPONENTS_MSFT, 1000097004) \ _(XR_TYPE_SCENE_COMPONENTS_GET_INFO_MSFT, 1000097005) \ _(XR_TYPE_SCENE_COMPONENT_LOCATIONS_MSFT, 1000097006) \ _(XR_TYPE_SCENE_COMPONENTS_LOCATE_INFO_MSFT, 1000097007) \ _(XR_TYPE_SCENE_OBJECTS_MSFT, 1000097008) \ _(XR_TYPE_SCENE_COMPONENT_PARENT_FILTER_INFO_MSFT, 1000097009) \ _(XR_TYPE_SCENE_OBJECT_TYPES_FILTER_INFO_MSFT, 1000097010) \ _(XR_TYPE_SCENE_PLANES_MSFT, 1000097011) \ _(XR_TYPE_SCENE_PLANE_ALIGNMENT_FILTER_INFO_MSFT, 1000097012) \ _(XR_TYPE_SCENE_MESHES_MSFT, 1000097013) \ _(XR_TYPE_SCENE_MESH_BUFFERS_GET_INFO_MSFT, 1000097014) \ _(XR_TYPE_SCENE_MESH_BUFFERS_MSFT, 1000097015) \ _(XR_TYPE_SCENE_MESH_VERTEX_BUFFER_MSFT, 1000097016) \ _(XR_TYPE_SCENE_MESH_INDICES_UINT32_MSFT, 1000097017) \ _(XR_TYPE_SCENE_MESH_INDICES_UINT16_MSFT, 1000097018) \ _(XR_TYPE_SERIALIZED_SCENE_FRAGMENT_DATA_GET_INFO_MSFT, 1000098000) \ _(XR_TYPE_SCENE_DESERIALIZE_INFO_MSFT, 1000098001) \ _(XR_TYPE_EVENT_DATA_DISPLAY_REFRESH_RATE_CHANGED_FB, 1000101000) \ _(XR_TYPE_VIVE_TRACKER_PATHS_HTCX, 1000103000) \ _(XR_TYPE_EVENT_DATA_VIVE_TRACKER_CONNECTED_HTCX, 1000103001) \ _(XR_TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB, 1000108000) \ _(XR_TYPE_HAND_TRACKING_MESH_FB, 1000110001) \ _(XR_TYPE_HAND_TRACKING_SCALE_FB, 1000110003) \ _(XR_TYPE_HAND_TRACKING_AIM_STATE_FB, 1000111001) \ _(XR_TYPE_HAND_TRACKING_CAPSULES_STATE_FB, 1000112000) \ _(XR_TYPE_FOVEATION_PROFILE_CREATE_INFO_FB, 1000114000) \ _(XR_TYPE_SWAPCHAIN_CREATE_INFO_FOVEATION_FB, 1000114001) \ _(XR_TYPE_SWAPCHAIN_STATE_FOVEATION_FB, 1000114002) \ _(XR_TYPE_FOVEATION_LEVEL_PROFILE_CREATE_INFO_FB, 1000115000) \ _(XR_TYPE_TRIANGLE_MESH_CREATE_INFO_FB, 1000117001) \ _(XR_TYPE_SYSTEM_PASSTHROUGH_PROPERTIES_FB, 1000118000) \ _(XR_TYPE_PASSTHROUGH_CREATE_INFO_FB, 1000118001) \ _(XR_TYPE_PASSTHROUGH_LAYER_CREATE_INFO_FB, 1000118002) \ _(XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_FB, 1000118003) \ _(XR_TYPE_GEOMETRY_INSTANCE_CREATE_INFO_FB, 1000118004) \ _(XR_TYPE_GEOMETRY_INSTANCE_TRANSFORM_FB, 1000118005) \ _(XR_TYPE_PASSTHROUGH_STYLE_FB, 1000118020) \ _(XR_TYPE_PASSTHROUGH_COLOR_MAP_MONO_TO_RGBA_FB, 1000118021) \ _(XR_TYPE_PASSTHROUGH_COLOR_MAP_MONO_TO_MONO_FB, 1000118022) \ _(XR_TYPE_EVENT_DATA_PASSTHROUGH_STATE_CHANGED_FB, 1000118030) \ _(XR_TYPE_BINDING_MODIFICATIONS_KHR, 1000120000) \ _(XR_TYPE_VIEW_LOCATE_FOVEATED_RENDERING_VARJO, 1000121000) \ _(XR_TYPE_FOVEATED_VIEW_CONFIGURATION_VIEW_VARJO, 1000121001) \ _(XR_TYPE_SYSTEM_FOVEATED_RENDERING_PROPERTIES_VARJO, 1000121002) \ _(XR_TYPE_COMPOSITION_LAYER_DEPTH_TEST_VARJO, 1000122000) \ _(XR_TYPE_SYSTEM_MARKER_TRACKING_PROPERTIES_VARJO, 1000124000) \ _(XR_TYPE_EVENT_DATA_MARKER_TRACKING_UPDATE_VARJO, 1000124001) \ _(XR_TYPE_MARKER_SPACE_CREATE_INFO_VARJO, 1000124002) \ _(XR_TYPE_SPATIAL_ANCHOR_PERSISTENCE_INFO_MSFT, 1000142000) \ _(XR_TYPE_SPATIAL_ANCHOR_FROM_PERSISTED_ANCHOR_CREATE_INFO_MSFT, 1000142001) \ _(XR_TYPE_SWAPCHAIN_IMAGE_FOVEATION_VULKAN_FB, 1000160000) \ _(XR_TYPE_SWAPCHAIN_STATE_ANDROID_SURFACE_DIMENSIONS_FB, 1000161000) \ _(XR_TYPE_SWAPCHAIN_STATE_SAMPLER_OPENGL_ES_FB, 1000162000) \ _(XR_TYPE_SWAPCHAIN_STATE_SAMPLER_VULKAN_FB, 1000163000) \ _(XR_TYPE_COMPOSITION_LAYER_SPACE_WARP_INFO_FB, 1000171000) \ _(XR_TYPE_SYSTEM_SPACE_WARP_PROPERTIES_FB, 1000171001) \ _(XR_STRUCTURE_TYPE_MAX_ENUM, 0x7FFFFFFF) #define XR_LIST_ENUM_XrFormFactor(_) \ _(XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY, 1) \ _(XR_FORM_FACTOR_HANDHELD_DISPLAY, 2) \ _(XR_FORM_FACTOR_MAX_ENUM, 0x7FFFFFFF) #define XR_LIST_ENUM_XrViewConfigurationType(_) \ _(XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO, 1) \ _(XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, 2) \ _(XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO, 1000037000) \ _(XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT, 1000054000) \ _(XR_VIEW_CONFIGURATION_TYPE_MAX_ENUM, 0x7FFFFFFF) #define XR_LIST_ENUM_XrEnvironmentBlendMode(_) \ _(XR_ENVIRONMENT_BLEND_MODE_OPAQUE, 1) \ _(XR_ENVIRONMENT_BLEND_MODE_ADDITIVE, 2) \ _(XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND, 3) \ _(XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM, 0x7FFFFFFF) #define XR_LIST_ENUM_XrReferenceSpaceType(_) \ _(XR_REFERENCE_SPACE_TYPE_VIEW, 1) \ _(XR_REFERENCE_SPACE_TYPE_LOCAL, 2) \ _(XR_REFERENCE_SPACE_TYPE_STAGE, 3) \ _(XR_REFERENCE_SPACE_TYPE_UNBOUNDED_MSFT, 1000038000) \ _(XR_REFERENCE_SPACE_TYPE_COMBINED_EYE_VARJO, 1000121000) \ _(XR_REFERENCE_SPACE_TYPE_MAX_ENUM, 0x7FFFFFFF) #define XR_LIST_ENUM_XrActionType(_) \ _(XR_ACTION_TYPE_BOOLEAN_INPUT, 1) \ _(XR_ACTION_TYPE_FLOAT_INPUT, 2) \ _(XR_ACTION_TYPE_VECTOR2F_INPUT, 3) \ _(XR_ACTION_TYPE_POSE_INPUT, 4) \ _(XR_ACTION_TYPE_VIBRATION_OUTPUT, 100) \ _(XR_ACTION_TYPE_MAX_ENUM, 0x7FFFFFFF) #define XR_LIST_ENUM_XrEyeVisibility(_) \ _(XR_EYE_VISIBILITY_BOTH, 0) \ _(XR_EYE_VISIBILITY_LEFT, 1) \ _(XR_EYE_VISIBILITY_RIGHT, 2) \ _(XR_EYE_VISIBILITY_MAX_ENUM, 0x7FFFFFFF) #define XR_LIST_ENUM_XrSessionState(_) \ _(XR_SESSION_STATE_UNKNOWN, 0) \ _(XR_SESSION_STATE_IDLE, 1) \ _(XR_SESSION_STATE_READY, 2) \ _(XR_SESSION_STATE_SYNCHRONIZED, 3) \ _(XR_SESSION_STATE_VISIBLE, 4) \ _(XR_SESSION_STATE_FOCUSED, 5) \ _(XR_SESSION_STATE_STOPPING, 6) \ _(XR_SESSION_STATE_LOSS_PENDING, 7) \ _(XR_SESSION_STATE_EXITING, 8) \ _(XR_SESSION_STATE_MAX_ENUM, 0x7FFFFFFF) #define XR_LIST_ENUM_XrObjectType(_) \ _(XR_OBJECT_TYPE_UNKNOWN, 0) \ _(XR_OBJECT_TYPE_INSTANCE, 1) \ _(XR_OBJECT_TYPE_SESSION, 2) \ _(XR_OBJECT_TYPE_SWAPCHAIN, 3) \ _(XR_OBJECT_TYPE_SPACE, 4) \ _(XR_OBJECT_TYPE_ACTION_SET, 5) \ _(XR_OBJECT_TYPE_ACTION, 6) \ _(XR_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT, 1000019000) \ _(XR_OBJECT_TYPE_SPATIAL_ANCHOR_MSFT, 1000039000) \ _(XR_OBJECT_TYPE_HAND_TRACKER_EXT, 1000051000) \ _(XR_OBJECT_TYPE_SCENE_OBSERVER_MSFT, 1000097000) \ _(XR_OBJECT_TYPE_SCENE_MSFT, 1000097001) \ _(XR_OBJECT_TYPE_FOVEATION_PROFILE_FB, 1000114000) \ _(XR_OBJECT_TYPE_TRIANGLE_MESH_FB, 1000117000) \ _(XR_OBJECT_TYPE_PASSTHROUGH_FB, 1000118000) \ _(XR_OBJECT_TYPE_PASSTHROUGH_LAYER_FB, 1000118002) \ _(XR_OBJECT_TYPE_GEOMETRY_INSTANCE_FB, 1000118004) \ _(XR_OBJECT_TYPE_SPATIAL_ANCHOR_STORE_CONNECTION_MSFT, 1000142000) \ _(XR_OBJECT_TYPE_MAX_ENUM, 0x7FFFFFFF) #define XR_LIST_ENUM_XrAndroidThreadTypeKHR(_) \ _(XR_ANDROID_THREAD_TYPE_APPLICATION_MAIN_KHR, 1) \ _(XR_ANDROID_THREAD_TYPE_APPLICATION_WORKER_KHR, 2) \ _(XR_ANDROID_THREAD_TYPE_RENDERER_MAIN_KHR, 3) \ _(XR_ANDROID_THREAD_TYPE_RENDERER_WORKER_KHR, 4) \ _(XR_ANDROID_THREAD_TYPE_MAX_ENUM_KHR, 0x7FFFFFFF) #define XR_LIST_ENUM_XrVisibilityMaskTypeKHR(_) \ _(XR_VISIBILITY_MASK_TYPE_HIDDEN_TRIANGLE_MESH_KHR, 1) \ _(XR_VISIBILITY_MASK_TYPE_VISIBLE_TRIANGLE_MESH_KHR, 2) \ _(XR_VISIBILITY_MASK_TYPE_LINE_LOOP_KHR, 3) \ _(XR_VISIBILITY_MASK_TYPE_MAX_ENUM_KHR, 0x7FFFFFFF) #define XR_LIST_ENUM_XrPerfSettingsDomainEXT(_) \ _(XR_PERF_SETTINGS_DOMAIN_CPU_EXT, 1) \ _(XR_PERF_SETTINGS_DOMAIN_GPU_EXT, 2) \ _(XR_PERF_SETTINGS_DOMAIN_MAX_ENUM_EXT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrPerfSettingsSubDomainEXT(_) \ _(XR_PERF_SETTINGS_SUB_DOMAIN_COMPOSITING_EXT, 1) \ _(XR_PERF_SETTINGS_SUB_DOMAIN_RENDERING_EXT, 2) \ _(XR_PERF_SETTINGS_SUB_DOMAIN_THERMAL_EXT, 3) \ _(XR_PERF_SETTINGS_SUB_DOMAIN_MAX_ENUM_EXT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrPerfSettingsLevelEXT(_) \ _(XR_PERF_SETTINGS_LEVEL_POWER_SAVINGS_EXT, 0) \ _(XR_PERF_SETTINGS_LEVEL_SUSTAINED_LOW_EXT, 25) \ _(XR_PERF_SETTINGS_LEVEL_SUSTAINED_HIGH_EXT, 50) \ _(XR_PERF_SETTINGS_LEVEL_BOOST_EXT, 75) \ _(XR_PERF_SETTINGS_LEVEL_MAX_ENUM_EXT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrPerfSettingsNotificationLevelEXT(_) \ _(XR_PERF_SETTINGS_NOTIF_LEVEL_NORMAL_EXT, 0) \ _(XR_PERF_SETTINGS_NOTIF_LEVEL_WARNING_EXT, 25) \ _(XR_PERF_SETTINGS_NOTIF_LEVEL_IMPAIRED_EXT, 75) \ _(XR_PERF_SETTINGS_NOTIFICATION_LEVEL_MAX_ENUM_EXT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrBlendFactorFB(_) \ _(XR_BLEND_FACTOR_ZERO_FB, 0) \ _(XR_BLEND_FACTOR_ONE_FB, 1) \ _(XR_BLEND_FACTOR_SRC_ALPHA_FB, 2) \ _(XR_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA_FB, 3) \ _(XR_BLEND_FACTOR_DST_ALPHA_FB, 4) \ _(XR_BLEND_FACTOR_ONE_MINUS_DST_ALPHA_FB, 5) \ _(XR_BLEND_FACTOR_MAX_ENUM_FB, 0x7FFFFFFF) #define XR_LIST_ENUM_XrSpatialGraphNodeTypeMSFT(_) \ _(XR_SPATIAL_GRAPH_NODE_TYPE_STATIC_MSFT, 1) \ _(XR_SPATIAL_GRAPH_NODE_TYPE_DYNAMIC_MSFT, 2) \ _(XR_SPATIAL_GRAPH_NODE_TYPE_MAX_ENUM_MSFT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrHandEXT(_) \ _(XR_HAND_LEFT_EXT, 1) \ _(XR_HAND_RIGHT_EXT, 2) \ _(XR_HAND_MAX_ENUM_EXT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrHandJointEXT(_) \ _(XR_HAND_JOINT_PALM_EXT, 0) \ _(XR_HAND_JOINT_WRIST_EXT, 1) \ _(XR_HAND_JOINT_THUMB_METACARPAL_EXT, 2) \ _(XR_HAND_JOINT_THUMB_PROXIMAL_EXT, 3) \ _(XR_HAND_JOINT_THUMB_DISTAL_EXT, 4) \ _(XR_HAND_JOINT_THUMB_TIP_EXT, 5) \ _(XR_HAND_JOINT_INDEX_METACARPAL_EXT, 6) \ _(XR_HAND_JOINT_INDEX_PROXIMAL_EXT, 7) \ _(XR_HAND_JOINT_INDEX_INTERMEDIATE_EXT, 8) \ _(XR_HAND_JOINT_INDEX_DISTAL_EXT, 9) \ _(XR_HAND_JOINT_INDEX_TIP_EXT, 10) \ _(XR_HAND_JOINT_MIDDLE_METACARPAL_EXT, 11) \ _(XR_HAND_JOINT_MIDDLE_PROXIMAL_EXT, 12) \ _(XR_HAND_JOINT_MIDDLE_INTERMEDIATE_EXT, 13) \ _(XR_HAND_JOINT_MIDDLE_DISTAL_EXT, 14) \ _(XR_HAND_JOINT_MIDDLE_TIP_EXT, 15) \ _(XR_HAND_JOINT_RING_METACARPAL_EXT, 16) \ _(XR_HAND_JOINT_RING_PROXIMAL_EXT, 17) \ _(XR_HAND_JOINT_RING_INTERMEDIATE_EXT, 18) \ _(XR_HAND_JOINT_RING_DISTAL_EXT, 19) \ _(XR_HAND_JOINT_RING_TIP_EXT, 20) \ _(XR_HAND_JOINT_LITTLE_METACARPAL_EXT, 21) \ _(XR_HAND_JOINT_LITTLE_PROXIMAL_EXT, 22) \ _(XR_HAND_JOINT_LITTLE_INTERMEDIATE_EXT, 23) \ _(XR_HAND_JOINT_LITTLE_DISTAL_EXT, 24) \ _(XR_HAND_JOINT_LITTLE_TIP_EXT, 25) \ _(XR_HAND_JOINT_MAX_ENUM_EXT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrHandJointSetEXT(_) \ _(XR_HAND_JOINT_SET_DEFAULT_EXT, 0) \ _(XR_HAND_JOINT_SET_MAX_ENUM_EXT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrHandPoseTypeMSFT(_) \ _(XR_HAND_POSE_TYPE_TRACKED_MSFT, 0) \ _(XR_HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT, 1) \ _(XR_HAND_POSE_TYPE_MAX_ENUM_MSFT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrReprojectionModeMSFT(_) \ _(XR_REPROJECTION_MODE_DEPTH_MSFT, 1) \ _(XR_REPROJECTION_MODE_PLANAR_FROM_DEPTH_MSFT, 2) \ _(XR_REPROJECTION_MODE_PLANAR_MANUAL_MSFT, 3) \ _(XR_REPROJECTION_MODE_ORIENTATION_ONLY_MSFT, 4) \ _(XR_REPROJECTION_MODE_MAX_ENUM_MSFT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrHandJointsMotionRangeEXT(_) \ _(XR_HAND_JOINTS_MOTION_RANGE_UNOBSTRUCTED_EXT, 1) \ _(XR_HAND_JOINTS_MOTION_RANGE_CONFORMING_TO_CONTROLLER_EXT, 2) \ _(XR_HAND_JOINTS_MOTION_RANGE_MAX_ENUM_EXT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrSceneComputeFeatureMSFT(_) \ _(XR_SCENE_COMPUTE_FEATURE_PLANE_MSFT, 1) \ _(XR_SCENE_COMPUTE_FEATURE_PLANE_MESH_MSFT, 2) \ _(XR_SCENE_COMPUTE_FEATURE_VISUAL_MESH_MSFT, 3) \ _(XR_SCENE_COMPUTE_FEATURE_COLLIDER_MESH_MSFT, 4) \ _(XR_SCENE_COMPUTE_FEATURE_SERIALIZE_SCENE_MSFT, 1000098000) \ _(XR_SCENE_COMPUTE_FEATURE_MAX_ENUM_MSFT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrSceneComputeConsistencyMSFT(_) \ _(XR_SCENE_COMPUTE_CONSISTENCY_SNAPSHOT_COMPLETE_MSFT, 1) \ _(XR_SCENE_COMPUTE_CONSISTENCY_SNAPSHOT_INCOMPLETE_FAST_MSFT, 2) \ _(XR_SCENE_COMPUTE_CONSISTENCY_OCCLUSION_OPTIMIZED_MSFT, 3) \ _(XR_SCENE_COMPUTE_CONSISTENCY_MAX_ENUM_MSFT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrMeshComputeLodMSFT(_) \ _(XR_MESH_COMPUTE_LOD_COARSE_MSFT, 1) \ _(XR_MESH_COMPUTE_LOD_MEDIUM_MSFT, 2) \ _(XR_MESH_COMPUTE_LOD_FINE_MSFT, 3) \ _(XR_MESH_COMPUTE_LOD_UNLIMITED_MSFT, 4) \ _(XR_MESH_COMPUTE_LOD_MAX_ENUM_MSFT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrSceneComponentTypeMSFT(_) \ _(XR_SCENE_COMPONENT_TYPE_INVALID_MSFT, -1) \ _(XR_SCENE_COMPONENT_TYPE_OBJECT_MSFT, 1) \ _(XR_SCENE_COMPONENT_TYPE_PLANE_MSFT, 2) \ _(XR_SCENE_COMPONENT_TYPE_VISUAL_MESH_MSFT, 3) \ _(XR_SCENE_COMPONENT_TYPE_COLLIDER_MESH_MSFT, 4) \ _(XR_SCENE_COMPONENT_TYPE_SERIALIZED_SCENE_FRAGMENT_MSFT, 1000098000) \ _(XR_SCENE_COMPONENT_TYPE_MAX_ENUM_MSFT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrSceneObjectTypeMSFT(_) \ _(XR_SCENE_OBJECT_TYPE_UNCATEGORIZED_MSFT, -1) \ _(XR_SCENE_OBJECT_TYPE_BACKGROUND_MSFT, 1) \ _(XR_SCENE_OBJECT_TYPE_WALL_MSFT, 2) \ _(XR_SCENE_OBJECT_TYPE_FLOOR_MSFT, 3) \ _(XR_SCENE_OBJECT_TYPE_CEILING_MSFT, 4) \ _(XR_SCENE_OBJECT_TYPE_PLATFORM_MSFT, 5) \ _(XR_SCENE_OBJECT_TYPE_INFERRED_MSFT, 6) \ _(XR_SCENE_OBJECT_TYPE_MAX_ENUM_MSFT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrScenePlaneAlignmentTypeMSFT(_) \ _(XR_SCENE_PLANE_ALIGNMENT_TYPE_NON_ORTHOGONAL_MSFT, 0) \ _(XR_SCENE_PLANE_ALIGNMENT_TYPE_HORIZONTAL_MSFT, 1) \ _(XR_SCENE_PLANE_ALIGNMENT_TYPE_VERTICAL_MSFT, 2) \ _(XR_SCENE_PLANE_ALIGNMENT_TYPE_MAX_ENUM_MSFT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrSceneComputeStateMSFT(_) \ _(XR_SCENE_COMPUTE_STATE_NONE_MSFT, 0) \ _(XR_SCENE_COMPUTE_STATE_UPDATING_MSFT, 1) \ _(XR_SCENE_COMPUTE_STATE_COMPLETED_MSFT, 2) \ _(XR_SCENE_COMPUTE_STATE_COMPLETED_WITH_ERROR_MSFT, 3) \ _(XR_SCENE_COMPUTE_STATE_MAX_ENUM_MSFT, 0x7FFFFFFF) #define XR_LIST_ENUM_XrColorSpaceFB(_) \ _(XR_COLOR_SPACE_UNMANAGED_FB, 0) \ _(XR_COLOR_SPACE_REC2020_FB, 1) \ _(XR_COLOR_SPACE_REC709_FB, 2) \ _(XR_COLOR_SPACE_RIFT_CV1_FB, 3) \ _(XR_COLOR_SPACE_RIFT_S_FB, 4) \ _(XR_COLOR_SPACE_QUEST_FB, 5) \ _(XR_COLOR_SPACE_P3_FB, 6) \ _(XR_COLOR_SPACE_ADOBE_RGB_FB, 7) \ _(XR_COLOR_SPACE_MAX_ENUM_FB, 0x7FFFFFFF) #define XR_LIST_ENUM_XrFoveationLevelFB(_) \ _(XR_FOVEATION_LEVEL_NONE_FB, 0) \ _(XR_FOVEATION_LEVEL_LOW_FB, 1) \ _(XR_FOVEATION_LEVEL_MEDIUM_FB, 2) \ _(XR_FOVEATION_LEVEL_HIGH_FB, 3) \ _(XR_FOVEATION_LEVEL_MAX_ENUM_FB, 0x7FFFFFFF) #define XR_LIST_ENUM_XrFoveationDynamicFB(_) \ _(XR_FOVEATION_DYNAMIC_DISABLED_FB, 0) \ _(XR_FOVEATION_DYNAMIC_LEVEL_ENABLED_FB, 1) \ _(XR_FOVEATION_DYNAMIC_MAX_ENUM_FB, 0x7FFFFFFF) #define XR_LIST_ENUM_XrWindingOrderFB(_) \ _(XR_WINDING_ORDER_UNKNOWN_FB, 0) \ _(XR_WINDING_ORDER_CW_FB, 1) \ _(XR_WINDING_ORDER_CCW_FB, 2) \ _(XR_WINDING_ORDER_MAX_ENUM_FB, 0x7FFFFFFF) #define XR_LIST_ENUM_XrPassthroughLayerPurposeFB(_) \ _(XR_PASSTHROUGH_LAYER_PURPOSE_RECONSTRUCTION_FB, 0) \ _(XR_PASSTHROUGH_LAYER_PURPOSE_PROJECTED_FB, 1) \ _(XR_PASSTHROUGH_LAYER_PURPOSE_MAX_ENUM_FB, 0x7FFFFFFF) #define XR_LIST_BITS_XrInstanceCreateFlags(_) #define XR_LIST_BITS_XrSessionCreateFlags(_) #define XR_LIST_BITS_XrSpaceVelocityFlags(_) \ _(XR_SPACE_VELOCITY_LINEAR_VALID_BIT, 0x00000001) \ _(XR_SPACE_VELOCITY_ANGULAR_VALID_BIT, 0x00000002) \ #define XR_LIST_BITS_XrSpaceLocationFlags(_) \ _(XR_SPACE_LOCATION_ORIENTATION_VALID_BIT, 0x00000001) \ _(XR_SPACE_LOCATION_POSITION_VALID_BIT, 0x00000002) \ _(XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT, 0x00000004) \ _(XR_SPACE_LOCATION_POSITION_TRACKED_BIT, 0x00000008) \ #define XR_LIST_BITS_XrSwapchainCreateFlags(_) \ _(XR_SWAPCHAIN_CREATE_PROTECTED_CONTENT_BIT, 0x00000001) \ _(XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT, 0x00000002) \ #define XR_LIST_BITS_XrSwapchainUsageFlags(_) \ _(XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, 0x00000001) \ _(XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, 0x00000002) \ _(XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT, 0x00000004) \ _(XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT, 0x00000008) \ _(XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, 0x00000010) \ _(XR_SWAPCHAIN_USAGE_SAMPLED_BIT, 0x00000020) \ _(XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, 0x00000040) \ _(XR_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT_MND, 0x00000080) \ _(XR_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT_KHR, XR_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT_MND) \ #define XR_LIST_BITS_XrCompositionLayerFlags(_) \ _(XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT, 0x00000001) \ _(XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, 0x00000002) \ _(XR_COMPOSITION_LAYER_UNPREMULTIPLIED_ALPHA_BIT, 0x00000004) \ #define XR_LIST_BITS_XrViewStateFlags(_) \ _(XR_VIEW_STATE_ORIENTATION_VALID_BIT, 0x00000001) \ _(XR_VIEW_STATE_POSITION_VALID_BIT, 0x00000002) \ _(XR_VIEW_STATE_ORIENTATION_TRACKED_BIT, 0x00000004) \ _(XR_VIEW_STATE_POSITION_TRACKED_BIT, 0x00000008) \ #define XR_LIST_BITS_XrInputSourceLocalizedNameFlags(_) \ _(XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT, 0x00000001) \ _(XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT, 0x00000002) \ _(XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT, 0x00000004) \ #define XR_LIST_BITS_XrVulkanInstanceCreateFlagsKHR(_) #define XR_LIST_BITS_XrVulkanDeviceCreateFlagsKHR(_) #define XR_LIST_BITS_XrDebugUtilsMessageSeverityFlagsEXT(_) \ _(XR_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT, 0x00000001) \ _(XR_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT, 0x00000010) \ _(XR_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT, 0x00000100) \ _(XR_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT, 0x00001000) \ #define XR_LIST_BITS_XrDebugUtilsMessageTypeFlagsEXT(_) \ _(XR_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT, 0x00000001) \ _(XR_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT, 0x00000002) \ _(XR_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, 0x00000004) \ _(XR_DEBUG_UTILS_MESSAGE_TYPE_CONFORMANCE_BIT_EXT, 0x00000008) \ #define XR_LIST_BITS_XrOverlaySessionCreateFlagsEXTX(_) #define XR_LIST_BITS_XrOverlayMainSessionFlagsEXTX(_) \ _(XR_OVERLAY_MAIN_SESSION_ENABLED_COMPOSITION_LAYER_INFO_DEPTH_BIT_EXTX, 0x00000001) \ #define XR_LIST_BITS_XrCompositionLayerImageLayoutFlagsFB(_) \ _(XR_COMPOSITION_LAYER_IMAGE_LAYOUT_VERTICAL_FLIP_BIT_FB, 0x00000001) \ #define XR_LIST_BITS_XrAndroidSurfaceSwapchainFlagsFB(_) \ _(XR_ANDROID_SURFACE_SWAPCHAIN_SYNCHRONOUS_BIT_FB, 0x00000001) \ _(XR_ANDROID_SURFACE_SWAPCHAIN_USE_TIMESTAMPS_BIT_FB, 0x00000002) \ #define XR_LIST_BITS_XrCompositionLayerSecureContentFlagsFB(_) \ _(XR_COMPOSITION_LAYER_SECURE_CONTENT_EXCLUDE_LAYER_BIT_FB, 0x00000001) \ _(XR_COMPOSITION_LAYER_SECURE_CONTENT_REPLACE_LAYER_BIT_FB, 0x00000002) \ #define XR_LIST_BITS_XrHandTrackingAimFlagsFB(_) \ _(XR_HAND_TRACKING_AIM_COMPUTED_BIT_FB, 0x00000001) \ _(XR_HAND_TRACKING_AIM_VALID_BIT_FB, 0x00000002) \ _(XR_HAND_TRACKING_AIM_INDEX_PINCHING_BIT_FB, 0x00000004) \ _(XR_HAND_TRACKING_AIM_MIDDLE_PINCHING_BIT_FB, 0x00000008) \ _(XR_HAND_TRACKING_AIM_RING_PINCHING_BIT_FB, 0x00000010) \ _(XR_HAND_TRACKING_AIM_LITTLE_PINCHING_BIT_FB, 0x00000020) \ _(XR_HAND_TRACKING_AIM_SYSTEM_GESTURE_BIT_FB, 0x00000040) \ _(XR_HAND_TRACKING_AIM_DOMINANT_HAND_BIT_FB, 0x00000080) \ _(XR_HAND_TRACKING_AIM_MENU_PRESSED_BIT_FB, 0x00000100) \ #define XR_LIST_BITS_XrSwapchainCreateFoveationFlagsFB(_) \ _(XR_SWAPCHAIN_CREATE_FOVEATION_SCALED_BIN_BIT_FB, 0x00000001) \ _(XR_SWAPCHAIN_CREATE_FOVEATION_FRAGMENT_DENSITY_MAP_BIT_FB, 0x00000002) \ #define XR_LIST_BITS_XrSwapchainStateFoveationFlagsFB(_) #define XR_LIST_BITS_XrTriangleMeshFlagsFB(_) \ _(XR_TRIANGLE_MESH_MUTABLE_BIT_FB, 0x00000001) \ #define XR_LIST_BITS_XrPassthroughFlagsFB(_) \ _(XR_PASSTHROUGH_IS_RUNNING_AT_CREATION_BIT_FB, 0x00000001) \ #define XR_LIST_BITS_XrPassthroughStateChangedFlagsFB(_) \ _(XR_PASSTHROUGH_STATE_CHANGED_REINIT_REQUIRED_BIT_FB, 0x00000001) \ _(XR_PASSTHROUGH_STATE_CHANGED_NON_RECOVERABLE_ERROR_BIT_FB, 0x00000002) \ _(XR_PASSTHROUGH_STATE_CHANGED_RECOVERABLE_ERROR_BIT_FB, 0x00000004) \ _(XR_PASSTHROUGH_STATE_CHANGED_RESTORED_ERROR_BIT_FB, 0x00000008) \ #define XR_LIST_BITS_XrCompositionLayerSpaceWarpInfoFlagsFB(_) #define XR_LIST_STRUCT_XrApiLayerProperties(_) \ _(type) \ _(next) \ _(layerName) \ _(specVersion) \ _(layerVersion) \ _(description) \ #define XR_LIST_STRUCT_XrExtensionProperties(_) \ _(type) \ _(next) \ _(extensionName) \ _(extensionVersion) \ #define XR_LIST_STRUCT_XrApplicationInfo(_) \ _(applicationName) \ _(applicationVersion) \ _(engineName) \ _(engineVersion) \ _(apiVersion) \ #define XR_LIST_STRUCT_XrInstanceCreateInfo(_) \ _(type) \ _(next) \ _(createFlags) \ _(applicationInfo) \ _(enabledApiLayerCount) \ _(enabledApiLayerNames) \ _(enabledExtensionCount) \ _(enabledExtensionNames) \ #define XR_LIST_STRUCT_XrInstanceProperties(_) \ _(type) \ _(next) \ _(runtimeVersion) \ _(runtimeName) \ #define XR_LIST_STRUCT_XrEventDataBuffer(_) \ _(type) \ _(next) \ _(varying) \ #define XR_LIST_STRUCT_XrSystemGetInfo(_) \ _(type) \ _(next) \ _(formFactor) \ #define XR_LIST_STRUCT_XrSystemGraphicsProperties(_) \ _(maxSwapchainImageHeight) \ _(maxSwapchainImageWidth) \ _(maxLayerCount) \ #define XR_LIST_STRUCT_XrSystemTrackingProperties(_) \ _(orientationTracking) \ _(positionTracking) \ #define XR_LIST_STRUCT_XrSystemProperties(_) \ _(type) \ _(next) \ _(systemId) \ _(vendorId) \ _(systemName) \ _(graphicsProperties) \ _(trackingProperties) \ #define XR_LIST_STRUCT_XrSessionCreateInfo(_) \ _(type) \ _(next) \ _(createFlags) \ _(systemId) \ #define XR_LIST_STRUCT_XrVector3f(_) \ _(x) \ _(y) \ _(z) \ #define XR_LIST_STRUCT_XrSpaceVelocity(_) \ _(type) \ _(next) \ _(velocityFlags) \ _(linearVelocity) \ _(angularVelocity) \ #define XR_LIST_STRUCT_XrQuaternionf(_) \ _(x) \ _(y) \ _(z) \ _(w) \ #define XR_LIST_STRUCT_XrPosef(_) \ _(orientation) \ _(position) \ #define XR_LIST_STRUCT_XrReferenceSpaceCreateInfo(_) \ _(type) \ _(next) \ _(referenceSpaceType) \ _(poseInReferenceSpace) \ #define XR_LIST_STRUCT_XrExtent2Df(_) \ _(width) \ _(height) \ #define XR_LIST_STRUCT_XrActionSpaceCreateInfo(_) \ _(type) \ _(next) \ _(action) \ _(subactionPath) \ _(poseInActionSpace) \ #define XR_LIST_STRUCT_XrSpaceLocation(_) \ _(type) \ _(next) \ _(locationFlags) \ _(pose) \ #define XR_LIST_STRUCT_XrViewConfigurationProperties(_) \ _(type) \ _(next) \ _(viewConfigurationType) \ _(fovMutable) \ #define XR_LIST_STRUCT_XrViewConfigurationView(_) \ _(type) \ _(next) \ _(recommendedImageRectWidth) \ _(maxImageRectWidth) \ _(recommendedImageRectHeight) \ _(maxImageRectHeight) \ _(recommendedSwapchainSampleCount) \ _(maxSwapchainSampleCount) \ #define XR_LIST_STRUCT_XrSwapchainCreateInfo(_) \ _(type) \ _(next) \ _(createFlags) \ _(usageFlags) \ _(format) \ _(sampleCount) \ _(width) \ _(height) \ _(faceCount) \ _(arraySize) \ _(mipCount) \ #define XR_LIST_STRUCT_XrSwapchainImageBaseHeader(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrSwapchainImageAcquireInfo(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrSwapchainImageWaitInfo(_) \ _(type) \ _(next) \ _(timeout) \ #define XR_LIST_STRUCT_XrSwapchainImageReleaseInfo(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrSessionBeginInfo(_) \ _(type) \ _(next) \ _(primaryViewConfigurationType) \ #define XR_LIST_STRUCT_XrFrameWaitInfo(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrFrameState(_) \ _(type) \ _(next) \ _(predictedDisplayTime) \ _(predictedDisplayPeriod) \ _(shouldRender) \ #define XR_LIST_STRUCT_XrFrameBeginInfo(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrCompositionLayerBaseHeader(_) \ _(type) \ _(next) \ _(layerFlags) \ _(space) \ #define XR_LIST_STRUCT_XrFrameEndInfo(_) \ _(type) \ _(next) \ _(displayTime) \ _(environmentBlendMode) \ _(layerCount) \ _(layers) \ #define XR_LIST_STRUCT_XrViewLocateInfo(_) \ _(type) \ _(next) \ _(viewConfigurationType) \ _(displayTime) \ _(space) \ #define XR_LIST_STRUCT_XrViewState(_) \ _(type) \ _(next) \ _(viewStateFlags) \ #define XR_LIST_STRUCT_XrFovf(_) \ _(angleLeft) \ _(angleRight) \ _(angleUp) \ _(angleDown) \ #define XR_LIST_STRUCT_XrView(_) \ _(type) \ _(next) \ _(pose) \ _(fov) \ #define XR_LIST_STRUCT_XrActionSetCreateInfo(_) \ _(type) \ _(next) \ _(actionSetName) \ _(localizedActionSetName) \ _(priority) \ #define XR_LIST_STRUCT_XrActionCreateInfo(_) \ _(type) \ _(next) \ _(actionName) \ _(actionType) \ _(countSubactionPaths) \ _(subactionPaths) \ _(localizedActionName) \ #define XR_LIST_STRUCT_XrActionSuggestedBinding(_) \ _(action) \ _(binding) \ #define XR_LIST_STRUCT_XrInteractionProfileSuggestedBinding(_) \ _(type) \ _(next) \ _(interactionProfile) \ _(countSuggestedBindings) \ _(suggestedBindings) \ #define XR_LIST_STRUCT_XrSessionActionSetsAttachInfo(_) \ _(type) \ _(next) \ _(countActionSets) \ _(actionSets) \ #define XR_LIST_STRUCT_XrInteractionProfileState(_) \ _(type) \ _(next) \ _(interactionProfile) \ #define XR_LIST_STRUCT_XrActionStateGetInfo(_) \ _(type) \ _(next) \ _(action) \ _(subactionPath) \ #define XR_LIST_STRUCT_XrActionStateBoolean(_) \ _(type) \ _(next) \ _(currentState) \ _(changedSinceLastSync) \ _(lastChangeTime) \ _(isActive) \ #define XR_LIST_STRUCT_XrActionStateFloat(_) \ _(type) \ _(next) \ _(currentState) \ _(changedSinceLastSync) \ _(lastChangeTime) \ _(isActive) \ #define XR_LIST_STRUCT_XrVector2f(_) \ _(x) \ _(y) \ #define XR_LIST_STRUCT_XrActionStateVector2f(_) \ _(type) \ _(next) \ _(currentState) \ _(changedSinceLastSync) \ _(lastChangeTime) \ _(isActive) \ #define XR_LIST_STRUCT_XrActionStatePose(_) \ _(type) \ _(next) \ _(isActive) \ #define XR_LIST_STRUCT_XrActiveActionSet(_) \ _(actionSet) \ _(subactionPath) \ #define XR_LIST_STRUCT_XrActionsSyncInfo(_) \ _(type) \ _(next) \ _(countActiveActionSets) \ _(activeActionSets) \ #define XR_LIST_STRUCT_XrBoundSourcesForActionEnumerateInfo(_) \ _(type) \ _(next) \ _(action) \ #define XR_LIST_STRUCT_XrInputSourceLocalizedNameGetInfo(_) \ _(type) \ _(next) \ _(sourcePath) \ _(whichComponents) \ #define XR_LIST_STRUCT_XrHapticActionInfo(_) \ _(type) \ _(next) \ _(action) \ _(subactionPath) \ #define XR_LIST_STRUCT_XrHapticBaseHeader(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrBaseInStructure(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrBaseOutStructure(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrOffset2Di(_) \ _(x) \ _(y) \ #define XR_LIST_STRUCT_XrExtent2Di(_) \ _(width) \ _(height) \ #define XR_LIST_STRUCT_XrRect2Di(_) \ _(offset) \ _(extent) \ #define XR_LIST_STRUCT_XrSwapchainSubImage(_) \ _(swapchain) \ _(imageRect) \ _(imageArrayIndex) \ #define XR_LIST_STRUCT_XrCompositionLayerProjectionView(_) \ _(type) \ _(next) \ _(pose) \ _(fov) \ _(subImage) \ #define XR_LIST_STRUCT_XrCompositionLayerProjection(_) \ _(type) \ _(next) \ _(layerFlags) \ _(space) \ _(viewCount) \ _(views) \ #define XR_LIST_STRUCT_XrCompositionLayerQuad(_) \ _(type) \ _(next) \ _(layerFlags) \ _(space) \ _(eyeVisibility) \ _(subImage) \ _(pose) \ _(size) \ #define XR_LIST_STRUCT_XrEventDataBaseHeader(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrEventDataEventsLost(_) \ _(type) \ _(next) \ _(lostEventCount) \ #define XR_LIST_STRUCT_XrEventDataInstanceLossPending(_) \ _(type) \ _(next) \ _(lossTime) \ #define XR_LIST_STRUCT_XrEventDataSessionStateChanged(_) \ _(type) \ _(next) \ _(session) \ _(state) \ _(time) \ #define XR_LIST_STRUCT_XrEventDataReferenceSpaceChangePending(_) \ _(type) \ _(next) \ _(session) \ _(referenceSpaceType) \ _(changeTime) \ _(poseValid) \ _(poseInPreviousSpace) \ #define XR_LIST_STRUCT_XrEventDataInteractionProfileChanged(_) \ _(type) \ _(next) \ _(session) \ #define XR_LIST_STRUCT_XrHapticVibration(_) \ _(type) \ _(next) \ _(duration) \ _(frequency) \ _(amplitude) \ #define XR_LIST_STRUCT_XrOffset2Df(_) \ _(x) \ _(y) \ #define XR_LIST_STRUCT_XrRect2Df(_) \ _(offset) \ _(extent) \ #define XR_LIST_STRUCT_XrVector4f(_) \ _(x) \ _(y) \ _(z) \ _(w) \ #define XR_LIST_STRUCT_XrColor4f(_) \ _(r) \ _(g) \ _(b) \ _(a) \ #define XR_LIST_STRUCT_XrCompositionLayerCubeKHR(_) \ _(type) \ _(next) \ _(layerFlags) \ _(space) \ _(eyeVisibility) \ _(swapchain) \ _(imageArrayIndex) \ _(orientation) \ #define XR_LIST_STRUCT_XrInstanceCreateInfoAndroidKHR(_) \ _(type) \ _(next) \ _(applicationVM) \ _(applicationActivity) \ #define XR_LIST_STRUCT_XrCompositionLayerDepthInfoKHR(_) \ _(type) \ _(next) \ _(subImage) \ _(minDepth) \ _(maxDepth) \ _(nearZ) \ _(farZ) \ #define XR_LIST_STRUCT_XrVulkanSwapchainFormatListCreateInfoKHR(_) \ _(type) \ _(next) \ _(viewFormatCount) \ _(viewFormats) \ #define XR_LIST_STRUCT_XrCompositionLayerCylinderKHR(_) \ _(type) \ _(next) \ _(layerFlags) \ _(space) \ _(eyeVisibility) \ _(subImage) \ _(pose) \ _(radius) \ _(centralAngle) \ _(aspectRatio) \ #define XR_LIST_STRUCT_XrCompositionLayerEquirectKHR(_) \ _(type) \ _(next) \ _(layerFlags) \ _(space) \ _(eyeVisibility) \ _(subImage) \ _(pose) \ _(radius) \ _(scale) \ _(bias) \ #define XR_LIST_STRUCT_XrGraphicsBindingOpenGLWin32KHR(_) \ _(type) \ _(next) \ _(hDC) \ _(hGLRC) \ #define XR_LIST_STRUCT_XrGraphicsBindingOpenGLXlibKHR(_) \ _(type) \ _(next) \ _(xDisplay) \ _(visualid) \ _(glxFBConfig) \ _(glxDrawable) \ _(glxContext) \ #define XR_LIST_STRUCT_XrGraphicsBindingOpenGLXcbKHR(_) \ _(type) \ _(next) \ _(connection) \ _(screenNumber) \ _(fbconfigid) \ _(visualid) \ _(glxDrawable) \ _(glxContext) \ #define XR_LIST_STRUCT_XrGraphicsBindingOpenGLWaylandKHR(_) \ _(type) \ _(next) \ _(display) \ #define XR_LIST_STRUCT_XrSwapchainImageOpenGLKHR(_) \ _(type) \ _(next) \ _(image) \ #define XR_LIST_STRUCT_XrGraphicsRequirementsOpenGLKHR(_) \ _(type) \ _(next) \ _(minApiVersionSupported) \ _(maxApiVersionSupported) \ #define XR_LIST_STRUCT_XrGraphicsBindingOpenGLESAndroidKHR(_) \ _(type) \ _(next) \ _(display) \ _(config) \ _(context) \ #define XR_LIST_STRUCT_XrSwapchainImageOpenGLESKHR(_) \ _(type) \ _(next) \ _(image) \ #define XR_LIST_STRUCT_XrGraphicsRequirementsOpenGLESKHR(_) \ _(type) \ _(next) \ _(minApiVersionSupported) \ _(maxApiVersionSupported) \ #define XR_LIST_STRUCT_XrGraphicsBindingVulkanKHR(_) \ _(type) \ _(next) \ _(instance) \ _(physicalDevice) \ _(device) \ _(queueFamilyIndex) \ _(queueIndex) \ #define XR_LIST_STRUCT_XrSwapchainImageVulkanKHR(_) \ _(type) \ _(next) \ _(image) \ #define XR_LIST_STRUCT_XrGraphicsRequirementsVulkanKHR(_) \ _(type) \ _(next) \ _(minApiVersionSupported) \ _(maxApiVersionSupported) \ #define XR_LIST_STRUCT_XrGraphicsBindingD3D11KHR(_) \ _(type) \ _(next) \ _(device) \ #define XR_LIST_STRUCT_XrSwapchainImageD3D11KHR(_) \ _(type) \ _(next) \ _(texture) \ #define XR_LIST_STRUCT_XrGraphicsRequirementsD3D11KHR(_) \ _(type) \ _(next) \ _(adapterLuid) \ _(minFeatureLevel) \ #define XR_LIST_STRUCT_XrGraphicsBindingD3D12KHR(_) \ _(type) \ _(next) \ _(device) \ _(queue) \ #define XR_LIST_STRUCT_XrSwapchainImageD3D12KHR(_) \ _(type) \ _(next) \ _(texture) \ #define XR_LIST_STRUCT_XrGraphicsRequirementsD3D12KHR(_) \ _(type) \ _(next) \ _(adapterLuid) \ _(minFeatureLevel) \ #define XR_LIST_STRUCT_XrVisibilityMaskKHR(_) \ _(type) \ _(next) \ _(vertexCapacityInput) \ _(vertexCountOutput) \ _(vertices) \ _(indexCapacityInput) \ _(indexCountOutput) \ _(indices) \ #define XR_LIST_STRUCT_XrEventDataVisibilityMaskChangedKHR(_) \ _(type) \ _(next) \ _(session) \ _(viewConfigurationType) \ _(viewIndex) \ #define XR_LIST_STRUCT_XrCompositionLayerColorScaleBiasKHR(_) \ _(type) \ _(next) \ _(colorScale) \ _(colorBias) \ #define XR_LIST_STRUCT_XrLoaderInitInfoBaseHeaderKHR(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrLoaderInitInfoAndroidKHR(_) \ _(type) \ _(next) \ _(applicationVM) \ _(applicationContext) \ #define XR_LIST_STRUCT_XrVulkanInstanceCreateInfoKHR(_) \ _(type) \ _(next) \ _(systemId) \ _(createFlags) \ _(pfnGetInstanceProcAddr) \ _(vulkanCreateInfo) \ _(vulkanAllocator) \ #define XR_LIST_STRUCT_XrVulkanDeviceCreateInfoKHR(_) \ _(type) \ _(next) \ _(systemId) \ _(createFlags) \ _(pfnGetInstanceProcAddr) \ _(vulkanPhysicalDevice) \ _(vulkanCreateInfo) \ _(vulkanAllocator) \ #define XR_LIST_STRUCT_XrVulkanGraphicsDeviceGetInfoKHR(_) \ _(type) \ _(next) \ _(systemId) \ _(vulkanInstance) \ #define XR_LIST_STRUCT_XrCompositionLayerEquirect2KHR(_) \ _(type) \ _(next) \ _(layerFlags) \ _(space) \ _(eyeVisibility) \ _(subImage) \ _(pose) \ _(radius) \ _(centralHorizontalAngle) \ _(upperVerticalAngle) \ _(lowerVerticalAngle) \ #define XR_LIST_STRUCT_XrBindingModificationBaseHeaderKHR(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrBindingModificationsKHR(_) \ _(type) \ _(next) \ _(bindingModificationCount) \ _(bindingModifications) \ #define XR_LIST_STRUCT_XrEventDataPerfSettingsEXT(_) \ _(type) \ _(next) \ _(domain) \ _(subDomain) \ _(fromLevel) \ _(toLevel) \ #define XR_LIST_STRUCT_XrDebugUtilsObjectNameInfoEXT(_) \ _(type) \ _(next) \ _(objectType) \ _(objectHandle) \ _(objectName) \ #define XR_LIST_STRUCT_XrDebugUtilsLabelEXT(_) \ _(type) \ _(next) \ _(labelName) \ #define XR_LIST_STRUCT_XrDebugUtilsMessengerCallbackDataEXT(_) \ _(type) \ _(next) \ _(messageId) \ _(functionName) \ _(message) \ _(objectCount) \ _(objects) \ _(sessionLabelCount) \ _(sessionLabels) \ #define XR_LIST_STRUCT_XrDebugUtilsMessengerCreateInfoEXT(_) \ _(type) \ _(next) \ _(messageSeverities) \ _(messageTypes) \ _(userCallback) \ _(userData) \ #define XR_LIST_STRUCT_XrSystemEyeGazeInteractionPropertiesEXT(_) \ _(type) \ _(next) \ _(supportsEyeGazeInteraction) \ #define XR_LIST_STRUCT_XrEyeGazeSampleTimeEXT(_) \ _(type) \ _(next) \ _(time) \ #define XR_LIST_STRUCT_XrSessionCreateInfoOverlayEXTX(_) \ _(type) \ _(next) \ _(createFlags) \ _(sessionLayersPlacement) \ #define XR_LIST_STRUCT_XrEventDataMainSessionVisibilityChangedEXTX(_) \ _(type) \ _(next) \ _(visible) \ _(flags) \ #define XR_LIST_STRUCT_XrSpatialAnchorCreateInfoMSFT(_) \ _(type) \ _(next) \ _(space) \ _(pose) \ _(time) \ #define XR_LIST_STRUCT_XrSpatialAnchorSpaceCreateInfoMSFT(_) \ _(type) \ _(next) \ _(anchor) \ _(poseInAnchorSpace) \ #define XR_LIST_STRUCT_XrCompositionLayerImageLayoutFB(_) \ _(type) \ _(next) \ _(flags) \ #define XR_LIST_STRUCT_XrCompositionLayerAlphaBlendFB(_) \ _(type) \ _(next) \ _(srcFactorColor) \ _(dstFactorColor) \ _(srcFactorAlpha) \ _(dstFactorAlpha) \ #define XR_LIST_STRUCT_XrViewConfigurationDepthRangeEXT(_) \ _(type) \ _(next) \ _(recommendedNearZ) \ _(minNearZ) \ _(recommendedFarZ) \ _(maxFarZ) \ #define XR_LIST_STRUCT_XrGraphicsBindingEGLMNDX(_) \ _(type) \ _(next) \ _(getProcAddress) \ _(display) \ _(config) \ _(context) \ #define XR_LIST_STRUCT_XrSpatialGraphNodeSpaceCreateInfoMSFT(_) \ _(type) \ _(next) \ _(nodeType) \ _(nodeId) \ _(pose) \ #define XR_LIST_STRUCT_XrSystemHandTrackingPropertiesEXT(_) \ _(type) \ _(next) \ _(supportsHandTracking) \ #define XR_LIST_STRUCT_XrHandTrackerCreateInfoEXT(_) \ _(type) \ _(next) \ _(hand) \ _(handJointSet) \ #define XR_LIST_STRUCT_XrHandJointsLocateInfoEXT(_) \ _(type) \ _(next) \ _(baseSpace) \ _(time) \ #define XR_LIST_STRUCT_XrHandJointLocationEXT(_) \ _(locationFlags) \ _(pose) \ _(radius) \ #define XR_LIST_STRUCT_XrHandJointVelocityEXT(_) \ _(velocityFlags) \ _(linearVelocity) \ _(angularVelocity) \ #define XR_LIST_STRUCT_XrHandJointLocationsEXT(_) \ _(type) \ _(next) \ _(isActive) \ _(jointCount) \ _(jointLocations) \ #define XR_LIST_STRUCT_XrHandJointVelocitiesEXT(_) \ _(type) \ _(next) \ _(jointCount) \ _(jointVelocities) \ #define XR_LIST_STRUCT_XrSystemHandTrackingMeshPropertiesMSFT(_) \ _(type) \ _(next) \ _(supportsHandTrackingMesh) \ _(maxHandMeshIndexCount) \ _(maxHandMeshVertexCount) \ #define XR_LIST_STRUCT_XrHandMeshSpaceCreateInfoMSFT(_) \ _(type) \ _(next) \ _(handPoseType) \ _(poseInHandMeshSpace) \ #define XR_LIST_STRUCT_XrHandMeshUpdateInfoMSFT(_) \ _(type) \ _(next) \ _(time) \ _(handPoseType) \ #define XR_LIST_STRUCT_XrHandMeshIndexBufferMSFT(_) \ _(indexBufferKey) \ _(indexCapacityInput) \ _(indexCountOutput) \ _(indices) \ #define XR_LIST_STRUCT_XrHandMeshVertexMSFT(_) \ _(position) \ _(normal) \ #define XR_LIST_STRUCT_XrHandMeshVertexBufferMSFT(_) \ _(vertexUpdateTime) \ _(vertexCapacityInput) \ _(vertexCountOutput) \ _(vertices) \ #define XR_LIST_STRUCT_XrHandMeshMSFT(_) \ _(type) \ _(next) \ _(isActive) \ _(indexBufferChanged) \ _(vertexBufferChanged) \ _(indexBuffer) \ _(vertexBuffer) \ #define XR_LIST_STRUCT_XrHandPoseTypeInfoMSFT(_) \ _(type) \ _(next) \ _(handPoseType) \ #define XR_LIST_STRUCT_XrSecondaryViewConfigurationSessionBeginInfoMSFT(_) \ _(type) \ _(next) \ _(viewConfigurationCount) \ _(enabledViewConfigurationTypes) \ #define XR_LIST_STRUCT_XrSecondaryViewConfigurationStateMSFT(_) \ _(type) \ _(next) \ _(viewConfigurationType) \ _(active) \ #define XR_LIST_STRUCT_XrSecondaryViewConfigurationFrameStateMSFT(_) \ _(type) \ _(next) \ _(viewConfigurationCount) \ _(viewConfigurationStates) \ #define XR_LIST_STRUCT_XrSecondaryViewConfigurationLayerInfoMSFT(_) \ _(type) \ _(next) \ _(viewConfigurationType) \ _(environmentBlendMode) \ _(layerCount) \ _(layers) \ #define XR_LIST_STRUCT_XrSecondaryViewConfigurationFrameEndInfoMSFT(_) \ _(type) \ _(next) \ _(viewConfigurationCount) \ _(viewConfigurationLayersInfo) \ #define XR_LIST_STRUCT_XrSecondaryViewConfigurationSwapchainCreateInfoMSFT(_) \ _(type) \ _(next) \ _(viewConfigurationType) \ #define XR_LIST_STRUCT_XrControllerModelKeyStateMSFT(_) \ _(type) \ _(next) \ _(modelKey) \ #define XR_LIST_STRUCT_XrControllerModelNodePropertiesMSFT(_) \ _(type) \ _(next) \ _(parentNodeName) \ _(nodeName) \ #define XR_LIST_STRUCT_XrControllerModelPropertiesMSFT(_) \ _(type) \ _(next) \ _(nodeCapacityInput) \ _(nodeCountOutput) \ _(nodeProperties) \ #define XR_LIST_STRUCT_XrControllerModelNodeStateMSFT(_) \ _(type) \ _(next) \ _(nodePose) \ #define XR_LIST_STRUCT_XrControllerModelStateMSFT(_) \ _(type) \ _(next) \ _(nodeCapacityInput) \ _(nodeCountOutput) \ _(nodeStates) \ #define XR_LIST_STRUCT_XrViewConfigurationViewFovEPIC(_) \ _(type) \ _(next) \ _(recommendedFov) \ _(maxMutableFov) \ #define XR_LIST_STRUCT_XrHolographicWindowAttachmentMSFT(_) \ _(type) \ _(next) \ _(holographicSpace) \ _(coreWindow) \ #define XR_LIST_STRUCT_XrCompositionLayerReprojectionInfoMSFT(_) \ _(type) \ _(next) \ _(reprojectionMode) \ #define XR_LIST_STRUCT_XrCompositionLayerReprojectionPlaneOverrideMSFT(_) \ _(type) \ _(next) \ _(position) \ _(normal) \ _(velocity) \ #define XR_LIST_STRUCT_XrAndroidSurfaceSwapchainCreateInfoFB(_) \ _(type) \ _(next) \ _(createFlags) \ #define XR_LIST_STRUCT_XrSwapchainStateBaseHeaderFB(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrCompositionLayerSecureContentFB(_) \ _(type) \ _(next) \ _(flags) \ #define XR_LIST_STRUCT_XrInteractionProfileAnalogThresholdVALVE(_) \ _(type) \ _(next) \ _(action) \ _(binding) \ _(onThreshold) \ _(offThreshold) \ _(onHaptic) \ _(offHaptic) \ #define XR_LIST_STRUCT_XrHandJointsMotionRangeInfoEXT(_) \ _(type) \ _(next) \ _(handJointsMotionRange) \ #define XR_LIST_STRUCT_XrUuidMSFT(_) \ _(bytes) \ #define XR_LIST_STRUCT_XrSceneObserverCreateInfoMSFT(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrSceneCreateInfoMSFT(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrSceneSphereBoundMSFT(_) \ _(center) \ _(radius) \ #define XR_LIST_STRUCT_XrSceneOrientedBoxBoundMSFT(_) \ _(pose) \ _(extents) \ #define XR_LIST_STRUCT_XrSceneFrustumBoundMSFT(_) \ _(pose) \ _(fov) \ _(farDistance) \ #define XR_LIST_STRUCT_XrSceneBoundsMSFT(_) \ _(space) \ _(time) \ _(sphereCount) \ _(spheres) \ _(boxCount) \ _(boxes) \ _(frustumCount) \ _(frustums) \ #define XR_LIST_STRUCT_XrNewSceneComputeInfoMSFT(_) \ _(type) \ _(next) \ _(requestedFeatureCount) \ _(requestedFeatures) \ _(consistency) \ _(bounds) \ #define XR_LIST_STRUCT_XrVisualMeshComputeLodInfoMSFT(_) \ _(type) \ _(next) \ _(lod) \ #define XR_LIST_STRUCT_XrSceneComponentMSFT(_) \ _(componentType) \ _(id) \ _(parentId) \ _(updateTime) \ #define XR_LIST_STRUCT_XrSceneComponentsMSFT(_) \ _(type) \ _(next) \ _(componentCapacityInput) \ _(componentCountOutput) \ _(components) \ #define XR_LIST_STRUCT_XrSceneComponentsGetInfoMSFT(_) \ _(type) \ _(next) \ _(componentType) \ #define XR_LIST_STRUCT_XrSceneComponentLocationMSFT(_) \ _(flags) \ _(pose) \ #define XR_LIST_STRUCT_XrSceneComponentLocationsMSFT(_) \ _(type) \ _(next) \ _(locationCount) \ _(locations) \ #define XR_LIST_STRUCT_XrSceneComponentsLocateInfoMSFT(_) \ _(type) \ _(next) \ _(baseSpace) \ _(time) \ _(componentIdCount) \ _(componentIds) \ #define XR_LIST_STRUCT_XrSceneObjectMSFT(_) \ _(objectType) \ #define XR_LIST_STRUCT_XrSceneObjectsMSFT(_) \ _(type) \ _(next) \ _(sceneObjectCount) \ _(sceneObjects) \ #define XR_LIST_STRUCT_XrSceneComponentParentFilterInfoMSFT(_) \ _(type) \ _(next) \ _(parentId) \ #define XR_LIST_STRUCT_XrSceneObjectTypesFilterInfoMSFT(_) \ _(type) \ _(next) \ _(objectTypeCount) \ _(objectTypes) \ #define XR_LIST_STRUCT_XrScenePlaneMSFT(_) \ _(alignment) \ _(size) \ _(meshBufferId) \ _(supportsIndicesUint16) \ #define XR_LIST_STRUCT_XrScenePlanesMSFT(_) \ _(type) \ _(next) \ _(scenePlaneCount) \ _(scenePlanes) \ #define XR_LIST_STRUCT_XrScenePlaneAlignmentFilterInfoMSFT(_) \ _(type) \ _(next) \ _(alignmentCount) \ _(alignments) \ #define XR_LIST_STRUCT_XrSceneMeshMSFT(_) \ _(meshBufferId) \ _(supportsIndicesUint16) \ #define XR_LIST_STRUCT_XrSceneMeshesMSFT(_) \ _(type) \ _(next) \ _(sceneMeshCount) \ _(sceneMeshes) \ #define XR_LIST_STRUCT_XrSceneMeshBuffersGetInfoMSFT(_) \ _(type) \ _(next) \ _(meshBufferId) \ #define XR_LIST_STRUCT_XrSceneMeshBuffersMSFT(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrSceneMeshVertexBufferMSFT(_) \ _(type) \ _(next) \ _(vertexCapacityInput) \ _(vertexCountOutput) \ _(vertices) \ #define XR_LIST_STRUCT_XrSceneMeshIndicesUint32MSFT(_) \ _(type) \ _(next) \ _(indexCapacityInput) \ _(indexCountOutput) \ _(indices) \ #define XR_LIST_STRUCT_XrSceneMeshIndicesUint16MSFT(_) \ _(type) \ _(next) \ _(indexCapacityInput) \ _(indexCountOutput) \ _(indices) \ #define XR_LIST_STRUCT_XrSerializedSceneFragmentDataGetInfoMSFT(_) \ _(type) \ _(next) \ _(sceneFragmentId) \ #define XR_LIST_STRUCT_XrDeserializeSceneFragmentMSFT(_) \ _(bufferSize) \ _(buffer) \ #define XR_LIST_STRUCT_XrSceneDeserializeInfoMSFT(_) \ _(type) \ _(next) \ _(fragmentCount) \ _(fragments) \ #define XR_LIST_STRUCT_XrEventDataDisplayRefreshRateChangedFB(_) \ _(type) \ _(next) \ _(fromDisplayRefreshRate) \ _(toDisplayRefreshRate) \ #define XR_LIST_STRUCT_XrViveTrackerPathsHTCX(_) \ _(type) \ _(next) \ _(persistentPath) \ _(rolePath) \ #define XR_LIST_STRUCT_XrEventDataViveTrackerConnectedHTCX(_) \ _(type) \ _(next) \ _(paths) \ #define XR_LIST_STRUCT_XrSystemColorSpacePropertiesFB(_) \ _(type) \ _(next) \ _(colorSpace) \ #define XR_LIST_STRUCT_XrVector4sFB(_) \ _(x) \ _(y) \ _(z) \ _(w) \ #define XR_LIST_STRUCT_XrHandTrackingMeshFB(_) \ _(type) \ _(next) \ _(jointCapacityInput) \ _(jointCountOutput) \ _(jointBindPoses) \ _(jointRadii) \ _(jointParents) \ _(vertexCapacityInput) \ _(vertexCountOutput) \ _(vertexPositions) \ _(vertexNormals) \ _(vertexUVs) \ _(vertexBlendIndices) \ _(vertexBlendWeights) \ _(indexCapacityInput) \ _(indexCountOutput) \ _(indices) \ #define XR_LIST_STRUCT_XrHandTrackingScaleFB(_) \ _(type) \ _(next) \ _(sensorOutput) \ _(currentOutput) \ _(overrideHandScale) \ _(overrideValueInput) \ #define XR_LIST_STRUCT_XrHandTrackingAimStateFB(_) \ _(type) \ _(next) \ _(status) \ _(aimPose) \ _(pinchStrengthIndex) \ _(pinchStrengthMiddle) \ _(pinchStrengthRing) \ _(pinchStrengthLittle) \ #define XR_LIST_STRUCT_XrHandCapsuleFB(_) \ _(points) \ _(radius) \ _(joint) \ #define XR_LIST_STRUCT_XrHandTrackingCapsulesStateFB(_) \ _(type) \ _(next) \ _(capsules) \ #define XR_LIST_STRUCT_XrFoveationProfileCreateInfoFB(_) \ _(type) \ _(next) \ #define XR_LIST_STRUCT_XrSwapchainCreateInfoFoveationFB(_) \ _(type) \ _(next) \ _(flags) \ #define XR_LIST_STRUCT_XrSwapchainStateFoveationFB(_) \ _(type) \ _(next) \ _(flags) \ _(profile) \ #define XR_LIST_STRUCT_XrFoveationLevelProfileCreateInfoFB(_) \ _(type) \ _(next) \ _(level) \ _(verticalOffset) \ _(dynamic) \ #define XR_LIST_STRUCT_XrTriangleMeshCreateInfoFB(_) \ _(type) \ _(next) \ _(flags) \ _(windingOrder) \ _(vertexCount) \ _(vertexBuffer) \ _(triangleCount) \ _(indexBuffer) \ #define XR_LIST_STRUCT_XrSystemPassthroughPropertiesFB(_) \ _(type) \ _(next) \ _(supportsPassthrough) \ #define XR_LIST_STRUCT_XrPassthroughCreateInfoFB(_) \ _(type) \ _(next) \ _(flags) \ #define XR_LIST_STRUCT_XrPassthroughLayerCreateInfoFB(_) \ _(type) \ _(next) \ _(passthrough) \ _(flags) \ _(purpose) \ #define XR_LIST_STRUCT_XrCompositionLayerPassthroughFB(_) \ _(type) \ _(next) \ _(flags) \ _(space) \ _(layerHandle) \ #define XR_LIST_STRUCT_XrGeometryInstanceCreateInfoFB(_) \ _(type) \ _(next) \ _(layer) \ _(mesh) \ _(baseSpace) \ _(pose) \ _(scale) \ #define XR_LIST_STRUCT_XrGeometryInstanceTransformFB(_) \ _(type) \ _(next) \ _(baseSpace) \ _(time) \ _(pose) \ _(scale) \ #define XR_LIST_STRUCT_XrPassthroughStyleFB(_) \ _(type) \ _(next) \ _(textureOpacityFactor) \ _(edgeColor) \ #define XR_LIST_STRUCT_XrPassthroughColorMapMonoToRgbaFB(_) \ _(type) \ _(next) \ _(textureColorMap) \ #define XR_LIST_STRUCT_XrPassthroughColorMapMonoToMonoFB(_) \ _(type) \ _(next) \ _(textureColorMap) \ #define XR_LIST_STRUCT_XrEventDataPassthroughStateChangedFB(_) \ _(type) \ _(next) \ _(flags) \ #define XR_LIST_STRUCT_XrViewLocateFoveatedRenderingVARJO(_) \ _(type) \ _(next) \ _(foveatedRenderingActive) \ #define XR_LIST_STRUCT_XrFoveatedViewConfigurationViewVARJO(_) \ _(type) \ _(next) \ _(foveatedRenderingActive) \ #define XR_LIST_STRUCT_XrSystemFoveatedRenderingPropertiesVARJO(_) \ _(type) \ _(next) \ _(supportsFoveatedRendering) \ #define XR_LIST_STRUCT_XrCompositionLayerDepthTestVARJO(_) \ _(type) \ _(next) \ _(depthTestRangeNearZ) \ _(depthTestRangeFarZ) \ #define XR_LIST_STRUCT_XrSystemMarkerTrackingPropertiesVARJO(_) \ _(type) \ _(next) \ _(supportsMarkerTracking) \ #define XR_LIST_STRUCT_XrEventDataMarkerTrackingUpdateVARJO(_) \ _(type) \ _(next) \ _(markerId) \ _(isActive) \ _(isPredicted) \ _(time) \ #define XR_LIST_STRUCT_XrMarkerSpaceCreateInfoVARJO(_) \ _(type) \ _(next) \ _(markerId) \ _(poseInMarkerSpace) \ #define XR_LIST_STRUCT_XrSpatialAnchorPersistenceNameMSFT(_) \ _(name) \ #define XR_LIST_STRUCT_XrSpatialAnchorPersistenceInfoMSFT(_) \ _(type) \ _(next) \ _(spatialAnchorPersistenceName) \ _(spatialAnchor) \ #define XR_LIST_STRUCT_XrSpatialAnchorFromPersistedAnchorCreateInfoMSFT(_) \ _(type) \ _(next) \ _(spatialAnchorStore) \ _(spatialAnchorPersistenceName) \ #define XR_LIST_STRUCT_XrSwapchainImageFoveationVulkanFB(_) \ _(type) \ _(next) \ _(image) \ _(width) \ _(height) \ #define XR_LIST_STRUCT_XrSwapchainStateAndroidSurfaceDimensionsFB(_) \ _(type) \ _(next) \ _(width) \ _(height) \ #define XR_LIST_STRUCT_XrSwapchainStateSamplerOpenGLESFB(_) \ _(type) \ _(next) \ _(minFilter) \ _(magFilter) \ _(wrapModeS) \ _(wrapModeT) \ _(swizzleRed) \ _(swizzleGreen) \ _(swizzleBlue) \ _(swizzleAlpha) \ _(maxAnisotropy) \ _(borderColor) \ #define XR_LIST_STRUCT_XrSwapchainStateSamplerVulkanFB(_) \ _(type) \ _(next) \ _(minFilter) \ _(magFilter) \ _(mipmapMode) \ _(wrapModeS) \ _(wrapModeT) \ _(swizzleRed) \ _(swizzleGreen) \ _(swizzleBlue) \ _(swizzleAlpha) \ _(maxAnisotropy) \ _(borderColor) \ #define XR_LIST_STRUCT_XrCompositionLayerSpaceWarpInfoFB(_) \ _(type) \ _(next) \ _(layerFlags) \ _(motionVectorSubImage) \ _(appSpaceDeltaPose) \ _(depthSubImage) \ _(minDepth) \ _(maxDepth) \ _(nearZ) \ _(farZ) \ #define XR_LIST_STRUCT_XrSystemSpaceWarpPropertiesFB(_) \ _(type) \ _(next) \ _(recommendedMotionVectorImageRectWidth) \ _(recommendedMotionVectorImageRectHeight) \ #define XR_LIST_STRUCTURE_TYPES_CORE(_) \ _(XrApiLayerProperties, XR_TYPE_API_LAYER_PROPERTIES) \ _(XrExtensionProperties, XR_TYPE_EXTENSION_PROPERTIES) \ _(XrInstanceCreateInfo, XR_TYPE_INSTANCE_CREATE_INFO) \ _(XrInstanceProperties, XR_TYPE_INSTANCE_PROPERTIES) \ _(XrEventDataBuffer, XR_TYPE_EVENT_DATA_BUFFER) \ _(XrSystemGetInfo, XR_TYPE_SYSTEM_GET_INFO) \ _(XrSystemProperties, XR_TYPE_SYSTEM_PROPERTIES) \ _(XrSessionCreateInfo, XR_TYPE_SESSION_CREATE_INFO) \ _(XrSpaceVelocity, XR_TYPE_SPACE_VELOCITY) \ _(XrReferenceSpaceCreateInfo, XR_TYPE_REFERENCE_SPACE_CREATE_INFO) \ _(XrActionSpaceCreateInfo, XR_TYPE_ACTION_SPACE_CREATE_INFO) \ _(XrSpaceLocation, XR_TYPE_SPACE_LOCATION) \ _(XrViewConfigurationProperties, XR_TYPE_VIEW_CONFIGURATION_PROPERTIES) \ _(XrViewConfigurationView, XR_TYPE_VIEW_CONFIGURATION_VIEW) \ _(XrSwapchainCreateInfo, XR_TYPE_SWAPCHAIN_CREATE_INFO) \ _(XrSwapchainImageAcquireInfo, XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO) \ _(XrSwapchainImageWaitInfo, XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO) \ _(XrSwapchainImageReleaseInfo, XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO) \ _(XrSessionBeginInfo, XR_TYPE_SESSION_BEGIN_INFO) \ _(XrFrameWaitInfo, XR_TYPE_FRAME_WAIT_INFO) \ _(XrFrameState, XR_TYPE_FRAME_STATE) \ _(XrFrameBeginInfo, XR_TYPE_FRAME_BEGIN_INFO) \ _(XrFrameEndInfo, XR_TYPE_FRAME_END_INFO) \ _(XrViewLocateInfo, XR_TYPE_VIEW_LOCATE_INFO) \ _(XrViewState, XR_TYPE_VIEW_STATE) \ _(XrView, XR_TYPE_VIEW) \ _(XrActionSetCreateInfo, XR_TYPE_ACTION_SET_CREATE_INFO) \ _(XrActionCreateInfo, XR_TYPE_ACTION_CREATE_INFO) \ _(XrInteractionProfileSuggestedBinding, XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING) \ _(XrSessionActionSetsAttachInfo, XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO) \ _(XrInteractionProfileState, XR_TYPE_INTERACTION_PROFILE_STATE) \ _(XrActionStateGetInfo, XR_TYPE_ACTION_STATE_GET_INFO) \ _(XrActionStateBoolean, XR_TYPE_ACTION_STATE_BOOLEAN) \ _(XrActionStateFloat, XR_TYPE_ACTION_STATE_FLOAT) \ _(XrActionStateVector2f, XR_TYPE_ACTION_STATE_VECTOR2F) \ _(XrActionStatePose, XR_TYPE_ACTION_STATE_POSE) \ _(XrActionsSyncInfo, XR_TYPE_ACTIONS_SYNC_INFO) \ _(XrBoundSourcesForActionEnumerateInfo, XR_TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO) \ _(XrInputSourceLocalizedNameGetInfo, XR_TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO) \ _(XrHapticActionInfo, XR_TYPE_HAPTIC_ACTION_INFO) \ _(XrCompositionLayerProjectionView, XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW) \ _(XrCompositionLayerProjection, XR_TYPE_COMPOSITION_LAYER_PROJECTION) \ _(XrCompositionLayerQuad, XR_TYPE_COMPOSITION_LAYER_QUAD) \ _(XrEventDataEventsLost, XR_TYPE_EVENT_DATA_EVENTS_LOST) \ _(XrEventDataInstanceLossPending, XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING) \ _(XrEventDataSessionStateChanged, XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED) \ _(XrEventDataReferenceSpaceChangePending, XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING) \ _(XrEventDataInteractionProfileChanged, XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED) \ _(XrHapticVibration, XR_TYPE_HAPTIC_VIBRATION) \ _(XrCompositionLayerCubeKHR, XR_TYPE_COMPOSITION_LAYER_CUBE_KHR) \ _(XrCompositionLayerDepthInfoKHR, XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR) \ _(XrCompositionLayerCylinderKHR, XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR) \ _(XrCompositionLayerEquirectKHR, XR_TYPE_COMPOSITION_LAYER_EQUIRECT_KHR) \ _(XrVisibilityMaskKHR, XR_TYPE_VISIBILITY_MASK_KHR) \ _(XrEventDataVisibilityMaskChangedKHR, XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR) \ _(XrCompositionLayerColorScaleBiasKHR, XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR) \ _(XrCompositionLayerEquirect2KHR, XR_TYPE_COMPOSITION_LAYER_EQUIRECT2_KHR) \ _(XrBindingModificationsKHR, XR_TYPE_BINDING_MODIFICATIONS_KHR) \ _(XrEventDataPerfSettingsEXT, XR_TYPE_EVENT_DATA_PERF_SETTINGS_EXT) \ _(XrDebugUtilsObjectNameInfoEXT, XR_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT) \ _(XrDebugUtilsLabelEXT, XR_TYPE_DEBUG_UTILS_LABEL_EXT) \ _(XrDebugUtilsMessengerCallbackDataEXT, XR_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT) \ _(XrDebugUtilsMessengerCreateInfoEXT, XR_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT) \ _(XrSystemEyeGazeInteractionPropertiesEXT, XR_TYPE_SYSTEM_EYE_GAZE_INTERACTION_PROPERTIES_EXT) \ _(XrEyeGazeSampleTimeEXT, XR_TYPE_EYE_GAZE_SAMPLE_TIME_EXT) \ _(XrSessionCreateInfoOverlayEXTX, XR_TYPE_SESSION_CREATE_INFO_OVERLAY_EXTX) \ _(XrEventDataMainSessionVisibilityChangedEXTX, XR_TYPE_EVENT_DATA_MAIN_SESSION_VISIBILITY_CHANGED_EXTX) \ _(XrSpatialAnchorCreateInfoMSFT, XR_TYPE_SPATIAL_ANCHOR_CREATE_INFO_MSFT) \ _(XrSpatialAnchorSpaceCreateInfoMSFT, XR_TYPE_SPATIAL_ANCHOR_SPACE_CREATE_INFO_MSFT) \ _(XrCompositionLayerImageLayoutFB, XR_TYPE_COMPOSITION_LAYER_IMAGE_LAYOUT_FB) \ _(XrCompositionLayerAlphaBlendFB, XR_TYPE_COMPOSITION_LAYER_ALPHA_BLEND_FB) \ _(XrViewConfigurationDepthRangeEXT, XR_TYPE_VIEW_CONFIGURATION_DEPTH_RANGE_EXT) \ _(XrSpatialGraphNodeSpaceCreateInfoMSFT, XR_TYPE_SPATIAL_GRAPH_NODE_SPACE_CREATE_INFO_MSFT) \ _(XrSystemHandTrackingPropertiesEXT, XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT) \ _(XrHandTrackerCreateInfoEXT, XR_TYPE_HAND_TRACKER_CREATE_INFO_EXT) \ _(XrHandJointsLocateInfoEXT, XR_TYPE_HAND_JOINTS_LOCATE_INFO_EXT) \ _(XrHandJointLocationsEXT, XR_TYPE_HAND_JOINT_LOCATIONS_EXT) \ _(XrHandJointVelocitiesEXT, XR_TYPE_HAND_JOINT_VELOCITIES_EXT) \ _(XrSystemHandTrackingMeshPropertiesMSFT, XR_TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT) \ _(XrHandMeshSpaceCreateInfoMSFT, XR_TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT) \ _(XrHandMeshUpdateInfoMSFT, XR_TYPE_HAND_MESH_UPDATE_INFO_MSFT) \ _(XrHandMeshMSFT, XR_TYPE_HAND_MESH_MSFT) \ _(XrHandPoseTypeInfoMSFT, XR_TYPE_HAND_POSE_TYPE_INFO_MSFT) \ _(XrSecondaryViewConfigurationSessionBeginInfoMSFT, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_SESSION_BEGIN_INFO_MSFT) \ _(XrSecondaryViewConfigurationStateMSFT, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_STATE_MSFT) \ _(XrSecondaryViewConfigurationFrameStateMSFT, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_FRAME_STATE_MSFT) \ _(XrSecondaryViewConfigurationLayerInfoMSFT, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_LAYER_INFO_MSFT) \ _(XrSecondaryViewConfigurationFrameEndInfoMSFT, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_FRAME_END_INFO_MSFT) \ _(XrSecondaryViewConfigurationSwapchainCreateInfoMSFT, XR_TYPE_SECONDARY_VIEW_CONFIGURATION_SWAPCHAIN_CREATE_INFO_MSFT) \ _(XrControllerModelKeyStateMSFT, XR_TYPE_CONTROLLER_MODEL_KEY_STATE_MSFT) \ _(XrControllerModelNodePropertiesMSFT, XR_TYPE_CONTROLLER_MODEL_NODE_PROPERTIES_MSFT) \ _(XrControllerModelPropertiesMSFT, XR_TYPE_CONTROLLER_MODEL_PROPERTIES_MSFT) \ _(XrControllerModelNodeStateMSFT, XR_TYPE_CONTROLLER_MODEL_NODE_STATE_MSFT) \ _(XrControllerModelStateMSFT, XR_TYPE_CONTROLLER_MODEL_STATE_MSFT) \ _(XrViewConfigurationViewFovEPIC, XR_TYPE_VIEW_CONFIGURATION_VIEW_FOV_EPIC) \ _(XrCompositionLayerReprojectionInfoMSFT, XR_TYPE_COMPOSITION_LAYER_REPROJECTION_INFO_MSFT) \ _(XrCompositionLayerReprojectionPlaneOverrideMSFT, XR_TYPE_COMPOSITION_LAYER_REPROJECTION_PLANE_OVERRIDE_MSFT) \ _(XrCompositionLayerSecureContentFB, XR_TYPE_COMPOSITION_LAYER_SECURE_CONTENT_FB) \ _(XrInteractionProfileAnalogThresholdVALVE, XR_TYPE_INTERACTION_PROFILE_ANALOG_THRESHOLD_VALVE) \ _(XrHandJointsMotionRangeInfoEXT, XR_TYPE_HAND_JOINTS_MOTION_RANGE_INFO_EXT) \ _(XrSceneObserverCreateInfoMSFT, XR_TYPE_SCENE_OBSERVER_CREATE_INFO_MSFT) \ _(XrSceneCreateInfoMSFT, XR_TYPE_SCENE_CREATE_INFO_MSFT) \ _(XrNewSceneComputeInfoMSFT, XR_TYPE_NEW_SCENE_COMPUTE_INFO_MSFT) \ _(XrVisualMeshComputeLodInfoMSFT, XR_TYPE_VISUAL_MESH_COMPUTE_LOD_INFO_MSFT) \ _(XrSceneComponentsMSFT, XR_TYPE_SCENE_COMPONENTS_MSFT) \ _(XrSceneComponentsGetInfoMSFT, XR_TYPE_SCENE_COMPONENTS_GET_INFO_MSFT) \ _(XrSceneComponentLocationsMSFT, XR_TYPE_SCENE_COMPONENT_LOCATIONS_MSFT) \ _(XrSceneComponentsLocateInfoMSFT, XR_TYPE_SCENE_COMPONENTS_LOCATE_INFO_MSFT) \ _(XrSceneObjectsMSFT, XR_TYPE_SCENE_OBJECTS_MSFT) \ _(XrSceneComponentParentFilterInfoMSFT, XR_TYPE_SCENE_COMPONENT_PARENT_FILTER_INFO_MSFT) \ _(XrSceneObjectTypesFilterInfoMSFT, XR_TYPE_SCENE_OBJECT_TYPES_FILTER_INFO_MSFT) \ _(XrScenePlanesMSFT, XR_TYPE_SCENE_PLANES_MSFT) \ _(XrScenePlaneAlignmentFilterInfoMSFT, XR_TYPE_SCENE_PLANE_ALIGNMENT_FILTER_INFO_MSFT) \ _(XrSceneMeshesMSFT, XR_TYPE_SCENE_MESHES_MSFT) \ _(XrSceneMeshBuffersGetInfoMSFT, XR_TYPE_SCENE_MESH_BUFFERS_GET_INFO_MSFT) \ _(XrSceneMeshBuffersMSFT, XR_TYPE_SCENE_MESH_BUFFERS_MSFT) \ _(XrSceneMeshVertexBufferMSFT, XR_TYPE_SCENE_MESH_VERTEX_BUFFER_MSFT) \ _(XrSceneMeshIndicesUint32MSFT, XR_TYPE_SCENE_MESH_INDICES_UINT32_MSFT) \ _(XrSceneMeshIndicesUint16MSFT, XR_TYPE_SCENE_MESH_INDICES_UINT16_MSFT) \ _(XrSerializedSceneFragmentDataGetInfoMSFT, XR_TYPE_SERIALIZED_SCENE_FRAGMENT_DATA_GET_INFO_MSFT) \ _(XrSceneDeserializeInfoMSFT, XR_TYPE_SCENE_DESERIALIZE_INFO_MSFT) \ _(XrEventDataDisplayRefreshRateChangedFB, XR_TYPE_EVENT_DATA_DISPLAY_REFRESH_RATE_CHANGED_FB) \ _(XrViveTrackerPathsHTCX, XR_TYPE_VIVE_TRACKER_PATHS_HTCX) \ _(XrEventDataViveTrackerConnectedHTCX, XR_TYPE_EVENT_DATA_VIVE_TRACKER_CONNECTED_HTCX) \ _(XrSystemColorSpacePropertiesFB, XR_TYPE_SYSTEM_COLOR_SPACE_PROPERTIES_FB) \ _(XrHandTrackingMeshFB, XR_TYPE_HAND_TRACKING_MESH_FB) \ _(XrHandTrackingScaleFB, XR_TYPE_HAND_TRACKING_SCALE_FB) \ _(XrHandTrackingAimStateFB, XR_TYPE_HAND_TRACKING_AIM_STATE_FB) \ _(XrHandTrackingCapsulesStateFB, XR_TYPE_HAND_TRACKING_CAPSULES_STATE_FB) \ _(XrFoveationProfileCreateInfoFB, XR_TYPE_FOVEATION_PROFILE_CREATE_INFO_FB) \ _(XrSwapchainCreateInfoFoveationFB, XR_TYPE_SWAPCHAIN_CREATE_INFO_FOVEATION_FB) \ _(XrSwapchainStateFoveationFB, XR_TYPE_SWAPCHAIN_STATE_FOVEATION_FB) \ _(XrFoveationLevelProfileCreateInfoFB, XR_TYPE_FOVEATION_LEVEL_PROFILE_CREATE_INFO_FB) \ _(XrTriangleMeshCreateInfoFB, XR_TYPE_TRIANGLE_MESH_CREATE_INFO_FB) \ _(XrSystemPassthroughPropertiesFB, XR_TYPE_SYSTEM_PASSTHROUGH_PROPERTIES_FB) \ _(XrPassthroughCreateInfoFB, XR_TYPE_PASSTHROUGH_CREATE_INFO_FB) \ _(XrPassthroughLayerCreateInfoFB, XR_TYPE_PASSTHROUGH_LAYER_CREATE_INFO_FB) \ _(XrCompositionLayerPassthroughFB, XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_FB) \ _(XrGeometryInstanceCreateInfoFB, XR_TYPE_GEOMETRY_INSTANCE_CREATE_INFO_FB) \ _(XrGeometryInstanceTransformFB, XR_TYPE_GEOMETRY_INSTANCE_TRANSFORM_FB) \ _(XrPassthroughStyleFB, XR_TYPE_PASSTHROUGH_STYLE_FB) \ _(XrPassthroughColorMapMonoToRgbaFB, XR_TYPE_PASSTHROUGH_COLOR_MAP_MONO_TO_RGBA_FB) \ _(XrPassthroughColorMapMonoToMonoFB, XR_TYPE_PASSTHROUGH_COLOR_MAP_MONO_TO_MONO_FB) \ _(XrEventDataPassthroughStateChangedFB, XR_TYPE_EVENT_DATA_PASSTHROUGH_STATE_CHANGED_FB) \ _(XrViewLocateFoveatedRenderingVARJO, XR_TYPE_VIEW_LOCATE_FOVEATED_RENDERING_VARJO) \ _(XrFoveatedViewConfigurationViewVARJO, XR_TYPE_FOVEATED_VIEW_CONFIGURATION_VIEW_VARJO) \ _(XrSystemFoveatedRenderingPropertiesVARJO, XR_TYPE_SYSTEM_FOVEATED_RENDERING_PROPERTIES_VARJO) \ _(XrCompositionLayerDepthTestVARJO, XR_TYPE_COMPOSITION_LAYER_DEPTH_TEST_VARJO) \ _(XrSystemMarkerTrackingPropertiesVARJO, XR_TYPE_SYSTEM_MARKER_TRACKING_PROPERTIES_VARJO) \ _(XrEventDataMarkerTrackingUpdateVARJO, XR_TYPE_EVENT_DATA_MARKER_TRACKING_UPDATE_VARJO) \ _(XrMarkerSpaceCreateInfoVARJO, XR_TYPE_MARKER_SPACE_CREATE_INFO_VARJO) \ _(XrSpatialAnchorPersistenceInfoMSFT, XR_TYPE_SPATIAL_ANCHOR_PERSISTENCE_INFO_MSFT) \ _(XrSpatialAnchorFromPersistedAnchorCreateInfoMSFT, XR_TYPE_SPATIAL_ANCHOR_FROM_PERSISTED_ANCHOR_CREATE_INFO_MSFT) \ _(XrCompositionLayerSpaceWarpInfoFB, XR_TYPE_COMPOSITION_LAYER_SPACE_WARP_INFO_FB) \ _(XrSystemSpaceWarpPropertiesFB, XR_TYPE_SYSTEM_SPACE_WARP_PROPERTIES_FB) \ #if defined(XR_USE_GRAPHICS_API_D3D11) #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_D3D11(_) \ _(XrGraphicsBindingD3D11KHR, XR_TYPE_GRAPHICS_BINDING_D3D11_KHR) \ _(XrSwapchainImageD3D11KHR, XR_TYPE_SWAPCHAIN_IMAGE_D3D11_KHR) \ _(XrGraphicsRequirementsD3D11KHR, XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_D3D11(_) #endif #if defined(XR_USE_GRAPHICS_API_D3D12) #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_D3D12(_) \ _(XrGraphicsBindingD3D12KHR, XR_TYPE_GRAPHICS_BINDING_D3D12_KHR) \ _(XrSwapchainImageD3D12KHR, XR_TYPE_SWAPCHAIN_IMAGE_D3D12_KHR) \ _(XrGraphicsRequirementsD3D12KHR, XR_TYPE_GRAPHICS_REQUIREMENTS_D3D12_KHR) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_D3D12(_) #endif #if defined(XR_USE_GRAPHICS_API_OPENGL) #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL(_) \ _(XrSwapchainImageOpenGLKHR, XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR) \ _(XrGraphicsRequirementsOpenGLKHR, XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL(_) #endif #if defined(XR_USE_GRAPHICS_API_OPENGL) && defined(XR_USE_PLATFORM_WAYLAND) #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_WAYLAND(_) \ _(XrGraphicsBindingOpenGLWaylandKHR, XR_TYPE_GRAPHICS_BINDING_OPENGL_WAYLAND_KHR) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_WAYLAND(_) #endif #if defined(XR_USE_GRAPHICS_API_OPENGL) && defined(XR_USE_PLATFORM_WIN32) #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_WIN32(_) \ _(XrGraphicsBindingOpenGLWin32KHR, XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_WIN32(_) #endif #if defined(XR_USE_GRAPHICS_API_OPENGL) && defined(XR_USE_PLATFORM_XCB) #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_XCB(_) \ _(XrGraphicsBindingOpenGLXcbKHR, XR_TYPE_GRAPHICS_BINDING_OPENGL_XCB_KHR) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_XCB(_) #endif #if defined(XR_USE_GRAPHICS_API_OPENGL) && defined(XR_USE_PLATFORM_XLIB) #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_XLIB(_) \ _(XrGraphicsBindingOpenGLXlibKHR, XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_XLIB(_) #endif #if defined(XR_USE_GRAPHICS_API_OPENGL_ES) #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_ES(_) \ _(XrSwapchainImageOpenGLESKHR, XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR) \ _(XrGraphicsRequirementsOpenGLESKHR, XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR) \ _(XrSwapchainStateSamplerOpenGLESFB, XR_TYPE_SWAPCHAIN_STATE_SAMPLER_OPENGL_ES_FB) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_ES(_) #endif #if defined(XR_USE_GRAPHICS_API_OPENGL_ES) && defined(XR_USE_PLATFORM_ANDROID) #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_ES_XR_USE_PLATFORM_ANDROID(_) \ _(XrGraphicsBindingOpenGLESAndroidKHR, XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_ES_XR_USE_PLATFORM_ANDROID(_) #endif #if defined(XR_USE_GRAPHICS_API_VULKAN) #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_VULKAN(_) \ _(XrVulkanSwapchainFormatListCreateInfoKHR, XR_TYPE_VULKAN_SWAPCHAIN_FORMAT_LIST_CREATE_INFO_KHR) \ _(XrGraphicsBindingVulkanKHR, XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR) \ _(XrSwapchainImageVulkanKHR, XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR) \ _(XrGraphicsRequirementsVulkanKHR, XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR) \ _(XrVulkanInstanceCreateInfoKHR, XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR) \ _(XrVulkanDeviceCreateInfoKHR, XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR) \ _(XrVulkanGraphicsDeviceGetInfoKHR, XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR) \ _(XrSwapchainImageFoveationVulkanFB, XR_TYPE_SWAPCHAIN_IMAGE_FOVEATION_VULKAN_FB) \ _(XrSwapchainStateSamplerVulkanFB, XR_TYPE_SWAPCHAIN_STATE_SAMPLER_VULKAN_FB) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_VULKAN(_) #endif #if defined(XR_USE_PLATFORM_ANDROID) #define XR_LIST_STRUCTURE_TYPES_XR_USE_PLATFORM_ANDROID(_) \ _(XrInstanceCreateInfoAndroidKHR, XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR) \ _(XrLoaderInitInfoAndroidKHR, XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR) \ _(XrAndroidSurfaceSwapchainCreateInfoFB, XR_TYPE_ANDROID_SURFACE_SWAPCHAIN_CREATE_INFO_FB) \ _(XrSwapchainStateAndroidSurfaceDimensionsFB, XR_TYPE_SWAPCHAIN_STATE_ANDROID_SURFACE_DIMENSIONS_FB) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_PLATFORM_ANDROID(_) #endif #if defined(XR_USE_PLATFORM_EGL) #define XR_LIST_STRUCTURE_TYPES_XR_USE_PLATFORM_EGL(_) \ _(XrGraphicsBindingEGLMNDX, XR_TYPE_GRAPHICS_BINDING_EGL_MNDX) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_PLATFORM_EGL(_) #endif #if defined(XR_USE_PLATFORM_WIN32) #define XR_LIST_STRUCTURE_TYPES_XR_USE_PLATFORM_WIN32(_) \ _(XrHolographicWindowAttachmentMSFT, XR_TYPE_HOLOGRAPHIC_WINDOW_ATTACHMENT_MSFT) \ #else #define XR_LIST_STRUCTURE_TYPES_XR_USE_PLATFORM_WIN32(_) #endif #define XR_LIST_STRUCTURE_TYPES(_) \ XR_LIST_STRUCTURE_TYPES_CORE(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_D3D11(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_D3D12(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_WAYLAND(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_WIN32(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_XCB(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_XR_USE_PLATFORM_XLIB(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_ES(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_OPENGL_ES_XR_USE_PLATFORM_ANDROID(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_GRAPHICS_API_VULKAN(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_PLATFORM_ANDROID(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_PLATFORM_EGL(_) \ XR_LIST_STRUCTURE_TYPES_XR_USE_PLATFORM_WIN32(_) \ #define XR_LIST_EXTENSIONS(_) \ _(XR_KHR_android_thread_settings, 4) \ _(XR_KHR_android_surface_swapchain, 5) \ _(XR_KHR_composition_layer_cube, 7) \ _(XR_KHR_android_create_instance, 9) \ _(XR_KHR_composition_layer_depth, 11) \ _(XR_KHR_vulkan_swapchain_format_list, 15) \ _(XR_EXT_performance_settings, 16) \ _(XR_EXT_thermal_query, 17) \ _(XR_KHR_composition_layer_cylinder, 18) \ _(XR_KHR_composition_layer_equirect, 19) \ _(XR_EXT_debug_utils, 20) \ _(XR_KHR_opengl_enable, 24) \ _(XR_KHR_opengl_es_enable, 25) \ _(XR_KHR_vulkan_enable, 26) \ _(XR_KHR_D3D11_enable, 28) \ _(XR_KHR_D3D12_enable, 29) \ _(XR_EXT_eye_gaze_interaction, 31) \ _(XR_KHR_visibility_mask, 32) \ _(XR_EXTX_overlay, 34) \ _(XR_KHR_composition_layer_color_scale_bias, 35) \ _(XR_KHR_win32_convert_performance_counter_time, 36) \ _(XR_KHR_convert_timespec_time, 37) \ _(XR_VARJO_quad_views, 38) \ _(XR_MSFT_unbounded_reference_space, 39) \ _(XR_MSFT_spatial_anchor, 40) \ _(XR_FB_composition_layer_image_layout, 41) \ _(XR_FB_composition_layer_alpha_blend, 42) \ _(XR_MND_headless, 43) \ _(XR_OCULUS_android_session_state_enable, 45) \ _(XR_EXT_view_configuration_depth_range, 47) \ _(XR_EXT_conformance_automation, 48) \ _(XR_MNDX_egl_enable, 49) \ _(XR_MSFT_spatial_graph_bridge, 50) \ _(XR_MSFT_hand_interaction, 51) \ _(XR_EXT_hand_tracking, 52) \ _(XR_MSFT_hand_tracking_mesh, 53) \ _(XR_MSFT_secondary_view_configuration, 54) \ _(XR_MSFT_first_person_observer, 55) \ _(XR_MSFT_controller_model, 56) \ _(XR_MSFT_perception_anchor_interop, 57) \ _(XR_EXT_win32_appcontainer_compatible, 58) \ _(XR_EPIC_view_configuration_fov, 60) \ _(XR_MSFT_holographic_window_attachment, 64) \ _(XR_MSFT_composition_layer_reprojection, 67) \ _(XR_HUAWEI_controller_interaction, 70) \ _(XR_FB_android_surface_swapchain_create, 71) \ _(XR_FB_swapchain_update_state, 72) \ _(XR_FB_composition_layer_secure_content, 73) \ _(XR_VALVE_analog_threshold, 80) \ _(XR_EXT_hand_joints_motion_range, 81) \ _(XR_KHR_loader_init, 89) \ _(XR_KHR_loader_init_android, 90) \ _(XR_KHR_vulkan_enable2, 91) \ _(XR_KHR_composition_layer_equirect2, 92) \ _(XR_EXT_samsung_odyssey_controller, 95) \ _(XR_EXT_hp_mixed_reality_controller, 96) \ _(XR_MND_swapchain_usage_input_attachment_bit, 97) \ _(XR_MSFT_scene_understanding, 98) \ _(XR_MSFT_scene_understanding_serialization, 99) \ _(XR_FB_display_refresh_rate, 102) \ _(XR_HTC_vive_cosmos_controller_interaction, 103) \ _(XR_HTCX_vive_tracker_interaction, 104) \ _(XR_FB_color_space, 109) \ _(XR_FB_hand_tracking_mesh, 111) \ _(XR_FB_hand_tracking_aim, 112) \ _(XR_FB_hand_tracking_capsules, 113) \ _(XR_FB_foveation, 115) \ _(XR_FB_foveation_configuration, 116) \ _(XR_FB_triangle_mesh, 118) \ _(XR_FB_passthrough, 119) \ _(XR_KHR_binding_modification, 121) \ _(XR_VARJO_foveated_rendering, 122) \ _(XR_VARJO_composition_layer_depth_test, 123) \ _(XR_VARJO_environment_depth_estimation, 124) \ _(XR_VARJO_marker_tracking, 125) \ _(XR_MSFT_spatial_anchor_persistence, 143) \ _(XR_OCULUS_audio_device_guid, 160) \ _(XR_FB_foveation_vulkan, 161) \ _(XR_FB_swapchain_update_state_android_surface, 162) \ _(XR_FB_swapchain_update_state_opengl_es, 163) \ _(XR_FB_swapchain_update_state_vulkan, 164) \ _(XR_KHR_swapchain_usage_input_attachment_bit, 166) \ _(XR_FB_space_warp, 172) \ #endif
85,550
C
32.575746
125
0.66623
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/openxr/include/openxr/xr_dependencies.h
// Copyright (c) 2018-2022, The Khronos Group Inc. // // SPDX-License-Identifier: Apache-2.0 OR MIT // // This file includes headers with types which openxr.h depends on in order // to compile when platforms, graphics apis, and the like are enabled. #pragma once #ifdef XR_USE_PLATFORM_ANDROID #include <android/native_window.h> #include <android/window.h> #include <android/native_window_jni.h> #endif // XR_USE_PLATFORM_ANDROID #ifdef XR_USE_PLATFORM_WIN32 #include <winapifamily.h> #if !(WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)) // Enable desktop partition APIs, such as RegOpenKeyEx, LoadLibraryEx, PathFileExists etc. #undef WINAPI_PARTITION_DESKTOP #define WINAPI_PARTITION_DESKTOP 1 #endif #ifndef NOMINMAX #define NOMINMAX #endif // !NOMINMAX #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif // !WIN32_LEAN_AND_MEAN #include <windows.h> #include <unknwn.h> #endif // XR_USE_PLATFORM_WIN32 #ifdef XR_USE_GRAPHICS_API_D3D11 #include <d3d11.h> #endif // XR_USE_GRAPHICS_API_D3D11 #ifdef XR_USE_GRAPHICS_API_D3D12 #include <d3d12.h> #endif // XR_USE_GRAPHICS_API_D3D12 #ifdef XR_USE_PLATFORM_XLIB #include <X11/Xlib.h> #include <X11/Xutil.h> #ifdef Success #undef Success #endif // Success #ifdef Always #undef Always #endif // Always #ifdef None #undef None #endif // None #endif // XR_USE_PLATFORM_XLIB #ifdef XR_USE_PLATFORM_XCB #include <xcb/xcb.h> #endif // XR_USE_PLATFORM_XCB #ifdef XR_USE_GRAPHICS_API_OPENGL #if defined(XR_USE_PLATFORM_XLIB) || defined(XR_USE_PLATFORM_XCB) #include <GL/glx.h> #endif // (XR_USE_PLATFORM_XLIB || XR_USE_PLATFORM_XCB) #ifdef XR_USE_PLATFORM_XCB #include <xcb/glx.h> #endif // XR_USE_PLATFORM_XCB #ifdef XR_USE_PLATFORM_MACOS #include <CL/cl_gl_ext.h> #endif // XR_USE_PLATFORM_MACOS #endif // XR_USE_GRAPHICS_API_OPENGL #ifdef XR_USE_GRAPHICS_API_OPENGL_ES #include <EGL/egl.h> #endif // XR_USE_GRAPHICS_API_OPENGL_ES #ifdef XR_USE_GRAPHICS_API_VULKAN #include <vulkan/vulkan.h> #endif // XR_USE_GRAPHICS_API_VULKAN #ifdef XR_USE_PLATFORM_WAYLAND #include "wayland-client.h" #endif // XR_USE_PLATFORM_WAYLAND
2,141
C
22.8
90
0.733769
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/iostream.h
/* pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python Copyright (c) 2017 Henry F. Schreiner All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. WARNING: The implementation in this file is NOT thread safe. Multiple threads writing to a redirected ostream concurrently cause data races and potentially buffer overflows. Therefore it is currently a requirement that all (possibly) concurrent redirected ostream writes are protected by a mutex. #HelpAppreciated: Work on iostream.h thread safety. For more background see the discussions under https://github.com/pybind/pybind11/pull/2982 and https://github.com/pybind/pybind11/pull/2995. */ #pragma once #include "pybind11.h" #include <algorithm> #include <cstring> #include <iostream> #include <iterator> #include <memory> #include <ostream> #include <streambuf> #include <string> #include <utility> PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) // Buffer that writes to Python instead of C++ class pythonbuf : public std::streambuf { private: using traits_type = std::streambuf::traits_type; const size_t buf_size; std::unique_ptr<char[]> d_buffer; object pywrite; object pyflush; int overflow(int c) override { if (!traits_type::eq_int_type(c, traits_type::eof())) { *pptr() = traits_type::to_char_type(c); pbump(1); } return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof(); } // Computes how many bytes at the end of the buffer are part of an // incomplete sequence of UTF-8 bytes. // Precondition: pbase() < pptr() size_t utf8_remainder() const { const auto rbase = std::reverse_iterator<char *>(pbase()); const auto rpptr = std::reverse_iterator<char *>(pptr()); auto is_ascii = [](char c) { return (static_cast<unsigned char>(c) & 0x80) == 0x00; }; auto is_leading = [](char c) { return (static_cast<unsigned char>(c) & 0xC0) == 0xC0; }; auto is_leading_2b = [](char c) { return static_cast<unsigned char>(c) <= 0xDF; }; auto is_leading_3b = [](char c) { return static_cast<unsigned char>(c) <= 0xEF; }; // If the last character is ASCII, there are no incomplete code points if (is_ascii(*rpptr)) return 0; // Otherwise, work back from the end of the buffer and find the first // UTF-8 leading byte const auto rpend = rbase - rpptr >= 3 ? rpptr + 3 : rbase; const auto leading = std::find_if(rpptr, rpend, is_leading); if (leading == rbase) return 0; const auto dist = static_cast<size_t>(leading - rpptr); size_t remainder = 0; if (dist == 0) remainder = 1; // 1-byte code point is impossible else if (dist == 1) remainder = is_leading_2b(*leading) ? 0 : dist + 1; else if (dist == 2) remainder = is_leading_3b(*leading) ? 0 : dist + 1; // else if (dist >= 3), at least 4 bytes before encountering an UTF-8 // leading byte, either no remainder or invalid UTF-8. // Invalid UTF-8 will cause an exception later when converting // to a Python string, so that's not handled here. return remainder; } // This function must be non-virtual to be called in a destructor. int _sync() { if (pbase() != pptr()) { // If buffer is not empty gil_scoped_acquire tmp; // This subtraction cannot be negative, so dropping the sign. auto size = static_cast<size_t>(pptr() - pbase()); size_t remainder = utf8_remainder(); if (size > remainder) { str line(pbase(), size - remainder); pywrite(line); pyflush(); } // Copy the remainder at the end of the buffer to the beginning: if (remainder > 0) std::memmove(pbase(), pptr() - remainder, remainder); setp(pbase(), epptr()); pbump(static_cast<int>(remainder)); } return 0; } int sync() override { return _sync(); } public: explicit pythonbuf(const object &pyostream, size_t buffer_size = 1024) : buf_size(buffer_size), d_buffer(new char[buf_size]), pywrite(pyostream.attr("write")), pyflush(pyostream.attr("flush")) { setp(d_buffer.get(), d_buffer.get() + buf_size - 1); } pythonbuf(pythonbuf&&) = default; /// Sync before destroy ~pythonbuf() override { _sync(); } }; PYBIND11_NAMESPACE_END(detail) /** \rst This a move-only guard that redirects output. .. code-block:: cpp #include <pybind11/iostream.h> ... { py::scoped_ostream_redirect output; std::cout << "Hello, World!"; // Python stdout } // <-- return std::cout to normal You can explicitly pass the c++ stream and the python object, for example to guard stderr instead. .. code-block:: cpp { py::scoped_ostream_redirect output{std::cerr, py::module::import("sys").attr("stderr")}; std::cout << "Hello, World!"; } \endrst */ class scoped_ostream_redirect { protected: std::streambuf *old; std::ostream &costream; detail::pythonbuf buffer; public: explicit scoped_ostream_redirect(std::ostream &costream = std::cout, const object &pyostream = module_::import("sys").attr("stdout")) : costream(costream), buffer(pyostream) { old = costream.rdbuf(&buffer); } ~scoped_ostream_redirect() { costream.rdbuf(old); } scoped_ostream_redirect(const scoped_ostream_redirect &) = delete; scoped_ostream_redirect(scoped_ostream_redirect &&other) = default; scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete; scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete; }; /** \rst Like `scoped_ostream_redirect`, but redirects cerr by default. This class is provided primary to make ``py::call_guard`` easier to make. .. code-block:: cpp m.def("noisy_func", &noisy_func, py::call_guard<scoped_ostream_redirect, scoped_estream_redirect>()); \endrst */ class scoped_estream_redirect : public scoped_ostream_redirect { public: explicit scoped_estream_redirect(std::ostream &costream = std::cerr, const object &pyostream = module_::import("sys").attr("stderr")) : scoped_ostream_redirect(costream, pyostream) {} }; PYBIND11_NAMESPACE_BEGIN(detail) // Class to redirect output as a context manager. C++ backend. class OstreamRedirect { bool do_stdout_; bool do_stderr_; std::unique_ptr<scoped_ostream_redirect> redirect_stdout; std::unique_ptr<scoped_estream_redirect> redirect_stderr; public: explicit OstreamRedirect(bool do_stdout = true, bool do_stderr = true) : do_stdout_(do_stdout), do_stderr_(do_stderr) {} void enter() { if (do_stdout_) redirect_stdout.reset(new scoped_ostream_redirect()); if (do_stderr_) redirect_stderr.reset(new scoped_estream_redirect()); } void exit() { redirect_stdout.reset(); redirect_stderr.reset(); } }; PYBIND11_NAMESPACE_END(detail) /** \rst This is a helper function to add a C++ redirect context manager to Python instead of using a C++ guard. To use it, add the following to your binding code: .. code-block:: cpp #include <pybind11/iostream.h> ... py::add_ostream_redirect(m, "ostream_redirect"); You now have a Python context manager that redirects your output: .. code-block:: python with m.ostream_redirect(): m.print_to_cout_function() This manager can optionally be told which streams to operate on: .. code-block:: python with m.ostream_redirect(stdout=true, stderr=true): m.noisy_function_with_error_printing() \endrst */ inline class_<detail::OstreamRedirect> add_ostream_redirect(module_ m, const std::string &name = "ostream_redirect") { return class_<detail::OstreamRedirect>(std::move(m), name.c_str(), module_local()) .def(init<bool, bool>(), arg("stdout") = true, arg("stderr") = true) .def("__enter__", &detail::OstreamRedirect::enter) .def("__exit__", [](detail::OstreamRedirect &self_, const args &) { self_.exit(); }); } PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
8,882
C
31.184782
100
0.60313
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/pybind11.h
/* pybind11/pybind11.h: Main header file of the C++11 python binding generator library Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "attr.h" #include "gil.h" #include "options.h" #include "detail/class.h" #include "detail/init.h" #include <memory> #include <new> #include <vector> #include <string> #include <utility> #include <string.h> #if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914)) # define PYBIND11_STD_LAUNDER std::launder # define PYBIND11_HAS_STD_LAUNDER 1 #else # define PYBIND11_STD_LAUNDER # define PYBIND11_HAS_STD_LAUNDER 0 #endif #if defined(__GNUG__) && !defined(__clang__) # include <cxxabi.h> #endif /* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning This warning is about ABI compatibility, not code health. It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore it could get triggered from seemingly random places, depending on user code. No other GCC version generates this warning. */ #if defined(__GNUC__) && __GNUC__ == 7 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wnoexcept-type" #endif PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) // Apply all the extensions translators from a list // Return true if one of the translators completed without raising an exception // itself. Return of false indicates that if there are other translators // available, they should be tried. inline bool apply_exception_translators(std::forward_list<ExceptionTranslator>& translators) { auto last_exception = std::current_exception(); for (auto &translator : translators) { try { translator(last_exception); return true; } catch (...) { last_exception = std::current_exception(); } } return false; } #if defined(_MSC_VER) # define PYBIND11_COMPAT_STRDUP _strdup #else # define PYBIND11_COMPAT_STRDUP strdup #endif PYBIND11_NAMESPACE_END(detail) /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object class cpp_function : public function { public: cpp_function() = default; // NOLINTNEXTLINE(google-explicit-constructor) cpp_function(std::nullptr_t) { } /// Construct a cpp_function from a vanilla function pointer template <typename Return, typename... Args, typename... Extra> // NOLINTNEXTLINE(google-explicit-constructor) cpp_function(Return (*f)(Args...), const Extra&... extra) { initialize(f, f, extra...); } /// Construct a cpp_function from a lambda function (possibly with internal state) template <typename Func, typename... Extra, typename = detail::enable_if_t<detail::is_lambda<Func>::value>> // NOLINTNEXTLINE(google-explicit-constructor) cpp_function(Func &&f, const Extra&... extra) { initialize(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...); } /// Construct a cpp_function from a class method (non-const, no ref-qualifier) template <typename Return, typename Class, typename... Arg, typename... Extra> // NOLINTNEXTLINE(google-explicit-constructor) cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) { initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); }, (Return (*) (Class *, Arg...)) nullptr, extra...); } /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier) /// A copy of the overload for non-const functions without explicit ref-qualifier /// but with an added `&`. template <typename Return, typename Class, typename... Arg, typename... Extra> // NOLINTNEXTLINE(google-explicit-constructor) cpp_function(Return (Class::*f)(Arg...)&, const Extra&... extra) { initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); }, (Return (*) (Class *, Arg...)) nullptr, extra...); } /// Construct a cpp_function from a class method (const, no ref-qualifier) template <typename Return, typename Class, typename... Arg, typename... Extra> // NOLINTNEXTLINE(google-explicit-constructor) cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) { initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); }, (Return (*)(const Class *, Arg ...)) nullptr, extra...); } /// Construct a cpp_function from a class method (const, lvalue ref-qualifier) /// A copy of the overload for const functions without explicit ref-qualifier /// but with an added `&`. template <typename Return, typename Class, typename... Arg, typename... Extra> // NOLINTNEXTLINE(google-explicit-constructor) cpp_function(Return (Class::*f)(Arg...) const&, const Extra&... extra) { initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); }, (Return (*)(const Class *, Arg ...)) nullptr, extra...); } /// Return the function name object name() const { return attr("__name__"); } protected: struct InitializingFunctionRecordDeleter { // `destruct(function_record, false)`: `initialize_generic` copies strings and // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`. void operator()(detail::function_record * rec) { destruct(rec, false); } }; using unique_function_record = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>; /// Space optimization: don't inline this frequently instantiated fragment PYBIND11_NOINLINE unique_function_record make_function_record() { return unique_function_record(new detail::function_record()); } /// Special internal constructor for functors, lambda functions, etc. template <typename Func, typename Return, typename... Args, typename... Extra> void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) { using namespace detail; struct capture { remove_reference_t<Func> f; }; /* Store the function including any extra state it might have (e.g. a lambda capture object) */ // The unique_ptr makes sure nothing is leaked in case of an exception. auto unique_rec = make_function_record(); auto rec = unique_rec.get(); /* Store the capture object directly in the function record if there is enough space */ if (PYBIND11_SILENCE_MSVC_C4127(sizeof(capture) <= sizeof(rec->data))) { /* Without these pragmas, GCC warns that there might not be enough space to use the placement new operator. However, the 'if' statement above ensures that this is the case. */ #if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wplacement-new" #endif new ((capture *) &rec->data) capture { std::forward<Func>(f) }; #if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER) # pragma GCC diagnostic pop #endif #if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // UB without std::launder, but without breaking ABI and/or // a significant refactoring it's "impossible" to solve. if (!std::is_trivially_destructible<capture>::value) rec->free_data = [](function_record *r) { auto data = PYBIND11_STD_LAUNDER((capture *) &r->data); (void) data; data->~capture(); }; #if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER) # pragma GCC diagnostic pop #endif } else { rec->data[0] = new capture { std::forward<Func>(f) }; rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); }; } /* Type casters for the function arguments and return value */ using cast_in = argument_loader<Args...>; using cast_out = make_caster< conditional_t<std::is_void<Return>::value, void_type, Return> >; static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs), "The number of argument annotations does not match the number of function arguments"); /* Dispatch code which converts function arguments and performs the actual function call */ rec->impl = [](function_call &call) -> handle { cast_in args_converter; /* Try to cast the function arguments into the C++ domain */ if (!args_converter.load_args(call)) return PYBIND11_TRY_NEXT_OVERLOAD; /* Invoke call policy pre-call hook */ process_attributes<Extra...>::precall(call); /* Get a pointer to the capture object */ auto data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data : call.func.data[0]); auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data)); /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */ return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy); /* Function scope guard -- defaults to the compile-to-nothing `void_type` */ using Guard = extract_guard_t<Extra...>; /* Perform the function call */ handle result = cast_out::cast( std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent); /* Invoke call policy post-call hook */ process_attributes<Extra...>::postcall(call, result); return result; }; /* Process any user-provided function attributes */ process_attributes<Extra...>::init(extra..., rec); { constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value, has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value, has_args = any_of<std::is_same<args, Args>...>::value, has_arg_annotations = any_of<is_keyword<Extra>...>::value; static_assert(has_arg_annotations || !has_kw_only_args, "py::kw_only requires the use of argument annotations"); static_assert(has_arg_annotations || !has_pos_only_args, "py::pos_only requires the use of argument annotations (for docstrings and aligning the annotations to the argument)"); static_assert(!(has_args && has_kw_only_args), "py::kw_only cannot be combined with a py::args argument"); } /* Generate a readable signature describing the function's arguments and return value types */ static constexpr auto signature = _("(") + cast_in::arg_names + _(") -> ") + cast_out::name; PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types(); /* Register the function with Python from generic (non-templated) code */ // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid. initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args)); if (cast_in::has_args) rec->has_args = true; if (cast_in::has_kwargs) rec->has_kwargs = true; /* Stash some additional information used by an important optimization in 'functional.h' */ using FunctionType = Return (*)(Args...); constexpr bool is_function_ptr = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *); if (is_function_ptr) { rec->is_stateless = true; rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType))); } } // Utility class that keeps track of all duplicated strings, and cleans them up in its destructor, // unless they are released. Basically a RAII-solution to deal with exceptions along the way. class strdup_guard { public: ~strdup_guard() { for (auto s : strings) std::free(s); } char *operator()(const char *s) { auto t = PYBIND11_COMPAT_STRDUP(s); strings.push_back(t); return t; } void release() { strings.clear(); } private: std::vector<char *> strings; }; /// Register a function call with Python (generic non-templated code goes here) void initialize_generic(unique_function_record &&unique_rec, const char *text, const std::type_info *const *types, size_t args) { // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr, // we do not want this to destuct the pointer. `initialize` (the caller) still relies on the // pointee being alive after this call. Only move out if a `capsule` is going to keep it alive. auto rec = unique_rec.get(); // Keep track of strdup'ed strings, and clean them up as long as the function's capsule // has not taken ownership yet (when `unique_rec.release()` is called). // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the strings // are only referenced before strdup'ing. So only *after* the following block could `destruct` // safely be called, but even then, `repr` could still throw in the middle of copying all strings. strdup_guard guarded_strdup; /* Create copies of all referenced C-style strings */ rec->name = guarded_strdup(rec->name ? rec->name : ""); if (rec->doc) rec->doc = guarded_strdup(rec->doc); for (auto &a: rec->args) { if (a.name) a.name = guarded_strdup(a.name); if (a.descr) a.descr = guarded_strdup(a.descr); else if (a.value) a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str()); } rec->is_constructor = (strcmp(rec->name, "__init__") == 0) || (strcmp(rec->name, "__setstate__") == 0); #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING) if (rec->is_constructor && !rec->is_new_style_constructor) { const auto class_name = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr()); const auto func_name = std::string(rec->name); PyErr_WarnEx( PyExc_FutureWarning, ("pybind11-bound class '" + class_name + "' is using an old-style " "placement-new '" + func_name + "' which has been deprecated. See " "the upgrade guide in pybind11's docs. This message is only visible " "when compiled in debug mode.").c_str(), 0 ); } #endif /* Generate a proper function signature */ std::string signature; size_t type_index = 0, arg_index = 0; for (auto *pc = text; *pc != '\0'; ++pc) { const auto c = *pc; if (c == '{') { // Write arg name for everything except *args and **kwargs. if (*(pc + 1) == '*') continue; // Separator for keyword-only arguments, placed before the kw // arguments start if (rec->nargs_kw_only > 0 && arg_index + rec->nargs_kw_only == args) signature += "*, "; if (arg_index < rec->args.size() && rec->args[arg_index].name) { signature += rec->args[arg_index].name; } else if (arg_index == 0 && rec->is_method) { signature += "self"; } else { signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0)); } signature += ": "; } else if (c == '}') { // Write default value if available. if (arg_index < rec->args.size() && rec->args[arg_index].descr) { signature += " = "; signature += rec->args[arg_index].descr; } // Separator for positional-only arguments (placed after the // argument, rather than before like * if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) signature += ", /"; arg_index++; } else if (c == '%') { const std::type_info *t = types[type_index++]; if (!t) pybind11_fail("Internal error while parsing type signature (1)"); if (auto tinfo = detail::get_type_info(*t)) { handle th((PyObject *) tinfo->type); signature += th.attr("__module__").cast<std::string>() + "." + th.attr("__qualname__").cast<std::string>(); // Python 3.3+, but we backport it to earlier versions } else if (rec->is_new_style_constructor && arg_index == 0) { // A new-style `__init__` takes `self` as `value_and_holder`. // Rewrite it to the proper class type. signature += rec->scope.attr("__module__").cast<std::string>() + "." + rec->scope.attr("__qualname__").cast<std::string>(); } else { std::string tname(t->name()); detail::clean_type_id(tname); signature += tname; } } else { signature += c; } } if (arg_index != args || types[type_index] != nullptr) pybind11_fail("Internal error while parsing type signature (2)"); #if PY_MAJOR_VERSION < 3 if (strcmp(rec->name, "__next__") == 0) { std::free(rec->name); rec->name = guarded_strdup("next"); } else if (strcmp(rec->name, "__bool__") == 0) { std::free(rec->name); rec->name = guarded_strdup("__nonzero__"); } #endif rec->signature = guarded_strdup(signature.c_str()); rec->args.shrink_to_fit(); rec->nargs = (std::uint16_t) args; if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr()); detail::function_record *chain = nullptr, *chain_start = rec; if (rec->sibling) { if (PyCFunction_Check(rec->sibling.ptr())) { auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr())); chain = (detail::function_record *) rec_capsule; /* Never append a method to an overload chain of a parent class; instead, hide the parent's overloads in this case */ if (!chain->scope.is(rec->scope)) chain = nullptr; } // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing else if (!rec->sibling.is_none() && rec->name[0] != '_') pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) + "\" with a function of the same name"); } if (!chain) { /* No existing overload was found, create a new function object */ rec->def = new PyMethodDef(); std::memset(rec->def, 0, sizeof(PyMethodDef)); rec->def->ml_name = rec->name; rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher)); rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS; capsule rec_capsule(unique_rec.release(), [](void *ptr) { destruct((detail::function_record *) ptr); }); guarded_strdup.release(); object scope_module; if (rec->scope) { if (hasattr(rec->scope, "__module__")) { scope_module = rec->scope.attr("__module__"); } else if (hasattr(rec->scope, "__name__")) { scope_module = rec->scope.attr("__name__"); } } m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr()); if (!m_ptr) pybind11_fail("cpp_function::cpp_function(): Could not allocate function object"); } else { /* Append at the beginning or end of the overload chain */ m_ptr = rec->sibling.ptr(); inc_ref(); if (chain->is_method != rec->is_method) pybind11_fail("overloading a method with both static and instance methods is not supported; " #if defined(NDEBUG) "compile in debug mode for more details" #else "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " + std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature #endif ); if (rec->prepend) { // Beginning of chain; we need to replace the capsule's current head-of-the-chain // pointer with this one, then make this one point to the previous head of the // chain. chain_start = rec; rec->next = chain; auto rec_capsule = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self); rec_capsule.set_pointer(unique_rec.release()); guarded_strdup.release(); } else { // Or end of chain (normal behavior) chain_start = chain; while (chain->next) chain = chain->next; chain->next = unique_rec.release(); guarded_strdup.release(); } } std::string signatures; int index = 0; /* Create a nice pydoc rec including all signatures and docstrings of the functions in the overload chain */ if (chain && options::show_function_signatures()) { // First a generic signature signatures += rec->name; signatures += "(*args, **kwargs)\n"; signatures += "Overloaded function.\n\n"; } // Then specific overload signatures bool first_user_def = true; for (auto it = chain_start; it != nullptr; it = it->next) { if (options::show_function_signatures()) { if (index > 0) signatures += "\n"; if (chain) signatures += std::to_string(++index) + ". "; signatures += rec->name; signatures += it->signature; signatures += "\n"; } if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) { // If we're appending another docstring, and aren't printing function signatures, we // need to append a newline first: if (!options::show_function_signatures()) { if (first_user_def) first_user_def = false; else signatures += "\n"; } if (options::show_function_signatures()) signatures += "\n"; signatures += it->doc; if (options::show_function_signatures()) signatures += "\n"; } } /* Install docstring */ auto *func = (PyCFunctionObject *) m_ptr; std::free(const_cast<char *>(func->m_ml->ml_doc)); // Install docstring if it's non-empty (when at least one option is enabled) func->m_ml->ml_doc = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str()); if (rec->is_method) { m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr()); if (!m_ptr) pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object"); Py_DECREF(func); } } /// When a cpp_function is GCed, release any memory allocated by pybind11 static void destruct(detail::function_record *rec, bool free_strings = true) { // If on Python 3.9, check the interpreter "MICRO" (patch) version. // If this is running on 3.9.0, we have to work around a bug. #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9 static bool is_zero = Py_GetVersion()[4] == '0'; #endif while (rec) { detail::function_record *next = rec->next; if (rec->free_data) rec->free_data(rec); // During initialization, these strings might not have been copied yet, // so they cannot be freed. Once the function has been created, they can. // Check `make_function_record` for more details. if (free_strings) { std::free((char *) rec->name); std::free((char *) rec->doc); std::free((char *) rec->signature); for (auto &arg: rec->args) { std::free(const_cast<char *>(arg.name)); std::free(const_cast<char *>(arg.descr)); } } for (auto &arg: rec->args) arg.value.dec_ref(); if (rec->def) { std::free(const_cast<char *>(rec->def->ml_doc)); // Python 3.9.0 decref's these in the wrong order; rec->def // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix) // See https://github.com/python/cpython/pull/22670 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9 if (!is_zero) delete rec->def; #else delete rec->def; #endif } delete rec; rec = next; } } /// Main dispatch logic for calls to functions bound using pybind11 static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) { using namespace detail; /* Iterator over the list of potentially admissible overloads */ const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr), *it = overloads; /* Need to know how many arguments + keyword arguments there are to pick the right overload */ const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in); handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr, result = PYBIND11_TRY_NEXT_OVERLOAD; auto self_value_and_holder = value_and_holder(); if (overloads->is_constructor) { if (!parent || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) { PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid or missing `self` argument"); return nullptr; } const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr()); const auto pi = reinterpret_cast<instance *>(parent.ptr()); self_value_and_holder = pi->get_value_and_holder(tinfo, true); // If this value is already registered it must mean __init__ is invoked multiple times; // we really can't support that in C++, so just ignore the second __init__. if (self_value_and_holder.instance_registered()) return none().release().ptr(); } try { // We do this in two passes: in the first pass, we load arguments with `convert=false`; // in the second, we allow conversion (except for arguments with an explicit // py::arg().noconvert()). This lets us prefer calls without conversion, with // conversion as a fallback. std::vector<function_call> second_pass; // However, if there are no overloads, we can just skip the no-convert pass entirely const bool overloaded = it != nullptr && it->next != nullptr; for (; it != nullptr; it = it->next) { /* For each overload: 1. Copy all positional arguments we were given, also checking to make sure that named positional arguments weren't *also* specified via kwarg. 2. If we weren't given enough, try to make up the omitted ones by checking whether they were provided by a kwarg matching the `py::arg("name")` name. If so, use it (and remove it from kwargs; if not, see if the function binding provided a default that we can use. 3. Ensure that either all keyword arguments were "consumed", or that the function takes a kwargs argument to accept unconsumed kwargs. 4. Any positional arguments still left get put into a tuple (for args), and any leftover kwargs get put into a dict. 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an extra tuple or dict at the end of the positional arguments. 6. Call the function call dispatcher (function_record::impl) If one of these fail, move on to the next overload and keep trying until we get a result other than PYBIND11_TRY_NEXT_OVERLOAD. */ const function_record &func = *it; size_t num_args = func.nargs; // Number of positional arguments that we need if (func.has_args) --num_args; // (but don't count py::args if (func.has_kwargs) --num_args; // or py::kwargs) size_t pos_args = num_args - func.nargs_kw_only; if (!func.has_args && n_args_in > pos_args) continue; // Too many positional arguments for this overload if (n_args_in < pos_args && func.args.size() < pos_args) continue; // Not enough positional arguments given, and not enough defaults to fill in the blanks function_call call(func, parent); size_t args_to_copy = (std::min)(pos_args, n_args_in); // Protect std::min with parentheses size_t args_copied = 0; // 0. Inject new-style `self` argument if (func.is_new_style_constructor) { // The `value` may have been preallocated by an old-style `__init__` // if it was a preceding candidate for overload resolution. if (self_value_and_holder) self_value_and_holder.type->dealloc(self_value_and_holder); call.init_self = PyTuple_GET_ITEM(args_in, 0); call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder)); call.args_convert.push_back(false); ++args_copied; } // 1. Copy any position arguments given. bool bad_arg = false; for (; args_copied < args_to_copy; ++args_copied) { const argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr; if (kwargs_in && arg_rec && arg_rec->name && dict_getitemstring(kwargs_in, arg_rec->name)) { bad_arg = true; break; } handle arg(PyTuple_GET_ITEM(args_in, args_copied)); if (arg_rec && !arg_rec->none && arg.is_none()) { bad_arg = true; break; } call.args.push_back(arg); call.args_convert.push_back(arg_rec ? arg_rec->convert : true); } if (bad_arg) continue; // Maybe it was meant for another overload (issue #688) // We'll need to copy this if we steal some kwargs for defaults dict kwargs = reinterpret_borrow<dict>(kwargs_in); // 1.5. Fill in any missing pos_only args from defaults if they exist if (args_copied < func.nargs_pos_only) { for (; args_copied < func.nargs_pos_only; ++args_copied) { const auto &arg_rec = func.args[args_copied]; handle value; if (arg_rec.value) { value = arg_rec.value; } if (value) { call.args.push_back(value); call.args_convert.push_back(arg_rec.convert); } else break; } if (args_copied < func.nargs_pos_only) continue; // Not enough defaults to fill the positional arguments } // 2. Check kwargs and, failing that, defaults that may help complete the list if (args_copied < num_args) { bool copied_kwargs = false; for (; args_copied < num_args; ++args_copied) { const auto &arg_rec = func.args[args_copied]; handle value; if (kwargs_in && arg_rec.name) value = dict_getitemstring(kwargs.ptr(), arg_rec.name); if (value) { // Consume a kwargs value if (!copied_kwargs) { kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr())); copied_kwargs = true; } if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) { throw error_already_set(); } } else if (arg_rec.value) { value = arg_rec.value; } if (!arg_rec.none && value.is_none()) { break; } if (value) { call.args.push_back(value); call.args_convert.push_back(arg_rec.convert); } else break; } if (args_copied < num_args) continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments } // 3. Check everything was consumed (unless we have a kwargs arg) if (kwargs && !kwargs.empty() && !func.has_kwargs) continue; // Unconsumed kwargs, but no py::kwargs argument to accept them // 4a. If we have a py::args argument, create a new tuple with leftovers if (func.has_args) { tuple extra_args; if (args_to_copy == 0) { // We didn't copy out any position arguments from the args_in tuple, so we // can reuse it directly without copying: extra_args = reinterpret_borrow<tuple>(args_in); } else if (args_copied >= n_args_in) { extra_args = tuple(0); } else { size_t args_size = n_args_in - args_copied; extra_args = tuple(args_size); for (size_t i = 0; i < args_size; ++i) { extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i); } } call.args.push_back(extra_args); call.args_convert.push_back(false); call.args_ref = std::move(extra_args); } // 4b. If we have a py::kwargs, pass on any remaining kwargs if (func.has_kwargs) { if (!kwargs.ptr()) kwargs = dict(); // If we didn't get one, send an empty one call.args.push_back(kwargs); call.args_convert.push_back(false); call.kwargs_ref = std::move(kwargs); } // 5. Put everything in a vector. Not technically step 5, we've been building it // in `call.args` all along. #if !defined(NDEBUG) if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!"); #endif std::vector<bool> second_pass_convert; if (overloaded) { // We're in the first no-convert pass, so swap out the conversion flags for a // set of all-false flags. If the call fails, we'll swap the flags back in for // the conversion-allowed call below. second_pass_convert.resize(func.nargs, false); call.args_convert.swap(second_pass_convert); } // 6. Call the function. try { loader_life_support guard{}; result = func.impl(call); } catch (reference_cast_error &) { result = PYBIND11_TRY_NEXT_OVERLOAD; } if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) break; if (overloaded) { // The (overloaded) call failed; if the call has at least one argument that // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`) // then add this call to the list of second pass overloads to try. for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) { if (second_pass_convert[i]) { // Found one: swap the converting flags back in and store the call for // the second pass. call.args_convert.swap(second_pass_convert); second_pass.push_back(std::move(call)); break; } } } } if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) { // The no-conversion pass finished without success, try again with conversion allowed for (auto &call : second_pass) { try { loader_life_support guard{}; result = call.func.impl(call); } catch (reference_cast_error &) { result = PYBIND11_TRY_NEXT_OVERLOAD; } if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) { // The error reporting logic below expects 'it' to be valid, as it would be // if we'd encountered this failure in the first-pass loop. if (!result) it = &call.func; break; } } } } catch (error_already_set &e) { e.restore(); return nullptr; #ifdef __GLIBCXX__ } catch ( abi::__forced_unwind& ) { throw; #endif } catch (...) { /* When an exception is caught, give each registered exception translator a chance to translate it to a Python exception. First all module-local translators will be tried in reverse order of registration. If none of the module-locale translators handle the exception (or there are no module-locale translators) then the global translators will be tried, also in reverse order of registration. A translator may choose to do one of the following: - catch the exception and call PyErr_SetString or PyErr_SetObject to set a standard (or custom) Python exception, or - do nothing and let the exception fall through to the next translator, or - delegate translation to the next translator by throwing a new type of exception. */ auto &local_exception_translators = get_local_internals().registered_exception_translators; if (detail::apply_exception_translators(local_exception_translators)) { return nullptr; } auto &exception_translators = get_internals().registered_exception_translators; if (detail::apply_exception_translators(exception_translators)) { return nullptr; } PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!"); return nullptr; } auto append_note_if_missing_header_is_suspected = [](std::string &msg) { if (msg.find("std::") != std::string::npos) { msg += "\n\n" "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n" "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n" "conversions are optional and require extra headers to be included\n" "when compiling your pybind11 module."; } }; if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) { if (overloads->is_operator) return handle(Py_NotImplemented).inc_ref().ptr(); std::string msg = std::string(overloads->name) + "(): incompatible " + std::string(overloads->is_constructor ? "constructor" : "function") + " arguments. The following argument types are supported:\n"; int ctr = 0; for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) { msg += " "+ std::to_string(++ctr) + ". "; bool wrote_sig = false; if (overloads->is_constructor) { // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)` std::string sig = it2->signature; size_t start = sig.find('(') + 7; // skip "(self: " if (start < sig.size()) { // End at the , for the next argument size_t end = sig.find(", "), next = end + 2; size_t ret = sig.rfind(" -> "); // Or the ), if there is no comma: if (end >= sig.size()) next = end = sig.find(')'); if (start < end && next < sig.size()) { msg.append(sig, start, end - start); msg += '('; msg.append(sig, next, ret - next); wrote_sig = true; } } } if (!wrote_sig) msg += it2->signature; msg += "\n"; } msg += "\nInvoked with: "; auto args_ = reinterpret_borrow<tuple>(args_in); bool some_args = false; for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) { if (!some_args) some_args = true; else msg += ", "; try { msg += pybind11::repr(args_[ti]); } catch (const error_already_set&) { msg += "<repr raised Error>"; } } if (kwargs_in) { auto kwargs = reinterpret_borrow<dict>(kwargs_in); if (!kwargs.empty()) { if (some_args) msg += "; "; msg += "kwargs: "; bool first = true; for (auto kwarg : kwargs) { if (first) first = false; else msg += ", "; msg += pybind11::str("{}=").format(kwarg.first); try { msg += pybind11::repr(kwarg.second); } catch (const error_already_set&) { msg += "<repr raised Error>"; } } } } append_note_if_missing_header_is_suspected(msg); PyErr_SetString(PyExc_TypeError, msg.c_str()); return nullptr; } if (!result) { std::string msg = "Unable to convert function return value to a " "Python type! The signature was\n\t"; msg += it->signature; append_note_if_missing_header_is_suspected(msg); PyErr_SetString(PyExc_TypeError, msg.c_str()); return nullptr; } if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) { auto *pi = reinterpret_cast<instance *>(parent.ptr()); self_value_and_holder.type->init_instance(pi, nullptr); } return result.ptr(); } }; /// Wrapper for Python extension modules class module_ : public object { public: PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check) /// Create a new top-level Python module with the given name and docstring PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead") explicit module_(const char *name, const char *doc = nullptr) { #if PY_MAJOR_VERSION >= 3 *this = create_extension_module(name, doc, new PyModuleDef()); #else *this = create_extension_module(name, doc, nullptr); #endif } /** \rst Create Python binding for a new function within the module scope. ``Func`` can be a plain C++ function, a function pointer, or a lambda function. For details on the ``Extra&& ... extra`` argument, see section :ref:`extras`. \endrst */ template <typename Func, typename... Extra> module_ &def(const char *name_, Func &&f, const Extra& ... extra) { cpp_function func(std::forward<Func>(f), name(name_), scope(*this), sibling(getattr(*this, name_, none())), extra...); // NB: allow overwriting here because cpp_function sets up a chain with the intention of // overwriting (and has already checked internally that it isn't overwriting non-functions). add_object(name_, func, true /* overwrite */); return *this; } /** \rst Create and return a new Python submodule with the given name and docstring. This also works recursively, i.e. .. code-block:: cpp py::module_ m("example", "pybind11 example plugin"); py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'"); py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'"); \endrst */ module_ def_submodule(const char *name, const char *doc = nullptr) { std::string full_name = std::string(PyModule_GetName(m_ptr)) + std::string(".") + std::string(name); auto result = reinterpret_borrow<module_>(PyImport_AddModule(full_name.c_str())); if (doc && options::show_user_defined_docstrings()) result.attr("__doc__") = pybind11::str(doc); attr(name) = result; return result; } /// Import and return a module or throws `error_already_set`. static module_ import(const char *name) { PyObject *obj = PyImport_ImportModule(name); if (!obj) throw error_already_set(); return reinterpret_steal<module_>(obj); } /// Reload the module or throws `error_already_set`. void reload() { PyObject *obj = PyImport_ReloadModule(ptr()); if (!obj) throw error_already_set(); *this = reinterpret_steal<module_>(obj); } /** \rst Adds an object to the module using the given name. Throws if an object with the given name already exists. ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11 has established will, in most cases, break things. \endrst */ PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) { if (!overwrite && hasattr(*this, name)) pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" + std::string(name) + "\""); PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */); } #if PY_MAJOR_VERSION >= 3 using module_def = PyModuleDef; #else struct module_def {}; #endif /** \rst Create a new top-level module that can be used as the main module of a C extension. For Python 3, ``def`` should point to a statically allocated module_def. For Python 2, ``def`` can be a nullptr and is completely ignored. \endrst */ static module_ create_extension_module(const char *name, const char *doc, module_def *def) { #if PY_MAJOR_VERSION >= 3 // module_def is PyModuleDef def = new (def) PyModuleDef { // Placement new (not an allocation). /* m_base */ PyModuleDef_HEAD_INIT, /* m_name */ name, /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr, /* m_size */ -1, /* m_methods */ nullptr, /* m_slots */ nullptr, /* m_traverse */ nullptr, /* m_clear */ nullptr, /* m_free */ nullptr }; auto m = PyModule_Create(def); #else // Ignore module_def *def; only necessary for Python 3 (void) def; auto m = Py_InitModule3(name, nullptr, options::show_user_defined_docstrings() ? doc : nullptr); #endif if (m == nullptr) { if (PyErr_Occurred()) throw error_already_set(); pybind11_fail("Internal error in module_::create_extension_module()"); } // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when returned from PyInit_... // For Python 2, reinterpret_borrow is correct. return reinterpret_borrow<module_>(m); } }; // When inside a namespace (or anywhere as long as it's not the first item on a line), // C++20 allows "module" to be used. This is provided for backward compatibility, and for // simplicity, if someone wants to use py::module for example, that is perfectly safe. using module = module_; /// \ingroup python_builtins /// Return a dictionary representing the global variables in the current execution frame, /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded). inline dict globals() { PyObject *p = PyEval_GetGlobals(); return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr()); } PYBIND11_NAMESPACE_BEGIN(detail) /// Generic support for creating new Python heap types class generic_type : public object { public: PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check) protected: void initialize(const type_record &rec) { if (rec.scope && hasattr(rec.scope, "__dict__") && rec.scope.attr("__dict__").contains(rec.name)) pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) + "\": an object with that name is already defined"); if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type)) != nullptr) pybind11_fail("generic_type: type \"" + std::string(rec.name) + "\" is already registered!"); m_ptr = make_new_python_type(rec); /* Register supplemental type information in C++ dict */ auto *tinfo = new detail::type_info(); tinfo->type = (PyTypeObject *) m_ptr; tinfo->cpptype = rec.type; tinfo->type_size = rec.type_size; tinfo->type_align = rec.type_align; tinfo->operator_new = rec.operator_new; tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size); tinfo->init_instance = rec.init_instance; tinfo->dealloc = rec.dealloc; tinfo->simple_type = true; tinfo->simple_ancestors = true; tinfo->default_holder = rec.default_holder; tinfo->module_local = rec.module_local; auto &internals = get_internals(); auto tindex = std::type_index(*rec.type); tinfo->direct_conversions = &internals.direct_conversions[tindex]; if (rec.module_local) get_local_internals().registered_types_cpp[tindex] = tinfo; else internals.registered_types_cpp[tindex] = tinfo; internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo }; if (rec.bases.size() > 1 || rec.multiple_inheritance) { mark_parents_nonsimple(tinfo->type); tinfo->simple_ancestors = false; } else if (rec.bases.size() == 1) { auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr()); tinfo->simple_ancestors = parent_tinfo->simple_ancestors; } if (rec.module_local) { // Stash the local typeinfo and loader so that external modules can access it. tinfo->module_local_load = &type_caster_generic::local_load; setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo)); } } /// Helper function which tags all parents of a type using mult. inheritance void mark_parents_nonsimple(PyTypeObject *value) { auto t = reinterpret_borrow<tuple>(value->tp_bases); for (handle h : t) { auto tinfo2 = get_type_info((PyTypeObject *) h.ptr()); if (tinfo2) tinfo2->simple_type = false; mark_parents_nonsimple((PyTypeObject *) h.ptr()); } } void install_buffer_funcs( buffer_info *(*get_buffer)(PyObject *, void *), void *get_buffer_data) { auto *type = (PyHeapTypeObject*) m_ptr; auto tinfo = detail::get_type_info(&type->ht_type); if (!type->ht_type.tp_as_buffer) pybind11_fail( "To be able to register buffer protocol support for the type '" + get_fully_qualified_tp_name(tinfo->type) + "' the associated class<>(..) invocation must " "include the pybind11::buffer_protocol() annotation!"); tinfo->get_buffer = get_buffer; tinfo->get_buffer_data = get_buffer_data; } // rec_func must be set for either fget or fset. void def_property_static_impl(const char *name, handle fget, handle fset, detail::function_record *rec_func) { const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope); const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr) && pybind11::options::show_user_defined_docstrings(); auto property = handle((PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type)); attr(name) = property(fget.ptr() ? fget : none(), fset.ptr() ? fset : none(), /*deleter*/none(), pybind11::str(has_doc ? rec_func->doc : "")); } }; /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded. template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>> void set_operator_new(type_record *r) { r->operator_new = &T::operator new; } template <typename> void set_operator_new(...) { } template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { }; template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>> : std::true_type { }; template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { }; template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type { }; /// Call class-specific delete if it exists or global otherwise. Can also be an overload set. template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0> void call_operator_delete(T *p, size_t, size_t) { T::operator delete(p); } template <typename T, enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0> void call_operator_delete(T *p, size_t s, size_t) { T::operator delete(p, s); } inline void call_operator_delete(void *p, size_t s, size_t a) { (void)s; (void)a; #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912) if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) { #ifdef __cpp_sized_deallocation ::operator delete(p, s, std::align_val_t(a)); #else ::operator delete(p, std::align_val_t(a)); #endif return; } #endif #ifdef __cpp_sized_deallocation ::operator delete(p, s); #else ::operator delete(p); #endif } inline void add_class_method(object& cls, const char *name_, const cpp_function &cf) { cls.attr(cf.name()) = cf; if (strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) { cls.attr("__hash__") = none(); } } PYBIND11_NAMESPACE_END(detail) /// Given a pointer to a member function, cast it to its `Derived` version. /// Forward everything else unchanged. template <typename /*Derived*/, typename F> auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); } template <typename Derived, typename Return, typename Class, typename... Args> auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) { static_assert(detail::is_accessible_base_of<Class, Derived>::value, "Cannot bind an inaccessible base class method; use a lambda definition instead"); return pmf; } template <typename Derived, typename Return, typename Class, typename... Args> auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const { static_assert(detail::is_accessible_base_of<Class, Derived>::value, "Cannot bind an inaccessible base class method; use a lambda definition instead"); return pmf; } template <typename type_, typename... options> class class_ : public detail::generic_type { template <typename T> using is_holder = detail::is_holder_type<type_, T>; template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>; template <typename T> using is_base = detail::is_strict_base_of<T, type_>; // struct instead of using here to help MSVC: template <typename T> struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {}; public: using type = type_; using type_alias = detail::exactly_one_t<is_subtype, void, options...>; constexpr static bool has_alias = !std::is_void<type_alias>::value; using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>; static_assert(detail::all_of<is_valid_class_option<options>...>::value, "Unknown/invalid class_ template parameters provided"); static_assert(!has_alias || std::is_polymorphic<type>::value, "Cannot use an alias class with a non-polymorphic type"); PYBIND11_OBJECT(class_, generic_type, PyType_Check) template <typename... Extra> class_(handle scope, const char *name, const Extra &... extra) { using namespace detail; // MI can only be specified via class_ template options, not constructor parameters static_assert( none_of<is_pyobject<Extra>...>::value || // no base class arguments, or: ( constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base constexpr_sum(is_base<options>::value...) == 0 && // no template option bases none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr "Error: multiple inheritance bases must be specified via class_ template options"); type_record record; record.scope = scope; record.name = name; record.type = &typeid(type); record.type_size = sizeof(conditional_t<has_alias, type_alias, type>); record.type_align = alignof(conditional_t<has_alias, type_alias, type>&); record.holder_size = sizeof(holder_type); record.init_instance = init_instance; record.dealloc = dealloc; record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value; set_operator_new<type>(&record); /* Register base classes specified via template arguments to class_, if any */ PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record)); /* Process optional arguments, if any */ process_attributes<Extra...>::init(extra..., &record); generic_type::initialize(record); if (has_alias) { auto &instances = record.module_local ? get_local_internals().registered_types_cpp : get_internals().registered_types_cpp; instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))]; } } template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0> static void add_base(detail::type_record &rec) { rec.add_base(typeid(Base), [](void *src) -> void * { return static_cast<Base *>(reinterpret_cast<type *>(src)); }); } template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0> static void add_base(detail::type_record &) { } template <typename Func, typename... Extra> class_ &def(const char *name_, Func&& f, const Extra&... extra) { cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this), sibling(getattr(*this, name_, none())), extra...); add_class_method(*this, name_, cf); return *this; } template <typename Func, typename... Extra> class_ & def_static(const char *name_, Func &&f, const Extra&... extra) { static_assert(!std::is_member_function_pointer<Func>::value, "def_static(...) called with a non-static member function pointer"); cpp_function cf(std::forward<Func>(f), name(name_), scope(*this), sibling(getattr(*this, name_, none())), extra...); attr(cf.name()) = staticmethod(cf); return *this; } template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra> class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) { op.execute(*this, extra...); return *this; } template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra> class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) { op.execute_cast(*this, extra...); return *this; } template <typename... Args, typename... Extra> class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init); init.execute(*this, extra...); return *this; } template <typename... Args, typename... Extra> class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init); init.execute(*this, extra...); return *this; } template <typename... Args, typename... Extra> class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) { std::move(init).execute(*this, extra...); return *this; } template <typename... Args, typename... Extra> class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) { std::move(pf).execute(*this, extra...); return *this; } template <typename Func> class_& def_buffer(Func &&func) { struct capture { Func func; }; auto *ptr = new capture { std::forward<Func>(func) }; install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* { detail::make_caster<type> caster; if (!caster.load(obj, false)) return nullptr; return new buffer_info(((capture *) ptr)->func(caster)); }, ptr); weakref(m_ptr, cpp_function([ptr](handle wr) { delete ptr; wr.dec_ref(); })).release(); return *this; } template <typename Return, typename Class, typename... Args> class_ &def_buffer(Return (Class::*func)(Args...)) { return def_buffer([func] (type &obj) { return (obj.*func)(); }); } template <typename Return, typename Class, typename... Args> class_ &def_buffer(Return (Class::*func)(Args...) const) { return def_buffer([func] (const type &obj) { return (obj.*func)(); }); } template <typename C, typename D, typename... Extra> class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) { static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)"); cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)), fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this)); def_property(name, fget, fset, return_value_policy::reference_internal, extra...); return *this; } template <typename C, typename D, typename... Extra> class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) { static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)"); cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)); def_property_readonly(name, fget, return_value_policy::reference_internal, extra...); return *this; } template <typename D, typename... Extra> class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) { cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)), fset([pm](const object &, const D &value) { *pm = value; }, scope(*this)); def_property_static(name, fget, fset, return_value_policy::reference, extra...); return *this; } template <typename D, typename... Extra> class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) { cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)); def_property_readonly_static(name, fget, return_value_policy::reference, extra...); return *this; } /// Uses return_value_policy::reference_internal by default template <typename Getter, typename... Extra> class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) { return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)), return_value_policy::reference_internal, extra...); } /// Uses cpp_function's return_value_policy by default template <typename... Extra> class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) { return def_property(name, fget, nullptr, extra...); } /// Uses return_value_policy::reference by default template <typename Getter, typename... Extra> class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) { return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...); } /// Uses cpp_function's return_value_policy by default template <typename... Extra> class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) { return def_property_static(name, fget, nullptr, extra...); } /// Uses return_value_policy::reference_internal by default template <typename Getter, typename Setter, typename... Extra> class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) { return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...); } template <typename Getter, typename... Extra> class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) { return def_property(name, cpp_function(method_adaptor<type>(fget)), fset, return_value_policy::reference_internal, extra...); } /// Uses cpp_function's return_value_policy by default template <typename... Extra> class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) { return def_property_static(name, fget, fset, is_method(*this), extra...); } /// Uses return_value_policy::reference by default template <typename Getter, typename... Extra> class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) { return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...); } /// Uses cpp_function's return_value_policy by default template <typename... Extra> class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) { static_assert( 0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...), "Argument annotations are not allowed for properties"); auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset); auto *rec_active = rec_fget; if (rec_fget) { char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */ detail::process_attributes<Extra...>::init(extra..., rec_fget); if (rec_fget->doc && rec_fget->doc != doc_prev) { free(doc_prev); rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc); } } if (rec_fset) { char *doc_prev = rec_fset->doc; detail::process_attributes<Extra...>::init(extra..., rec_fset); if (rec_fset->doc && rec_fset->doc != doc_prev) { free(doc_prev); rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc); } if (! rec_active) rec_active = rec_fset; } def_property_static_impl(name, fget, fset, rec_active); return *this; } private: /// Initialize holder object, variant 1: object derives from enable_shared_from_this template <typename T> static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) { auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>( detail::try_get_shared_from_this(v_h.value_ptr<type>())); if (sh) { new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh)); v_h.set_holder_constructed(); } if (!v_h.holder_constructed() && inst->owned) { new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>()); v_h.set_holder_constructed(); } } static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) { new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr)); } static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) { new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr))); } /// Initialize holder object, variant 2: try to construct from existing holder object, if possible static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) { if (holder_ptr) { init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>()); v_h.set_holder_constructed(); } else if (inst->owned || detail::always_construct_holder<holder_type>::value) { new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>()); v_h.set_holder_constructed(); } } /// Performs instance initialization including constructing a holder and registering the known /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes an /// optional pointer to an existing holder to use; if not specified and the instance is /// `.owned`, a new holder will be constructed to manage the value pointer. static void init_instance(detail::instance *inst, const void *holder_ptr) { auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type))); if (!v_h.instance_registered()) { register_instance(inst, v_h.value_ptr(), v_h.type); v_h.set_instance_registered(); } init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>()); } /// Deallocates an instance; via holder, if constructed; otherwise via operator delete. static void dealloc(detail::value_and_holder &v_h) { // We could be deallocating because we are cleaning up after a Python exception. // If so, the Python error indicator will be set. We need to clear that before // running the destructor, in case the destructor code calls more Python. // If we don't, the Python API will exit with an exception, and pybind11 will // throw error_already_set from the C++ destructor which is forbidden and triggers // std::terminate(). error_scope scope; if (v_h.holder_constructed()) { v_h.holder<holder_type>().~holder_type(); v_h.set_holder_constructed(false); } else { detail::call_operator_delete(v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align ); } v_h.value_ptr() = nullptr; } static detail::function_record *get_function_record(handle h) { h = detail::get_function(h); return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr())) : nullptr; } }; /// Binds an existing constructor taking arguments Args... template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; } /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even /// when not inheriting on the Python side). template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; } /// Binds a factory function as a constructor template <typename Func, typename Ret = detail::initimpl::factory<Func>> Ret init(Func &&f) { return {std::forward<Func>(f)}; } /// Dual-argument factory function: the first function is called when no alias is needed, the second /// when an alias is needed (i.e. due to python-side inheritance). Arguments must be identical. template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>> Ret init(CFunc &&c, AFunc &&a) { return {std::forward<CFunc>(c), std::forward<AFunc>(a)}; } /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`. template <typename GetState, typename SetState> detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) { return {std::forward<GetState>(g), std::forward<SetState>(s)}; } PYBIND11_NAMESPACE_BEGIN(detail) inline str enum_name(handle arg) { dict entries = arg.get_type().attr("__entries"); for (auto kv : entries) { if (handle(kv.second[int_(0)]).equal(arg)) return pybind11::str(kv.first); } return "???"; } struct enum_base { enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) { } PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) { m_base.attr("__entries") = dict(); auto property = handle((PyObject *) &PyProperty_Type); auto static_property = handle((PyObject *) get_internals().static_property_type); m_base.attr("__repr__") = cpp_function( [](const object &arg) -> str { handle type = type::handle_of(arg); object type_name = type.attr("__name__"); return pybind11::str("<{}.{}: {}>").format(type_name, enum_name(arg), int_(arg)); }, name("__repr__"), is_method(m_base)); m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base))); m_base.attr("__str__") = cpp_function( [](handle arg) -> str { object type_name = type::handle_of(arg).attr("__name__"); return pybind11::str("{}.{}").format(type_name, enum_name(arg)); }, name("name"), is_method(m_base) ); m_base.attr("__doc__") = static_property(cpp_function( [](handle arg) -> std::string { std::string docstring; dict entries = arg.attr("__entries"); if (((PyTypeObject *) arg.ptr())->tp_doc) docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n"; docstring += "Members:"; for (auto kv : entries) { auto key = std::string(pybind11::str(kv.first)); auto comment = kv.second[int_(1)]; docstring += "\n\n " + key; if (!comment.is_none()) docstring += " : " + (std::string) pybind11::str(comment); } return docstring; }, name("__doc__") ), none(), none(), ""); m_base.attr("__members__") = static_property(cpp_function( [](handle arg) -> dict { dict entries = arg.attr("__entries"), m; for (auto kv : entries) m[kv.first] = kv.second[int_(0)]; return m; }, name("__members__")), none(), none(), "" ); #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \ m_base.attr(op) = cpp_function( \ [](const object &a, const object &b) { \ if (!type::handle_of(a).is(type::handle_of(b))) \ strict_behavior; /* NOLINT(bugprone-macro-parentheses) */ \ return expr; \ }, \ name(op), \ is_method(m_base), \ arg("other")) #define PYBIND11_ENUM_OP_CONV(op, expr) \ m_base.attr(op) = cpp_function( \ [](const object &a_, const object &b_) { \ int_ a(a_), b(b_); \ return expr; \ }, \ name(op), \ is_method(m_base), \ arg("other")) #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \ m_base.attr(op) = cpp_function( \ [](const object &a_, const object &b) { \ int_ a(a_); \ return expr; \ }, \ name(op), \ is_method(m_base), \ arg("other")) if (is_convertible) { PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b)); PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b)); if (is_arithmetic) { PYBIND11_ENUM_OP_CONV("__lt__", a < b); PYBIND11_ENUM_OP_CONV("__gt__", a > b); PYBIND11_ENUM_OP_CONV("__le__", a <= b); PYBIND11_ENUM_OP_CONV("__ge__", a >= b); PYBIND11_ENUM_OP_CONV("__and__", a & b); PYBIND11_ENUM_OP_CONV("__rand__", a & b); PYBIND11_ENUM_OP_CONV("__or__", a | b); PYBIND11_ENUM_OP_CONV("__ror__", a | b); PYBIND11_ENUM_OP_CONV("__xor__", a ^ b); PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b); m_base.attr("__invert__") = cpp_function([](const object &arg) { return ~(int_(arg)); }, name("__invert__"), is_method(m_base)); } } else { PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false); PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true); if (is_arithmetic) { #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!"); PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW); PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW); PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW); PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW); #undef PYBIND11_THROW } } #undef PYBIND11_ENUM_OP_CONV_LHS #undef PYBIND11_ENUM_OP_CONV #undef PYBIND11_ENUM_OP_STRICT m_base.attr("__getstate__") = cpp_function( [](const object &arg) { return int_(arg); }, name("__getstate__"), is_method(m_base)); m_base.attr("__hash__") = cpp_function( [](const object &arg) { return int_(arg); }, name("__hash__"), is_method(m_base)); } PYBIND11_NOINLINE void value(char const* name_, object value, const char *doc = nullptr) { dict entries = m_base.attr("__entries"); str name(name_); if (entries.contains(name)) { std::string type_name = (std::string) str(m_base.attr("__name__")); throw value_error(type_name + ": element \"" + std::string(name_) + "\" already exists!"); } entries[name] = std::make_pair(value, doc); m_base.attr(name) = value; } PYBIND11_NOINLINE void export_values() { dict entries = m_base.attr("__entries"); for (auto kv : entries) m_parent.attr(kv.first) = kv.second[int_(0)]; } handle m_base; handle m_parent; }; template <bool is_signed, size_t length> struct equivalent_integer {}; template <> struct equivalent_integer<true, 1> { using type = int8_t; }; template <> struct equivalent_integer<false, 1> { using type = uint8_t; }; template <> struct equivalent_integer<true, 2> { using type = int16_t; }; template <> struct equivalent_integer<false, 2> { using type = uint16_t; }; template <> struct equivalent_integer<true, 4> { using type = int32_t; }; template <> struct equivalent_integer<false, 4> { using type = uint32_t; }; template <> struct equivalent_integer<true, 8> { using type = int64_t; }; template <> struct equivalent_integer<false, 8> { using type = uint64_t; }; template <typename IntLike> using equivalent_integer_t = typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type; PYBIND11_NAMESPACE_END(detail) /// Binds C++ enumerations and enumeration classes to Python template <typename Type> class enum_ : public class_<Type> { public: using Base = class_<Type>; using Base::def; using Base::attr; using Base::def_property_readonly; using Base::def_property_readonly_static; using Underlying = typename std::underlying_type<Type>::type; // Scalar is the integer representation of underlying type using Scalar = detail::conditional_t<detail::any_of< detail::is_std_char_type<Underlying>, std::is_same<Underlying, bool> >::value, detail::equivalent_integer_t<Underlying>, Underlying>; template <typename... Extra> enum_(const handle &scope, const char *name, const Extra&... extra) : class_<Type>(scope, name, extra...), m_base(*this, scope) { constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value; constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value; m_base.init(is_arithmetic, is_convertible); def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value")); def_property_readonly("value", [](Type value) { return (Scalar) value; }); def("__int__", [](Type value) { return (Scalar) value; }); #if PY_MAJOR_VERSION < 3 def("__long__", [](Type value) { return (Scalar) value; }); #endif #if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 8) def("__index__", [](Type value) { return (Scalar) value; }); #endif attr("__setstate__") = cpp_function( [](detail::value_and_holder &v_h, Scalar arg) { detail::initimpl::setstate<Base>(v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type); }, detail::is_new_style_constructor(), pybind11::name("__setstate__"), is_method(*this), arg("state")); } /// Export enumeration entries into the parent scope enum_& export_values() { m_base.export_values(); return *this; } /// Add an enumeration entry enum_& value(char const* name, Type value, const char *doc = nullptr) { m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc); return *this; } private: detail::enum_base m_base; }; PYBIND11_NAMESPACE_BEGIN(detail) PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) { if (!nurse || !patient) pybind11_fail("Could not activate keep_alive!"); if (patient.is_none() || nurse.is_none()) return; /* Nothing to keep alive or nothing to be kept alive by */ auto tinfo = all_type_info(Py_TYPE(nurse.ptr())); if (!tinfo.empty()) { /* It's a pybind-registered type, so we can store the patient in the * internal list. */ add_patient(nurse.ptr(), patient.ptr()); } else { /* Fall back to clever approach based on weak references taken from * Boost.Python. This is not used for pybind-registered types because * the objects can be destroyed out-of-order in a GC pass. */ cpp_function disable_lifesupport( [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); }); weakref wr(nurse, disable_lifesupport); patient.inc_ref(); /* reference patient and leak the weak reference */ (void) wr.release(); } } PYBIND11_NOINLINE void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) { auto get_arg = [&](size_t n) { if (n == 0) return ret; if (n == 1 && call.init_self) return call.init_self; if (n <= call.args.size()) return call.args[n - 1]; return handle(); }; keep_alive_impl(get_arg(Nurse), get_arg(Patient)); } inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) { auto res = get_internals().registered_types_py #ifdef __cpp_lib_unordered_map_try_emplace .try_emplace(type); #else .emplace(type, std::vector<detail::type_info *>()); #endif if (res.second) { // New cache entry created; set up a weak reference to automatically remove it if the type // gets destroyed: weakref((PyObject *) type, cpp_function([type](handle wr) { get_internals().registered_types_py.erase(type); wr.dec_ref(); })).release(); } return res; } template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy> struct iterator_state { Iterator it; Sentinel end; bool first_or_done; }; PYBIND11_NAMESPACE_END(detail) /// Makes a python iterator from a first and past-the-end C++ InputIterator. template <return_value_policy Policy = return_value_policy::reference_internal, typename Iterator, typename Sentinel, #ifndef DOXYGEN_SHOULD_SKIP_THIS // Issue in breathe 4.26.1 typename ValueType = decltype(*std::declval<Iterator>()), #endif typename... Extra> iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) { using state = detail::iterator_state<Iterator, Sentinel, false, Policy>; if (!detail::get_type_info(typeid(state), false)) { class_<state>(handle(), "iterator", pybind11::module_local()) .def("__iter__", [](state &s) -> state& { return s; }) .def("__next__", [](state &s) -> ValueType { if (!s.first_or_done) ++s.it; else s.first_or_done = false; if (s.it == s.end) { s.first_or_done = true; throw stop_iteration(); } return *s.it; // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 }, std::forward<Extra>(extra)..., Policy); } return cast(state{first, last, true}); } /// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a /// first and past-the-end InputIterator. template <return_value_policy Policy = return_value_policy::reference_internal, typename Iterator, typename Sentinel, #ifndef DOXYGEN_SHOULD_SKIP_THIS // Issue in breathe 4.26.1 typename KeyType = decltype((*std::declval<Iterator>()).first), #endif typename... Extra> iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) { using state = detail::iterator_state<Iterator, Sentinel, true, Policy>; if (!detail::get_type_info(typeid(state), false)) { class_<state>(handle(), "iterator", pybind11::module_local()) .def("__iter__", [](state &s) -> state& { return s; }) .def("__next__", [](state &s) -> detail::remove_cv_t<KeyType> { if (!s.first_or_done) ++s.it; else s.first_or_done = false; if (s.it == s.end) { s.first_or_done = true; throw stop_iteration(); } return (*s.it).first; }, std::forward<Extra>(extra)..., Policy); } return cast(state{first, last, true}); } /// Makes an iterator over values of an stl container or other container supporting /// `std::begin()`/`std::end()` template <return_value_policy Policy = return_value_policy::reference_internal, typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) { return make_iterator<Policy>(std::begin(value), std::end(value), extra...); } /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting /// `std::begin()`/`std::end()` template <return_value_policy Policy = return_value_policy::reference_internal, typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) { return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...); } template <typename InputType, typename OutputType> void implicitly_convertible() { struct set_flag { bool &flag; explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; } ~set_flag() { flag = false; } }; auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * { static bool currently_used = false; if (currently_used) // implicit conversions are non-reentrant return nullptr; set_flag flag_helper(currently_used); if (!detail::make_caster<InputType>().load(obj, false)) return nullptr; tuple args(1); args[0] = obj; PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr); if (result == nullptr) PyErr_Clear(); return result; }; if (auto tinfo = detail::get_type_info(typeid(OutputType))) tinfo->implicit_conversions.push_back(implicit_caster); else pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>()); } inline void register_exception_translator(ExceptionTranslator &&translator) { detail::get_internals().registered_exception_translators.push_front( std::forward<ExceptionTranslator>(translator)); } /** * Add a new module-local exception translator. Locally registered functions * will be tried before any globally registered exception translators, which * will only be invoked if the module-local handlers do not deal with * the exception. */ inline void register_local_exception_translator(ExceptionTranslator &&translator) { detail::get_local_internals().registered_exception_translators.push_front( std::forward<ExceptionTranslator>(translator)); } /** * Wrapper to generate a new Python exception type. * * This should only be used with PyErr_SetString for now. * It is not (yet) possible to use as a py::base. * Template type argument is reserved for future use. */ template <typename type> class exception : public object { public: exception() = default; exception(handle scope, const char *name, handle base = PyExc_Exception) { std::string full_name = scope.attr("__name__").cast<std::string>() + std::string(".") + name; m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), NULL); if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) pybind11_fail("Error during initialization: multiple incompatible " "definitions with name \"" + std::string(name) + "\""); scope.attr(name) = *this; } // Sets the current python exception to this exception object with the given message void operator()(const char *message) { PyErr_SetString(m_ptr, message); } }; PYBIND11_NAMESPACE_BEGIN(detail) // Returns a reference to a function-local static exception object used in the simple // register_exception approach below. (It would be simpler to have the static local variable // directly in register_exception, but that makes clang <3.5 segfault - issue #1349). template <typename CppException> exception<CppException> &get_exception_object() { static exception<CppException> ex; return ex; } // Helper function for register_exception and register_local_exception template <typename CppException> exception<CppException> &register_exception_impl(handle scope, const char *name, handle base, bool isLocal) { auto &ex = detail::get_exception_object<CppException>(); if (!ex) ex = exception<CppException>(scope, name, base); auto register_func = isLocal ? &register_local_exception_translator : &register_exception_translator; register_func([](std::exception_ptr p) { if (!p) return; try { std::rethrow_exception(p); } catch (const CppException &e) { detail::get_exception_object<CppException>()(e.what()); } }); return ex; } PYBIND11_NAMESPACE_END(detail) /** * Registers a Python exception in `m` of the given `name` and installs a translator to * translate the C++ exception to the created Python exception using the what() method. * This is intended for simple exception translations; for more complex translation, register the * exception object and translator directly. */ template <typename CppException> exception<CppException> &register_exception(handle scope, const char *name, handle base = PyExc_Exception) { return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */); } /** * Registers a Python exception in `m` of the given `name` and installs a translator to * translate the C++ exception to the created Python exception using the what() method. * This translator will only be used for exceptions that are thrown in this module and will be * tried before global exception translators, including those registered with register_exception. * This is intended for simple exception translations; for more complex translation, register the * exception object and translator directly. */ template <typename CppException> exception<CppException> &register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) { return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */); } PYBIND11_NAMESPACE_BEGIN(detail) PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) { auto strings = tuple(args.size()); for (size_t i = 0; i < args.size(); ++i) { strings[i] = str(args[i]); } auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" "); auto line = sep.attr("join")(strings); object file; if (kwargs.contains("file")) { file = kwargs["file"].cast<object>(); } else { try { file = module_::import("sys").attr("stdout"); } catch (const error_already_set &) { /* If print() is called from code that is executed as part of garbage collection during interpreter shutdown, importing 'sys' can fail. Give up rather than crashing the interpreter in this case. */ return; } } auto write = file.attr("write"); write(line); write(kwargs.contains("end") ? kwargs["end"] : cast("\n")); if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) file.attr("flush")(); } PYBIND11_NAMESPACE_END(detail) template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> void print(Args &&...args) { auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...); detail::print(c.args(), c.kwargs()); } error_already_set::~error_already_set() { if (m_type) { gil_scoped_acquire gil; error_scope scope; m_type.release().dec_ref(); m_value.release().dec_ref(); m_trace.release().dec_ref(); } } PYBIND11_NAMESPACE_BEGIN(detail) inline function get_type_override(const void *this_ptr, const type_info *this_type, const char *name) { handle self = get_object_handle(this_ptr, this_type); if (!self) return function(); handle type = type::handle_of(self); auto key = std::make_pair(type.ptr(), name); /* Cache functions that aren't overridden in Python to avoid many costly Python dictionary lookups below */ auto &cache = get_internals().inactive_override_cache; if (cache.find(key) != cache.end()) return function(); function override = getattr(self, name, function()); if (override.is_cpp_function()) { cache.insert(key); return function(); } /* Don't call dispatch code if invoked from overridden function. Unfortunately this doesn't work on PyPy. */ #if !defined(PYPY_VERSION) PyFrameObject *frame = PyThreadState_Get()->frame; if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name && frame->f_code->co_argcount > 0) { PyFrame_FastToLocals(frame); PyObject *self_caller = dict_getitem( frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0)); if (self_caller == self.ptr()) return function(); } #else /* PyPy currently doesn't provide a detailed cpyext emulation of frame objects, so we have to emulate this using Python. This is going to be slow..*/ dict d; d["self"] = self; d["name"] = pybind11::str(name); PyObject *result = PyRun_String( "import inspect\n" "frame = inspect.currentframe()\n" "if frame is not None:\n" " frame = frame.f_back\n" " if frame is not None and str(frame.f_code.co_name) == name and " "frame.f_code.co_argcount > 0:\n" " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n" " if self_caller == self:\n" " self = None\n", Py_file_input, d.ptr(), d.ptr()); if (result == nullptr) throw error_already_set(); if (d["self"].is_none()) return function(); Py_DECREF(result); #endif return override; } PYBIND11_NAMESPACE_END(detail) /** \rst Try to retrieve a python method by the provided name from the instance pointed to by the this_ptr. :this_ptr: The pointer to the object the overridden method should be retrieved for. This should be the first non-trampoline class encountered in the inheritance chain. :name: The name of the overridden Python method to retrieve. :return: The Python method by this name from the object or an empty function wrapper. \endrst */ template <class T> function get_override(const T *this_ptr, const char *name) { auto tinfo = detail::get_type_info(typeid(T)); return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function(); } #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \ do { \ pybind11::gil_scoped_acquire gil; \ pybind11::function override \ = pybind11::get_override(static_cast<const cname *>(this), name); \ if (override) { \ auto o = override(__VA_ARGS__); \ if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \ static pybind11::detail::override_caster_t<ret_type> caster; \ return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \ } \ return pybind11::detail::cast_safe<ret_type>(std::move(o)); \ } \ } while (false) /** \rst Macro to populate the virtual method in the trampoline class. This macro tries to look up a method named 'fn' from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return the appropriate type. See :ref:`overriding_virtuals` for more information. This macro should be used when the method name in C is not the same as the method name in Python. For example with `__str__`. .. code-block:: cpp std::string toString() override { PYBIND11_OVERRIDE_NAME( std::string, // Return type (ret_type) Animal, // Parent class (cname) "__str__", // Name of method in Python (name) toString, // Name of function in C++ (fn) ); } \endrst */ #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \ do { \ PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \ return cname::fn(__VA_ARGS__); \ } while (false) /** \rst Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it throws if no override can be found. \endrst */ #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \ do { \ PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \ pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \ } while (false) /** \rst Macro to populate the virtual method in the trampoline class. This macro tries to look up the method from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return the appropriate type. This macro should be used if the method name in C and in Python are identical. See :ref:`overriding_virtuals` for more information. .. code-block:: cpp class PyAnimal : public Animal { public: // Inherit the constructors using Animal::Animal; // Trampoline (need one for each virtual function) std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE( std::string, // Return type (ret_type) Animal, // Parent class (cname) go, // Name of function in C++ (must match Python name) (fn) n_times // Argument(s) (...) ); } }; \endrst */ #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \ PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) /** \rst Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`, except that it throws if no override can be found. \endrst */ #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \ PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) // Deprecated versions PYBIND11_DEPRECATED("get_type_overload has been deprecated") inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) { return detail::get_type_override(this_ptr, this_type, name); } template <class T> inline function get_overload(const T *this_ptr, const char *name) { return get_override(this_ptr, name); } #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \ PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \ PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__) #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \ PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__); #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \ PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__) #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \ PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__); PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) #if defined(__GNUC__) && __GNUC__ == 7 # pragma GCC diagnostic pop // -Wnoexcept-type #endif
111,391
C
45.297589
188
0.558797
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/chrono.h
/* pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime Copyright (c) 2016 Trent Houliston <[email protected]> and Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "pybind11.h" #include <chrono> #include <cmath> #include <ctime> #include <mutex> #include <time.h> #include <datetime.h> // Backport the PyDateTime_DELTA functions from Python3.3 if required #ifndef PyDateTime_DELTA_GET_DAYS #define PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta*)o)->days) #endif #ifndef PyDateTime_DELTA_GET_SECONDS #define PyDateTime_DELTA_GET_SECONDS(o) (((PyDateTime_Delta*)o)->seconds) #endif #ifndef PyDateTime_DELTA_GET_MICROSECONDS #define PyDateTime_DELTA_GET_MICROSECONDS(o) (((PyDateTime_Delta*)o)->microseconds) #endif PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) template <typename type> class duration_caster { public: using rep = typename type::rep; using period = typename type::period; using days = std::chrono::duration<int_least32_t, std::ratio<86400>>; // signed 25 bits required by the standard. bool load(handle src, bool) { using namespace std::chrono; // Lazy initialise the PyDateTime import if (!PyDateTimeAPI) { PyDateTime_IMPORT; } if (!src) return false; // If invoked with datetime.delta object if (PyDelta_Check(src.ptr())) { value = type(duration_cast<duration<rep, period>>( days(PyDateTime_DELTA_GET_DAYS(src.ptr())) + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr())) + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr())))); return true; } // If invoked with a float we assume it is seconds and convert if (PyFloat_Check(src.ptr())) { value = type(duration_cast<duration<rep, period>>(duration<double>(PyFloat_AsDouble(src.ptr())))); return true; } return false; } // If this is a duration just return it back static const std::chrono::duration<rep, period>& get_duration(const std::chrono::duration<rep, period> &src) { return src; } // If this is a time_point get the time_since_epoch template <typename Clock> static std::chrono::duration<rep, period> get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) { return src.time_since_epoch(); } static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) { using namespace std::chrono; // Use overloaded function to get our duration from our source // Works out if it is a duration or time_point and get the duration auto d = get_duration(src); // Lazy initialise the PyDateTime import if (!PyDateTimeAPI) { PyDateTime_IMPORT; } // Declare these special duration types so the conversions happen with the correct primitive types (int) using dd_t = duration<int, std::ratio<86400>>; using ss_t = duration<int, std::ratio<1>>; using us_t = duration<int, std::micro>; auto dd = duration_cast<dd_t>(d); auto subd = d - dd; auto ss = duration_cast<ss_t>(subd); auto us = duration_cast<us_t>(subd - ss); return PyDelta_FromDSU(dd.count(), ss.count(), us.count()); } PYBIND11_TYPE_CASTER(type, _("datetime.timedelta")); }; inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) { #if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER) if (localtime_s(buf, time)) return nullptr; return buf; #else static std::mutex mtx; std::lock_guard<std::mutex> lock(mtx); std::tm *tm_ptr = localtime(time); if (tm_ptr != nullptr) { *buf = *tm_ptr; } return tm_ptr; #endif } // This is for casting times on the system clock into datetime.datetime instances template <typename Duration> class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> { public: using type = std::chrono::time_point<std::chrono::system_clock, Duration>; bool load(handle src, bool) { using namespace std::chrono; // Lazy initialise the PyDateTime import if (!PyDateTimeAPI) { PyDateTime_IMPORT; } if (!src) return false; std::tm cal; microseconds msecs; if (PyDateTime_Check(src.ptr())) { cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr()); cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr()); cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr()); cal.tm_mday = PyDateTime_GET_DAY(src.ptr()); cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1; cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900; cal.tm_isdst = -1; msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr())); } else if (PyDate_Check(src.ptr())) { cal.tm_sec = 0; cal.tm_min = 0; cal.tm_hour = 0; cal.tm_mday = PyDateTime_GET_DAY(src.ptr()); cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1; cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900; cal.tm_isdst = -1; msecs = microseconds(0); } else if (PyTime_Check(src.ptr())) { cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr()); cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr()); cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr()); cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70) cal.tm_mon = 0; // represents 1-Jan-1970, which is the first cal.tm_year = 70; // earliest available date for Python's datetime cal.tm_isdst = -1; msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr())); } else return false; value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs); return true; } static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src, return_value_policy /* policy */, handle /* parent */) { using namespace std::chrono; // Lazy initialise the PyDateTime import if (!PyDateTimeAPI) { PyDateTime_IMPORT; } // Get out microseconds, and make sure they are positive, to avoid bug in eastern hemisphere time zones // (cfr. https://github.com/pybind/pybind11/issues/2417) using us_t = duration<int, std::micro>; auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1)); if (us.count() < 0) us += seconds(1); // Subtract microseconds BEFORE `system_clock::to_time_t`, because: // > If std::time_t has lower precision, it is implementation-defined whether the value is rounded or truncated. // (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t) std::time_t tt = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us)); std::tm localtime; std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime); if (!localtime_ptr) throw cast_error("Unable to represent system_clock in local time"); return PyDateTime_FromDateAndTime(localtime.tm_year + 1900, localtime.tm_mon + 1, localtime.tm_mday, localtime.tm_hour, localtime.tm_min, localtime.tm_sec, us.count()); } PYBIND11_TYPE_CASTER(type, _("datetime.datetime")); }; // Other clocks that are not the system clock are not measured as datetime.datetime objects // since they are not measured on calendar time. So instead we just make them timedeltas // Or if they have passed us a time as a float we convert that template <typename Clock, typename Duration> class type_caster<std::chrono::time_point<Clock, Duration>> : public duration_caster<std::chrono::time_point<Clock, Duration>> { }; template <typename Rep, typename Period> class type_caster<std::chrono::duration<Rep, Period>> : public duration_caster<std::chrono::duration<Rep, Period>> { }; PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
8,674
C
39.537383
165
0.61229
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/complex.h
/* pybind11/complex.h: Complex number support Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "pybind11.h" #include <complex> /// glibc defines I as a macro which breaks things, e.g., boost template names #ifdef I # undef I #endif PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) template <typename T> struct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> { static constexpr const char c = format_descriptor<T>::c; static constexpr const char value[3] = { 'Z', c, '\0' }; static std::string format() { return std::string(value); } }; #ifndef PYBIND11_CPP17 template <typename T> constexpr const char format_descriptor< std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>>::value[3]; #endif PYBIND11_NAMESPACE_BEGIN(detail) template <typename T> struct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> { static constexpr bool value = true; static constexpr int index = is_fmt_numeric<T>::index + 3; }; template <typename T> class type_caster<std::complex<T>> { public: bool load(handle src, bool convert) { if (!src) return false; if (!convert && !PyComplex_Check(src.ptr())) return false; Py_complex result = PyComplex_AsCComplex(src.ptr()); if (result.real == -1.0 && PyErr_Occurred()) { PyErr_Clear(); return false; } value = std::complex<T>((T) result.real, (T) result.imag); return true; } static handle cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) { return PyComplex_FromDoubles((double) src.real(), (double) src.imag()); } PYBIND11_TYPE_CASTER(std::complex<T>, _("complex")); }; PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
2,037
C
29.878787
120
0.655866
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/attr.h
/* pybind11/attr.h: Infrastructure for processing custom type and function attributes Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "cast.h" PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) /// \addtogroup annotations /// @{ /// Annotation for methods struct is_method { handle class_; explicit is_method(const handle &c) : class_(c) {} }; /// Annotation for operators struct is_operator { }; /// Annotation for classes that cannot be subclassed struct is_final { }; /// Annotation for parent scope struct scope { handle value; explicit scope(const handle &s) : value(s) {} }; /// Annotation for documentation struct doc { const char *value; explicit doc(const char *value) : value(value) {} }; /// Annotation for function names struct name { const char *value; explicit name(const char *value) : value(value) {} }; /// Annotation indicating that a function is an overload associated with a given "sibling" struct sibling { handle value; explicit sibling(const handle &value) : value(value.ptr()) {} }; /// Annotation indicating that a class derives from another given type template <typename T> struct base { PYBIND11_DEPRECATED("base<T>() was deprecated in favor of specifying 'T' as a template argument to class_") base() { } // NOLINT(modernize-use-equals-default): breaks MSVC 2015 when adding an attribute }; /// Keep patient alive while nurse lives template <size_t Nurse, size_t Patient> struct keep_alive { }; /// Annotation indicating that a class is involved in a multiple inheritance relationship struct multiple_inheritance { }; /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class struct dynamic_attr { }; /// Annotation which enables the buffer protocol for a type struct buffer_protocol { }; /// Annotation which requests that a special metaclass is created for a type struct metaclass { handle value; PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.") // NOLINTNEXTLINE(modernize-use-equals-default): breaks MSVC 2015 when adding an attribute metaclass() {} /// Override pybind11's default metaclass explicit metaclass(handle value) : value(value) { } }; /// Annotation that marks a class as local to the module: struct module_local { const bool value; constexpr explicit module_local(bool v = true) : value(v) {} }; /// Annotation to mark enums as an arithmetic type struct arithmetic { }; /// Mark a function for addition at the beginning of the existing overload chain instead of the end struct prepend { }; /** \rst A call policy which places one or more guard variables (``Ts...``) around the function call. For example, this definition: .. code-block:: cpp m.def("foo", foo, py::call_guard<T>()); is equivalent to the following pseudocode: .. code-block:: cpp m.def("foo", [](args...) { T scope_guard; return foo(args...); // forwarded arguments }); \endrst */ template <typename... Ts> struct call_guard; template <> struct call_guard<> { using type = detail::void_type; }; template <typename T> struct call_guard<T> { static_assert(std::is_default_constructible<T>::value, "The guard type must be default constructible"); using type = T; }; template <typename T, typename... Ts> struct call_guard<T, Ts...> { struct type { T guard{}; // Compose multiple guard types with left-to-right default-constructor order typename call_guard<Ts...>::type next{}; }; }; /// @} annotations PYBIND11_NAMESPACE_BEGIN(detail) /* Forward declarations */ enum op_id : int; enum op_type : int; struct undefined_t; template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_; void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret); /// Internal data structure which holds metadata about a keyword argument struct argument_record { const char *name; ///< Argument name const char *descr; ///< Human-readable version of the argument value handle value; ///< Associated Python object bool convert : 1; ///< True if the argument is allowed to convert when loading bool none : 1; ///< True if None is allowed when loading argument_record(const char *name, const char *descr, handle value, bool convert, bool none) : name(name), descr(descr), value(value), convert(convert), none(none) { } }; /// Internal data structure which holds metadata about a bound function (signature, overloads, etc.) struct function_record { function_record() : is_constructor(false), is_new_style_constructor(false), is_stateless(false), is_operator(false), is_method(false), has_args(false), has_kwargs(false), has_kw_only_args(false), prepend(false) { } /// Function name char *name = nullptr; /* why no C++ strings? They generate heavier code.. */ // User-specified documentation string char *doc = nullptr; /// Human-readable version of the function signature char *signature = nullptr; /// List of registered keyword arguments std::vector<argument_record> args; /// Pointer to lambda function which converts arguments and performs the actual call handle (*impl) (function_call &) = nullptr; /// Storage for the wrapped function pointer and captured data, if any void *data[3] = { }; /// Pointer to custom destructor for 'data' (if needed) void (*free_data) (function_record *ptr) = nullptr; /// Return value policy associated with this function return_value_policy policy = return_value_policy::automatic; /// True if name == '__init__' bool is_constructor : 1; /// True if this is a new-style `__init__` defined in `detail/init.h` bool is_new_style_constructor : 1; /// True if this is a stateless function pointer bool is_stateless : 1; /// True if this is an operator (__add__), etc. bool is_operator : 1; /// True if this is a method bool is_method : 1; /// True if the function has a '*args' argument bool has_args : 1; /// True if the function has a '**kwargs' argument bool has_kwargs : 1; /// True once a 'py::kw_only' is encountered (any following args are keyword-only) bool has_kw_only_args : 1; /// True if this function is to be inserted at the beginning of the overload resolution chain bool prepend : 1; /// Number of arguments (including py::args and/or py::kwargs, if present) std::uint16_t nargs; /// Number of trailing arguments (counted in `nargs`) that are keyword-only std::uint16_t nargs_kw_only = 0; /// Number of leading arguments (counted in `nargs`) that are positional-only std::uint16_t nargs_pos_only = 0; /// Python method object PyMethodDef *def = nullptr; /// Python handle to the parent scope (a class or a module) handle scope; /// Python handle to the sibling function representing an overload chain handle sibling; /// Pointer to next overload function_record *next = nullptr; }; /// Special data structure which (temporarily) holds metadata about a bound class struct type_record { PYBIND11_NOINLINE type_record() : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false), default_holder(true), module_local(false), is_final(false) { } /// Handle to the parent scope handle scope; /// Name of the class const char *name = nullptr; // Pointer to RTTI type_info data structure const std::type_info *type = nullptr; /// How large is the underlying C++ type? size_t type_size = 0; /// What is the alignment of the underlying C++ type? size_t type_align = 0; /// How large is the type's holder? size_t holder_size = 0; /// The global operator new can be overridden with a class-specific variant void *(*operator_new)(size_t) = nullptr; /// Function pointer to class_<..>::init_instance void (*init_instance)(instance *, const void *) = nullptr; /// Function pointer to class_<..>::dealloc void (*dealloc)(detail::value_and_holder &) = nullptr; /// List of base classes of the newly created type list bases; /// Optional docstring const char *doc = nullptr; /// Custom metaclass (optional) handle metaclass; /// Multiple inheritance marker bool multiple_inheritance : 1; /// Does the class manage a __dict__? bool dynamic_attr : 1; /// Does the class implement the buffer protocol? bool buffer_protocol : 1; /// Is the default (unique_ptr) holder type used? bool default_holder : 1; /// Is the class definition local to the module shared object? bool module_local : 1; /// Is the class inheritable from python classes? bool is_final : 1; PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *)) { auto base_info = detail::get_type_info(base, false); if (!base_info) { std::string tname(base.name()); detail::clean_type_id(tname); pybind11_fail("generic_type: type \"" + std::string(name) + "\" referenced unknown base type \"" + tname + "\""); } if (default_holder != base_info->default_holder) { std::string tname(base.name()); detail::clean_type_id(tname); pybind11_fail("generic_type: type \"" + std::string(name) + "\" " + (default_holder ? "does not have" : "has") + " a non-default holder type while its base \"" + tname + "\" " + (base_info->default_holder ? "does not" : "does")); } bases.append((PyObject *) base_info->type); if (base_info->type->tp_dictoffset != 0) dynamic_attr = true; if (caster) base_info->implicit_casts.emplace_back(type, caster); } }; inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) { args.reserve(f.nargs); args_convert.reserve(f.nargs); } /// Tag for a new-style `__init__` defined in `detail/init.h` struct is_new_style_constructor { }; /** * Partial template specializations to process custom attributes provided to * cpp_function_ and class_. These are either used to initialize the respective * fields in the type_record and function_record data structures or executed at * runtime to deal with custom call policies (e.g. keep_alive). */ template <typename T, typename SFINAE = void> struct process_attribute; template <typename T> struct process_attribute_default { /// Default implementation: do nothing static void init(const T &, function_record *) { } static void init(const T &, type_record *) { } static void precall(function_call &) { } static void postcall(function_call &, handle) { } }; /// Process an attribute specifying the function's name template <> struct process_attribute<name> : process_attribute_default<name> { static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); } }; /// Process an attribute specifying the function's docstring template <> struct process_attribute<doc> : process_attribute_default<doc> { static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); } }; /// Process an attribute specifying the function's docstring (provided as a C-style string) template <> struct process_attribute<const char *> : process_attribute_default<const char *> { static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); } static void init(const char *d, type_record *r) { r->doc = const_cast<char *>(d); } }; template <> struct process_attribute<char *> : process_attribute<const char *> { }; /// Process an attribute indicating the function's return value policy template <> struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> { static void init(const return_value_policy &p, function_record *r) { r->policy = p; } }; /// Process an attribute which indicates that this is an overloaded function associated with a given sibling template <> struct process_attribute<sibling> : process_attribute_default<sibling> { static void init(const sibling &s, function_record *r) { r->sibling = s.value; } }; /// Process an attribute which indicates that this function is a method template <> struct process_attribute<is_method> : process_attribute_default<is_method> { static void init(const is_method &s, function_record *r) { r->is_method = true; r->scope = s.class_; } }; /// Process an attribute which indicates the parent scope of a method template <> struct process_attribute<scope> : process_attribute_default<scope> { static void init(const scope &s, function_record *r) { r->scope = s.value; } }; /// Process an attribute which indicates that this function is an operator template <> struct process_attribute<is_operator> : process_attribute_default<is_operator> { static void init(const is_operator &, function_record *r) { r->is_operator = true; } }; template <> struct process_attribute<is_new_style_constructor> : process_attribute_default<is_new_style_constructor> { static void init(const is_new_style_constructor &, function_record *r) { r->is_new_style_constructor = true; } }; inline void process_kw_only_arg(const arg &a, function_record *r) { if (!a.name || a.name[0] == '\0') pybind11_fail("arg(): cannot specify an unnamed argument after an kw_only() annotation"); ++r->nargs_kw_only; } /// Process a keyword argument attribute (*without* a default value) template <> struct process_attribute<arg> : process_attribute_default<arg> { static void init(const arg &a, function_record *r) { if (r->is_method && r->args.empty()) r->args.emplace_back("self", nullptr, handle(), true /*convert*/, false /*none not allowed*/); r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none); if (r->has_kw_only_args) process_kw_only_arg(a, r); } }; /// Process a keyword argument attribute (*with* a default value) template <> struct process_attribute<arg_v> : process_attribute_default<arg_v> { static void init(const arg_v &a, function_record *r) { if (r->is_method && r->args.empty()) r->args.emplace_back("self", nullptr /*descr*/, handle() /*parent*/, true /*convert*/, false /*none not allowed*/); if (!a.value) { #if !defined(NDEBUG) std::string descr("'"); if (a.name) descr += std::string(a.name) + ": "; descr += a.type + "'"; if (r->is_method) { if (r->name) descr += " in method '" + (std::string) str(r->scope) + "." + (std::string) r->name + "'"; else descr += " in method of '" + (std::string) str(r->scope) + "'"; } else if (r->name) { descr += " in function '" + (std::string) r->name + "'"; } pybind11_fail("arg(): could not convert default argument " + descr + " into a Python object (type not registered yet?)"); #else pybind11_fail("arg(): could not convert default argument " "into a Python object (type not registered yet?). " "Compile in debug mode for more information."); #endif } r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none); if (r->has_kw_only_args) process_kw_only_arg(a, r); } }; /// Process a keyword-only-arguments-follow pseudo argument template <> struct process_attribute<kw_only> : process_attribute_default<kw_only> { static void init(const kw_only &, function_record *r) { r->has_kw_only_args = true; } }; /// Process a positional-only-argument maker template <> struct process_attribute<pos_only> : process_attribute_default<pos_only> { static void init(const pos_only &, function_record *r) { r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size()); } }; /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees that) template <typename T> struct process_attribute<T, enable_if_t<is_pyobject<T>::value>> : process_attribute_default<handle> { static void init(const handle &h, type_record *r) { r->bases.append(h); } }; /// Process a parent class attribute (deprecated, does not support multiple inheritance) template <typename T> struct process_attribute<base<T>> : process_attribute_default<base<T>> { static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); } }; /// Process a multiple inheritance attribute template <> struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> { static void init(const multiple_inheritance &, type_record *r) { r->multiple_inheritance = true; } }; template <> struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> { static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; } }; template <> struct process_attribute<is_final> : process_attribute_default<is_final> { static void init(const is_final &, type_record *r) { r->is_final = true; } }; template <> struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> { static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; } }; template <> struct process_attribute<metaclass> : process_attribute_default<metaclass> { static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; } }; template <> struct process_attribute<module_local> : process_attribute_default<module_local> { static void init(const module_local &l, type_record *r) { r->module_local = l.value; } }; /// Process a 'prepend' attribute, putting this at the beginning of the overload chain template <> struct process_attribute<prepend> : process_attribute_default<prepend> { static void init(const prepend &, function_record *r) { r->prepend = true; } }; /// Process an 'arithmetic' attribute for enums (does nothing here) template <> struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {}; template <typename... Ts> struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> { }; /** * Process a keep_alive call policy -- invokes keep_alive_impl during the * pre-call handler if both Nurse, Patient != 0 and use the post-call handler * otherwise */ template <size_t Nurse, size_t Patient> struct process_attribute<keep_alive<Nurse, Patient>> : public process_attribute_default<keep_alive<Nurse, Patient>> { template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0> static void precall(function_call &call) { keep_alive_impl(Nurse, Patient, call, handle()); } template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0> static void postcall(function_call &, handle) { } template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0> static void precall(function_call &) { } template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0> static void postcall(function_call &call, handle ret) { keep_alive_impl(Nurse, Patient, call, ret); } }; /// Recursively iterate over variadic template arguments template <typename... Args> struct process_attributes { static void init(const Args&... args, function_record *r) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r); PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r); using expander = int[]; (void) expander{ 0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...}; } static void init(const Args&... args, type_record *r) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r); PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r); using expander = int[]; (void) expander{0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...}; } static void precall(function_call &call) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call); using expander = int[]; (void) expander{0, (process_attribute<typename std::decay<Args>::type>::precall(call), 0)...}; } static void postcall(function_call &call, handle fn_ret) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret); PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret); using expander = int[]; (void) expander{ 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...}; } }; template <typename T> using is_call_guard = is_instantiation<call_guard, T>; /// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found) template <typename... Extra> using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type; /// Check the number of named arguments at compile time template <typename... Extra, size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...), size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)> constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs); return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs; } PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
22,078
C
37.265165
157
0.658257
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/numpy.h
/* pybind11/numpy.h: Basic NumPy support, vectorize() wrapper Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "pybind11.h" #include "complex.h" #include <numeric> #include <algorithm> #include <array> #include <cstdint> #include <cstdlib> #include <cstring> #include <sstream> #include <string> #include <functional> #include <type_traits> #include <utility> #include <vector> #include <typeindex> /* This will be true on all flat address space platforms and allows us to reduce the whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size and dimension types (e.g. shape, strides, indexing), instead of inflicting this upon the library user. */ static_assert(sizeof(::pybind11::ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t"); static_assert(std::is_signed<Py_intptr_t>::value, "Py_intptr_t must be signed"); // We now can reinterpret_cast between py::ssize_t and Py_intptr_t (MSVC + PyPy cares) PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) class array; // Forward declaration PYBIND11_NAMESPACE_BEGIN(detail) template <> struct handle_type_name<array> { static constexpr auto name = _("numpy.ndarray"); }; template <typename type, typename SFINAE = void> struct npy_format_descriptor; struct PyArrayDescr_Proxy { PyObject_HEAD PyObject *typeobj; char kind; char type; char byteorder; char flags; int type_num; int elsize; int alignment; char *subarray; PyObject *fields; PyObject *names; }; struct PyArray_Proxy { PyObject_HEAD char *data; int nd; ssize_t *dimensions; ssize_t *strides; PyObject *base; PyObject *descr; int flags; }; struct PyVoidScalarObject_Proxy { PyObject_VAR_HEAD char *obval; PyArrayDescr_Proxy *descr; int flags; PyObject *base; }; struct numpy_type_info { PyObject* dtype_ptr; std::string format_str; }; struct numpy_internals { std::unordered_map<std::type_index, numpy_type_info> registered_dtypes; numpy_type_info *get_type_info(const std::type_info& tinfo, bool throw_if_missing = true) { auto it = registered_dtypes.find(std::type_index(tinfo)); if (it != registered_dtypes.end()) return &(it->second); if (throw_if_missing) pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name()); return nullptr; } template<typename T> numpy_type_info *get_type_info(bool throw_if_missing = true) { return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing); } }; PYBIND11_NOINLINE void load_numpy_internals(numpy_internals* &ptr) { ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals"); } inline numpy_internals& get_numpy_internals() { static numpy_internals* ptr = nullptr; if (!ptr) load_numpy_internals(ptr); return *ptr; } template <typename T> struct same_size { template <typename U> using as = bool_constant<sizeof(T) == sizeof(U)>; }; template <typename Concrete> constexpr int platform_lookup() { return -1; } // Lookup a type according to its size, and return a value corresponding to the NumPy typenum. template <typename Concrete, typename T, typename... Ts, typename... Ints> constexpr int platform_lookup(int I, Ints... Is) { return sizeof(Concrete) == sizeof(T) ? I : platform_lookup<Concrete, Ts...>(Is...); } struct npy_api { enum constants { NPY_ARRAY_C_CONTIGUOUS_ = 0x0001, NPY_ARRAY_F_CONTIGUOUS_ = 0x0002, NPY_ARRAY_OWNDATA_ = 0x0004, NPY_ARRAY_FORCECAST_ = 0x0010, NPY_ARRAY_ENSUREARRAY_ = 0x0040, NPY_ARRAY_ALIGNED_ = 0x0100, NPY_ARRAY_WRITEABLE_ = 0x0400, NPY_BOOL_ = 0, NPY_BYTE_, NPY_UBYTE_, NPY_SHORT_, NPY_USHORT_, NPY_INT_, NPY_UINT_, NPY_LONG_, NPY_ULONG_, NPY_LONGLONG_, NPY_ULONGLONG_, NPY_FLOAT_, NPY_DOUBLE_, NPY_LONGDOUBLE_, NPY_CFLOAT_, NPY_CDOUBLE_, NPY_CLONGDOUBLE_, NPY_OBJECT_ = 17, NPY_STRING_, NPY_UNICODE_, NPY_VOID_, // Platform-dependent normalization NPY_INT8_ = NPY_BYTE_, NPY_UINT8_ = NPY_UBYTE_, NPY_INT16_ = NPY_SHORT_, NPY_UINT16_ = NPY_USHORT_, // `npy_common.h` defines the integer aliases. In order, it checks: // NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR // and assigns the alias to the first matching size, so we should check in this order. NPY_INT32_ = platform_lookup<std::int32_t, long, int, short>( NPY_LONG_, NPY_INT_, NPY_SHORT_), NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>( NPY_ULONG_, NPY_UINT_, NPY_USHORT_), NPY_INT64_ = platform_lookup<std::int64_t, long, long long, int>( NPY_LONG_, NPY_LONGLONG_, NPY_INT_), NPY_UINT64_ = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>( NPY_ULONG_, NPY_ULONGLONG_, NPY_UINT_), }; struct PyArray_Dims { Py_intptr_t *ptr; int len; }; static npy_api& get() { static npy_api api = lookup(); return api; } bool PyArray_Check_(PyObject *obj) const { return (bool) PyObject_TypeCheck(obj, PyArray_Type_); } bool PyArrayDescr_Check_(PyObject *obj) const { return (bool) PyObject_TypeCheck(obj, PyArrayDescr_Type_); } unsigned int (*PyArray_GetNDArrayCFeatureVersion_)(); PyObject *(*PyArray_DescrFromType_)(int); PyObject *(*PyArray_NewFromDescr_) (PyTypeObject *, PyObject *, int, Py_intptr_t const *, Py_intptr_t const *, void *, int, PyObject *); // Unused. Not removed because that affects ABI of the class. PyObject *(*PyArray_DescrNewFromType_)(int); int (*PyArray_CopyInto_)(PyObject *, PyObject *); PyObject *(*PyArray_NewCopy_)(PyObject *, int); PyTypeObject *PyArray_Type_; PyTypeObject *PyVoidArrType_Type_; PyTypeObject *PyArrayDescr_Type_; PyObject *(*PyArray_DescrFromScalar_)(PyObject *); PyObject *(*PyArray_FromAny_) (PyObject *, PyObject *, int, int, int, PyObject *); int (*PyArray_DescrConverter_) (PyObject *, PyObject **); bool (*PyArray_EquivTypes_) (PyObject *, PyObject *); int (*PyArray_GetArrayParamsFromObject_)(PyObject *, PyObject *, unsigned char, PyObject **, int *, Py_intptr_t *, PyObject **, PyObject *); PyObject *(*PyArray_Squeeze_)(PyObject *); // Unused. Not removed because that affects ABI of the class. int (*PyArray_SetBaseObject_)(PyObject *, PyObject *); PyObject* (*PyArray_Resize_)(PyObject*, PyArray_Dims*, int, int); PyObject* (*PyArray_Newshape_)(PyObject*, PyArray_Dims*, int); PyObject* (*PyArray_View_)(PyObject*, PyObject*, PyObject*); private: enum functions { API_PyArray_GetNDArrayCFeatureVersion = 211, API_PyArray_Type = 2, API_PyArrayDescr_Type = 3, API_PyVoidArrType_Type = 39, API_PyArray_DescrFromType = 45, API_PyArray_DescrFromScalar = 57, API_PyArray_FromAny = 69, API_PyArray_Resize = 80, API_PyArray_CopyInto = 82, API_PyArray_NewCopy = 85, API_PyArray_NewFromDescr = 94, API_PyArray_DescrNewFromType = 96, API_PyArray_Newshape = 135, API_PyArray_Squeeze = 136, API_PyArray_View = 137, API_PyArray_DescrConverter = 174, API_PyArray_EquivTypes = 182, API_PyArray_GetArrayParamsFromObject = 278, API_PyArray_SetBaseObject = 282 }; static npy_api lookup() { module_ m = module_::import("numpy.core.multiarray"); auto c = m.attr("_ARRAY_API"); #if PY_MAJOR_VERSION >= 3 void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), NULL); #else void **api_ptr = (void **) PyCObject_AsVoidPtr(c.ptr()); #endif npy_api api; #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func]; DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion); if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7) pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0"); DECL_NPY_API(PyArray_Type); DECL_NPY_API(PyVoidArrType_Type); DECL_NPY_API(PyArrayDescr_Type); DECL_NPY_API(PyArray_DescrFromType); DECL_NPY_API(PyArray_DescrFromScalar); DECL_NPY_API(PyArray_FromAny); DECL_NPY_API(PyArray_Resize); DECL_NPY_API(PyArray_CopyInto); DECL_NPY_API(PyArray_NewCopy); DECL_NPY_API(PyArray_NewFromDescr); DECL_NPY_API(PyArray_DescrNewFromType); DECL_NPY_API(PyArray_Newshape); DECL_NPY_API(PyArray_Squeeze); DECL_NPY_API(PyArray_View); DECL_NPY_API(PyArray_DescrConverter); DECL_NPY_API(PyArray_EquivTypes); DECL_NPY_API(PyArray_GetArrayParamsFromObject); DECL_NPY_API(PyArray_SetBaseObject); #undef DECL_NPY_API return api; } }; inline PyArray_Proxy* array_proxy(void* ptr) { return reinterpret_cast<PyArray_Proxy*>(ptr); } inline const PyArray_Proxy* array_proxy(const void* ptr) { return reinterpret_cast<const PyArray_Proxy*>(ptr); } inline PyArrayDescr_Proxy* array_descriptor_proxy(PyObject* ptr) { return reinterpret_cast<PyArrayDescr_Proxy*>(ptr); } inline const PyArrayDescr_Proxy* array_descriptor_proxy(const PyObject* ptr) { return reinterpret_cast<const PyArrayDescr_Proxy*>(ptr); } inline bool check_flags(const void* ptr, int flag) { return (flag == (array_proxy(ptr)->flags & flag)); } template <typename T> struct is_std_array : std::false_type { }; template <typename T, size_t N> struct is_std_array<std::array<T, N>> : std::true_type { }; template <typename T> struct is_complex : std::false_type { }; template <typename T> struct is_complex<std::complex<T>> : std::true_type { }; template <typename T> struct array_info_scalar { using type = T; static constexpr bool is_array = false; static constexpr bool is_empty = false; static constexpr auto extents = _(""); static void append_extents(list& /* shape */) { } }; // Computes underlying type and a comma-separated list of extents for array // types (any mix of std::array and built-in arrays). An array of char is // treated as scalar because it gets special handling. template <typename T> struct array_info : array_info_scalar<T> { }; template <typename T, size_t N> struct array_info<std::array<T, N>> { using type = typename array_info<T>::type; static constexpr bool is_array = true; static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty; static constexpr size_t extent = N; // appends the extents to shape static void append_extents(list& shape) { shape.append(N); array_info<T>::append_extents(shape); } static constexpr auto extents = _<array_info<T>::is_array>( concat(_<N>(), array_info<T>::extents), _<N>() ); }; // For numpy we have special handling for arrays of characters, so we don't include // the size in the array extents. template <size_t N> struct array_info<char[N]> : array_info_scalar<char[N]> { }; template <size_t N> struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> { }; template <typename T, size_t N> struct array_info<T[N]> : array_info<std::array<T, N>> { }; template <typename T> using remove_all_extents_t = typename array_info<T>::type; template <typename T> using is_pod_struct = all_of< std::is_standard_layout<T>, // since we're accessing directly in memory we need a standard layout type #if defined(__GLIBCXX__) && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150426 || __GLIBCXX__ == 20150623 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803) // libstdc++ < 5 (including versions 4.8.5, 4.9.3 and 4.9.4 which were released after 5) // don't implement is_trivially_copyable, so approximate it std::is_trivially_destructible<T>, satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>, #else std::is_trivially_copyable<T>, #endif satisfies_none_of<T, std::is_reference, std::is_array, is_std_array, std::is_arithmetic, is_complex, std::is_enum> >; // Replacement for std::is_pod (deprecated in C++20) template <typename T> using is_pod = all_of< std::is_standard_layout<T>, std::is_trivial<T> >; template <ssize_t Dim = 0, typename Strides> ssize_t byte_offset_unsafe(const Strides &) { return 0; } template <ssize_t Dim = 0, typename Strides, typename... Ix> ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) { return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...); } /** * Proxy class providing unsafe, unchecked const access to array data. This is constructed through * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`. `Dims` * will be -1 for dimensions determined at runtime. */ template <typename T, ssize_t Dims> class unchecked_reference { protected: static constexpr bool Dynamic = Dims < 0; const unsigned char *data_; // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to // make large performance gains on big, nested loops, but requires compile-time dimensions conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>> shape_, strides_; const ssize_t dims_; friend class pybind11::array; // Constructor for compile-time dimensions: template <bool Dyn = Dynamic> unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<!Dyn, ssize_t>) : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} { for (size_t i = 0; i < (size_t) dims_; i++) { shape_[i] = shape[i]; strides_[i] = strides[i]; } } // Constructor for runtime dimensions: template <bool Dyn = Dynamic> unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<Dyn, ssize_t> dims) : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides}, dims_{dims} {} public: /** * Unchecked const reference access to data at the given indices. For a compile-time known * number of dimensions, this requires the correct number of arguments; for run-time * dimensionality, this is not checked (and so is up to the caller to use safely). */ template <typename... Ix> const T &operator()(Ix... index) const { static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic, "Invalid number of indices for unchecked array reference"); return *reinterpret_cast<const T *>(data_ + byte_offset_unsafe(strides_, ssize_t(index)...)); } /** * Unchecked const reference access to data; this operator only participates if the reference * is to a 1-dimensional array. When present, this is exactly equivalent to `obj(index)`. */ template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>> const T &operator[](ssize_t index) const { return operator()(index); } /// Pointer access to the data at the given indices. template <typename... Ix> const T *data(Ix... ix) const { return &operator()(ssize_t(ix)...); } /// Returns the item size, i.e. sizeof(T) constexpr static ssize_t itemsize() { return sizeof(T); } /// Returns the shape (i.e. size) of dimension `dim` ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; } /// Returns the number of dimensions of the array ssize_t ndim() const { return dims_; } /// Returns the total number of elements in the referenced array, i.e. the product of the shapes template <bool Dyn = Dynamic> enable_if_t<!Dyn, ssize_t> size() const { return std::accumulate(shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>()); } template <bool Dyn = Dynamic> enable_if_t<Dyn, ssize_t> size() const { return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>()); } /// Returns the total number of bytes used by the referenced data. Note that the actual span in /// memory may be larger if the referenced array has non-contiguous strides (e.g. for a slice). ssize_t nbytes() const { return size() * itemsize(); } }; template <typename T, ssize_t Dims> class unchecked_mutable_reference : public unchecked_reference<T, Dims> { friend class pybind11::array; using ConstBase = unchecked_reference<T, Dims>; using ConstBase::ConstBase; using ConstBase::Dynamic; public: // Bring in const-qualified versions from base class using ConstBase::operator(); using ConstBase::operator[]; /// Mutable, unchecked access to data at the given indices. template <typename... Ix> T& operator()(Ix... index) { static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic, "Invalid number of indices for unchecked array reference"); return const_cast<T &>(ConstBase::operator()(index...)); } /** * Mutable, unchecked access data at the given index; this operator only participates if the * reference is to a 1-dimensional array (or has runtime dimensions). When present, this is * exactly equivalent to `obj(index)`. */ template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>> T &operator[](ssize_t index) { return operator()(index); } /// Mutable pointer access to the data at the given indices. template <typename... Ix> T *mutable_data(Ix... ix) { return &operator()(ssize_t(ix)...); } }; template <typename T, ssize_t Dim> struct type_caster<unchecked_reference<T, Dim>> { static_assert(Dim == 0 && Dim > 0 /* always fail */, "unchecked array proxy object is not castable"); }; template <typename T, ssize_t Dim> struct type_caster<unchecked_mutable_reference<T, Dim>> : type_caster<unchecked_reference<T, Dim>> {}; PYBIND11_NAMESPACE_END(detail) class dtype : public object { public: PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_); explicit dtype(const buffer_info &info) { dtype descr(_dtype_from_pep3118()(PYBIND11_STR_TYPE(info.format))); // If info.itemsize == 0, use the value calculated from the format string m_ptr = descr.strip_padding(info.itemsize != 0 ? info.itemsize : descr.itemsize()) .release() .ptr(); } explicit dtype(const std::string &format) { m_ptr = from_args(pybind11::str(format)).release().ptr(); } explicit dtype(const char *format) : dtype(std::string(format)) {} dtype(list names, list formats, list offsets, ssize_t itemsize) { dict args; args["names"] = std::move(names); args["formats"] = std::move(formats); args["offsets"] = std::move(offsets); args["itemsize"] = pybind11::int_(itemsize); m_ptr = from_args(std::move(args)).release().ptr(); } /// This is essentially the same as calling numpy.dtype(args) in Python. static dtype from_args(object args) { PyObject *ptr = nullptr; if ((detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) == 0) || !ptr) throw error_already_set(); return reinterpret_steal<dtype>(ptr); } /// Return dtype associated with a C++ type. template <typename T> static dtype of() { return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype(); } /// Size of the data type in bytes. ssize_t itemsize() const { return detail::array_descriptor_proxy(m_ptr)->elsize; } /// Returns true for structured data types. bool has_fields() const { return detail::array_descriptor_proxy(m_ptr)->names != nullptr; } /// Single-character code for dtype's kind. /// For example, floating point types are 'f' and integral types are 'i'. char kind() const { return detail::array_descriptor_proxy(m_ptr)->kind; } /// Single-character for dtype's type. /// For example, ``float`` is 'f', ``double`` 'd', ``int`` 'i', and ``long`` 'd'. char char_() const { // Note: The signature, `dtype::char_` follows the naming of NumPy's // public Python API (i.e., ``dtype.char``), rather than its internal // C API (``PyArray_Descr::type``). return detail::array_descriptor_proxy(m_ptr)->type; } private: static object _dtype_from_pep3118() { static PyObject *obj = module_::import("numpy.core._internal") .attr("_dtype_from_pep3118").cast<object>().release().ptr(); return reinterpret_borrow<object>(obj); } dtype strip_padding(ssize_t itemsize) { // Recursively strip all void fields with empty names that are generated for // padding fields (as of NumPy v1.11). if (!has_fields()) return *this; struct field_descr { PYBIND11_STR_TYPE name; object format; pybind11::int_ offset; }; std::vector<field_descr> field_descriptors; for (auto field : attr("fields").attr("items")()) { auto spec = field.cast<tuple>(); auto name = spec[0].cast<pybind11::str>(); auto format = spec[1].cast<tuple>()[0].cast<dtype>(); auto offset = spec[1].cast<tuple>()[1].cast<pybind11::int_>(); if ((len(name) == 0u) && format.kind() == 'V') continue; field_descriptors.push_back({(PYBIND11_STR_TYPE) name, format.strip_padding(format.itemsize()), offset}); } std::sort(field_descriptors.begin(), field_descriptors.end(), [](const field_descr& a, const field_descr& b) { return a.offset.cast<int>() < b.offset.cast<int>(); }); list names, formats, offsets; for (auto& descr : field_descriptors) { names.append(descr.name); formats.append(descr.format); offsets.append(descr.offset); } return dtype(std::move(names), std::move(formats), std::move(offsets), itemsize); } }; class array : public buffer { public: PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array) enum { c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_, f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_, forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_ }; array() : array(0, static_cast<const double *>(nullptr)) {} using ShapeContainer = detail::any_container<ssize_t>; using StridesContainer = detail::any_container<ssize_t>; // Constructs an array taking shape/strides from arbitrary container types array(const pybind11::dtype &dt, ShapeContainer shape, StridesContainer strides, const void *ptr = nullptr, handle base = handle()) { if (strides->empty()) *strides = detail::c_strides(*shape, dt.itemsize()); auto ndim = shape->size(); if (ndim != strides->size()) pybind11_fail("NumPy: shape ndim doesn't match strides ndim"); auto descr = dt; int flags = 0; if (base && ptr) { if (isinstance<array>(base)) /* Copy flags from base (except ownership bit) */ flags = reinterpret_borrow<array>(base).flags() & ~detail::npy_api::NPY_ARRAY_OWNDATA_; else /* Writable by default, easy to downgrade later on if needed */ flags = detail::npy_api::NPY_ARRAY_WRITEABLE_; } auto &api = detail::npy_api::get(); auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_( api.PyArray_Type_, descr.release().ptr(), (int) ndim, // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1) reinterpret_cast<Py_intptr_t*>(shape->data()), reinterpret_cast<Py_intptr_t*>(strides->data()), const_cast<void *>(ptr), flags, nullptr)); if (!tmp) throw error_already_set(); if (ptr) { if (base) { api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr()); } else { tmp = reinterpret_steal<object>(api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */)); } } m_ptr = tmp.release().ptr(); } array(const pybind11::dtype &dt, ShapeContainer shape, const void *ptr = nullptr, handle base = handle()) : array(dt, std::move(shape), {}, ptr, base) { } template <typename T, typename = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>> array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle()) : array(dt, {{count}}, ptr, base) { } template <typename T> array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle()) : array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) { } template <typename T> array(ShapeContainer shape, const T *ptr, handle base = handle()) : array(std::move(shape), {}, ptr, base) { } template <typename T> explicit array(ssize_t count, const T *ptr, handle base = handle()) : array({count}, {}, ptr, base) { } explicit array(const buffer_info &info, handle base = handle()) : array(pybind11::dtype(info), info.shape, info.strides, info.ptr, base) { } /// Array descriptor (dtype) pybind11::dtype dtype() const { return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr); } /// Total number of elements ssize_t size() const { return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>()); } /// Byte size of a single element ssize_t itemsize() const { return detail::array_descriptor_proxy(detail::array_proxy(m_ptr)->descr)->elsize; } /// Total number of bytes ssize_t nbytes() const { return size() * itemsize(); } /// Number of dimensions ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; } /// Base object object base() const { return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base); } /// Dimensions of the array const ssize_t* shape() const { return detail::array_proxy(m_ptr)->dimensions; } /// Dimension along a given axis ssize_t shape(ssize_t dim) const { if (dim >= ndim()) fail_dim_check(dim, "invalid axis"); return shape()[dim]; } /// Strides of the array const ssize_t* strides() const { return detail::array_proxy(m_ptr)->strides; } /// Stride along a given axis ssize_t strides(ssize_t dim) const { if (dim >= ndim()) fail_dim_check(dim, "invalid axis"); return strides()[dim]; } /// Return the NumPy array flags int flags() const { return detail::array_proxy(m_ptr)->flags; } /// If set, the array is writeable (otherwise the buffer is read-only) bool writeable() const { return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_); } /// If set, the array owns the data (will be freed when the array is deleted) bool owndata() const { return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_); } /// Pointer to the contained data. If index is not provided, points to the /// beginning of the buffer. May throw if the index would lead to out of bounds access. template<typename... Ix> const void* data(Ix... index) const { return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...)); } /// Mutable pointer to the contained data. If index is not provided, points to the /// beginning of the buffer. May throw if the index would lead to out of bounds access. /// May throw if the array is not writeable. template<typename... Ix> void* mutable_data(Ix... index) { check_writeable(); return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...)); } /// Byte offset from beginning of the array to a given index (full or partial). /// May throw if the index would lead to out of bounds access. template<typename... Ix> ssize_t offset_at(Ix... index) const { if ((ssize_t) sizeof...(index) > ndim()) fail_dim_check(sizeof...(index), "too many indices for an array"); return byte_offset(ssize_t(index)...); } ssize_t offset_at() const { return 0; } /// Item count from beginning of the array to a given index (full or partial). /// May throw if the index would lead to out of bounds access. template<typename... Ix> ssize_t index_at(Ix... index) const { return offset_at(index...) / itemsize(); } /** * Returns a proxy object that provides access to the array's data without bounds or * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with * care: the array must not be destroyed or reshaped for the duration of the returned object, * and the caller must take care not to access invalid dimensions or dimension indices. */ template <typename T, ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & { if (PYBIND11_SILENCE_MSVC_C4127(Dims >= 0) && ndim() != Dims) throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) + "; expected " + std::to_string(Dims)); return detail::unchecked_mutable_reference<T, Dims>(mutable_data(), shape(), strides(), ndim()); } /** * Returns a proxy object that provides const access to the array's data without bounds or * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the * underlying array have the `writable` flag. Use with care: the array must not be destroyed or * reshaped for the duration of the returned object, and the caller must take care not to access * invalid dimensions or dimension indices. */ template <typename T, ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & { if (PYBIND11_SILENCE_MSVC_C4127(Dims >= 0) && ndim() != Dims) throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) + "; expected " + std::to_string(Dims)); return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim()); } /// Return a new view with all of the dimensions of length 1 removed array squeeze() { auto& api = detail::npy_api::get(); return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr)); } /// Resize array to given shape /// If refcheck is true and more that one reference exist to this array /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change void resize(ShapeContainer new_shape, bool refcheck = true) { detail::npy_api::PyArray_Dims d = { // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1) reinterpret_cast<Py_intptr_t*>(new_shape->data()), int(new_shape->size()) }; // try to resize, set ordering param to -1 cause it's not used anyway auto new_array = reinterpret_steal<object>( detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1) ); if (!new_array) throw error_already_set(); if (isinstance<array>(new_array)) { *this = std::move(new_array); } } /// Optional `order` parameter omitted, to be added as needed. array reshape(ShapeContainer new_shape) { detail::npy_api::PyArray_Dims d = {reinterpret_cast<Py_intptr_t *>(new_shape->data()), int(new_shape->size())}; auto new_array = reinterpret_steal<array>(detail::npy_api::get().PyArray_Newshape_(m_ptr, &d, 0)); if (!new_array) { throw error_already_set(); } return new_array; } /// Create a view of an array in a different data type. /// This function may fundamentally reinterpret the data in the array. /// It is the responsibility of the caller to ensure that this is safe. /// Only supports the `dtype` argument, the `type` argument is omitted, /// to be added as needed. array view(const std::string &dtype) { auto &api = detail::npy_api::get(); auto new_view = reinterpret_steal<array>(api.PyArray_View_( m_ptr, dtype::from_args(pybind11::str(dtype)).release().ptr(), nullptr)); if (!new_view) { throw error_already_set(); } return new_view; } /// Ensure that the argument is a NumPy array /// In case of an error, nullptr is returned and the Python error is cleared. static array ensure(handle h, int ExtraFlags = 0) { auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags)); if (!result) PyErr_Clear(); return result; } protected: template<typename, typename> friend struct detail::npy_format_descriptor; void fail_dim_check(ssize_t dim, const std::string& msg) const { throw index_error(msg + ": " + std::to_string(dim) + " (ndim = " + std::to_string(ndim()) + ")"); } template<typename... Ix> ssize_t byte_offset(Ix... index) const { check_dimensions(index...); return detail::byte_offset_unsafe(strides(), ssize_t(index)...); } void check_writeable() const { if (!writeable()) throw std::domain_error("array is not writeable"); } template<typename... Ix> void check_dimensions(Ix... index) const { check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...); } void check_dimensions_impl(ssize_t, const ssize_t*) const { } template<typename... Ix> void check_dimensions_impl(ssize_t axis, const ssize_t* shape, ssize_t i, Ix... index) const { if (i >= *shape) { throw index_error(std::string("index ") + std::to_string(i) + " is out of bounds for axis " + std::to_string(axis) + " with size " + std::to_string(*shape)); } check_dimensions_impl(axis + 1, shape + 1, index...); } /// Create array from any object -- always returns a new reference static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) { if (ptr == nullptr) { PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array from a nullptr"); return nullptr; } return detail::npy_api::get().PyArray_FromAny_( ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr); } }; template <typename T, int ExtraFlags = array::forcecast> class array_t : public array { private: struct private_ctor {}; // Delegating constructor needed when both moving and accessing in the same constructor array_t(private_ctor, ShapeContainer &&shape, StridesContainer &&strides, const T *ptr, handle base) : array(std::move(shape), std::move(strides), ptr, base) {} public: static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t"); using value_type = T; array_t() : array(0, static_cast<const T *>(nullptr)) {} array_t(handle h, borrowed_t) : array(h, borrowed_t{}) { } array_t(handle h, stolen_t) : array(h, stolen_t{}) { } PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead") array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) { if (!m_ptr) PyErr_Clear(); if (!is_borrowed) Py_XDECREF(h.ptr()); } // NOLINTNEXTLINE(google-explicit-constructor) array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) { if (!m_ptr) throw error_already_set(); } explicit array_t(const buffer_info& info, handle base = handle()) : array(info, base) { } array_t(ShapeContainer shape, StridesContainer strides, const T *ptr = nullptr, handle base = handle()) : array(std::move(shape), std::move(strides), ptr, base) { } explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle()) : array_t(private_ctor{}, std::move(shape), (ExtraFlags & f_style) != 0 ? detail::f_strides(*shape, itemsize()) : detail::c_strides(*shape, itemsize()), ptr, base) {} explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle()) : array({count}, {}, ptr, base) { } constexpr ssize_t itemsize() const { return sizeof(T); } template<typename... Ix> ssize_t index_at(Ix... index) const { return offset_at(index...) / itemsize(); } template<typename... Ix> const T* data(Ix... index) const { return static_cast<const T*>(array::data(index...)); } template<typename... Ix> T* mutable_data(Ix... index) { return static_cast<T*>(array::mutable_data(index...)); } // Reference to element at a given index template<typename... Ix> const T& at(Ix... index) const { if ((ssize_t) sizeof...(index) != ndim()) fail_dim_check(sizeof...(index), "index dimension mismatch"); return *(static_cast<const T*>(array::data()) + byte_offset(ssize_t(index)...) / itemsize()); } // Mutable reference to element at a given index template<typename... Ix> T& mutable_at(Ix... index) { if ((ssize_t) sizeof...(index) != ndim()) fail_dim_check(sizeof...(index), "index dimension mismatch"); return *(static_cast<T*>(array::mutable_data()) + byte_offset(ssize_t(index)...) / itemsize()); } /** * Returns a proxy object that provides access to the array's data without bounds or * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with * care: the array must not be destroyed or reshaped for the duration of the returned object, * and the caller must take care not to access invalid dimensions or dimension indices. */ template <ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & { return array::mutable_unchecked<T, Dims>(); } /** * Returns a proxy object that provides const access to the array's data without bounds or * dimensionality checking. Unlike `unchecked()`, this does not require that the underlying * array have the `writable` flag. Use with care: the array must not be destroyed or reshaped * for the duration of the returned object, and the caller must take care not to access invalid * dimensions or dimension indices. */ template <ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & { return array::unchecked<T, Dims>(); } /// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert /// it). In case of an error, nullptr is returned and the Python error is cleared. static array_t ensure(handle h) { auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr())); if (!result) PyErr_Clear(); return result; } static bool check_(handle h) { const auto &api = detail::npy_api::get(); return api.PyArray_Check_(h.ptr()) && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr, dtype::of<T>().ptr()) && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style)); } protected: /// Create array from any object -- always returns a new reference static PyObject *raw_array_t(PyObject *ptr) { if (ptr == nullptr) { PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr"); return nullptr; } return detail::npy_api::get().PyArray_FromAny_( ptr, dtype::of<T>().release().ptr(), 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr); } }; template <typename T> struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> { static std::string format() { return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::format(); } }; template <size_t N> struct format_descriptor<char[N]> { static std::string format() { return std::to_string(N) + "s"; } }; template <size_t N> struct format_descriptor<std::array<char, N>> { static std::string format() { return std::to_string(N) + "s"; } }; template <typename T> struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> { static std::string format() { return format_descriptor< typename std::remove_cv<typename std::underlying_type<T>::type>::type>::format(); } }; template <typename T> struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> { static std::string format() { using namespace detail; static constexpr auto extents = _("(") + array_info<T>::extents + _(")"); return extents.text + format_descriptor<remove_all_extents_t<T>>::format(); } }; PYBIND11_NAMESPACE_BEGIN(detail) template <typename T, int ExtraFlags> struct pyobject_caster<array_t<T, ExtraFlags>> { using type = array_t<T, ExtraFlags>; bool load(handle src, bool convert) { if (!convert && !type::check_(src)) return false; value = type::ensure(src); return static_cast<bool>(value); } static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) { return src.inc_ref(); } PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name); }; template <typename T> struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> { static bool compare(const buffer_info& b) { return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr()); } }; template <typename T, typename = void> struct npy_format_descriptor_name; template <typename T> struct npy_format_descriptor_name<T, enable_if_t<std::is_integral<T>::value>> { static constexpr auto name = _<std::is_same<T, bool>::value>( _("bool"), _<std::is_signed<T>::value>("numpy.int", "numpy.uint") + _<sizeof(T)*8>() ); }; template <typename T> struct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> { static constexpr auto name = _<std::is_same<T, float>::value || std::is_same<T, const float>::value || std::is_same<T, double>::value || std::is_same<T, const double>::value>( _("numpy.float") + _<sizeof(T)*8>(), _("numpy.longdouble") ); }; template <typename T> struct npy_format_descriptor_name<T, enable_if_t<is_complex<T>::value>> { static constexpr auto name = _<std::is_same<typename T::value_type, float>::value || std::is_same<typename T::value_type, const float>::value || std::is_same<typename T::value_type, double>::value || std::is_same<typename T::value_type, const double>::value>( _("numpy.complex") + _<sizeof(typename T::value_type)*16>(), _("numpy.longcomplex") ); }; template <typename T> struct npy_format_descriptor<T, enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>> : npy_format_descriptor_name<T> { private: // NB: the order here must match the one in common.h constexpr static const int values[15] = { npy_api::NPY_BOOL_, npy_api::NPY_BYTE_, npy_api::NPY_UBYTE_, npy_api::NPY_INT16_, npy_api::NPY_UINT16_, npy_api::NPY_INT32_, npy_api::NPY_UINT32_, npy_api::NPY_INT64_, npy_api::NPY_UINT64_, npy_api::NPY_FLOAT_, npy_api::NPY_DOUBLE_, npy_api::NPY_LONGDOUBLE_, npy_api::NPY_CFLOAT_, npy_api::NPY_CDOUBLE_, npy_api::NPY_CLONGDOUBLE_ }; public: static constexpr int value = values[detail::is_fmt_numeric<T>::index]; static pybind11::dtype dtype() { if (auto ptr = npy_api::get().PyArray_DescrFromType_(value)) return reinterpret_steal<pybind11::dtype>(ptr); pybind11_fail("Unsupported buffer format!"); } }; #define PYBIND11_DECL_CHAR_FMT \ static constexpr auto name = _("S") + _<N>(); \ static pybind11::dtype dtype() { return pybind11::dtype(std::string("S") + std::to_string(N)); } template <size_t N> struct npy_format_descriptor<char[N]> { PYBIND11_DECL_CHAR_FMT }; template <size_t N> struct npy_format_descriptor<std::array<char, N>> { PYBIND11_DECL_CHAR_FMT }; #undef PYBIND11_DECL_CHAR_FMT template<typename T> struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> { private: using base_descr = npy_format_descriptor<typename array_info<T>::type>; public: static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported"); static constexpr auto name = _("(") + array_info<T>::extents + _(")") + base_descr::name; static pybind11::dtype dtype() { list shape; array_info<T>::append_extents(shape); return pybind11::dtype::from_args(pybind11::make_tuple(base_descr::dtype(), shape)); } }; template<typename T> struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> { private: using base_descr = npy_format_descriptor<typename std::underlying_type<T>::type>; public: static constexpr auto name = base_descr::name; static pybind11::dtype dtype() { return base_descr::dtype(); } }; struct field_descriptor { const char *name; ssize_t offset; ssize_t size; std::string format; dtype descr; }; PYBIND11_NOINLINE void register_structured_dtype( any_container<field_descriptor> fields, const std::type_info& tinfo, ssize_t itemsize, bool (*direct_converter)(PyObject *, void *&)) { auto& numpy_internals = get_numpy_internals(); if (numpy_internals.get_type_info(tinfo, false)) pybind11_fail("NumPy: dtype is already registered"); // Use ordered fields because order matters as of NumPy 1.14: // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays std::vector<field_descriptor> ordered_fields(std::move(fields)); std::sort(ordered_fields.begin(), ordered_fields.end(), [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; }); list names, formats, offsets; for (auto& field : ordered_fields) { if (!field.descr) pybind11_fail(std::string("NumPy: unsupported field dtype: `") + field.name + "` @ " + tinfo.name()); names.append(PYBIND11_STR_TYPE(field.name)); formats.append(field.descr); offsets.append(pybind11::int_(field.offset)); } auto dtype_ptr = pybind11::dtype(std::move(names), std::move(formats), std::move(offsets), itemsize) .release() .ptr(); // There is an existing bug in NumPy (as of v1.11): trailing bytes are // not encoded explicitly into the format string. This will supposedly // get fixed in v1.12; for further details, see these: // - https://github.com/numpy/numpy/issues/7797 // - https://github.com/numpy/numpy/pull/7798 // Because of this, we won't use numpy's logic to generate buffer format // strings and will just do it ourselves. ssize_t offset = 0; std::ostringstream oss; // mark the structure as unaligned with '^', because numpy and C++ don't // always agree about alignment (particularly for complex), and we're // explicitly listing all our padding. This depends on none of the fields // overriding the endianness. Putting the ^ in front of individual fields // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049 oss << "^T{"; for (auto& field : ordered_fields) { if (field.offset > offset) oss << (field.offset - offset) << 'x'; oss << field.format << ':' << field.name << ':'; offset = field.offset + field.size; } if (itemsize > offset) oss << (itemsize - offset) << 'x'; oss << '}'; auto format_str = oss.str(); // Sanity check: verify that NumPy properly parses our buffer format string auto& api = npy_api::get(); auto arr = array(buffer_info(nullptr, itemsize, format_str, 1)); if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr())) pybind11_fail("NumPy: invalid buffer descriptor!"); auto tindex = std::type_index(tinfo); numpy_internals.registered_dtypes[tindex] = { dtype_ptr, format_str }; get_internals().direct_conversions[tindex].push_back(direct_converter); } template <typename T, typename SFINAE> struct npy_format_descriptor { static_assert(is_pod_struct<T>::value, "Attempt to use a non-POD or unimplemented POD type as a numpy dtype"); static constexpr auto name = make_caster<T>::name; static pybind11::dtype dtype() { return reinterpret_borrow<pybind11::dtype>(dtype_ptr()); } static std::string format() { static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str; return format_str; } static void register_dtype(any_container<field_descriptor> fields) { register_structured_dtype(std::move(fields), typeid(typename std::remove_cv<T>::type), sizeof(T), &direct_converter); } private: static PyObject* dtype_ptr() { static PyObject* ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr; return ptr; } static bool direct_converter(PyObject *obj, void*& value) { auto& api = npy_api::get(); if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_)) return false; if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) { if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) { value = ((PyVoidScalarObject_Proxy *) obj)->obval; return true; } } return false; } }; #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code) # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void)0) # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void)0) #else #define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \ ::pybind11::detail::field_descriptor { \ Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \ ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \ ::pybind11::detail::npy_format_descriptor<decltype(std::declval<T>().Field)>::dtype() \ } // Extract name, offset and format descriptor for a struct field #define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field) // The main idea of this macro is borrowed from https://github.com/swansontec/map-macro // (C) William Swanson, Paul Fultz #define PYBIND11_EVAL0(...) __VA_ARGS__ #define PYBIND11_EVAL1(...) PYBIND11_EVAL0 (PYBIND11_EVAL0 (PYBIND11_EVAL0 (__VA_ARGS__))) #define PYBIND11_EVAL2(...) PYBIND11_EVAL1 (PYBIND11_EVAL1 (PYBIND11_EVAL1 (__VA_ARGS__))) #define PYBIND11_EVAL3(...) PYBIND11_EVAL2 (PYBIND11_EVAL2 (PYBIND11_EVAL2 (__VA_ARGS__))) #define PYBIND11_EVAL4(...) PYBIND11_EVAL3 (PYBIND11_EVAL3 (PYBIND11_EVAL3 (__VA_ARGS__))) #define PYBIND11_EVAL(...) PYBIND11_EVAL4 (PYBIND11_EVAL4 (PYBIND11_EVAL4 (__VA_ARGS__))) #define PYBIND11_MAP_END(...) #define PYBIND11_MAP_OUT #define PYBIND11_MAP_COMMA , #define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END #define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT #define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0 (test, next, 0) #define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1 (PYBIND11_MAP_GET_END test, next) #if defined(_MSC_VER) && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround #define PYBIND11_MAP_LIST_NEXT1(test, next) \ PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)) #else #define PYBIND11_MAP_LIST_NEXT1(test, next) \ PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0) #endif #define PYBIND11_MAP_LIST_NEXT(test, next) \ PYBIND11_MAP_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next) #define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \ f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST1) (f, t, peek, __VA_ARGS__) #define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \ f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST0) (f, t, peek, __VA_ARGS__) // PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ... #define PYBIND11_MAP_LIST(f, t, ...) \ PYBIND11_EVAL (PYBIND11_MAP_LIST1 (f, t, __VA_ARGS__, (), 0)) #define PYBIND11_NUMPY_DTYPE(Type, ...) \ ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \ (::std::vector<::pybind11::detail::field_descriptor> \ {PYBIND11_MAP_LIST (PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)}) #if defined(_MSC_VER) && !defined(__clang__) #define PYBIND11_MAP2_LIST_NEXT1(test, next) \ PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)) #else #define PYBIND11_MAP2_LIST_NEXT1(test, next) \ PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0) #endif #define PYBIND11_MAP2_LIST_NEXT(test, next) \ PYBIND11_MAP2_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next) #define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \ f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST1) (f, t, peek, __VA_ARGS__) #define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \ f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST0) (f, t, peek, __VA_ARGS__) // PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ... #define PYBIND11_MAP2_LIST(f, t, ...) \ PYBIND11_EVAL (PYBIND11_MAP2_LIST1 (f, t, __VA_ARGS__, (), 0)) #define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \ ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \ (::std::vector<::pybind11::detail::field_descriptor> \ {PYBIND11_MAP2_LIST (PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)}) #endif // __CLION_IDE__ class common_iterator { public: using container_type = std::vector<ssize_t>; using value_type = container_type::value_type; using size_type = container_type::size_type; common_iterator() : m_strides() {} common_iterator(void* ptr, const container_type& strides, const container_type& shape) : p_ptr(reinterpret_cast<char*>(ptr)), m_strides(strides.size()) { m_strides.back() = static_cast<value_type>(strides.back()); for (size_type i = m_strides.size() - 1; i != 0; --i) { size_type j = i - 1; auto s = static_cast<value_type>(shape[i]); m_strides[j] = strides[j] + m_strides[i] - strides[i] * s; } } void increment(size_type dim) { p_ptr += m_strides[dim]; } void* data() const { return p_ptr; } private: char *p_ptr{0}; container_type m_strides; }; template <size_t N> class multi_array_iterator { public: using container_type = std::vector<ssize_t>; multi_array_iterator(const std::array<buffer_info, N> &buffers, const container_type &shape) : m_shape(shape.size()), m_index(shape.size(), 0), m_common_iterator() { // Manual copy to avoid conversion warning if using std::copy for (size_t i = 0; i < shape.size(); ++i) m_shape[i] = shape[i]; container_type strides(shape.size()); for (size_t i = 0; i < N; ++i) init_common_iterator(buffers[i], shape, m_common_iterator[i], strides); } multi_array_iterator& operator++() { for (size_t j = m_index.size(); j != 0; --j) { size_t i = j - 1; if (++m_index[i] != m_shape[i]) { increment_common_iterator(i); break; } m_index[i] = 0; } return *this; } template <size_t K, class T = void> T* data() const { return reinterpret_cast<T*>(m_common_iterator[K].data()); } private: using common_iter = common_iterator; void init_common_iterator(const buffer_info &buffer, const container_type &shape, common_iter &iterator, container_type &strides) { auto buffer_shape_iter = buffer.shape.rbegin(); auto buffer_strides_iter = buffer.strides.rbegin(); auto shape_iter = shape.rbegin(); auto strides_iter = strides.rbegin(); while (buffer_shape_iter != buffer.shape.rend()) { if (*shape_iter == *buffer_shape_iter) *strides_iter = *buffer_strides_iter; else *strides_iter = 0; ++buffer_shape_iter; ++buffer_strides_iter; ++shape_iter; ++strides_iter; } std::fill(strides_iter, strides.rend(), 0); iterator = common_iter(buffer.ptr, strides, shape); } void increment_common_iterator(size_t dim) { for (auto &iter : m_common_iterator) iter.increment(dim); } container_type m_shape; container_type m_index; std::array<common_iter, N> m_common_iterator; }; enum class broadcast_trivial { non_trivial, c_trivial, f_trivial }; // Populates the shape and number of dimensions for the set of buffers. Returns a broadcast_trivial // enum value indicating whether the broadcast is "trivial"--that is, has each buffer being either a // singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous (`f_trivial`) storage // buffer; returns `non_trivial` otherwise. template <size_t N> broadcast_trivial broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) { ndim = std::accumulate(buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) { return std::max(res, buf.ndim); }); shape.clear(); shape.resize((size_t) ndim, 1); // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1 or // the full size). for (size_t i = 0; i < N; ++i) { auto res_iter = shape.rbegin(); auto end = buffers[i].shape.rend(); for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end; ++shape_iter, ++res_iter) { const auto &dim_size_in = *shape_iter; auto &dim_size_out = *res_iter; // Each input dimension can either be 1 or `n`, but `n` values must match across buffers if (dim_size_out == 1) dim_size_out = dim_size_in; else if (dim_size_in != 1 && dim_size_in != dim_size_out) pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!"); } } bool trivial_broadcast_c = true; bool trivial_broadcast_f = true; for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) { if (buffers[i].size == 1) continue; // Require the same number of dimensions: if (buffers[i].ndim != ndim) return broadcast_trivial::non_trivial; // Require all dimensions be full-size: if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin())) return broadcast_trivial::non_trivial; // Check for C contiguity (but only if previous inputs were also C contiguous) if (trivial_broadcast_c) { ssize_t expect_stride = buffers[i].itemsize; auto end = buffers[i].shape.crend(); for (auto shape_iter = buffers[i].shape.crbegin(), stride_iter = buffers[i].strides.crbegin(); trivial_broadcast_c && shape_iter != end; ++shape_iter, ++stride_iter) { if (expect_stride == *stride_iter) expect_stride *= *shape_iter; else trivial_broadcast_c = false; } } // Check for Fortran contiguity (if previous inputs were also F contiguous) if (trivial_broadcast_f) { ssize_t expect_stride = buffers[i].itemsize; auto end = buffers[i].shape.cend(); for (auto shape_iter = buffers[i].shape.cbegin(), stride_iter = buffers[i].strides.cbegin(); trivial_broadcast_f && shape_iter != end; ++shape_iter, ++stride_iter) { if (expect_stride == *stride_iter) expect_stride *= *shape_iter; else trivial_broadcast_f = false; } } } return trivial_broadcast_c ? broadcast_trivial::c_trivial : trivial_broadcast_f ? broadcast_trivial::f_trivial : broadcast_trivial::non_trivial; } template <typename T> struct vectorize_arg { static_assert(!std::is_rvalue_reference<T>::value, "Functions with rvalue reference arguments cannot be vectorized"); // The wrapped function gets called with this type: using call_type = remove_reference_t<T>; // Is this a vectorized argument? static constexpr bool vectorize = satisfies_any_of<call_type, std::is_arithmetic, is_complex, is_pod>::value && satisfies_none_of<call_type, std::is_pointer, std::is_array, is_std_array, std::is_enum>::value && (!std::is_reference<T>::value || (std::is_lvalue_reference<T>::value && std::is_const<call_type>::value)); // Accept this type: an array for vectorized types, otherwise the type as-is: using type = conditional_t<vectorize, array_t<remove_cv_t<call_type>, array::forcecast>, T>; }; // py::vectorize when a return type is present template <typename Func, typename Return, typename... Args> struct vectorize_returned_array { using Type = array_t<Return>; static Type create(broadcast_trivial trivial, const std::vector<ssize_t> &shape) { if (trivial == broadcast_trivial::f_trivial) return array_t<Return, array::f_style>(shape); return array_t<Return>(shape); } static Return *mutable_data(Type &array) { return array.mutable_data(); } static Return call(Func &f, Args &... args) { return f(args...); } static void call(Return *out, size_t i, Func &f, Args &... args) { out[i] = f(args...); } }; // py::vectorize when a return type is not present template <typename Func, typename... Args> struct vectorize_returned_array<Func, void, Args...> { using Type = none; static Type create(broadcast_trivial, const std::vector<ssize_t> &) { return none(); } static void *mutable_data(Type &) { return nullptr; } static detail::void_type call(Func &f, Args &... args) { f(args...); return {}; } static void call(void *, size_t, Func &f, Args &... args) { f(args...); } }; template <typename Func, typename Return, typename... Args> struct vectorize_helper { // NVCC for some reason breaks if NVectorized is private #ifdef __CUDACC__ public: #else private: #endif static constexpr size_t N = sizeof...(Args); static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...); static_assert(NVectorized >= 1, "pybind11::vectorize(...) requires a function with at least one vectorizable argument"); public: template <typename T, // SFINAE to prevent shadowing the copy constructor. typename = detail::enable_if_t< !std::is_same<vectorize_helper, typename std::decay<T>::type>::value>> explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) {} object operator()(typename vectorize_arg<Args>::type... args) { return run(args..., make_index_sequence<N>(), select_indices<vectorize_arg<Args>::vectorize...>(), make_index_sequence<NVectorized>()); } private: remove_reference_t<Func> f; // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling with "/permissive-" flag // when arg_call_types is manually inlined. using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>; template <size_t Index> using param_n_t = typename std::tuple_element<Index, arg_call_types>::type; using returned_array = vectorize_returned_array<Func, Return, Args...>; // Runs a vectorized function given arguments tuple and three index sequences: // - Index is the full set of 0 ... (N-1) argument indices; // - VIndex is the subset of argument indices with vectorized parameters, letting us access // vectorized arguments (anything not in this sequence is passed through) // - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that // we can store vectorized buffer_infos in an array (argument VIndex has its buffer at // index BIndex in the array). template <size_t... Index, size_t... VIndex, size_t... BIndex> object run( typename vectorize_arg<Args>::type &...args, index_sequence<Index...> i_seq, index_sequence<VIndex...> vi_seq, index_sequence<BIndex...> bi_seq) { // Pointers to values the function was called with; the vectorized ones set here will start // out as array_t<T> pointers, but they will be changed them to T pointers before we make // call the wrapped function. Non-vectorized pointers are left as-is. std::array<void *, N> params{{ &args... }}; // The array of `buffer_info`s of vectorized arguments: std::array<buffer_info, NVectorized> buffers{{ reinterpret_cast<array *>(params[VIndex])->request()... }}; /* Determine dimensions parameters of output array */ ssize_t nd = 0; std::vector<ssize_t> shape(0); auto trivial = broadcast(buffers, nd, shape); auto ndim = (size_t) nd; size_t size = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>()); // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e. // not wrapped in an array). if (size == 1 && ndim == 0) { PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr); return cast(returned_array::call(f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...)); } auto result = returned_array::create(trivial, shape); if (size == 0) return std::move(result); /* Call the function */ auto mutable_data = returned_array::mutable_data(result); if (trivial == broadcast_trivial::non_trivial) apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq); else apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq); return std::move(result); } template <size_t... Index, size_t... VIndex, size_t... BIndex> void apply_trivial(std::array<buffer_info, NVectorized> &buffers, std::array<void *, N> &params, Return *out, size_t size, index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) { // Initialize an array of mutable byte references and sizes with references set to the // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size // (except for singletons, which get an increment of 0). std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{{ std::pair<unsigned char *&, const size_t>( reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr), buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>) )... }}; for (size_t i = 0; i < size; ++i) { returned_array::call(out, i, f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...); for (auto &x : vecparams) x.first += x.second; } } template <size_t... Index, size_t... VIndex, size_t... BIndex> void apply_broadcast(std::array<buffer_info, NVectorized> &buffers, std::array<void *, N> &params, Return *out, size_t size, const std::vector<ssize_t> &output_shape, index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) { multi_array_iterator<NVectorized> input_iter(buffers, output_shape); for (size_t i = 0; i < size; ++i, ++input_iter) { PYBIND11_EXPAND_SIDE_EFFECTS(( params[VIndex] = input_iter.template data<BIndex>() )); returned_array::call(out, i, f, *reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...); } } }; template <typename Func, typename Return, typename... Args> vectorize_helper<Func, Return, Args...> vectorize_extractor(const Func &f, Return (*) (Args ...)) { return detail::vectorize_helper<Func, Return, Args...>(f); } template <typename T, int Flags> struct handle_type_name<array_t<T, Flags>> { static constexpr auto name = _("numpy.ndarray[") + npy_format_descriptor<T>::name + _("]"); }; PYBIND11_NAMESPACE_END(detail) // Vanilla pointer vectorizer: template <typename Return, typename... Args> detail::vectorize_helper<Return (*)(Args...), Return, Args...> vectorize(Return (*f) (Args ...)) { return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f); } // lambda vectorizer: template <typename Func, detail::enable_if_t<detail::is_lambda<Func>::value, int> = 0> auto vectorize(Func &&f) -> decltype( detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr)) { return detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr); } // Vectorize a class method (non-const): template <typename Return, typename Class, typename... Args, typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())), Return, Class *, Args...>> Helper vectorize(Return (Class::*f)(Args...)) { return Helper(std::mem_fn(f)); } // Vectorize a class method (const): template <typename Return, typename Class, typename... Args, typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())), Return, const Class *, Args...>> Helper vectorize(Return (Class::*f)(Args...) const) { return Helper(std::mem_fn(f)); } PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
71,895
C
40.272101
160
0.619292
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/cast.h
/* pybind11/cast.h: Partial template specializations to cast between C++ and Python types Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "pytypes.h" #include "detail/common.h" #include "detail/descr.h" #include "detail/type_caster_base.h" #include "detail/typeid.h" #include <array> #include <cstring> #include <functional> #include <iosfwd> #include <iterator> #include <memory> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #if defined(PYBIND11_CPP17) # if defined(__has_include) # if __has_include(<string_view>) # define PYBIND11_HAS_STRING_VIEW # endif # elif defined(_MSC_VER) # define PYBIND11_HAS_STRING_VIEW # endif #endif #ifdef PYBIND11_HAS_STRING_VIEW #include <string_view> #endif #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L # define PYBIND11_HAS_U8STRING #endif PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) template <typename type, typename SFINAE = void> class type_caster : public type_caster_base<type> { }; template <typename type> using make_caster = type_caster<intrinsic_t<type>>; // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T template <typename T> typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) { return caster.operator typename make_caster<T>::template cast_op_type<T>(); } template <typename T> typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type> cast_op(make_caster<T> &&caster) { return std::move(caster).operator typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>(); } template <typename type> class type_caster<std::reference_wrapper<type>> { private: using caster_t = make_caster<type>; caster_t subcaster; using reference_t = type&; using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>; static_assert(std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value || std::is_same<reference_t, subcaster_cast_op_type>::value, "std::reference_wrapper<T> caster requires T to have a caster with an " "`operator T &()` or `operator const T &()`"); public: bool load(handle src, bool convert) { return subcaster.load(src, convert); } static constexpr auto name = caster_t::name; static handle cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) { // It is definitely wrong to take ownership of this pointer, so mask that rvp if (policy == return_value_policy::take_ownership || policy == return_value_policy::automatic) policy = return_value_policy::automatic_reference; return caster_t::cast(&src.get(), policy, parent); } template <typename T> using cast_op_type = std::reference_wrapper<type>; explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); } }; #define PYBIND11_TYPE_CASTER(type, py_name) \ protected: \ type value; \ \ public: \ static constexpr auto name = py_name; \ template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0> \ static handle cast(T_ *src, return_value_policy policy, handle parent) { \ if (!src) \ return none().release(); \ if (policy == return_value_policy::take_ownership) { \ auto h = cast(std::move(*src), policy, parent); \ delete src; \ return h; \ } \ return cast(*src, policy, parent); \ } \ operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \ operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \ operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \ template <typename T_> \ using cast_op_type = pybind11::detail::movable_cast_op_type<T_> template <typename CharT> using is_std_char_type = any_of< std::is_same<CharT, char>, /* std::string */ #if defined(PYBIND11_HAS_U8STRING) std::is_same<CharT, char8_t>, /* std::u8string */ #endif std::is_same<CharT, char16_t>, /* std::u16string */ std::is_same<CharT, char32_t>, /* std::u32string */ std::is_same<CharT, wchar_t> /* std::wstring */ >; template <typename T> struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> { using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>; using _py_type_1 = conditional_t<std::is_signed<T>::value, _py_type_0, typename std::make_unsigned<_py_type_0>::type>; using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>; public: bool load(handle src, bool convert) { py_type py_value; if (!src) return false; #if !defined(PYPY_VERSION) auto index_check = [](PyObject *o) { return PyIndex_Check(o); }; #else // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`, // while CPython only considers the existence of `nb_index`/`__index__`. auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); }; #endif if (std::is_floating_point<T>::value) { if (convert || PyFloat_Check(src.ptr())) py_value = (py_type) PyFloat_AsDouble(src.ptr()); else return false; } else if (PyFloat_Check(src.ptr()) || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) { return false; } else { handle src_or_index = src; #if PY_VERSION_HEX < 0x03080000 object index; if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr()) index = reinterpret_steal<object>(PyNumber_Index(src.ptr())); if (!index) { PyErr_Clear(); if (!convert) return false; } else { src_or_index = index; } } #endif if (std::is_unsigned<py_type>::value) { py_value = as_unsigned<py_type>(src_or_index.ptr()); } else { // signed integer: py_value = sizeof(T) <= sizeof(long) ? (py_type) PyLong_AsLong(src_or_index.ptr()) : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr()); } } // Python API reported an error bool py_err = py_value == (py_type) -1 && PyErr_Occurred(); // Check to see if the conversion is valid (integers should match exactly) // Signed/unsigned checks happen elsewhere if (py_err || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T) && py_value != (py_type) (T) py_value)) { PyErr_Clear(); if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) { auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value ? PyNumber_Float(src.ptr()) : PyNumber_Long(src.ptr())); PyErr_Clear(); return load(tmp, false); } return false; } value = (T) py_value; return true; } template<typename U = T> static typename std::enable_if<std::is_floating_point<U>::value, handle>::type cast(U src, return_value_policy /* policy */, handle /* parent */) { return PyFloat_FromDouble((double) src); } template<typename U = T> static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) <= sizeof(long)), handle>::type cast(U src, return_value_policy /* policy */, handle /* parent */) { return PYBIND11_LONG_FROM_SIGNED((long) src); } template<typename U = T> static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) <= sizeof(unsigned long)), handle>::type cast(U src, return_value_policy /* policy */, handle /* parent */) { return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src); } template<typename U = T> static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) > sizeof(long)), handle>::type cast(U src, return_value_policy /* policy */, handle /* parent */) { return PyLong_FromLongLong((long long) src); } template<typename U = T> static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) > sizeof(unsigned long)), handle>::type cast(U src, return_value_policy /* policy */, handle /* parent */) { return PyLong_FromUnsignedLongLong((unsigned long long) src); } PYBIND11_TYPE_CASTER(T, _<std::is_integral<T>::value>("int", "float")); }; template<typename T> struct void_caster { public: bool load(handle src, bool) { if (src && src.is_none()) return true; return false; } static handle cast(T, return_value_policy /* policy */, handle /* parent */) { return none().inc_ref(); } PYBIND11_TYPE_CASTER(T, _("None")); }; template <> class type_caster<void_type> : public void_caster<void_type> {}; template <> class type_caster<void> : public type_caster<void_type> { public: using type_caster<void_type>::cast; bool load(handle h, bool) { if (!h) { return false; } if (h.is_none()) { value = nullptr; return true; } /* Check if this is a capsule */ if (isinstance<capsule>(h)) { value = reinterpret_borrow<capsule>(h); return true; } /* Check if this is a C++ type */ auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr()); if (bases.size() == 1) { // Only allowing loading from a single-value type value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr(); return true; } /* Fail */ return false; } static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) { if (ptr) return capsule(ptr).release(); return none().inc_ref(); } template <typename T> using cast_op_type = void*&; explicit operator void *&() { return value; } static constexpr auto name = _("capsule"); private: void *value = nullptr; }; template <> class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> { }; template <> class type_caster<bool> { public: bool load(handle src, bool convert) { if (!src) return false; if (src.ptr() == Py_True) { value = true; return true; } if (src.ptr() == Py_False) { value = false; return true; } if (convert || (std::strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name) == 0)) { // (allow non-implicit conversion for numpy booleans) Py_ssize_t res = -1; if (src.is_none()) { res = 0; // None is implicitly converted to False } #if defined(PYPY_VERSION) // On PyPy, check that "__bool__" (or "__nonzero__" on Python 2.7) attr exists else if (hasattr(src, PYBIND11_BOOL_ATTR)) { res = PyObject_IsTrue(src.ptr()); } #else // Alternate approach for CPython: this does the same as the above, but optimized // using the CPython API so as to avoid an unneeded attribute lookup. else if (auto tp_as_number = src.ptr()->ob_type->tp_as_number) { if (PYBIND11_NB_BOOL(tp_as_number)) { res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr()); } } #endif if (res == 0 || res == 1) { value = (res != 0); return true; } PyErr_Clear(); } return false; } static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) { return handle(src ? Py_True : Py_False).inc_ref(); } PYBIND11_TYPE_CASTER(bool, _("bool")); }; // Helper class for UTF-{8,16,32} C++ stl strings: template <typename StringType, bool IsView = false> struct string_caster { using CharT = typename StringType::value_type; // Simplify life by being able to assume standard char sizes (the standard only guarantees // minimums, but Python requires exact sizes) static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1, "Unsupported char size != 1"); #if defined(PYBIND11_HAS_U8STRING) static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1, "Unsupported char8_t size != 1"); #endif static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2, "Unsupported char16_t size != 2"); static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4, "Unsupported char32_t size != 4"); // wchar_t can be either 16 bits (Windows) or 32 (everywhere else) static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4, "Unsupported wchar_t size != 2/4"); static constexpr size_t UTF_N = 8 * sizeof(CharT); bool load(handle src, bool) { #if PY_MAJOR_VERSION < 3 object temp; #endif handle load_src = src; if (!src) { return false; } if (!PyUnicode_Check(load_src.ptr())) { #if PY_MAJOR_VERSION >= 3 return load_bytes(load_src); #else if (std::is_same<CharT, char>::value) { return load_bytes(load_src); } // The below is a guaranteed failure in Python 3 when PyUnicode_Check returns false if (!PYBIND11_BYTES_CHECK(load_src.ptr())) return false; temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr())); if (!temp) { PyErr_Clear(); return false; } load_src = temp; #endif } #if PY_VERSION_HEX >= 0x03030000 // On Python >= 3.3, for UTF-8 we avoid the need for a temporary `bytes` // object by using `PyUnicode_AsUTF8AndSize`. if (PYBIND11_SILENCE_MSVC_C4127(UTF_N == 8)) { Py_ssize_t size = -1; const auto *buffer = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size)); if (!buffer) { PyErr_Clear(); return false; } value = StringType(buffer, static_cast<size_t>(size)); return true; } #endif auto utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString( load_src.ptr(), UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr)); if (!utfNbytes) { PyErr_Clear(); return false; } const auto *buffer = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr())); size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT); // Skip BOM for UTF-16/32 if (PYBIND11_SILENCE_MSVC_C4127(UTF_N > 8)) { buffer++; length--; } value = StringType(buffer, length); // If we're loading a string_view we need to keep the encoded Python object alive: if (IsView) loader_life_support::add_patient(utfNbytes); return true; } static handle cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) { const char *buffer = reinterpret_cast<const char *>(src.data()); auto nbytes = ssize_t(src.size() * sizeof(CharT)); handle s = decode_utfN(buffer, nbytes); if (!s) throw error_already_set(); return s; } PYBIND11_TYPE_CASTER(StringType, _(PYBIND11_STRING_NAME)); private: static handle decode_utfN(const char *buffer, ssize_t nbytes) { #if !defined(PYPY_VERSION) return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr) : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr) : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr); #else // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as well), // so bypass the whole thing by just passing the encoding as a string value, which works properly: return PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr); #endif } // When loading into a std::string or char*, accept a bytes object as-is (i.e. // without any encoding/decoding attempt). For other C++ char sizes this is a no-op. // which supports loading a unicode from a str, doesn't take this path. template <typename C = CharT> bool load_bytes(enable_if_t<std::is_same<C, char>::value, handle> src) { if (PYBIND11_BYTES_CHECK(src.ptr())) { // We were passed a Python 3 raw bytes; accept it into a std::string or char* // without any encoding attempt. const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr()); if (bytes) { value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr())); return true; } } return false; } template <typename C = CharT> bool load_bytes(enable_if_t<!std::is_same<C, char>::value, handle>) { return false; } }; template <typename CharT, class Traits, class Allocator> struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_std_char_type<CharT>::value>> : string_caster<std::basic_string<CharT, Traits, Allocator>> {}; #ifdef PYBIND11_HAS_STRING_VIEW template <typename CharT, class Traits> struct type_caster<std::basic_string_view<CharT, Traits>, enable_if_t<is_std_char_type<CharT>::value>> : string_caster<std::basic_string_view<CharT, Traits>, true> {}; #endif // Type caster for C-style strings. We basically use a std::string type caster, but also add the // ability to use None as a nullptr char* (which the string caster doesn't allow). template <typename CharT> struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> { using StringType = std::basic_string<CharT>; using StringCaster = type_caster<StringType>; StringCaster str_caster; bool none = false; CharT one_char = 0; public: bool load(handle src, bool convert) { if (!src) return false; if (src.is_none()) { // Defer accepting None to other overloads (if we aren't in convert mode): if (!convert) return false; none = true; return true; } return str_caster.load(src, convert); } static handle cast(const CharT *src, return_value_policy policy, handle parent) { if (src == nullptr) return pybind11::none().inc_ref(); return StringCaster::cast(StringType(src), policy, parent); } static handle cast(CharT src, return_value_policy policy, handle parent) { if (std::is_same<char, CharT>::value) { handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr); if (!s) throw error_already_set(); return s; } return StringCaster::cast(StringType(1, src), policy, parent); } explicit operator CharT *() { return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str()); } explicit operator CharT &() { if (none) throw value_error("Cannot convert None to a character"); auto &value = static_cast<StringType &>(str_caster); size_t str_len = value.size(); if (str_len == 0) throw value_error("Cannot convert empty string to a character"); // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that // is too high, and one for multiple unicode characters (caught later), so we need to figure // out how long the first encoded character is in bytes to distinguish between these two // errors. We also allow want to allow unicode characters U+0080 through U+00FF, as those // can fit into a single char value. if (PYBIND11_SILENCE_MSVC_C4127(StringCaster::UTF_N == 8) && str_len > 1 && str_len <= 4) { auto v0 = static_cast<unsigned char>(value[0]); // low bits only: 0-127 // 0b110xxxxx - start of 2-byte sequence // 0b1110xxxx - start of 3-byte sequence // 0b11110xxx - start of 4-byte sequence size_t char0_bytes = (v0 & 0x80) == 0 ? 1 : (v0 & 0xE0) == 0xC0 ? 2 : (v0 & 0xF0) == 0xE0 ? 3 : 4; if (char0_bytes == str_len) { // If we have a 128-255 value, we can decode it into a single char: if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx one_char = static_cast<CharT>(((v0 & 3) << 6) + (static_cast<unsigned char>(value[1]) & 0x3F)); return one_char; } // Otherwise we have a single character, but it's > U+00FF throw value_error("Character code point not in range(0x100)"); } } // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a // surrogate pair with total length 2 instantly indicates a range error (but not a "your // string was too long" error). else if (PYBIND11_SILENCE_MSVC_C4127(StringCaster::UTF_N == 16) && str_len == 2) { one_char = static_cast<CharT>(value[0]); if (one_char >= 0xD800 && one_char < 0xE000) throw value_error("Character code point not in range(0x10000)"); } if (str_len != 1) throw value_error("Expected a character, but multi-character string found"); one_char = value[0]; return one_char; } static constexpr auto name = _(PYBIND11_STRING_NAME); template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>; }; // Base implementation for std::tuple and std::pair template <template<typename...> class Tuple, typename... Ts> class tuple_caster { using type = Tuple<Ts...>; static constexpr auto size = sizeof...(Ts); using indices = make_index_sequence<size>; public: bool load(handle src, bool convert) { if (!isinstance<sequence>(src)) return false; const auto seq = reinterpret_borrow<sequence>(src); if (seq.size() != size) return false; return load_impl(seq, convert, indices{}); } template <typename T> static handle cast(T &&src, return_value_policy policy, handle parent) { return cast_impl(std::forward<T>(src), policy, parent, indices{}); } // copied from the PYBIND11_TYPE_CASTER macro template <typename T> static handle cast(T *src, return_value_policy policy, handle parent) { if (!src) return none().release(); if (policy == return_value_policy::take_ownership) { auto h = cast(std::move(*src), policy, parent); delete src; return h; } return cast(*src, policy, parent); } static constexpr auto name = _("Tuple[") + concat(make_caster<Ts>::name...) + _("]"); template <typename T> using cast_op_type = type; explicit operator type() & { return implicit_cast(indices{}); } explicit operator type() && { return std::move(*this).implicit_cast(indices{}); } protected: template <size_t... Is> type implicit_cast(index_sequence<Is...>) & { return type(cast_op<Ts>(std::get<Is>(subcasters))...); } template <size_t... Is> type implicit_cast(index_sequence<Is...>) && { return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...); } static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; } template <size_t... Is> bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) { #ifdef __cpp_fold_expressions if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) return false; #else for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) if (!r) return false; #endif return true; } /* Implementation: Convert a C++ tuple into a Python tuple */ template <typename T, size_t... Is> static handle cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) { PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent); PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent); std::array<object, size> entries{{ reinterpret_steal<object>(make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))... }}; for (const auto &entry: entries) if (!entry) return handle(); tuple result(size); int counter = 0; for (auto & entry: entries) PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr()); return result.release(); } Tuple<make_caster<Ts>...> subcasters; }; template <typename T1, typename T2> class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {}; template <typename... Ts> class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {}; /// Helper class which abstracts away certain actions. Users can provide specializations for /// custom holders, but it's only necessary if the type has a non-standard interface. template <typename T> struct holder_helper { static auto get(const T &p) -> decltype(p.get()) { return p.get(); } }; /// Type caster for holder types like std::shared_ptr, etc. /// The SFINAE hook is provided to help work around the current lack of support /// for smart-pointer interoperability. Please consider it an implementation /// detail that may change in the future, as formal support for smart-pointer /// interoperability is added into pybind11. template <typename type, typename holder_type, typename SFINAE = void> struct copyable_holder_caster : public type_caster_base<type> { public: using base = type_caster_base<type>; static_assert(std::is_base_of<base, type_caster<type>>::value, "Holder classes are only supported for custom types"); using base::base; using base::cast; using base::typeinfo; using base::value; bool load(handle src, bool convert) { return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert); } explicit operator type*() { return this->value; } // static_cast works around compiler error with MSVC 17 and CUDA 10.2 // see issue #2180 explicit operator type&() { return *(static_cast<type *>(this->value)); } explicit operator holder_type*() { return std::addressof(holder); } explicit operator holder_type&() { return holder; } static handle cast(const holder_type &src, return_value_policy, handle) { const auto *ptr = holder_helper<holder_type>::get(src); return type_caster_base<type>::cast_holder(ptr, &src); } protected: friend class type_caster_generic; void check_holder_compat() { if (typeinfo->default_holder) throw cast_error("Unable to load a custom holder type from a default-holder instance"); } bool load_value(value_and_holder &&v_h) { if (v_h.holder_constructed()) { value = v_h.value_ptr(); holder = v_h.template holder<holder_type>(); return true; } throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) " #if defined(NDEBUG) "(compile in debug mode for type information)"); #else "of type '" + type_id<holder_type>() + "''"); #endif } template <typename T = holder_type, detail::enable_if_t<!std::is_constructible<T, const T &, type*>::value, int> = 0> bool try_implicit_casts(handle, bool) { return false; } template <typename T = holder_type, detail::enable_if_t<std::is_constructible<T, const T &, type*>::value, int> = 0> bool try_implicit_casts(handle src, bool convert) { for (auto &cast : typeinfo->implicit_casts) { copyable_holder_caster sub_caster(*cast.first); if (sub_caster.load(src, convert)) { value = cast.second(sub_caster.value); holder = holder_type(sub_caster.holder, (type *) value); return true; } } return false; } static bool try_direct_conversions(handle) { return false; } holder_type holder; }; /// Specialize for the common std::shared_ptr, so users don't need to template <typename T> class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> { }; /// Type caster for holder types like std::unique_ptr. /// Please consider the SFINAE hook an implementation detail, as explained /// in the comment for the copyable_holder_caster. template <typename type, typename holder_type, typename SFINAE = void> struct move_only_holder_caster { static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value, "Holder classes are only supported for custom types"); static handle cast(holder_type &&src, return_value_policy, handle) { auto *ptr = holder_helper<holder_type>::get(src); return type_caster_base<type>::cast_holder(ptr, std::addressof(src)); } static constexpr auto name = type_caster_base<type>::name; }; template <typename type, typename deleter> class type_caster<std::unique_ptr<type, deleter>> : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> { }; template <typename type, typename holder_type> using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value, copyable_holder_caster<type, holder_type>, move_only_holder_caster<type, holder_type>>; template <typename T, bool Value = false> struct always_construct_holder { static constexpr bool value = Value; }; /// Create a specialization for custom holder types (silently ignores std::shared_ptr) #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \ namespace pybind11 { namespace detail { \ template <typename type> \ struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { }; \ template <typename type> \ class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \ : public type_caster_holder<type, holder_type> { }; \ }} // PYBIND11_DECLARE_HOLDER_TYPE holder types: template <typename base, typename holder> struct is_holder_type : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {}; // Specialization for always-supported unique_ptr holders: template <typename base, typename deleter> struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {}; template <typename T> struct handle_type_name { static constexpr auto name = _<T>(); }; template <> struct handle_type_name<bytes> { static constexpr auto name = _(PYBIND11_BYTES_NAME); }; template <> struct handle_type_name<int_> { static constexpr auto name = _("int"); }; template <> struct handle_type_name<iterable> { static constexpr auto name = _("Iterable"); }; template <> struct handle_type_name<iterator> { static constexpr auto name = _("Iterator"); }; template <> struct handle_type_name<none> { static constexpr auto name = _("None"); }; template <> struct handle_type_name<args> { static constexpr auto name = _("*args"); }; template <> struct handle_type_name<kwargs> { static constexpr auto name = _("**kwargs"); }; template <typename type> struct pyobject_caster { template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0> bool load(handle src, bool /* convert */) { value = src; return static_cast<bool>(value); } template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0> bool load(handle src, bool /* convert */) { #if PY_MAJOR_VERSION < 3 && !defined(PYBIND11_STR_LEGACY_PERMISSIVE) // For Python 2, without this implicit conversion, Python code would // need to be cluttered with six.ensure_text() or similar, only to be // un-cluttered later after Python 2 support is dropped. if (PYBIND11_SILENCE_MSVC_C4127(std::is_same<T, str>::value) && isinstance<bytes>(src)) { PyObject *str_from_bytes = PyUnicode_FromEncodedObject(src.ptr(), "utf-8", nullptr); if (!str_from_bytes) throw error_already_set(); value = reinterpret_steal<type>(str_from_bytes); return true; } #endif if (!isinstance<type>(src)) return false; value = reinterpret_borrow<type>(src); return true; } static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) { return src.inc_ref(); } PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name); }; template <typename T> class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> { }; // Our conditions for enabling moving are quite restrictive: // At compile time: // - T needs to be a non-const, non-pointer, non-reference type // - type_caster<T>::operator T&() must exist // - the type must be move constructible (obviously) // At run-time: // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it // must have ref_count() == 1)h // If any of the above are not satisfied, we fall back to copying. template <typename T> using move_is_plain_type = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const >; template <typename T, typename SFINAE = void> struct move_always : std::false_type {}; template <typename T> struct move_always<T, enable_if_t<all_of< move_is_plain_type<T>, negation<is_copy_constructible<T>>, std::is_move_constructible<T>, std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&> >::value>> : std::true_type {}; template <typename T, typename SFINAE = void> struct move_if_unreferenced : std::false_type {}; template <typename T> struct move_if_unreferenced<T, enable_if_t<all_of< move_is_plain_type<T>, negation<move_always<T>>, std::is_move_constructible<T>, std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&> >::value>> : std::true_type {}; template <typename T> using move_never = none_of<move_always<T>, move_if_unreferenced<T>>; // Detect whether returning a `type` from a cast on type's type_caster is going to result in a // reference or pointer to a local variable of the type_caster. Basically, only // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe; // everything else returns a reference/pointer to a local variable. template <typename type> using cast_is_temporary_value_reference = bool_constant< (std::is_reference<type>::value || std::is_pointer<type>::value) && !std::is_base_of<type_caster_generic, make_caster<type>>::value && !std::is_same<intrinsic_t<type>, void>::value >; // When a value returned from a C++ function is being cast back to Python, we almost always want to // force `policy = move`, regardless of the return value policy the function/method was declared // with. template <typename Return, typename SFINAE = void> struct return_value_policy_override { static return_value_policy policy(return_value_policy p) { return p; } }; template <typename Return> struct return_value_policy_override<Return, detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> { static return_value_policy policy(return_value_policy p) { return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value ? return_value_policy::move : p; } }; // Basic python -> C++ casting; throws if casting fails template <typename T, typename SFINAE> type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) { if (!conv.load(handle, true)) { #if defined(NDEBUG) throw cast_error("Unable to cast Python instance to C++ type (compile in debug mode for details)"); #else throw cast_error("Unable to cast Python instance of type " + (std::string) str(type::handle_of(handle)) + " to C++ type '" + type_id<T>() + "'"); #endif } return conv; } // Wrapper around the above that also constructs and returns a type_caster template <typename T> make_caster<T> load_type(const handle &handle) { make_caster<T> conv; load_type(conv, handle); return conv; } PYBIND11_NAMESPACE_END(detail) // pytype -> C++ type template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0> T cast(const handle &handle) { using namespace detail; static_assert(!cast_is_temporary_value_reference<T>::value, "Unable to cast type to reference: value is local to type caster"); return cast_op<T>(load_type<T>(handle)); } // pytype -> pytype (calls converting constructor) template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0> T cast(const handle &handle) { return T(reinterpret_borrow<object>(handle)); } // C++ type -> py::object template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0> object cast(T &&value, return_value_policy policy = return_value_policy::automatic_reference, handle parent = handle()) { using no_ref_T = typename std::remove_reference<T>::type; if (policy == return_value_policy::automatic) policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership : std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move; else if (policy == return_value_policy::automatic_reference) policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference : std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move; return reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(value), policy, parent)); } template <typename T> T handle::cast() const { return pybind11::cast<T>(*this); } template <> inline void handle::cast() const { return; } template <typename T> detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) { if (obj.ref_count() > 1) #if defined(NDEBUG) throw cast_error("Unable to cast Python instance to C++ rvalue: instance has multiple references" " (compile in debug mode for details)"); #else throw cast_error("Unable to move from Python " + (std::string) str(type::handle_of(obj)) + " instance to C++ " + type_id<T>() + " instance: instance has multiple references"); #endif // Move into a temporary and return that, because the reference may be a local value of `conv` T ret = std::move(detail::load_type<T>(obj).operator T&()); return ret; } // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does: // - If we have to move (because T has no copy constructor), do it. This will fail if the moved // object has multiple references, but trying to copy will fail to compile. // - If both movable and copyable, check ref count: if 1, move; otherwise copy // - Otherwise (not movable), copy. template <typename T> detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) { return move<T>(std::move(object)); } template <typename T> detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) { if (object.ref_count() > 1) return cast<T>(object); return move<T>(std::move(object)); } template <typename T> detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) { return cast<T>(object); } template <typename T> T object::cast() const & { return pybind11::cast<T>(*this); } template <typename T> T object::cast() && { return pybind11::cast<T>(std::move(*this)); } template <> inline void object::cast() const & { return; } template <> inline void object::cast() && { return; } PYBIND11_NAMESPACE_BEGIN(detail) // Declared in pytypes.h: template <typename T, enable_if_t<!is_pyobject<T>::value, int>> object object_or_cast(T &&o) { return pybind11::cast(std::forward<T>(o)); } struct override_unused {}; // Placeholder type for the unneeded (and dead code) static variable in the PYBIND11_OVERRIDE_OVERRIDE macro template <typename ret_type> using override_caster_t = conditional_t< cast_is_temporary_value_reference<ret_type>::value, make_caster<ret_type>, override_unused>; // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then // store the result in the given variable. For other types, this is a no-op. template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o, make_caster<T> &caster) { return cast_op<T>(load_type(caster, o)); } template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&, override_unused &) { pybind11_fail("Internal error: cast_ref fallback invoked"); } // Trampoline use: Having a pybind11::cast with an invalid reference type is going to static_assert, even // though if it's in dead code, so we provide a "trampoline" to pybind11::cast that only does anything in // cases where pybind11::cast is valid. template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&o) { return pybind11::cast<T>(std::move(o)); } template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) { pybind11_fail("Internal error: cast_safe fallback invoked"); } template <> inline void cast_safe<void>(object &&) {} PYBIND11_NAMESPACE_END(detail) // The overloads could coexist, i.e. the #if is not strictly speaking needed, // but it is an easy minor optimization. #if defined(NDEBUG) inline cast_error cast_error_unable_to_convert_call_arg() { return cast_error( "Unable to convert call argument to Python object (compile in debug mode for details)"); } #else inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name, const std::string &type) { return cast_error("Unable to convert call argument '" + name + "' of type '" + type + "' to Python object"); } #endif template <return_value_policy policy = return_value_policy::automatic_reference> tuple make_tuple() { return tuple(0); } template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> tuple make_tuple(Args&&... args_) { constexpr size_t size = sizeof...(Args); std::array<object, size> args { { reinterpret_steal<object>(detail::make_caster<Args>::cast( std::forward<Args>(args_), policy, nullptr))... } }; for (size_t i = 0; i < args.size(); i++) { if (!args[i]) { #if defined(NDEBUG) throw cast_error_unable_to_convert_call_arg(); #else std::array<std::string, size> argtypes { {type_id<Args>()...} }; throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]); #endif } } tuple result(size); int counter = 0; for (auto &arg_value : args) PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr()); return result; } #if PY_VERSION_HEX >= 0x03030000 template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>> object make_simple_namespace(Args&&... args_) { PyObject *ns = _PyNamespace_New(dict(std::forward<Args>(args_)...).ptr()); if (!ns) throw error_already_set(); return reinterpret_steal<object>(ns); } #endif /// \ingroup annotations /// Annotation for arguments struct arg { /// Constructs an argument with the name of the argument; if null or omitted, this is a positional argument. constexpr explicit arg(const char *name = nullptr) : name(name), flag_noconvert(false), flag_none(true) { } /// Assign a value to this argument template <typename T> arg_v operator=(T &&value) const; /// Indicate that the type should not be converted in the type caster arg &noconvert(bool flag = true) { flag_noconvert = flag; return *this; } /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args) arg &none(bool flag = true) { flag_none = flag; return *this; } const char *name; ///< If non-null, this is a named kwargs argument bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type caster!) bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument }; /// \ingroup annotations /// Annotation for arguments with values struct arg_v : arg { private: template <typename T> arg_v(arg &&base, T &&x, const char *descr = nullptr) : arg(base), value(reinterpret_steal<object>( detail::make_caster<T>::cast(x, return_value_policy::automatic, {}) )), descr(descr) #if !defined(NDEBUG) , type(type_id<T>()) #endif { // Workaround! See: // https://github.com/pybind/pybind11/issues/2336 // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700 if (PyErr_Occurred()) { PyErr_Clear(); } } public: /// Direct construction with name, default, and description template <typename T> arg_v(const char *name, T &&x, const char *descr = nullptr) : arg_v(arg(name), std::forward<T>(x), descr) { } /// Called internally when invoking `py::arg("a") = value` template <typename T> arg_v(const arg &base, T &&x, const char *descr = nullptr) : arg_v(arg(base), std::forward<T>(x), descr) { } /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg& arg_v &noconvert(bool flag = true) { arg::noconvert(flag); return *this; } /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg& arg_v &none(bool flag = true) { arg::none(flag); return *this; } /// The default value object value; /// The (optional) description of the default value const char *descr; #if !defined(NDEBUG) /// The C++ type name of the default value (only available when compiled in debug mode) std::string type; #endif }; /// \ingroup annotations /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of an /// unnamed '*' argument (in Python 3) struct kw_only {}; /// \ingroup annotations /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of an /// unnamed '/' argument (in Python 3.8) struct pos_only {}; template <typename T> arg_v arg::operator=(T &&value) const { return {*this, std::forward<T>(value)}; } /// Alias for backward compatibility -- to be removed in version 2.0 template <typename /*unused*/> using arg_t = arg_v; inline namespace literals { /** \rst String literal version of `arg` \endrst */ constexpr arg operator"" _a(const char *name, size_t) { return arg(name); } } // namespace literals PYBIND11_NAMESPACE_BEGIN(detail) // forward declaration (definition in attr.h) struct function_record; /// Internal data associated with a single function call struct function_call { function_call(const function_record &f, handle p); // Implementation in attr.h /// The function data: const function_record &func; /// Arguments passed to the function: std::vector<handle> args; /// The `convert` value the arguments should be loaded with std::vector<bool> args_convert; /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if /// present, are also in `args` but without a reference). object args_ref, kwargs_ref; /// The parent, if any handle parent; /// If this is a call to an initializer, this argument contains `self` handle init_self; }; /// Helper class which loads arguments for C++ functions called from Python template <typename... Args> class argument_loader { using indices = make_index_sequence<sizeof...(Args)>; template <typename Arg> using argument_is_args = std::is_same<intrinsic_t<Arg>, args>; template <typename Arg> using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>; // Get args/kwargs argument positions relative to the end of the argument list: static constexpr auto args_pos = constexpr_first<argument_is_args, Args...>() - (int) sizeof...(Args), kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int) sizeof...(Args); static constexpr bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1; static_assert(args_kwargs_are_last, "py::args/py::kwargs are only permitted as the last argument(s) of a function"); public: static constexpr bool has_kwargs = kwargs_pos < 0; static constexpr bool has_args = args_pos < 0; static constexpr auto arg_names = concat(type_descr(make_caster<Args>::name)...); bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); } template <typename Return, typename Guard, typename Func> // NOLINTNEXTLINE(readability-const-return-type) enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && { return std::move(*this).template call_impl<remove_cv_t<Return>>(std::forward<Func>(f), indices{}, Guard{}); } template <typename Return, typename Guard, typename Func> enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && { std::move(*this).template call_impl<remove_cv_t<Return>>(std::forward<Func>(f), indices{}, Guard{}); return void_type(); } private: static bool load_impl_sequence(function_call &, index_sequence<>) { return true; } template <size_t... Is> bool load_impl_sequence(function_call &call, index_sequence<Is...>) { #ifdef __cpp_fold_expressions if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) return false; #else for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) if (!r) return false; #endif return true; } template <typename Return, typename Func, size_t... Is, typename Guard> Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && { return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...); } std::tuple<make_caster<Args>...> argcasters; }; /// Helper class which collects only positional arguments for a Python function call. /// A fancier version below can collect any argument, but this one is optimal for simple calls. template <return_value_policy policy> class simple_collector { public: template <typename... Ts> explicit simple_collector(Ts &&...values) : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) { } const tuple &args() const & { return m_args; } dict kwargs() const { return {}; } tuple args() && { return std::move(m_args); } /// Call a Python function and pass the collected arguments object call(PyObject *ptr) const { PyObject *result = PyObject_CallObject(ptr, m_args.ptr()); if (!result) throw error_already_set(); return reinterpret_steal<object>(result); } private: tuple m_args; }; /// Helper class which collects positional, keyword, * and ** arguments for a Python function call template <return_value_policy policy> class unpacking_collector { public: template <typename... Ts> explicit unpacking_collector(Ts &&...values) { // Tuples aren't (easily) resizable so a list is needed for collection, // but the actual function call strictly requires a tuple. auto args_list = list(); using expander = int[]; (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...}; m_args = std::move(args_list); } const tuple &args() const & { return m_args; } const dict &kwargs() const & { return m_kwargs; } tuple args() && { return std::move(m_args); } dict kwargs() && { return std::move(m_kwargs); } /// Call a Python function and pass the collected arguments object call(PyObject *ptr) const { PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr()); if (!result) throw error_already_set(); return reinterpret_steal<object>(result); } private: template <typename T> void process(list &args_list, T &&x) { auto o = reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(x), policy, {})); if (!o) { #if defined(NDEBUG) throw cast_error_unable_to_convert_call_arg(); #else throw cast_error_unable_to_convert_call_arg( std::to_string(args_list.size()), type_id<T>()); #endif } args_list.append(o); } void process(list &args_list, detail::args_proxy ap) { for (auto a : ap) args_list.append(a); } void process(list &/*args_list*/, arg_v a) { if (!a.name) #if defined(NDEBUG) nameless_argument_error(); #else nameless_argument_error(a.type); #endif if (m_kwargs.contains(a.name)) { #if defined(NDEBUG) multiple_values_error(); #else multiple_values_error(a.name); #endif } if (!a.value) { #if defined(NDEBUG) throw cast_error_unable_to_convert_call_arg(); #else throw cast_error_unable_to_convert_call_arg(a.name, a.type); #endif } m_kwargs[a.name] = a.value; } void process(list &/*args_list*/, detail::kwargs_proxy kp) { if (!kp) return; for (auto k : reinterpret_borrow<dict>(kp)) { if (m_kwargs.contains(k.first)) { #if defined(NDEBUG) multiple_values_error(); #else multiple_values_error(str(k.first)); #endif } m_kwargs[k.first] = k.second; } } [[noreturn]] static void nameless_argument_error() { throw type_error("Got kwargs without a name; only named arguments " "may be passed via py::arg() to a python function call. " "(compile in debug mode for details)"); } [[noreturn]] static void nameless_argument_error(const std::string &type) { throw type_error("Got kwargs without a name of type '" + type + "'; only named " "arguments may be passed via py::arg() to a python function call. "); } [[noreturn]] static void multiple_values_error() { throw type_error("Got multiple values for keyword argument " "(compile in debug mode for details)"); } [[noreturn]] static void multiple_values_error(const std::string &name) { throw type_error("Got multiple values for keyword argument '" + name + "'"); } private: tuple m_args; dict m_kwargs; }; // [workaround(intel)] Separate function required here // We need to put this into a separate function because the Intel compiler // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value> // (tested with ICC 2021.1 Beta 20200827). template <typename... Args> constexpr bool args_are_all_positional() { return all_of<is_positional<Args>...>::value; } /// Collect only positional arguments for a Python function call template <return_value_policy policy, typename... Args, typename = enable_if_t<args_are_all_positional<Args...>()>> simple_collector<policy> collect_arguments(Args &&...args) { return simple_collector<policy>(std::forward<Args>(args)...); } /// Collect all arguments, including keywords and unpacking (only instantiated when needed) template <return_value_policy policy, typename... Args, typename = enable_if_t<!args_are_all_positional<Args...>()>> unpacking_collector<policy> collect_arguments(Args &&...args) { // Following argument order rules for generalized unpacking according to PEP 448 static_assert( constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>() && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(), "Invalid function call: positional args must precede keywords and ** unpacking; " "* unpacking must precede ** unpacking" ); return unpacking_collector<policy>(std::forward<Args>(args)...); } template <typename Derived> template <return_value_policy policy, typename... Args> object object_api<Derived>::operator()(Args &&...args) const { #if !defined(NDEBUG) && PY_VERSION_HEX >= 0x03060000 if (!PyGILState_Check()) { pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure."); } #endif return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr()); } template <typename Derived> template <return_value_policy policy, typename... Args> object object_api<Derived>::call(Args &&...args) const { return operator()<policy>(std::forward<Args>(args)...); } PYBIND11_NAMESPACE_END(detail) template<typename T> handle type::handle_of() { static_assert( std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value, "py::type::of<T> only supports the case where T is a registered C++ types." ); return detail::get_type_handle(typeid(T), true); } #define PYBIND11_MAKE_OPAQUE(...) \ namespace pybind11 { namespace detail { \ template<> class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { }; \ }} /// Lets you pass a type containing a `,` through a macro parameter without needing a separate /// typedef, e.g.: `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)` #define PYBIND11_TYPE(...) __VA_ARGS__ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
60,553
C
40.963964
153
0.612207
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/eval.h
/* pybind11/exec.h: Support for evaluating Python expressions and statements from strings and files Copyright (c) 2016 Klemens Morgenstern <[email protected]> and Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include <utility> #include "pybind11.h" PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) inline void ensure_builtins_in_globals(object &global) { #if PY_VERSION_HEX < 0x03080000 // Running exec and eval on Python 2 and 3 adds `builtins` module under // `__builtins__` key to globals if not yet present. // Python 3.8 made PyRun_String behave similarly. Let's also do that for // older versions, for consistency. if (!global.contains("__builtins__")) global["__builtins__"] = module_::import(PYBIND11_BUILTINS_MODULE); #else (void) global; #endif } PYBIND11_NAMESPACE_END(detail) enum eval_mode { /// Evaluate a string containing an isolated expression eval_expr, /// Evaluate a string containing a single statement. Returns \c none eval_single_statement, /// Evaluate a string containing a sequence of statement. Returns \c none eval_statements }; template <eval_mode mode = eval_expr> object eval(const str &expr, object global = globals(), object local = object()) { if (!local) local = global; detail::ensure_builtins_in_globals(global); /* PyRun_String does not accept a PyObject / encoding specifier, this seems to be the only alternative */ std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr; int start = 0; switch (mode) { case eval_expr: start = Py_eval_input; break; case eval_single_statement: start = Py_single_input; break; case eval_statements: start = Py_file_input; break; default: pybind11_fail("invalid evaluation mode"); } PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr()); if (!result) throw error_already_set(); return reinterpret_steal<object>(result); } template <eval_mode mode = eval_expr, size_t N> object eval(const char (&s)[N], object global = globals(), object local = object()) { /* Support raw string literals by removing common leading whitespace */ auto expr = (s[0] == '\n') ? str(module_::import("textwrap").attr("dedent")(s)) : str(s); return eval<mode>(expr, global, local); } inline void exec(const str &expr, object global = globals(), object local = object()) { eval<eval_statements>(expr, std::move(global), std::move(local)); } template <size_t N> void exec(const char (&s)[N], object global = globals(), object local = object()) { eval<eval_statements>(s, global, local); } #if defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x03000000 template <eval_mode mode = eval_statements> object eval_file(str, object, object) { pybind11_fail("eval_file not supported in PyPy3. Use eval"); } template <eval_mode mode = eval_statements> object eval_file(str, object) { pybind11_fail("eval_file not supported in PyPy3. Use eval"); } template <eval_mode mode = eval_statements> object eval_file(str) { pybind11_fail("eval_file not supported in PyPy3. Use eval"); } #else template <eval_mode mode = eval_statements> object eval_file(str fname, object global = globals(), object local = object()) { if (!local) local = global; detail::ensure_builtins_in_globals(global); int start = 0; switch (mode) { case eval_expr: start = Py_eval_input; break; case eval_single_statement: start = Py_single_input; break; case eval_statements: start = Py_file_input; break; default: pybind11_fail("invalid evaluation mode"); } int closeFile = 1; std::string fname_str = (std::string) fname; #if PY_VERSION_HEX >= 0x03040000 FILE *f = _Py_fopen_obj(fname.ptr(), "r"); #elif PY_VERSION_HEX >= 0x03000000 FILE *f = _Py_fopen(fname.ptr(), "r"); #else /* No unicode support in open() :( */ auto fobj = reinterpret_steal<object>(PyFile_FromString( const_cast<char *>(fname_str.c_str()), const_cast<char*>("r"))); FILE *f = nullptr; if (fobj) f = PyFile_AsFile(fobj.ptr()); closeFile = 0; #endif if (!f) { PyErr_Clear(); pybind11_fail("File \"" + fname_str + "\" could not be opened!"); } // In Python2, this should be encoded by getfilesystemencoding. // We don't boher setting it since Python2 is past EOL anyway. // See PR#3233 #if PY_VERSION_HEX >= 0x03000000 if (!global.contains("__file__")) { global["__file__"] = std::move(fname); } #endif #if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION) PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(), local.ptr()); (void) closeFile; #else PyObject *result = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), local.ptr(), closeFile); #endif if (!result) throw error_already_set(); return reinterpret_steal<object>(result); } #endif PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
5,431
C
32.121951
87
0.632664
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/functional.h
/* pybind11/functional.h: std::function<> support Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "pybind11.h" #include <functional> PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) template <typename Return, typename... Args> struct type_caster<std::function<Return(Args...)>> { using type = std::function<Return(Args...)>; using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>; using function_type = Return (*) (Args...); public: bool load(handle src, bool convert) { if (src.is_none()) { // Defer accepting None to other overloads (if we aren't in convert mode): if (!convert) return false; return true; } if (!isinstance<function>(src)) return false; auto func = reinterpret_borrow<function>(src); /* When passing a C++ function as an argument to another C++ function via Python, every function call would normally involve a full C++ -> Python -> C++ roundtrip, which can be prohibitive. Here, we try to at least detect the case where the function is stateless (i.e. function pointer or lambda function without captured variables), in which case the roundtrip can be avoided. */ if (auto cfunc = func.cpp_function()) { auto cfunc_self = PyCFunction_GET_SELF(cfunc.ptr()); if (isinstance<capsule>(cfunc_self)) { auto c = reinterpret_borrow<capsule>(cfunc_self); auto rec = (function_record *) c; while (rec != nullptr) { if (rec->is_stateless && same_type(typeid(function_type), *reinterpret_cast<const std::type_info *>(rec->data[1]))) { struct capture { function_type f; }; value = ((capture *) &rec->data)->f; return true; } rec = rec->next; } } // PYPY segfaults here when passing builtin function like sum. // Raising an fail exception here works to prevent the segfault, but only on gcc. // See PR #1413 for full details } // ensure GIL is held during functor destruction struct func_handle { function f; #if !(defined(_MSC_VER) && _MSC_VER == 1916 && defined(PYBIND11_CPP17) && PY_MAJOR_VERSION < 3) // This triggers a syntax error under very special conditions (very weird indeed). explicit #endif func_handle(function &&f_) noexcept : f(std::move(f_)) {} func_handle(const func_handle &f_) { operator=(f_); } func_handle &operator=(const func_handle &f_) { gil_scoped_acquire acq; f = f_.f; return *this; } ~func_handle() { gil_scoped_acquire acq; function kill_f(std::move(f)); } }; // to emulate 'move initialization capture' in C++11 struct func_wrapper { func_handle hfunc; explicit func_wrapper(func_handle &&hf) noexcept : hfunc(std::move(hf)) {} Return operator()(Args... args) const { gil_scoped_acquire acq; object retval(hfunc.f(std::forward<Args>(args)...)); /* Visual studio 2015 parser issue: need parentheses around this expression */ return (retval.template cast<Return>()); } }; value = func_wrapper(func_handle(std::move(func))); return true; } template <typename Func> static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) { if (!f_) return none().inc_ref(); auto result = f_.template target<function_type>(); if (result) return cpp_function(*result, policy).release(); return cpp_function(std::forward<Func>(f_), policy).release(); } PYBIND11_TYPE_CASTER(type, _("Callable[[") + concat(make_caster<Args>::name...) + _("], ") + make_caster<retval_type>::name + _("]")); }; PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
4,597
C
36.688524
96
0.546878
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/operators.h
/* pybind11/operator.h: Metatemplates for operator overloading Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "pybind11.h" PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) /// Enumeration with all supported operator types enum op_id : int { op_add, op_sub, op_mul, op_div, op_mod, op_divmod, op_pow, op_lshift, op_rshift, op_and, op_xor, op_or, op_neg, op_pos, op_abs, op_invert, op_int, op_long, op_float, op_str, op_cmp, op_gt, op_ge, op_lt, op_le, op_eq, op_ne, op_iadd, op_isub, op_imul, op_idiv, op_imod, op_ilshift, op_irshift, op_iand, op_ixor, op_ior, op_complex, op_bool, op_nonzero, op_repr, op_truediv, op_itruediv, op_hash }; enum op_type : int { op_l, /* base type on left */ op_r, /* base type on right */ op_u /* unary operator */ }; struct self_t { }; static const self_t self = self_t(); /// Type for an unused type slot struct undefined_t { }; /// Don't warn about an unused variable inline self_t __self() { return self; } /// base template of operator implementations template <op_id, op_type, typename B, typename L, typename R> struct op_impl { }; /// Operator implementation generator template <op_id id, op_type ot, typename L, typename R> struct op_ { template <typename Class, typename... Extra> void execute(Class &cl, const Extra&... extra) const { using Base = typename Class::type; using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>; using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>; using op = op_impl<id, ot, Base, L_type, R_type>; cl.def(op::name(), &op::execute, is_operator(), extra...); #if PY_MAJOR_VERSION < 3 if (PYBIND11_SILENCE_MSVC_C4127(id == op_truediv) || PYBIND11_SILENCE_MSVC_C4127(id == op_itruediv)) cl.def(id == op_itruediv ? "__idiv__" : ot == op_l ? "__div__" : "__rdiv__", &op::execute, is_operator(), extra...); #endif } template <typename Class, typename... Extra> void execute_cast(Class &cl, const Extra&... extra) const { using Base = typename Class::type; using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>; using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>; using op = op_impl<id, ot, Base, L_type, R_type>; cl.def(op::name(), &op::execute_cast, is_operator(), extra...); #if PY_MAJOR_VERSION < 3 if (id == op_truediv || id == op_itruediv) cl.def(id == op_itruediv ? "__idiv__" : ot == op_l ? "__div__" : "__rdiv__", &op::execute, is_operator(), extra...); #endif } }; #define PYBIND11_BINARY_OPERATOR(id, rid, op, expr) \ template <typename B, typename L, typename R> struct op_impl<op_##id, op_l, B, L, R> { \ static char const* name() { return "__" #id "__"; } \ static auto execute(const L &l, const R &r) -> decltype(expr) { return (expr); } \ static B execute_cast(const L &l, const R &r) { return B(expr); } \ }; \ template <typename B, typename L, typename R> struct op_impl<op_##id, op_r, B, L, R> { \ static char const* name() { return "__" #rid "__"; } \ static auto execute(const R &r, const L &l) -> decltype(expr) { return (expr); } \ static B execute_cast(const R &r, const L &l) { return B(expr); } \ }; \ inline op_<op_##id, op_l, self_t, self_t> op(const self_t &, const self_t &) { \ return op_<op_##id, op_l, self_t, self_t>(); \ } \ template <typename T> op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \ return op_<op_##id, op_l, self_t, T>(); \ } \ template <typename T> op_<op_##id, op_r, T, self_t> op(const T &, const self_t &) { \ return op_<op_##id, op_r, T, self_t>(); \ } #define PYBIND11_INPLACE_OPERATOR(id, op, expr) \ template <typename B, typename L, typename R> struct op_impl<op_##id, op_l, B, L, R> { \ static char const* name() { return "__" #id "__"; } \ static auto execute(L &l, const R &r) -> decltype(expr) { return expr; } \ static B execute_cast(L &l, const R &r) { return B(expr); } \ }; \ template <typename T> op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \ return op_<op_##id, op_l, self_t, T>(); \ } #define PYBIND11_UNARY_OPERATOR(id, op, expr) \ template <typename B, typename L> struct op_impl<op_##id, op_u, B, L, undefined_t> { \ static char const* name() { return "__" #id "__"; } \ static auto execute(const L &l) -> decltype(expr) { return expr; } \ static B execute_cast(const L &l) { return B(expr); } \ }; \ inline op_<op_##id, op_u, self_t, undefined_t> op(const self_t &) { \ return op_<op_##id, op_u, self_t, undefined_t>(); \ } PYBIND11_BINARY_OPERATOR(sub, rsub, operator-, l - r) PYBIND11_BINARY_OPERATOR(add, radd, operator+, l + r) PYBIND11_BINARY_OPERATOR(mul, rmul, operator*, l * r) PYBIND11_BINARY_OPERATOR(truediv, rtruediv, operator/, l / r) PYBIND11_BINARY_OPERATOR(mod, rmod, operator%, l % r) PYBIND11_BINARY_OPERATOR(lshift, rlshift, operator<<, l << r) PYBIND11_BINARY_OPERATOR(rshift, rrshift, operator>>, l >> r) PYBIND11_BINARY_OPERATOR(and, rand, operator&, l & r) PYBIND11_BINARY_OPERATOR(xor, rxor, operator^, l ^ r) PYBIND11_BINARY_OPERATOR(eq, eq, operator==, l == r) PYBIND11_BINARY_OPERATOR(ne, ne, operator!=, l != r) PYBIND11_BINARY_OPERATOR(or, ror, operator|, l | r) PYBIND11_BINARY_OPERATOR(gt, lt, operator>, l > r) PYBIND11_BINARY_OPERATOR(ge, le, operator>=, l >= r) PYBIND11_BINARY_OPERATOR(lt, gt, operator<, l < r) PYBIND11_BINARY_OPERATOR(le, ge, operator<=, l <= r) //PYBIND11_BINARY_OPERATOR(pow, rpow, pow, std::pow(l, r)) PYBIND11_INPLACE_OPERATOR(iadd, operator+=, l += r) PYBIND11_INPLACE_OPERATOR(isub, operator-=, l -= r) PYBIND11_INPLACE_OPERATOR(imul, operator*=, l *= r) PYBIND11_INPLACE_OPERATOR(itruediv, operator/=, l /= r) PYBIND11_INPLACE_OPERATOR(imod, operator%=, l %= r) PYBIND11_INPLACE_OPERATOR(ilshift, operator<<=, l <<= r) PYBIND11_INPLACE_OPERATOR(irshift, operator>>=, l >>= r) PYBIND11_INPLACE_OPERATOR(iand, operator&=, l &= r) PYBIND11_INPLACE_OPERATOR(ixor, operator^=, l ^= r) PYBIND11_INPLACE_OPERATOR(ior, operator|=, l |= r) PYBIND11_UNARY_OPERATOR(neg, operator-, -l) PYBIND11_UNARY_OPERATOR(pos, operator+, +l) // WARNING: This usage of `abs` should only be done for existing STL overloads. // Adding overloads directly in to the `std::` namespace is advised against: // https://en.cppreference.com/w/cpp/language/extending_std PYBIND11_UNARY_OPERATOR(abs, abs, std::abs(l)) PYBIND11_UNARY_OPERATOR(hash, hash, std::hash<L>()(l)) PYBIND11_UNARY_OPERATOR(invert, operator~, (~l)) PYBIND11_UNARY_OPERATOR(bool, operator!, !!l) PYBIND11_UNARY_OPERATOR(int, int_, (int) l) PYBIND11_UNARY_OPERATOR(float, float_, (double) l) #undef PYBIND11_BINARY_OPERATOR #undef PYBIND11_INPLACE_OPERATOR #undef PYBIND11_UNARY_OPERATOR PYBIND11_NAMESPACE_END(detail) using detail::self; // Add named operators so that they are accessible via `py::`. using detail::hash; PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
8,771
C
52.487805
108
0.525482
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/eigen.h
/* pybind11/eigen.h: Transparent conversion for dense and sparse Eigen matrices Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once /* HINT: To suppress warnings originating from the Eigen headers, use -isystem. See also: https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler */ #include "numpy.h" #include <Eigen/Core> #include <Eigen/SparseCore> // Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit // move constructors that break things. We could detect this an explicitly copy, but an extra copy // of matrices seems highly undesirable. static_assert(EIGEN_VERSION_AT_LEAST(3,2,7), "Eigen support in pybind11 requires Eigen >= 3.2.7"); PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) // Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides: using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>; template <typename MatrixType> using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>; template <typename MatrixType> using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>; PYBIND11_NAMESPACE_BEGIN(detail) #if EIGEN_VERSION_AT_LEAST(3,3,0) using EigenIndex = Eigen::Index; #else using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE; #endif // Matches Eigen::Map, Eigen::Ref, blocks, etc: template <typename T> using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>, std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>; template <typename T> using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>; template <typename T> using is_eigen_dense_plain = all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>; template <typename T> using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>; // Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This // basically covers anything that can be assigned to a dense matrix but that don't have a typical // matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and // SelfAdjointView fall into this category. template <typename T> using is_eigen_other = all_of< is_template_base_of<Eigen::EigenBase, T>, negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>> >; // Captures numpy/eigen conformability status (returned by EigenProps::conformable()): template <bool EigenRowMajor> struct EigenConformable { bool conformable = false; EigenIndex rows = 0, cols = 0; EigenDStride stride{0, 0}; // Only valid if negativestrides is false! bool negativestrides = false; // If true, do not use stride! // NOLINTNEXTLINE(google-explicit-constructor) EigenConformable(bool fits = false) : conformable{fits} {} // Matrix type: EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride) : conformable{true}, rows{r}, cols{c} { // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity. http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747 if (rstride < 0 || cstride < 0) { negativestrides = true; } else { stride = {EigenRowMajor ? rstride : cstride /* outer stride */, EigenRowMajor ? cstride : rstride /* inner stride */ }; } } // Vector type: EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride) : EigenConformable(r, c, r == 1 ? c*stride : stride, c == 1 ? r : r*stride) {} template <typename props> bool stride_compatible() const { // To have compatible strides, we need (on both dimensions) one of fully dynamic strides, // matching strides, or a dimension size of 1 (in which case the stride value is irrelevant) return !negativestrides && (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner() || (EigenRowMajor ? cols : rows) == 1) && (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer() || (EigenRowMajor ? rows : cols) == 1); } // NOLINTNEXTLINE(google-explicit-constructor) operator bool() const { return conformable; } }; template <typename Type> struct eigen_extract_stride { using type = Type; }; template <typename PlainObjectType, int MapOptions, typename StrideType> struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> { using type = StrideType; }; template <typename PlainObjectType, int Options, typename StrideType> struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> { using type = StrideType; }; // Helper struct for extracting information from an Eigen type template <typename Type_> struct EigenProps { using Type = Type_; using Scalar = typename Type::Scalar; using StrideType = typename eigen_extract_stride<Type>::type; static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime, size = Type::SizeAtCompileTime; static constexpr bool row_major = Type::IsRowMajor, vector = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1 fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic, fixed = size != Eigen::Dynamic, // Fully-fixed size dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size template <EigenIndex i, EigenIndex ifzero> using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>; static constexpr EigenIndex inner_stride = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value, outer_stride = if_zero<StrideType::OuterStrideAtCompileTime, vector ? size : row_major ? cols : rows>::value; static constexpr bool dynamic_stride = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic; static constexpr bool requires_row_major = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1; static constexpr bool requires_col_major = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1; // Takes an input array and determines whether we can make it fit into the Eigen type. If // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type). static EigenConformable<row_major> conformable(const array &a) { const auto dims = a.ndim(); if (dims < 1 || dims > 2) return false; if (dims == 2) { // Matrix type: require exact match (or dynamic) EigenIndex np_rows = a.shape(0), np_cols = a.shape(1), np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)), np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar)); if ((PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && np_rows != rows) || (PYBIND11_SILENCE_MSVC_C4127(fixed_cols) && np_cols != cols)) return false; return {np_rows, np_cols, np_rstride, np_cstride}; } // Otherwise we're storing an n-vector. Only one of the strides will be used, but whichever // is used, we want the (single) numpy stride value. const EigenIndex n = a.shape(0), stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)); if (vector) { // Eigen type is a compile-time vector if (PYBIND11_SILENCE_MSVC_C4127(fixed) && size != n) return false; // Vector size mismatch return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride}; } if (fixed) { // The type has a fixed size, but is not a vector: abort return false; } if (fixed_cols) { // Since this isn't a vector, cols must be != 1. We allow this only if it exactly // equals the number of elements (rows is Dynamic, and so 1 row is allowed). if (cols != n) return false; return {1, n, stride}; } // Otherwise it's either fully dynamic, or column dynamic; both become a column vector if (PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && rows != n) return false; return {n, 1, stride}; } static constexpr bool show_writeable = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value; static constexpr bool show_order = is_eigen_dense_map<Type>::value; static constexpr bool show_c_contiguous = show_order && requires_row_major; static constexpr bool show_f_contiguous = !show_c_contiguous && show_order && requires_col_major; static constexpr auto descriptor = _("numpy.ndarray[") + npy_format_descriptor<Scalar>::name + _("[") + _<fixed_rows>(_<(size_t) rows>(), _("m")) + _(", ") + _<fixed_cols>(_<(size_t) cols>(), _("n")) + _("]") + // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to be // satisfied: writeable=True (for a mutable reference), and, depending on the map's stride // options, possibly f_contiguous or c_contiguous. We include them in the descriptor output // to provide some hint as to why a TypeError is occurring (otherwise it can be confusing to // see that a function accepts a 'numpy.ndarray[float64[3,2]]' and an error message that you // *gave* a numpy.ndarray of the right type and dimensions. _<show_writeable>(", flags.writeable", "") + _<show_c_contiguous>(", flags.c_contiguous", "") + _<show_f_contiguous>(", flags.f_contiguous", "") + _("]"); }; // Casts an Eigen type to numpy array. If given a base, the numpy array references the src data, // otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array. template <typename props> handle eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) { constexpr ssize_t elem_size = sizeof(typename props::Scalar); array a; if (props::vector) a = array({ src.size() }, { elem_size * src.innerStride() }, src.data(), base); else a = array({ src.rows(), src.cols() }, { elem_size * src.rowStride(), elem_size * src.colStride() }, src.data(), base); if (!writeable) array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_; return a.release(); } // Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that // reference the Eigen object's data with `base` as the python-registered base class (if omitted, // the base will be set to None, and lifetime management is up to the caller). The numpy array is // non-writeable if the given type is const. template <typename props, typename Type> handle eigen_ref_array(Type &src, handle parent = none()) { // none here is to get past array's should-we-copy detection, which currently always // copies when there is no base. Setting the base to None should be harmless. return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value); } // Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a numpy // array that references the encapsulated data with a python-side reference to the capsule to tie // its destruction to that of any dependent python objects. Const-ness is determined by whether or // not the Type of the pointer given is const. template <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>> handle eigen_encapsulate(Type *src) { capsule base(src, [](void *o) { delete static_cast<Type *>(o); }); return eigen_ref_array<props>(*src, base); } // Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense // types. template<typename Type> struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> { using Scalar = typename Type::Scalar; using props = EigenProps<Type>; bool load(handle src, bool convert) { // If we're in no-convert mode, only load if given an array of the correct type if (!convert && !isinstance<array_t<Scalar>>(src)) return false; // Coerce into an array, but don't do type conversion yet; the copy below handles it. auto buf = array::ensure(src); if (!buf) return false; auto dims = buf.ndim(); if (dims < 1 || dims > 2) return false; auto fits = props::conformable(buf); if (!fits) return false; // Allocate the new type, then build a numpy reference into it value = Type(fits.rows, fits.cols); auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value)); if (dims == 1) ref = ref.squeeze(); else if (ref.ndim() == 1) buf = buf.squeeze(); int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr()); if (result < 0) { // Copy failed! PyErr_Clear(); return false; } return true; } private: // Cast implementation template <typename CType> static handle cast_impl(CType *src, return_value_policy policy, handle parent) { switch (policy) { case return_value_policy::take_ownership: case return_value_policy::automatic: return eigen_encapsulate<props>(src); case return_value_policy::move: return eigen_encapsulate<props>(new CType(std::move(*src))); case return_value_policy::copy: return eigen_array_cast<props>(*src); case return_value_policy::reference: case return_value_policy::automatic_reference: return eigen_ref_array<props>(*src); case return_value_policy::reference_internal: return eigen_ref_array<props>(*src, parent); default: throw cast_error("unhandled return_value_policy: should not happen!"); }; } public: // Normal returned non-reference, non-const value: static handle cast(Type &&src, return_value_policy /* policy */, handle parent) { return cast_impl(&src, return_value_policy::move, parent); } // If you return a non-reference const, we mark the numpy array readonly: static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) { return cast_impl(&src, return_value_policy::move, parent); } // lvalue reference return; default (automatic) becomes copy static handle cast(Type &src, return_value_policy policy, handle parent) { if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) policy = return_value_policy::copy; return cast_impl(&src, policy, parent); } // const lvalue reference return; default (automatic) becomes copy static handle cast(const Type &src, return_value_policy policy, handle parent) { if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) policy = return_value_policy::copy; return cast(&src, policy, parent); } // non-const pointer return static handle cast(Type *src, return_value_policy policy, handle parent) { return cast_impl(src, policy, parent); } // const pointer return static handle cast(const Type *src, return_value_policy policy, handle parent) { return cast_impl(src, policy, parent); } static constexpr auto name = props::descriptor; // NOLINTNEXTLINE(google-explicit-constructor) operator Type*() { return &value; } // NOLINTNEXTLINE(google-explicit-constructor) operator Type&() { return value; } // NOLINTNEXTLINE(google-explicit-constructor) operator Type&&() && { return std::move(value); } template <typename T> using cast_op_type = movable_cast_op_type<T>; private: Type value; }; // Base class for casting reference/map/block/etc. objects back to python. template <typename MapType> struct eigen_map_caster { private: using props = EigenProps<MapType>; public: // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has // to stay around), but we'll allow it under the assumption that you know what you're doing (and // have an appropriate keep_alive in place). We return a numpy array pointing directly at the // ref's data (The numpy array ends up read-only if the ref was to a const matrix type.) Note // that this means you need to ensure you don't destroy the object in some other way (e.g. with // an appropriate keep_alive, or with a reference to a statically allocated matrix). static handle cast(const MapType &src, return_value_policy policy, handle parent) { switch (policy) { case return_value_policy::copy: return eigen_array_cast<props>(src); case return_value_policy::reference_internal: return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value); case return_value_policy::reference: case return_value_policy::automatic: case return_value_policy::automatic_reference: return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value); default: // move, take_ownership don't make any sense for a ref/map: pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type"); } } static constexpr auto name = props::descriptor; // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return // types but not bound arguments). We still provide them (with an explicitly delete) so that // you end up here if you try anyway. bool load(handle, bool) = delete; operator MapType() = delete; template <typename> using cast_op_type = MapType; }; // We can return any map-like object (but can only load Refs, specialized next): template <typename Type> struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> : eigen_map_caster<Type> {}; // Loader for Ref<...> arguments. See the documentation for info on how to make this work without // copying (it requires some extra effort in many cases). template <typename PlainObjectType, typename StrideType> struct type_caster< Eigen::Ref<PlainObjectType, 0, StrideType>, enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value> > : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> { private: using Type = Eigen::Ref<PlainObjectType, 0, StrideType>; using props = EigenProps<Type>; using Scalar = typename props::Scalar; using MapType = Eigen::Map<PlainObjectType, 0, StrideType>; using Array = array_t<Scalar, array::forcecast | ((props::row_major ? props::inner_stride : props::outer_stride) == 1 ? array::c_style : (props::row_major ? props::outer_stride : props::inner_stride) == 1 ? array::f_style : 0)>; static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value; // Delay construction (these have no default constructor) std::unique_ptr<MapType> map; std::unique_ptr<Type> ref; // Our array. When possible, this is just a numpy array pointing to the source data, but // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an incompatible // layout, or is an array of a type that needs to be converted). Using a numpy temporary // (rather than an Eigen temporary) saves an extra copy when we need both type conversion and // storage order conversion. (Note that we refuse to use this temporary copy when loading an // argument for a Ref<M> with M non-const, i.e. a read-write reference). Array copy_or_ref; public: bool load(handle src, bool convert) { // First check whether what we have is already an array of the right type. If not, we can't // avoid a copy (because the copy is also going to do type conversion). bool need_copy = !isinstance<Array>(src); EigenConformable<props::row_major> fits; if (!need_copy) { // We don't need a converting copy, but we also need to check whether the strides are // compatible with the Ref's stride requirements auto aref = reinterpret_borrow<Array>(src); if (aref && (!need_writeable || aref.writeable())) { fits = props::conformable(aref); if (!fits) return false; // Incompatible dimensions if (!fits.template stride_compatible<props>()) need_copy = true; else copy_or_ref = std::move(aref); } else { need_copy = true; } } if (need_copy) { // We need to copy: If we need a mutable reference, or we're not supposed to convert // (either because we're in the no-convert overload pass, or because we're explicitly // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading. if (!convert || need_writeable) return false; Array copy = Array::ensure(src); if (!copy) return false; fits = props::conformable(copy); if (!fits || !fits.template stride_compatible<props>()) return false; copy_or_ref = std::move(copy); loader_life_support::add_patient(copy_or_ref); } ref.reset(); map.reset(new MapType(data(copy_or_ref), fits.rows, fits.cols, make_stride(fits.stride.outer(), fits.stride.inner()))); ref.reset(new Type(*map)); return true; } // NOLINTNEXTLINE(google-explicit-constructor) operator Type*() { return ref.get(); } // NOLINTNEXTLINE(google-explicit-constructor) operator Type&() { return *ref; } template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>; private: template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0> Scalar *data(Array &a) { return a.mutable_data(); } template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0> const Scalar *data(Array &a) { return a.data(); } // Attempt to figure out a constructor of `Stride` that will work. // If both strides are fixed, use a default constructor: template <typename S> using stride_ctor_default = bool_constant< S::InnerStrideAtCompileTime != Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic && std::is_default_constructible<S>::value>; // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like // Eigen::Stride, and use it: template <typename S> using stride_ctor_dual = bool_constant< !stride_ctor_default<S>::value && std::is_constructible<S, EigenIndex, EigenIndex>::value>; // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use // it (passing whichever stride is dynamic). template <typename S> using stride_ctor_outer = bool_constant< !any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value && S::OuterStrideAtCompileTime == Eigen::Dynamic && S::InnerStrideAtCompileTime != Eigen::Dynamic && std::is_constructible<S, EigenIndex>::value>; template <typename S> using stride_ctor_inner = bool_constant< !any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value && S::InnerStrideAtCompileTime == Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic && std::is_constructible<S, EigenIndex>::value>; template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0> static S make_stride(EigenIndex, EigenIndex) { return S(); } template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0> static S make_stride(EigenIndex outer, EigenIndex inner) { return S(outer, inner); } template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0> static S make_stride(EigenIndex outer, EigenIndex) { return S(outer); } template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0> static S make_stride(EigenIndex, EigenIndex inner) { return S(inner); } }; // type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not // EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout). // load() is not supported, but we can cast them into the python domain by first copying to a // regular Eigen::Matrix, then casting that. template <typename Type> struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> { protected: using Matrix = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>; using props = EigenProps<Matrix>; public: static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) { handle h = eigen_encapsulate<props>(new Matrix(src)); return h; } static handle cast(const Type *src, return_value_policy policy, handle parent) { return cast(*src, policy, parent); } static constexpr auto name = props::descriptor; // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return // types but not bound arguments). We still provide them (with an explicitly delete) so that // you end up here if you try anyway. bool load(handle, bool) = delete; operator Type() = delete; template <typename> using cast_op_type = Type; }; template<typename Type> struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> { using Scalar = typename Type::Scalar; using StorageIndex = remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())>; using Index = typename Type::Index; static constexpr bool rowMajor = Type::IsRowMajor; bool load(handle src, bool) { if (!src) return false; auto obj = reinterpret_borrow<object>(src); object sparse_module = module_::import("scipy.sparse"); object matrix_type = sparse_module.attr( rowMajor ? "csr_matrix" : "csc_matrix"); if (!type::handle_of(obj).is(matrix_type)) { try { obj = matrix_type(obj); } catch (const error_already_set &) { return false; } } auto values = array_t<Scalar>((object) obj.attr("data")); auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices")); auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr")); auto shape = pybind11::tuple((pybind11::object) obj.attr("shape")); auto nnz = obj.attr("nnz").cast<Index>(); if (!values || !innerIndices || !outerIndices) return false; value = Eigen::MappedSparseMatrix<Scalar, Type::Flags, StorageIndex>( shape[0].cast<Index>(), shape[1].cast<Index>(), nnz, outerIndices.mutable_data(), innerIndices.mutable_data(), values.mutable_data()); return true; } static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) { const_cast<Type&>(src).makeCompressed(); object matrix_type = module_::import("scipy.sparse").attr( rowMajor ? "csr_matrix" : "csc_matrix"); array data(src.nonZeros(), src.valuePtr()); array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr()); array innerIndices(src.nonZeros(), src.innerIndexPtr()); return matrix_type( std::make_tuple(data, innerIndices, outerIndices), std::make_pair(src.rows(), src.cols()) ).release(); } PYBIND11_TYPE_CASTER(Type, _<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[", "scipy.sparse.csc_matrix[") + npy_format_descriptor<Scalar>::name + _("]")); }; PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
28,751
C
47.649746
163
0.648256
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/buffer_info.h
/* pybind11/buffer_info.h: Python buffer object interface Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "detail/common.h" PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) // Default, C-style strides inline std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) { auto ndim = shape.size(); std::vector<ssize_t> strides(ndim, itemsize); if (ndim > 0) for (size_t i = ndim - 1; i > 0; --i) strides[i - 1] = strides[i] * shape[i]; return strides; } // F-style strides; default when constructing an array_t with `ExtraFlags & f_style` inline std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) { auto ndim = shape.size(); std::vector<ssize_t> strides(ndim, itemsize); for (size_t i = 1; i < ndim; ++i) strides[i] = strides[i - 1] * shape[i - 1]; return strides; } PYBIND11_NAMESPACE_END(detail) /// Information record describing a Python buffer object struct buffer_info { void *ptr = nullptr; // Pointer to the underlying storage ssize_t itemsize = 0; // Size of individual items in bytes ssize_t size = 0; // Total number of entries std::string format; // For homogeneous buffers, this should be set to format_descriptor<T>::format() ssize_t ndim = 0; // Number of dimensions std::vector<ssize_t> shape; // Shape of the tensor (1 entry per dimension) std::vector<ssize_t> strides; // Number of bytes between adjacent entries (for each per dimension) bool readonly = false; // flag to indicate if the underlying storage may be written to buffer_info() = default; buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim, detail::any_container<ssize_t> shape_in, detail::any_container<ssize_t> strides_in, bool readonly=false) : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim), shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) { if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size()) pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length"); for (size_t i = 0; i < (size_t) ndim; ++i) size *= shape[i]; } template <typename T> buffer_info(T *ptr, detail::any_container<ssize_t> shape_in, detail::any_container<ssize_t> strides_in, bool readonly=false) : buffer_info(private_ctr_tag(), ptr, sizeof(T), format_descriptor<T>::format(), static_cast<ssize_t>(shape_in->size()), std::move(shape_in), std::move(strides_in), readonly) { } buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t size, bool readonly=false) : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) { } template <typename T> buffer_info(T *ptr, ssize_t size, bool readonly=false) : buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size, readonly) { } template <typename T> buffer_info(const T *ptr, ssize_t size, bool readonly=true) : buffer_info(const_cast<T*>(ptr), sizeof(T), format_descriptor<T>::format(), size, readonly) { } explicit buffer_info(Py_buffer *view, bool ownview = true) : buffer_info(view->buf, view->itemsize, view->format, view->ndim, {view->shape, view->shape + view->ndim}, /* Though buffer::request() requests PyBUF_STRIDES, ctypes objects * ignore this flag and return a view with NULL strides. * When strides are NULL, build them manually. */ view->strides ? std::vector<ssize_t>(view->strides, view->strides + view->ndim) : detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize), (view->readonly != 0)) { this->m_view = view; this->ownview = ownview; } buffer_info(const buffer_info &) = delete; buffer_info& operator=(const buffer_info &) = delete; buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); } buffer_info &operator=(buffer_info &&rhs) noexcept { ptr = rhs.ptr; itemsize = rhs.itemsize; size = rhs.size; format = std::move(rhs.format); ndim = rhs.ndim; shape = std::move(rhs.shape); strides = std::move(rhs.strides); std::swap(m_view, rhs.m_view); std::swap(ownview, rhs.ownview); readonly = rhs.readonly; return *this; } ~buffer_info() { if (m_view && ownview) { PyBuffer_Release(m_view); delete m_view; } } Py_buffer *view() const { return m_view; } Py_buffer *&view() { return m_view; } private: struct private_ctr_tag { }; buffer_info(private_ctr_tag, void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim, detail::any_container<ssize_t> &&shape_in, detail::any_container<ssize_t> &&strides_in, bool readonly) : buffer_info(ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) { } Py_buffer *m_view = nullptr; bool ownview = false; }; PYBIND11_NAMESPACE_BEGIN(detail) template <typename T, typename SFINAE = void> struct compare_buffer_info { static bool compare(const buffer_info& b) { return b.format == format_descriptor<T>::format() && b.itemsize == (ssize_t) sizeof(T); } }; template <typename T> struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> { static bool compare(const buffer_info& b) { return (size_t) b.itemsize == sizeof(T) && (b.format == format_descriptor<T>::value || ((sizeof(T) == sizeof(long)) && b.format == (std::is_unsigned<T>::value ? "L" : "l")) || ((sizeof(T) == sizeof(size_t)) && b.format == (std::is_unsigned<T>::value ? "N" : "n"))); } }; PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
6,131
C
41.289655
182
0.627304
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/options.h
/* pybind11/options.h: global settings that are configurable at runtime. Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "detail/common.h" PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) class options { public: // Default RAII constructor, which leaves settings as they currently are. options() : previous_state(global_state()) {} // Class is non-copyable. options(const options&) = delete; options& operator=(const options&) = delete; // Destructor, which restores settings that were in effect before. ~options() { global_state() = previous_state; } // Setter methods (affect the global state): options& disable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = false; return *this; } options& enable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = true; return *this; } options& disable_function_signatures() & { global_state().show_function_signatures = false; return *this; } options& enable_function_signatures() & { global_state().show_function_signatures = true; return *this; } // Getter methods (return the global state): static bool show_user_defined_docstrings() { return global_state().show_user_defined_docstrings; } static bool show_function_signatures() { return global_state().show_function_signatures; } // This type is not meant to be allocated on the heap. void* operator new(size_t) = delete; private: struct state { bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings. bool show_function_signatures = true; //< Include auto-generated function signatures in docstrings. }; static state &global_state() { static state instance; return instance; } state previous_state; }; PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
2,049
C
30.060606
119
0.691069
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/embed.h
/* pybind11/embed.h: Support for embedding the interpreter Copyright (c) 2017 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "pybind11.h" #include "eval.h" #include <memory> #include <vector> #if defined(PYPY_VERSION) # error Embedding the interpreter is not supported with PyPy #endif #if PY_MAJOR_VERSION >= 3 # define PYBIND11_EMBEDDED_MODULE_IMPL(name) \ extern "C" PyObject *pybind11_init_impl_##name(); \ extern "C" PyObject *pybind11_init_impl_##name() { \ return pybind11_init_wrapper_##name(); \ } #else # define PYBIND11_EMBEDDED_MODULE_IMPL(name) \ extern "C" void pybind11_init_impl_##name(); \ extern "C" void pybind11_init_impl_##name() { \ pybind11_init_wrapper_##name(); \ } #endif /** \rst Add a new module to the table of builtins for the interpreter. Must be defined in global scope. The first macro parameter is the name of the module (without quotes). The second parameter is the variable which will be used as the interface to add functions and classes to the module. .. code-block:: cpp PYBIND11_EMBEDDED_MODULE(example, m) { // ... initialize functions and classes here m.def("foo", []() { return "Hello, World!"; }); } \endrst */ #define PYBIND11_EMBEDDED_MODULE(name, variable) \ static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name); \ static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \ static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \ auto m = ::pybind11::module_::create_extension_module( \ PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \ try { \ PYBIND11_CONCAT(pybind11_init_, name)(m); \ return m.ptr(); \ } \ PYBIND11_CATCH_INIT_EXCEPTIONS \ } \ PYBIND11_EMBEDDED_MODULE_IMPL(name) \ ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)( \ PYBIND11_TOSTRING(name), PYBIND11_CONCAT(pybind11_init_impl_, name)); \ void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ \ & variable) // NOLINT(bugprone-macro-parentheses) PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) /// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks. struct embedded_module { #if PY_MAJOR_VERSION >= 3 using init_t = PyObject *(*)(); #else using init_t = void (*)(); #endif embedded_module(const char *name, init_t init) { if (Py_IsInitialized() != 0) pybind11_fail("Can't add new modules after the interpreter has been initialized"); auto result = PyImport_AppendInittab(name, init); if (result == -1) pybind11_fail("Insufficient memory to add a new module"); } }; struct wide_char_arg_deleter { void operator()(wchar_t *ptr) const { #if PY_VERSION_HEX >= 0x030500f0 // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale PyMem_RawFree(ptr); #else delete[] ptr; #endif } }; inline wchar_t *widen_chars(const char *safe_arg) { #if PY_VERSION_HEX >= 0x030500f0 wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr); #else wchar_t *widened_arg = nullptr; # if defined(HAVE_BROKEN_MBSTOWCS) && HAVE_BROKEN_MBSTOWCS size_t count = strlen(safe_arg); # else size_t count = mbstowcs(nullptr, safe_arg, 0); # endif if (count != static_cast<size_t>(-1)) { widened_arg = new wchar_t[count + 1]; mbstowcs(widened_arg, safe_arg, count + 1); } #endif return widened_arg; } /// Python 2.x/3.x-compatible version of `PySys_SetArgv` inline void set_interpreter_argv(int argc, const char *const *argv, bool add_program_dir_to_path) { // Before it was special-cased in python 3.8, passing an empty or null argv // caused a segfault, so we have to reimplement the special case ourselves. bool special_case = (argv == nullptr || argc <= 0); const char *const empty_argv[]{"\0"}; const char *const *safe_argv = special_case ? empty_argv : argv; if (special_case) argc = 1; auto argv_size = static_cast<size_t>(argc); #if PY_MAJOR_VERSION >= 3 // SetArgv* on python 3 takes wchar_t, so we have to convert. std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]); std::vector<std::unique_ptr<wchar_t[], wide_char_arg_deleter>> widened_argv_entries; widened_argv_entries.reserve(argv_size); for (size_t ii = 0; ii < argv_size; ++ii) { widened_argv_entries.emplace_back(widen_chars(safe_argv[ii])); if (!widened_argv_entries.back()) { // A null here indicates a character-encoding failure or the python // interpreter out of memory. Give up. return; } widened_argv[ii] = widened_argv_entries.back().get(); } auto pysys_argv = widened_argv.get(); #else // python 2.x std::vector<std::string> strings{safe_argv, safe_argv + argv_size}; std::vector<char *> char_strings{argv_size}; for (std::size_t i = 0; i < argv_size; ++i) char_strings[i] = &strings[i][0]; char **pysys_argv = char_strings.data(); #endif PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path)); } PYBIND11_NAMESPACE_END(detail) /** \rst Initialize the Python interpreter. No other pybind11 or CPython API functions can be called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The optional `init_signal_handlers` parameter can be used to skip the registration of signal handlers (see the `Python documentation`_ for details). Calling this function again after the interpreter has already been initialized is a fatal error. If initializing the Python interpreter fails, then the program is terminated. (This is controlled by the CPython runtime and is an exception to pybind11's normal behavior of throwing exceptions on errors.) The remaining optional parameters, `argc`, `argv`, and `add_program_dir_to_path` are used to populate ``sys.argv`` and ``sys.path``. See the |PySys_SetArgvEx documentation|_ for details. .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx .. |PySys_SetArgvEx documentation| replace:: ``PySys_SetArgvEx`` documentation .. _PySys_SetArgvEx documentation: https://docs.python.org/3/c-api/init.html#c.PySys_SetArgvEx \endrst */ inline void initialize_interpreter(bool init_signal_handlers = true, int argc = 0, const char *const *argv = nullptr, bool add_program_dir_to_path = true) { if (Py_IsInitialized() != 0) pybind11_fail("The interpreter is already running"); Py_InitializeEx(init_signal_handlers ? 1 : 0); detail::set_interpreter_argv(argc, argv, add_program_dir_to_path); } /** \rst Shut down the Python interpreter. No pybind11 or CPython API functions can be called after this. In addition, pybind11 objects must not outlive the interpreter: .. code-block:: cpp { // BAD py::initialize_interpreter(); auto hello = py::str("Hello, World!"); py::finalize_interpreter(); } // <-- BOOM, hello's destructor is called after interpreter shutdown { // GOOD py::initialize_interpreter(); { // scoped auto hello = py::str("Hello, World!"); } // <-- OK, hello is cleaned up properly py::finalize_interpreter(); } { // BETTER py::scoped_interpreter guard{}; auto hello = py::str("Hello, World!"); } .. warning:: The interpreter can be restarted by calling `initialize_interpreter` again. Modules created using pybind11 can be safely re-initialized. However, Python itself cannot completely unload binary extension modules and there are several caveats with regard to interpreter restarting. All the details can be found in the CPython documentation. In short, not all interpreter memory may be freed, either due to reference cycles or user-created global data. \endrst */ inline void finalize_interpreter() { handle builtins(PyEval_GetBuiltins()); const char *id = PYBIND11_INTERNALS_ID; // Get the internals pointer (without creating it if it doesn't exist). It's possible for the // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()` // during destruction), so we get the pointer-pointer here and check it after Py_Finalize(). detail::internals **internals_ptr_ptr = detail::get_internals_pp(); // It could also be stashed in builtins, so look there too: if (builtins.contains(id) && isinstance<capsule>(builtins[id])) internals_ptr_ptr = capsule(builtins[id]); Py_Finalize(); if (internals_ptr_ptr) { delete *internals_ptr_ptr; *internals_ptr_ptr = nullptr; } } /** \rst Scope guard version of `initialize_interpreter` and `finalize_interpreter`. This a move-only guard and only a single instance can exist. See `initialize_interpreter` for a discussion of its constructor arguments. .. code-block:: cpp #include <pybind11/embed.h> int main() { py::scoped_interpreter guard{}; py::print(Hello, World!); } // <-- interpreter shutdown \endrst */ class scoped_interpreter { public: explicit scoped_interpreter(bool init_signal_handlers = true, int argc = 0, const char *const *argv = nullptr, bool add_program_dir_to_path = true) { initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path); } scoped_interpreter(const scoped_interpreter &) = delete; scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; } scoped_interpreter &operator=(const scoped_interpreter &) = delete; scoped_interpreter &operator=(scoped_interpreter &&) = delete; ~scoped_interpreter() { if (is_valid) finalize_interpreter(); } private: bool is_valid = true; }; PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
11,439
C
39.140351
99
0.596818
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/gil.h
/* pybind11/gil.h: RAII helpers for managing the GIL Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "detail/common.h" #include "detail/internals.h" PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) // forward declarations PyThreadState *get_thread_state_unchecked(); PYBIND11_NAMESPACE_END(detail) #if defined(WITH_THREAD) && !defined(PYPY_VERSION) /* The functions below essentially reproduce the PyGILState_* API using a RAII * pattern, but there are a few important differences: * * 1. When acquiring the GIL from an non-main thread during the finalization * phase, the GILState API blindly terminates the calling thread, which * is often not what is wanted. This API does not do this. * * 2. The gil_scoped_release function can optionally cut the relationship * of a PyThreadState and its associated thread, which allows moving it to * another thread (this is a fairly rare/advanced use case). * * 3. The reference count of an acquired thread state can be controlled. This * can be handy to prevent cases where callbacks issued from an external * thread would otherwise constantly construct and destroy thread state data * structures. * * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an * example which uses features 2 and 3 to migrate the Python thread of * execution to another thread (to run the event loop on the original thread, * in this case). */ class gil_scoped_acquire { public: PYBIND11_NOINLINE gil_scoped_acquire() { auto const &internals = detail::get_internals(); tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate); if (!tstate) { /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if calling from a Python thread). Since we use a different key, this ensures we don't create a new thread state and deadlock in PyEval_AcquireThread below. Note we don't save this state with internals.tstate, since we don't create it we would fail to clear it (its reference count should be > 0). */ tstate = PyGILState_GetThisThreadState(); } if (!tstate) { tstate = PyThreadState_New(internals.istate); #if !defined(NDEBUG) if (!tstate) pybind11_fail("scoped_acquire: could not create thread state!"); #endif tstate->gilstate_counter = 0; PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate); } else { release = detail::get_thread_state_unchecked() != tstate; } if (release) { PyEval_AcquireThread(tstate); } inc_ref(); } void inc_ref() { ++tstate->gilstate_counter; } PYBIND11_NOINLINE void dec_ref() { --tstate->gilstate_counter; #if !defined(NDEBUG) if (detail::get_thread_state_unchecked() != tstate) pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!"); if (tstate->gilstate_counter < 0) pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!"); #endif if (tstate->gilstate_counter == 0) { #if !defined(NDEBUG) if (!release) pybind11_fail("scoped_acquire::dec_ref(): internal error!"); #endif PyThreadState_Clear(tstate); if (active) PyThreadState_DeleteCurrent(); PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate); release = false; } } /// This method will disable the PyThreadState_DeleteCurrent call and the /// GIL won't be acquired. This method should be used if the interpreter /// could be shutting down when this is called, as thread deletion is not /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and /// protect subsequent code. PYBIND11_NOINLINE void disarm() { active = false; } PYBIND11_NOINLINE ~gil_scoped_acquire() { dec_ref(); if (release) PyEval_SaveThread(); } private: PyThreadState *tstate = nullptr; bool release = true; bool active = true; }; class gil_scoped_release { public: explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) { // `get_internals()` must be called here unconditionally in order to initialize // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an // initialization race could occur as multiple threads try `gil_scoped_acquire`. const auto &internals = detail::get_internals(); tstate = PyEval_SaveThread(); if (disassoc) { auto key = internals.tstate; PYBIND11_TLS_DELETE_VALUE(key); } } /// This method will disable the PyThreadState_DeleteCurrent call and the /// GIL won't be acquired. This method should be used if the interpreter /// could be shutting down when this is called, as thread deletion is not /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and /// protect subsequent code. PYBIND11_NOINLINE void disarm() { active = false; } ~gil_scoped_release() { if (!tstate) return; // `PyEval_RestoreThread()` should not be called if runtime is finalizing if (active) PyEval_RestoreThread(tstate); if (disassoc) { auto key = detail::get_internals().tstate; PYBIND11_TLS_REPLACE_VALUE(key, tstate); } } private: PyThreadState *tstate; bool disassoc; bool active = true; }; #elif defined(PYPY_VERSION) class gil_scoped_acquire { PyGILState_STATE state; public: gil_scoped_acquire() { state = PyGILState_Ensure(); } ~gil_scoped_acquire() { PyGILState_Release(state); } void disarm() {} }; class gil_scoped_release { PyThreadState *state; public: gil_scoped_release() { state = PyEval_SaveThread(); } ~gil_scoped_release() { PyEval_RestoreThread(state); } void disarm() {} }; #else class gil_scoped_acquire { void disarm() {} }; class gil_scoped_release { void disarm() {} }; #endif PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
6,532
C
32.675258
90
0.637171
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/pytypes.h
/* pybind11/pytypes.h: Convenience wrapper classes for basic Python types Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "detail/common.h" #include "buffer_info.h" #include <utility> #include <type_traits> PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) /* A few forward declarations */ class handle; class object; class str; class iterator; class type; struct arg; struct arg_v; PYBIND11_NAMESPACE_BEGIN(detail) class args_proxy; bool isinstance_generic(handle obj, const std::type_info &tp); // Accessor forward declarations template <typename Policy> class accessor; namespace accessor_policies { struct obj_attr; struct str_attr; struct generic_item; struct sequence_item; struct list_item; struct tuple_item; } // namespace accessor_policies using obj_attr_accessor = accessor<accessor_policies::obj_attr>; using str_attr_accessor = accessor<accessor_policies::str_attr>; using item_accessor = accessor<accessor_policies::generic_item>; using sequence_accessor = accessor<accessor_policies::sequence_item>; using list_accessor = accessor<accessor_policies::list_item>; using tuple_accessor = accessor<accessor_policies::tuple_item>; /// Tag and check to identify a class which implements the Python object API class pyobject_tag { }; template <typename T> using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>; /** \rst A mixin class which adds common functions to `handle`, `object` and various accessors. The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``. \endrst */ template <typename Derived> class object_api : public pyobject_tag { const Derived &derived() const { return static_cast<const Derived &>(*this); } public: /** \rst Return an iterator equivalent to calling ``iter()`` in Python. The object must be a collection which supports the iteration protocol. \endrst */ iterator begin() const; /// Return a sentinel which ends iteration. iterator end() const; /** \rst Return an internal functor to invoke the object's sequence protocol. Casting the returned ``detail::item_accessor`` instance to a `handle` or `object` subclass causes a corresponding call to ``__getitem__``. Assigning a `handle` or `object` subclass causes a call to ``__setitem__``. \endrst */ item_accessor operator[](handle key) const; /// See above (the only difference is that they key is provided as a string literal) item_accessor operator[](const char *key) const; /** \rst Return an internal functor to access the object's attributes. Casting the returned ``detail::obj_attr_accessor`` instance to a `handle` or `object` subclass causes a corresponding call to ``getattr``. Assigning a `handle` or `object` subclass causes a call to ``setattr``. \endrst */ obj_attr_accessor attr(handle key) const; /// See above (the only difference is that they key is provided as a string literal) str_attr_accessor attr(const char *key) const; /** \rst Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple`` or ``list`` for a function call. Applying another * to the result yields ** unpacking, e.g. to unpack a dict as function keyword arguments. See :ref:`calling_python_functions`. \endrst */ args_proxy operator*() const; /// Check if the given item is contained within this object, i.e. ``item in obj``. template <typename T> bool contains(T &&item) const; /** \rst Assuming the Python object is a function or implements the ``__call__`` protocol, ``operator()`` invokes the underlying function, passing an arbitrary set of parameters. The result is returned as a `object` and may need to be converted back into a Python object using `handle::cast()`. When some of the arguments cannot be converted to Python objects, the function will throw a `cast_error` exception. When the Python function call fails, a `error_already_set` exception is thrown. \endrst */ template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> object operator()(Args &&...args) const; template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)") object call(Args&&... args) const; /// Equivalent to ``obj is other`` in Python. bool is(object_api const& other) const { return derived().ptr() == other.derived().ptr(); } /// Equivalent to ``obj is None`` in Python. bool is_none() const { return derived().ptr() == Py_None; } /// Equivalent to obj == other in Python bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); } bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); } bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); } bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); } bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); } bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); } object operator-() const; object operator~() const; object operator+(object_api const &other) const; object operator+=(object_api const &other) const; object operator-(object_api const &other) const; object operator-=(object_api const &other) const; object operator*(object_api const &other) const; object operator*=(object_api const &other) const; object operator/(object_api const &other) const; object operator/=(object_api const &other) const; object operator|(object_api const &other) const; object operator|=(object_api const &other) const; object operator&(object_api const &other) const; object operator&=(object_api const &other) const; object operator^(object_api const &other) const; object operator^=(object_api const &other) const; object operator<<(object_api const &other) const; object operator<<=(object_api const &other) const; object operator>>(object_api const &other) const; object operator>>=(object_api const &other) const; PYBIND11_DEPRECATED("Use py::str(obj) instead") pybind11::str str() const; /// Get or set the object's docstring, i.e. ``obj.__doc__``. str_attr_accessor doc() const; /// Return the object's current reference count int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); } // TODO PYBIND11_DEPRECATED("Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()") handle get_type() const; private: bool rich_compare(object_api const &other, int value) const; }; PYBIND11_NAMESPACE_END(detail) /** \rst Holds a reference to a Python object (no reference counting) The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a ``PyObject *`` in Python's C API). It does not perform any automatic reference counting and merely provides a basic C++ interface to various Python API functions. .. seealso:: The `object` class inherits from `handle` and adds automatic reference counting features. \endrst */ class handle : public detail::object_api<handle> { public: /// The default constructor creates a handle with a ``nullptr``-valued pointer handle() = default; /// Creates a ``handle`` from the given raw Python object pointer // NOLINTNEXTLINE(google-explicit-constructor) handle(PyObject *ptr) : m_ptr(ptr) { } // Allow implicit conversion from PyObject* /// Return the underlying ``PyObject *`` pointer PyObject *ptr() const { return m_ptr; } PyObject *&ptr() { return m_ptr; } /** \rst Manually increase the reference count of the Python object. Usually, it is preferable to use the `object` class which derives from `handle` and calls this function automatically. Returns a reference to itself. \endrst */ const handle& inc_ref() const & { Py_XINCREF(m_ptr); return *this; } /** \rst Manually decrease the reference count of the Python object. Usually, it is preferable to use the `object` class which derives from `handle` and calls this function automatically. Returns a reference to itself. \endrst */ const handle& dec_ref() const & { Py_XDECREF(m_ptr); return *this; } /** \rst Attempt to cast the Python object into the given C++ type. A `cast_error` will be throw upon failure. \endrst */ template <typename T> T cast() const; /// Return ``true`` when the `handle` wraps a valid Python object explicit operator bool() const { return m_ptr != nullptr; } /** \rst Deprecated: Check that the underlying pointers are the same. Equivalent to ``obj1 is obj2`` in Python. \endrst */ PYBIND11_DEPRECATED("Use obj1.is(obj2) instead") bool operator==(const handle &h) const { return m_ptr == h.m_ptr; } PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead") bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; } PYBIND11_DEPRECATED("Use handle::operator bool() instead") bool check() const { return m_ptr != nullptr; } protected: PyObject *m_ptr = nullptr; }; /** \rst Holds a reference to a Python object (with reference counting) Like `handle`, the `object` class is a thin wrapper around an arbitrary Python object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it optionally increases the object's reference count upon construction, and it *always* decreases the reference count when the `object` instance goes out of scope and is destructed. When using `object` instances consistently, it is much easier to get reference counting right at the first attempt. \endrst */ class object : public handle { public: object() = default; PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") object(handle h, bool is_borrowed) : handle(h) { if (is_borrowed) inc_ref(); } /// Copy constructor; always increases the reference count object(const object &o) : handle(o) { inc_ref(); } /// Move constructor; steals the object from ``other`` and preserves its reference count object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; } /// Destructor; automatically calls `handle::dec_ref()` ~object() { dec_ref(); } /** \rst Resets the internal pointer to ``nullptr`` without decreasing the object's reference count. The function returns a raw handle to the original Python object. \endrst */ handle release() { PyObject *tmp = m_ptr; m_ptr = nullptr; return handle(tmp); } object& operator=(const object &other) { other.inc_ref(); dec_ref(); m_ptr = other.m_ptr; return *this; } object& operator=(object &&other) noexcept { if (this != &other) { handle temp(m_ptr); m_ptr = other.m_ptr; other.m_ptr = nullptr; temp.dec_ref(); } return *this; } // Calling cast() on an object lvalue just copies (via handle::cast) template <typename T> T cast() const &; // Calling on an object rvalue does a move, if needed and/or possible template <typename T> T cast() &&; protected: // Tags for choosing constructors from raw PyObject * struct borrowed_t { }; struct stolen_t { }; #ifndef DOXYGEN_SHOULD_SKIP_THIS // Issue in breathe 4.26.1 template <typename T> friend T reinterpret_borrow(handle); template <typename T> friend T reinterpret_steal(handle); #endif public: // Only accessible from derived classes and the reinterpret_* functions object(handle h, borrowed_t) : handle(h) { inc_ref(); } object(handle h, stolen_t) : handle(h) { } }; /** \rst Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference. The target type ``T`` must be `object` or one of its derived classes. The function doesn't do any conversions or checks. It's up to the user to make sure that the target type is correct. .. code-block:: cpp PyObject *p = PyList_GetItem(obj, index); py::object o = reinterpret_borrow<py::object>(p); // or py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple` \endrst */ template <typename T> T reinterpret_borrow(handle h) { return {h, object::borrowed_t{}}; } /** \rst Like `reinterpret_borrow`, but steals the reference. .. code-block:: cpp PyObject *p = PyObject_Str(obj); py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str` \endrst */ template <typename T> T reinterpret_steal(handle h) { return {h, object::stolen_t{}}; } PYBIND11_NAMESPACE_BEGIN(detail) std::string error_string(); PYBIND11_NAMESPACE_END(detail) #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable: 4275 4251) // warning C4275: An exported class was derived from a class that wasn't exported. Can be ignored when derived from a STL class. #endif /// Fetch and hold an error which was already set in Python. An instance of this is typically /// thrown to propagate python-side errors back through C++ which can either be caught manually or /// else falls back to the function dispatcher (which then raises the captured error back to /// python). class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::runtime_error { public: /// Constructs a new exception from the current Python error indicator, if any. The current /// Python error indicator will be cleared. error_already_set() : std::runtime_error(detail::error_string()) { PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr()); } error_already_set(const error_already_set &) = default; error_already_set(error_already_set &&) = default; inline ~error_already_set() override; /// Give the currently-held error back to Python, if any. If there is currently a Python error /// already set it is cleared first. After this call, the current object no longer stores the /// error variables (but the `.what()` string is still available). void restore() { PyErr_Restore(m_type.release().ptr(), m_value.release().ptr(), m_trace.release().ptr()); } /// If it is impossible to raise the currently-held error, such as in a destructor, we can write /// it out using Python's unraisable hook (`sys.unraisablehook`). The error context should be /// some object whose `repr()` helps identify the location of the error. Python already knows the /// type and value of the error, so there is no need to repeat that. After this call, the current /// object no longer stores the error variables, and neither does Python. void discard_as_unraisable(object err_context) { restore(); PyErr_WriteUnraisable(err_context.ptr()); } /// An alternate version of `discard_as_unraisable()`, where a string provides information on the /// location of the error. For example, `__func__` could be helpful. void discard_as_unraisable(const char *err_context) { discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context))); } // Does nothing; provided for backwards compatibility. PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated") void clear() {} /// Check if the currently trapped error type matches the given Python exception class (or a /// subclass thereof). May also be passed a tuple to search for any exception class matches in /// the given tuple. bool matches(handle exc) const { return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0); } const object& type() const { return m_type; } const object& value() const { return m_value; } const object& trace() const { return m_trace; } private: object m_type, m_value, m_trace; }; #if defined(_MSC_VER) # pragma warning(pop) #endif #if PY_VERSION_HEX >= 0x03030000 /// Replaces the current Python error indicator with the chosen error, performing a /// 'raise from' to indicate that the chosen error was caused by the original error. inline void raise_from(PyObject *type, const char *message) { // Based on _PyErr_FormatVFromCause: // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405 // See https://github.com/pybind/pybind11/pull/2112 for details. PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr; assert(PyErr_Occurred()); PyErr_Fetch(&exc, &val, &tb); PyErr_NormalizeException(&exc, &val, &tb); if (tb != nullptr) { PyException_SetTraceback(val, tb); Py_DECREF(tb); } Py_DECREF(exc); assert(!PyErr_Occurred()); PyErr_SetString(type, message); PyErr_Fetch(&exc, &val2, &tb); PyErr_NormalizeException(&exc, &val2, &tb); Py_INCREF(val); PyException_SetCause(val2, val); PyException_SetContext(val2, val); PyErr_Restore(exc, val2, tb); } /// Sets the current Python error indicator with the chosen error, performing a 'raise from' /// from the error contained in error_already_set to indicate that the chosen error was /// caused by the original error. After this function is called error_already_set will /// no longer contain an error. inline void raise_from(error_already_set& err, PyObject *type, const char *message) { err.restore(); raise_from(type, message); } #endif /** \defgroup python_builtins _ Unless stated otherwise, the following C++ functions behave the same as their Python counterparts. */ /** \ingroup python_builtins \rst Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of `object` or a class which was exposed to Python as ``py::class_<T>``. \endrst */ template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0> bool isinstance(handle obj) { return T::check_(obj); } template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0> bool isinstance(handle obj) { return detail::isinstance_generic(obj, typeid(T)); } template <> inline bool isinstance<handle>(handle) = delete; template <> inline bool isinstance<object>(handle obj) { return obj.ptr() != nullptr; } /// \ingroup python_builtins /// Return true if ``obj`` is an instance of the ``type``. inline bool isinstance(handle obj, handle type) { const auto result = PyObject_IsInstance(obj.ptr(), type.ptr()); if (result == -1) throw error_already_set(); return result != 0; } /// \addtogroup python_builtins /// @{ inline bool hasattr(handle obj, handle name) { return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1; } inline bool hasattr(handle obj, const char *name) { return PyObject_HasAttrString(obj.ptr(), name) == 1; } inline void delattr(handle obj, handle name) { if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { throw error_already_set(); } } inline void delattr(handle obj, const char *name) { if (PyObject_DelAttrString(obj.ptr(), name) != 0) { throw error_already_set(); } } inline object getattr(handle obj, handle name) { PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr()); if (!result) { throw error_already_set(); } return reinterpret_steal<object>(result); } inline object getattr(handle obj, const char *name) { PyObject *result = PyObject_GetAttrString(obj.ptr(), name); if (!result) { throw error_already_set(); } return reinterpret_steal<object>(result); } inline object getattr(handle obj, handle name, handle default_) { if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) { return reinterpret_steal<object>(result); } PyErr_Clear(); return reinterpret_borrow<object>(default_); } inline object getattr(handle obj, const char *name, handle default_) { if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) { return reinterpret_steal<object>(result); } PyErr_Clear(); return reinterpret_borrow<object>(default_); } inline void setattr(handle obj, handle name, handle value) { if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { throw error_already_set(); } } inline void setattr(handle obj, const char *name, handle value) { if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { throw error_already_set(); } } inline ssize_t hash(handle obj) { auto h = PyObject_Hash(obj.ptr()); if (h == -1) { throw error_already_set(); } return h; } /// @} python_builtins PYBIND11_NAMESPACE_BEGIN(detail) inline handle get_function(handle value) { if (value) { #if PY_MAJOR_VERSION >= 3 if (PyInstanceMethod_Check(value.ptr())) value = PyInstanceMethod_GET_FUNCTION(value.ptr()); else #endif if (PyMethod_Check(value.ptr())) value = PyMethod_GET_FUNCTION(value.ptr()); } return value; } // Reimplementation of python's dict helper functions to ensure that exceptions // aren't swallowed (see #2862) // copied from cpython _PyDict_GetItemStringWithError inline PyObject * dict_getitemstring(PyObject *v, const char *key) { #if PY_MAJOR_VERSION >= 3 PyObject *kv = nullptr, *rv = nullptr; kv = PyUnicode_FromString(key); if (kv == NULL) { throw error_already_set(); } rv = PyDict_GetItemWithError(v, kv); Py_DECREF(kv); if (rv == NULL && PyErr_Occurred()) { throw error_already_set(); } return rv; #else return PyDict_GetItemString(v, key); #endif } inline PyObject * dict_getitem(PyObject *v, PyObject *key) { #if PY_MAJOR_VERSION >= 3 PyObject *rv = PyDict_GetItemWithError(v, key); if (rv == NULL && PyErr_Occurred()) { throw error_already_set(); } return rv; #else return PyDict_GetItem(v, key); #endif } // Helper aliases/functions to support implicit casting of values given to python accessors/methods. // When given a pyobject, this simply returns the pyobject as-is; for other C++ type, the value goes // through pybind11::cast(obj) to convert it to an `object`. template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0> auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) { return std::forward<T>(o); } // The following casting version is implemented in cast.h: template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0> object object_or_cast(T &&o); // Match a PyObject*, which we want to convert directly to handle via its converting constructor inline handle object_or_cast(PyObject *ptr) { return ptr; } #if defined(_MSC_VER) && _MSC_VER < 1920 # pragma warning(push) # pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified #endif template <typename Policy> class accessor : public object_api<accessor<Policy>> { using key_type = typename Policy::key_type; public: accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) { } accessor(const accessor &) = default; accessor(accessor &&) noexcept = default; // accessor overload required to override default assignment operator (templates are not allowed // to replace default compiler-generated assignments). void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); } void operator=(const accessor &a) & { operator=(handle(a)); } template <typename T> void operator=(T &&value) && { Policy::set(obj, key, object_or_cast(std::forward<T>(value))); } template <typename T> void operator=(T &&value) & { get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value))); } template <typename T = Policy> PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)") explicit operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value || std::is_same<T, accessor_policies::obj_attr>::value, bool>() const { return hasattr(obj, key); } template <typename T = Policy> PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)") explicit operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const { return obj.contains(key); } // NOLINTNEXTLINE(google-explicit-constructor) operator object() const { return get_cache(); } PyObject *ptr() const { return get_cache().ptr(); } template <typename T> T cast() const { return get_cache().template cast<T>(); } private: object &get_cache() const { if (!cache) { cache = Policy::get(obj, key); } return cache; } private: handle obj; key_type key; mutable object cache; }; #if defined(_MSC_VER) && _MSC_VER < 1920 # pragma warning(pop) #endif PYBIND11_NAMESPACE_BEGIN(accessor_policies) struct obj_attr { using key_type = object; static object get(handle obj, handle key) { return getattr(obj, key); } static void set(handle obj, handle key, handle val) { setattr(obj, key, val); } }; struct str_attr { using key_type = const char *; static object get(handle obj, const char *key) { return getattr(obj, key); } static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); } }; struct generic_item { using key_type = object; static object get(handle obj, handle key) { PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr()); if (!result) { throw error_already_set(); } return reinterpret_steal<object>(result); } static void set(handle obj, handle key, handle val) { if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { throw error_already_set(); } } }; struct sequence_item { using key_type = size_t; template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> static object get(handle obj, const IdxType &index) { PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index)); if (!result) { throw error_already_set(); } return reinterpret_steal<object>(result); } template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> static void set(handle obj, const IdxType &index, handle val) { // PySequence_SetItem does not steal a reference to 'val' if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) { throw error_already_set(); } } }; struct list_item { using key_type = size_t; template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> static object get(handle obj, const IdxType &index) { PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index)); if (!result) { throw error_already_set(); } return reinterpret_borrow<object>(result); } template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> static void set(handle obj, const IdxType &index, handle val) { // PyList_SetItem steals a reference to 'val' if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) { throw error_already_set(); } } }; struct tuple_item { using key_type = size_t; template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> static object get(handle obj, const IdxType &index) { PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index)); if (!result) { throw error_already_set(); } return reinterpret_borrow<object>(result); } template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> static void set(handle obj, const IdxType &index, handle val) { // PyTuple_SetItem steals a reference to 'val' if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) { throw error_already_set(); } } }; PYBIND11_NAMESPACE_END(accessor_policies) /// STL iterator template used for tuple, list, sequence and dict template <typename Policy> class generic_iterator : public Policy { using It = generic_iterator; public: using difference_type = ssize_t; using iterator_category = typename Policy::iterator_category; using value_type = typename Policy::value_type; using reference = typename Policy::reference; using pointer = typename Policy::pointer; generic_iterator() = default; generic_iterator(handle seq, ssize_t index) : Policy(seq, index) { } // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 reference operator*() const { return Policy::dereference(); } // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 reference operator[](difference_type n) const { return *(*this + n); } pointer operator->() const { return **this; } It &operator++() { Policy::increment(); return *this; } It operator++(int) { auto copy = *this; Policy::increment(); return copy; } It &operator--() { Policy::decrement(); return *this; } It operator--(int) { auto copy = *this; Policy::decrement(); return copy; } It &operator+=(difference_type n) { Policy::advance(n); return *this; } It &operator-=(difference_type n) { Policy::advance(-n); return *this; } friend It operator+(const It &a, difference_type n) { auto copy = a; return copy += n; } friend It operator+(difference_type n, const It &b) { return b + n; } friend It operator-(const It &a, difference_type n) { auto copy = a; return copy -= n; } friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); } friend bool operator==(const It &a, const It &b) { return a.equal(b); } friend bool operator!=(const It &a, const It &b) { return !(a == b); } friend bool operator< (const It &a, const It &b) { return b - a > 0; } friend bool operator> (const It &a, const It &b) { return b < a; } friend bool operator>=(const It &a, const It &b) { return !(a < b); } friend bool operator<=(const It &a, const It &b) { return !(a > b); } }; PYBIND11_NAMESPACE_BEGIN(iterator_policies) /// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers template <typename T> struct arrow_proxy { T value; // NOLINTNEXTLINE(google-explicit-constructor) arrow_proxy(T &&value) noexcept : value(std::move(value)) { } T *operator->() const { return &value; } }; /// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS`` class sequence_fast_readonly { protected: using iterator_category = std::random_access_iterator_tag; using value_type = handle; using reference = const handle; // PR #3263 using pointer = arrow_proxy<const handle>; sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) { } // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 reference dereference() const { return *ptr; } void increment() { ++ptr; } void decrement() { --ptr; } void advance(ssize_t n) { ptr += n; } bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; } ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; } private: PyObject **ptr; }; /// Full read and write access using the sequence protocol: see ``detail::sequence_accessor`` class sequence_slow_readwrite { protected: using iterator_category = std::random_access_iterator_tag; using value_type = object; using reference = sequence_accessor; using pointer = arrow_proxy<const sequence_accessor>; sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) { } reference dereference() const { return {obj, static_cast<size_t>(index)}; } void increment() { ++index; } void decrement() { --index; } void advance(ssize_t n) { index += n; } bool equal(const sequence_slow_readwrite &b) const { return index == b.index; } ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; } private: handle obj; ssize_t index; }; /// Python's dictionary protocol permits this to be a forward iterator class dict_readonly { protected: using iterator_category = std::forward_iterator_tag; using value_type = std::pair<handle, handle>; using reference = const value_type; // PR #3263 using pointer = arrow_proxy<const value_type>; dict_readonly() = default; dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); } // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 reference dereference() const { return {key, value}; } void increment() { if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) { pos = -1; } } bool equal(const dict_readonly &b) const { return pos == b.pos; } private: handle obj; PyObject *key = nullptr, *value = nullptr; ssize_t pos = -1; }; PYBIND11_NAMESPACE_END(iterator_policies) #if !defined(PYPY_VERSION) using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>; using list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>; #else using tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; using list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; #endif using sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>; using dict_iterator = generic_iterator<iterator_policies::dict_readonly>; inline bool PyIterable_Check(PyObject *obj) { PyObject *iter = PyObject_GetIter(obj); if (iter) { Py_DECREF(iter); return true; } PyErr_Clear(); return false; } inline bool PyNone_Check(PyObject *o) { return o == Py_None; } inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; } #ifdef PYBIND11_STR_LEGACY_PERMISSIVE inline bool PyUnicode_Check_Permissive(PyObject *o) { return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); } #define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive #else #define PYBIND11_STR_CHECK_FUN PyUnicode_Check #endif inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; } class kwargs_proxy : public handle { public: explicit kwargs_proxy(handle h) : handle(h) { } }; class args_proxy : public handle { public: explicit args_proxy(handle h) : handle(h) { } kwargs_proxy operator*() const { return kwargs_proxy(*this); } }; /// Python argument categories (using PEP 448 terms) template <typename T> using is_keyword = std::is_base_of<arg, T>; template <typename T> using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking template <typename T> using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking template <typename T> using is_positional = satisfies_none_of<T, is_keyword, is_s_unpacking, is_ds_unpacking >; template <typename T> using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>; // Call argument collector forward declarations template <return_value_policy policy = return_value_policy::automatic_reference> class simple_collector; template <return_value_policy policy = return_value_policy::automatic_reference> class unpacking_collector; PYBIND11_NAMESPACE_END(detail) // TODO: After the deprecated constructors are removed, this macro can be simplified by // inheriting ctors: `using Parent::Parent`. It's not an option right now because // the `using` statement triggers the parent deprecation warning even if the ctor // isn't even used. #define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ public: \ PYBIND11_DEPRECATED("Use reinterpret_borrow<"#Name">() or reinterpret_steal<"#Name">()") \ Name(handle h, bool is_borrowed) : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) { } \ Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) { } \ Name(handle h, stolen_t) : Parent(h, stolen_t{}) { } \ PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \ bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \ static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \ template <typename Policy_> \ /* NOLINTNEXTLINE(google-explicit-constructor) */ \ Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) { } #define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ /* NOLINTNEXTLINE(google-explicit-constructor) */ \ Name(const object &o) \ : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) \ { if (!m_ptr) throw error_already_set(); } \ /* NOLINTNEXTLINE(google-explicit-constructor) */ \ Name(object &&o) \ : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) \ { if (!m_ptr) throw error_already_set(); } #define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \ PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ Name() : Parent() { } #define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \ ::pybind11::type_error("Object of type '" + \ ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) + \ "' is not an instance of '" #Name "'") #define PYBIND11_OBJECT(Name, Parent, CheckFun) \ PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ /* NOLINTNEXTLINE(google-explicit-constructor) */ \ Name(const object &o) : Parent(o) \ { if (m_ptr && !check_(m_ptr)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); } \ /* NOLINTNEXTLINE(google-explicit-constructor) */ \ Name(object &&o) : Parent(std::move(o)) \ { if (m_ptr && !check_(m_ptr)) throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); } #define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \ PYBIND11_OBJECT(Name, Parent, CheckFun) \ Name() : Parent() { } /// \addtogroup pytypes /// @{ /** \rst Wraps a Python iterator so that it can also be used as a C++ input iterator Caveat: copying an iterator does not (and cannot) clone the internal state of the Python iterable. This also applies to the post-increment operator. This iterator should only be used to retrieve the current value using ``operator*()``. \endrst */ class iterator : public object { public: using iterator_category = std::input_iterator_tag; using difference_type = ssize_t; using value_type = handle; using reference = const handle; // PR #3263 using pointer = const handle *; PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check) iterator& operator++() { advance(); return *this; } iterator operator++(int) { auto rv = *this; advance(); return rv; } // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 reference operator*() const { if (m_ptr && !value.ptr()) { auto& self = const_cast<iterator &>(*this); self.advance(); } return value; } pointer operator->() const { operator*(); return &value; } /** \rst The value which marks the end of the iteration. ``it == iterator::sentinel()`` is equivalent to catching ``StopIteration`` in Python. .. code-block:: cpp void foo(py::iterator it) { while (it != py::iterator::sentinel()) { // use `*it` ++it; } } \endrst */ static iterator sentinel() { return {}; } friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); } friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); } private: void advance() { value = reinterpret_steal<object>(PyIter_Next(m_ptr)); if (PyErr_Occurred()) { throw error_already_set(); } } private: object value = {}; }; class type : public object { public: PYBIND11_OBJECT(type, object, PyType_Check) /// Return a type handle from a handle or an object static handle handle_of(handle h) { return handle((PyObject*) Py_TYPE(h.ptr())); } /// Return a type object from a handle or an object static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); } // Defined in pybind11/cast.h /// Convert C++ type to handle if previously registered. Does not convert /// standard types, like int, float. etc. yet. /// See https://github.com/pybind/pybind11/issues/2486 template<typename T> static handle handle_of(); /// Convert C++ type to type if previously registered. Does not convert /// standard types, like int, float. etc. yet. /// See https://github.com/pybind/pybind11/issues/2486 template<typename T> static type of() {return type(type::handle_of<T>(), borrowed_t{}); } }; class iterable : public object { public: PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check) }; class bytes; class str : public object { public: PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str) template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> str(const char *c, const SzType &n) : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate string object!"); } // 'explicit' is explicitly omitted from the following constructors to allow implicit conversion to py::str from C++ string-like objects // NOLINTNEXTLINE(google-explicit-constructor) str(const char *c = "") : object(PyUnicode_FromString(c), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate string object!"); } // NOLINTNEXTLINE(google-explicit-constructor) str(const std::string &s) : str(s.data(), s.size()) { } explicit str(const bytes &b); /** \rst Return a string representation of the object. This is analogous to the ``str()`` function in Python. \endrst */ explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { if (!m_ptr) throw error_already_set(); } // NOLINTNEXTLINE(google-explicit-constructor) operator std::string() const { object temp = *this; if (PyUnicode_Check(m_ptr)) { temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr)); if (!temp) throw error_already_set(); } char *buffer = nullptr; ssize_t length = 0; if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) pybind11_fail("Unable to extract string contents! (invalid type)"); return std::string(buffer, (size_t) length); } template <typename... Args> str format(Args &&...args) const { return attr("format")(std::forward<Args>(args)...); } private: /// Return string representation -- always returns a new reference, even if already a str static PyObject *raw_str(PyObject *op) { PyObject *str_value = PyObject_Str(op); #if PY_MAJOR_VERSION < 3 if (!str_value) throw error_already_set(); PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr); Py_XDECREF(str_value); str_value = unicode; #endif return str_value; } }; /// @} pytypes inline namespace literals { /** \rst String literal version of `str` \endrst */ inline str operator"" _s(const char *s, size_t size) { return {s, size}; } } // namespace literals /// \addtogroup pytypes /// @{ class bytes : public object { public: PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK) // Allow implicit conversion: // NOLINTNEXTLINE(google-explicit-constructor) bytes(const char *c = "") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate bytes object!"); } template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> bytes(const char *c, const SzType &n) : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate bytes object!"); } // Allow implicit conversion: // NOLINTNEXTLINE(google-explicit-constructor) bytes(const std::string &s) : bytes(s.data(), s.size()) { } explicit bytes(const pybind11::str &s); // NOLINTNEXTLINE(google-explicit-constructor) operator std::string() const { char *buffer = nullptr; ssize_t length = 0; if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length)) pybind11_fail("Unable to extract bytes contents!"); return std::string(buffer, (size_t) length); } }; // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors // are included in the doxygen group; close here and reopen after as a workaround /// @} pytypes inline bytes::bytes(const pybind11::str &s) { object temp = s; if (PyUnicode_Check(s.ptr())) { temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr())); if (!temp) pybind11_fail("Unable to extract string contents! (encoding issue)"); } char *buffer = nullptr; ssize_t length = 0; if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) pybind11_fail("Unable to extract string contents! (invalid type)"); auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length)); if (!obj) pybind11_fail("Could not allocate bytes object!"); m_ptr = obj.release().ptr(); } inline str::str(const bytes& b) { char *buffer = nullptr; ssize_t length = 0; if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length)) pybind11_fail("Unable to extract bytes contents!"); auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length)); if (!obj) pybind11_fail("Could not allocate string object!"); m_ptr = obj.release().ptr(); } /// \addtogroup pytypes /// @{ class bytearray : public object { public: PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject) template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> bytearray(const char *c, const SzType &n) : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate bytearray object!"); } bytearray() : bytearray("", 0) {} explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) { } size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); } explicit operator std::string() const { char *buffer = PyByteArray_AS_STRING(m_ptr); ssize_t size = PyByteArray_GET_SIZE(m_ptr); return std::string(buffer, static_cast<size_t>(size)); } }; // Note: breathe >= 4.17.0 will fail to build docs if the below two constructors // are included in the doxygen group; close here and reopen after as a workaround /// @} pytypes /// \addtogroup pytypes /// @{ class none : public object { public: PYBIND11_OBJECT(none, object, detail::PyNone_Check) none() : object(Py_None, borrowed_t{}) { } }; class ellipsis : public object { public: PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check) ellipsis() : object(Py_Ellipsis, borrowed_t{}) { } }; class bool_ : public object { public: PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool) bool_() : object(Py_False, borrowed_t{}) { } // Allow implicit conversion from and to `bool`: // NOLINTNEXTLINE(google-explicit-constructor) bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) { } // NOLINTNEXTLINE(google-explicit-constructor) operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; } private: /// Return the truth value of an object -- always returns a new reference static PyObject *raw_bool(PyObject *op) { const auto value = PyObject_IsTrue(op); if (value == -1) return nullptr; return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr(); } }; PYBIND11_NAMESPACE_BEGIN(detail) // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1; // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned). // (The distinction is critically important when casting a returned -1 error value to some other // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes). template <typename Unsigned> Unsigned as_unsigned(PyObject *o) { if (PYBIND11_SILENCE_MSVC_C4127(sizeof(Unsigned) <= sizeof(unsigned long)) #if PY_VERSION_HEX < 0x03000000 || PyInt_Check(o) #endif ) { unsigned long v = PyLong_AsUnsignedLong(o); return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v; } unsigned long long v = PyLong_AsUnsignedLongLong(o); return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v; } PYBIND11_NAMESPACE_END(detail) class int_ : public object { public: PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long) int_() : object(PyLong_FromLong(0), stolen_t{}) { } // Allow implicit conversion from C++ integral types: template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0> // NOLINTNEXTLINE(google-explicit-constructor) int_(T value) { if (PYBIND11_SILENCE_MSVC_C4127(sizeof(T) <= sizeof(long))) { if (std::is_signed<T>::value) m_ptr = PyLong_FromLong((long) value); else m_ptr = PyLong_FromUnsignedLong((unsigned long) value); } else { if (std::is_signed<T>::value) m_ptr = PyLong_FromLongLong((long long) value); else m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value); } if (!m_ptr) pybind11_fail("Could not allocate int object!"); } template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0> // NOLINTNEXTLINE(google-explicit-constructor) operator T() const { return std::is_unsigned<T>::value ? detail::as_unsigned<T>(m_ptr) : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr) : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr); } }; class float_ : public object { public: PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float) // Allow implicit conversion from float/double: // NOLINTNEXTLINE(google-explicit-constructor) float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate float object!"); } // NOLINTNEXTLINE(google-explicit-constructor) float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate float object!"); } // NOLINTNEXTLINE(google-explicit-constructor) operator float() const { return (float) PyFloat_AsDouble(m_ptr); } // NOLINTNEXTLINE(google-explicit-constructor) operator double() const { return (double) PyFloat_AsDouble(m_ptr); } }; class weakref : public object { public: PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref) explicit weakref(handle obj, handle callback = {}) : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate weak reference!"); } private: static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); } }; class slice : public object { public: PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check) slice(ssize_t start_, ssize_t stop_, ssize_t step_) { int_ start(start_), stop(stop_), step(step_); m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.ptr()); if (!m_ptr) pybind11_fail("Could not allocate slice object!"); } bool compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const { return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr, (ssize_t) length, (ssize_t *) start, (ssize_t *) stop, (ssize_t *) step, (ssize_t *) slicelength) == 0; } bool compute(ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const { return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength) == 0; } }; class capsule : public object { public: PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact) PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()") capsule(PyObject *ptr, bool is_borrowed) : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) { } explicit capsule(const void *value, const char *name = nullptr, void (*destructor)(PyObject *) = nullptr) : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate capsule object!"); } PYBIND11_DEPRECATED("Please pass a destructor that takes a void pointer as input") capsule(const void *value, void (*destruct)(PyObject *)) : object(PyCapsule_New(const_cast<void*>(value), nullptr, destruct), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate capsule object!"); } capsule(const void *value, void (*destructor)(void *)) { m_ptr = PyCapsule_New(const_cast<void *>(value), nullptr, [](PyObject *o) { auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o)); void *ptr = PyCapsule_GetPointer(o, nullptr); destructor(ptr); }); if (!m_ptr) pybind11_fail("Could not allocate capsule object!"); if (PyCapsule_SetContext(m_ptr, (void *) destructor) != 0) pybind11_fail("Could not set capsule context!"); } explicit capsule(void (*destructor)()) { m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) { auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, nullptr)); destructor(); }); if (!m_ptr) pybind11_fail("Could not allocate capsule object!"); } // NOLINTNEXTLINE(google-explicit-constructor) template <typename T> operator T *() const { return get_pointer<T>(); } /// Get the pointer the capsule holds. template<typename T = void> T* get_pointer() const { auto name = this->name(); T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name)); if (!result) { PyErr_Clear(); pybind11_fail("Unable to extract capsule contents!"); } return result; } /// Replaces a capsule's pointer *without* calling the destructor on the existing one. void set_pointer(const void *value) { if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) { PyErr_Clear(); pybind11_fail("Could not set capsule pointer"); } } const char *name() const { return PyCapsule_GetName(m_ptr); } }; class tuple : public object { public: PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple) template <typename SzType = ssize_t, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> // Some compilers generate link errors when using `const SzType &` here: explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate tuple object!"); } size_t size() const { return (size_t) PyTuple_Size(m_ptr); } bool empty() const { return size() == 0; } detail::tuple_accessor operator[](size_t index) const { return {*this, index}; } detail::item_accessor operator[](handle h) const { return object::operator[](h); } detail::tuple_iterator begin() const { return {*this, 0}; } detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; } }; // We need to put this into a separate function because the Intel compiler // fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below // (tested with ICC 2021.1 Beta 20200827). template <typename... Args> constexpr bool args_are_all_keyword_or_ds() { return detail::all_of<detail::is_keyword_or_ds<Args>...>::value; } class dict : public object { public: PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict) dict() : object(PyDict_New(), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate dict object!"); } template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>, // MSVC workaround: it can't compile an out-of-line definition, so defer the collector typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>> explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) { } size_t size() const { return (size_t) PyDict_Size(m_ptr); } bool empty() const { return size() == 0; } detail::dict_iterator begin() const { return {*this, 0}; } detail::dict_iterator end() const { return {}; } void clear() /* py-non-const */ { PyDict_Clear(ptr()); } template <typename T> bool contains(T &&key) const { return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1; } private: /// Call the `dict` Python type -- always returns a new reference static PyObject *raw_dict(PyObject *op) { if (PyDict_Check(op)) return handle(op).inc_ref().ptr(); return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr); } }; class sequence : public object { public: PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check) size_t size() const { ssize_t result = PySequence_Size(m_ptr); if (result == -1) throw error_already_set(); return (size_t) result; } bool empty() const { return size() == 0; } detail::sequence_accessor operator[](size_t index) const { return {*this, index}; } detail::item_accessor operator[](handle h) const { return object::operator[](h); } detail::sequence_iterator begin() const { return {*this, 0}; } detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; } }; class list : public object { public: PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List) template <typename SzType = ssize_t, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0> // Some compilers generate link errors when using `const SzType &` here: explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate list object!"); } size_t size() const { return (size_t) PyList_Size(m_ptr); } bool empty() const { return size() == 0; } detail::list_accessor operator[](size_t index) const { return {*this, index}; } detail::item_accessor operator[](handle h) const { return object::operator[](h); } detail::list_iterator begin() const { return {*this, 0}; } detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; } template <typename T> void append(T &&val) /* py-non-const */ { PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()); } template <typename IdxType, typename ValType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0> void insert(const IdxType &index, ValType &&val) /* py-non-const */ { PyList_Insert( m_ptr, ssize_t_cast(index), detail::object_or_cast(std::forward<ValType>(val)).ptr()); } }; class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) }; class kwargs : public dict { PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) }; class set : public object { public: PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New) set() : object(PySet_New(nullptr), stolen_t{}) { if (!m_ptr) pybind11_fail("Could not allocate set object!"); } size_t size() const { return (size_t) PySet_Size(m_ptr); } bool empty() const { return size() == 0; } template <typename T> bool add(T &&val) /* py-non-const */ { return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0; } void clear() /* py-non-const */ { PySet_Clear(m_ptr); } template <typename T> bool contains(T &&val) const { return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1; } }; class function : public object { public: PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check) handle cpp_function() const { handle fun = detail::get_function(m_ptr); if (fun && PyCFunction_Check(fun.ptr())) return fun; return handle(); } bool is_cpp_function() const { return (bool) cpp_function(); } }; class staticmethod : public object { public: PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New) }; class buffer : public object { public: PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer) buffer_info request(bool writable = false) const { int flags = PyBUF_STRIDES | PyBUF_FORMAT; if (writable) flags |= PyBUF_WRITABLE; auto *view = new Py_buffer(); if (PyObject_GetBuffer(m_ptr, view, flags) != 0) { delete view; throw error_already_set(); } return buffer_info(view); } }; class memoryview : public object { public: PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject) /** \rst Creates ``memoryview`` from ``buffer_info``. ``buffer_info`` must be created from ``buffer::request()``. Otherwise throws an exception. For creating a ``memoryview`` from objects that support buffer protocol, use ``memoryview(const object& obj)`` instead of this constructor. \endrst */ explicit memoryview(const buffer_info& info) { if (!info.view()) pybind11_fail("Prohibited to create memoryview without Py_buffer"); // Note: PyMemoryView_FromBuffer never increments obj reference. m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj) : PyMemoryView_FromBuffer(info.view()); if (!m_ptr) pybind11_fail("Unable to create memoryview from buffer descriptor"); } /** \rst Creates ``memoryview`` from static buffer. This method is meant for providing a ``memoryview`` for C/C++ buffer not managed by Python. The caller is responsible for managing the lifetime of ``ptr`` and ``format``, which MUST outlive the memoryview constructed here. See also: Python C API documentation for `PyMemoryView_FromBuffer`_. .. _PyMemoryView_FromBuffer: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer :param ptr: Pointer to the buffer. :param itemsize: Byte size of an element. :param format: Pointer to the null-terminated format string. For homogeneous Buffers, this should be set to ``format_descriptor<T>::value``. :param shape: Shape of the tensor (1 entry per dimension). :param strides: Number of bytes between adjacent entries (for each per dimension). :param readonly: Flag to indicate if the underlying storage may be written to. \endrst */ static memoryview from_buffer( void *ptr, ssize_t itemsize, const char *format, detail::any_container<ssize_t> shape, detail::any_container<ssize_t> strides, bool readonly = false); static memoryview from_buffer( const void *ptr, ssize_t itemsize, const char *format, detail::any_container<ssize_t> shape, detail::any_container<ssize_t> strides) { return memoryview::from_buffer( const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true); } template<typename T> static memoryview from_buffer( T *ptr, detail::any_container<ssize_t> shape, detail::any_container<ssize_t> strides, bool readonly = false) { return memoryview::from_buffer( reinterpret_cast<void*>(ptr), sizeof(T), format_descriptor<T>::value, shape, strides, readonly); } template<typename T> static memoryview from_buffer( const T *ptr, detail::any_container<ssize_t> shape, detail::any_container<ssize_t> strides) { return memoryview::from_buffer( const_cast<T*>(ptr), shape, strides, true); } #if PY_MAJOR_VERSION >= 3 /** \rst Creates ``memoryview`` from static memory. This method is meant for providing a ``memoryview`` for C/C++ buffer not managed by Python. The caller is responsible for managing the lifetime of ``mem``, which MUST outlive the memoryview constructed here. This method is not available in Python 2. See also: Python C API documentation for `PyMemoryView_FromBuffer`_. .. _PyMemoryView_FromMemory: https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory \endrst */ static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) { PyObject* ptr = PyMemoryView_FromMemory( reinterpret_cast<char*>(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE); if (!ptr) pybind11_fail("Could not allocate memoryview object!"); return memoryview(object(ptr, stolen_t{})); } static memoryview from_memory(const void *mem, ssize_t size) { return memoryview::from_memory(const_cast<void*>(mem), size, true); } #endif }; #ifndef DOXYGEN_SHOULD_SKIP_THIS inline memoryview memoryview::from_buffer( void *ptr, ssize_t itemsize, const char* format, detail::any_container<ssize_t> shape, detail::any_container<ssize_t> strides, bool readonly) { size_t ndim = shape->size(); if (ndim != strides->size()) pybind11_fail("memoryview: shape length doesn't match strides length"); ssize_t size = ndim != 0u ? 1 : 0; for (size_t i = 0; i < ndim; ++i) size *= (*shape)[i]; Py_buffer view; view.buf = ptr; view.obj = nullptr; view.len = size * itemsize; view.readonly = static_cast<int>(readonly); view.itemsize = itemsize; view.format = const_cast<char*>(format); view.ndim = static_cast<int>(ndim); view.shape = shape->data(); view.strides = strides->data(); view.suboffsets = nullptr; view.internal = nullptr; PyObject* obj = PyMemoryView_FromBuffer(&view); if (!obj) throw error_already_set(); return memoryview(object(obj, stolen_t{})); } #endif // DOXYGEN_SHOULD_SKIP_THIS /// @} pytypes /// \addtogroup python_builtins /// @{ /// Get the length of a Python object. inline size_t len(handle h) { ssize_t result = PyObject_Length(h.ptr()); if (result < 0) throw error_already_set(); return (size_t) result; } /// Get the length hint of a Python object. /// Returns 0 when this cannot be determined. inline size_t len_hint(handle h) { #if PY_VERSION_HEX >= 0x03040000 ssize_t result = PyObject_LengthHint(h.ptr(), 0); #else ssize_t result = PyObject_Length(h.ptr()); #endif if (result < 0) { // Sometimes a length can't be determined at all (eg generators) // In which case simply return 0 PyErr_Clear(); return 0; } return (size_t) result; } inline str repr(handle h) { PyObject *str_value = PyObject_Repr(h.ptr()); if (!str_value) throw error_already_set(); #if PY_MAJOR_VERSION < 3 PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr); Py_XDECREF(str_value); str_value = unicode; if (!str_value) throw error_already_set(); #endif return reinterpret_steal<str>(str_value); } inline iterator iter(handle obj) { PyObject *result = PyObject_GetIter(obj.ptr()); if (!result) { throw error_already_set(); } return reinterpret_steal<iterator>(result); } /// @} python_builtins PYBIND11_NAMESPACE_BEGIN(detail) template <typename D> iterator object_api<D>::begin() const { return iter(derived()); } template <typename D> iterator object_api<D>::end() const { return iterator::sentinel(); } template <typename D> item_accessor object_api<D>::operator[](handle key) const { return {derived(), reinterpret_borrow<object>(key)}; } template <typename D> item_accessor object_api<D>::operator[](const char *key) const { return {derived(), pybind11::str(key)}; } template <typename D> obj_attr_accessor object_api<D>::attr(handle key) const { return {derived(), reinterpret_borrow<object>(key)}; } template <typename D> str_attr_accessor object_api<D>::attr(const char *key) const { return {derived(), key}; } template <typename D> args_proxy object_api<D>::operator*() const { return args_proxy(derived().ptr()); } template <typename D> template <typename T> bool object_api<D>::contains(T &&item) const { return attr("__contains__")(std::forward<T>(item)).template cast<bool>(); } template <typename D> pybind11::str object_api<D>::str() const { return pybind11::str(derived()); } template <typename D> str_attr_accessor object_api<D>::doc() const { return attr("__doc__"); } template <typename D> handle object_api<D>::get_type() const { return type::handle_of(derived()); } template <typename D> bool object_api<D>::rich_compare(object_api const &other, int value) const { int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value); if (rv == -1) throw error_already_set(); return rv == 1; } #define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \ template <typename D> object object_api<D>::op() const { \ object result = reinterpret_steal<object>(fn(derived().ptr())); \ if (!result.ptr()) \ throw error_already_set(); \ return result; \ } #define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \ template <typename D> \ object object_api<D>::op(object_api const &other) const { \ object result = reinterpret_steal<object>( \ fn(derived().ptr(), other.derived().ptr())); \ if (!result.ptr()) \ throw error_already_set(); \ return result; \ } PYBIND11_MATH_OPERATOR_UNARY (operator~, PyNumber_Invert) PYBIND11_MATH_OPERATOR_UNARY (operator-, PyNumber_Negative) PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add) PYBIND11_MATH_OPERATOR_BINARY(operator+=, PyNumber_InPlaceAdd) PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract) PYBIND11_MATH_OPERATOR_BINARY(operator-=, PyNumber_InPlaceSubtract) PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply) PYBIND11_MATH_OPERATOR_BINARY(operator*=, PyNumber_InPlaceMultiply) PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide) PYBIND11_MATH_OPERATOR_BINARY(operator/=, PyNumber_InPlaceTrueDivide) PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or) PYBIND11_MATH_OPERATOR_BINARY(operator|=, PyNumber_InPlaceOr) PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And) PYBIND11_MATH_OPERATOR_BINARY(operator&=, PyNumber_InPlaceAnd) PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor) PYBIND11_MATH_OPERATOR_BINARY(operator^=, PyNumber_InPlaceXor) PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift) PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift) PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift) PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift) #undef PYBIND11_MATH_OPERATOR_UNARY #undef PYBIND11_MATH_OPERATOR_BINARY PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
73,915
C
38.782562
166
0.648799
Toni-SM/semu.xr.openxr/src/semu.xr.openxr/sources/thirdparty/pybind11/common.h
#include "detail/common.h" #warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'."
120
C
39.33332
92
0.725