file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/semu/misc/jupyter_notebook/__init__.py | from .scripts.extension import * | 32 | Python | 31.999968 | 32 | 0.8125 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/semu/misc/jupyter_notebook/scripts/extension.py | import __future__
import os
import sys
import jedi
import json
import glob
import socket
import asyncio
import traceback
import subprocess
import contextlib
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
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 Jupyter Notebook"
MENU_PATH = f"Window/{WINDOW_NAME}"
def on_startup(self, ext_id):
self._globals = {**globals()}
self._locals = self._globals
self._server = None
self._process = None
self._settings = carb.settings.get_settings()
self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
sys.path.append(os.path.join(self._extension_path, "data", "provisioners"))
# get extension settings
self._token = self._settings.get("/exts/semu.misc.jupyter_notebook/token")
self._notebook_ip = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_ip")
self._notebook_port = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_port")
self._notebook_dir = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_dir")
self._command_line_options = self._settings.get("/exts/semu.misc.jupyter_notebook/command_line_options")
self._classic_notebook_interface = self._settings.get("/exts/semu.misc.jupyter_notebook/classic_notebook_interface")
self._socket_port = self._settings.get("/exts/semu.misc.jupyter_notebook/socket_port")
kill_processes_with_port_in_use = self._settings.get("/exts/semu.misc.jupyter_notebook/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_event = omni.kit.app.get_app().get_shutdown_event_stream() \
.create_subscription_to_pop(self._on_shutdown_event, name="semu.misc.jupyter_notebook", order=0)
# ensure port is free
if kill_processes_with_port_in_use:
# windows
if sys.platform == "win32":
pids = []
cmd = ["netstat", "-ano"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
if f":{self._socket_port}".encode() in line or f":{self._notebook_port}".encode() in line:
if "listening".encode() in line.lower():
carb.log_info(f"Open port: {line.strip().decode()}")
pids.append(line.strip().split(b" ")[-1].decode())
p.wait()
for pid in pids:
if not pid.isnumeric():
continue
carb.log_warn(f"Forced process shutdown with PID {pid}")
cmd = ["taskkill", "/PID", pid, "/F"]
subprocess.Popen(cmd).wait()
# linux
elif sys.platform == "linux":
pids = []
cmd = ["netstat", "-ltnup"]
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
if f":{self._socket_port}".encode() in line or f":{self._notebook_port}".encode() in line:
carb.log_info(f"Open port: {line.strip().decode()}")
pids.append([chunk for chunk in line.strip().split(b" ") if b'/' in chunk][-1].decode().split("/")[0])
p.wait()
except FileNotFoundError as e:
carb.log_warn(f"Command (netstat) not available. Install it using `apt install net-tools`")
for pid in pids:
if not pid.isnumeric():
continue
carb.log_warn(f"Forced process shutdown with PID {pid}")
cmd = ["kill", "-9", pid]
subprocess.Popen(cmd).wait()
# create socket
self._create_socket()
# run jupyter notebook in a separate process
self._launch_jupyter_process()
# jedi (autocompletion)
# application root path
app_folder = carb.settings.get_settings().get_as_string("/app/folder")
if not app_folder:
app_folder = carb.tokens.get_tokens_interface().resolve("${app}")
path = os.path.normpath(os.path.join(app_folder, os.pardir))
# get extension paths
folders = [
"exts",
"extscache",
os.path.join("kit", "extensions"),
os.path.join("kit", "exts"),
os.path.join("kit", "extsPhysics"),
os.path.join("kit", "extscore"),
]
added_sys_path = []
for folder in folders:
sys_paths = glob.glob(os.path.join(path, folder, "*"))
for sys_path in sys_paths:
if os.path.isdir(sys_path):
added_sys_path.append(sys_path)
# python environment
python_exe = "python.exe" if sys.platform == "win32" else "bin/python3"
environment_path = os.path.join(path, "kit", "python", python_exe)
# jedi project
carb.log_info("Autocompletion: jedi.Project")
carb.log_info(f" |-- path: {path}")
carb.log_info(f" |-- added_sys_path: {len(added_sys_path)} items")
carb.log_info(f" |-- environment_path: {environment_path}")
self._jedi_project = jedi.Project(path=path,
environment_path=environment_path,
added_sys_path=added_sys_path,
load_unsafe_extensions=False)
def on_shutdown(self):
# clean extension paths from sys.path
if self._extension_path is not None:
sys.path.remove(os.path.join(self._extension_path, "data", "provisioners"))
self._extension_path = None
# clean up menu item
if self._menu is not None:
self._editor_menu.remove_item(self._menu)
self._menu = None
# close the socket
if self._server:
self._server.close()
_get_event_loop().run_until_complete(self._server.wait_closed())
# close the jupyter notebook (external process)
if self._process is not None:
process_pid = self._process.pid
try:
self._process.terminate() # .kill()
except OSError as e:
if sys.platform == 'win32':
if e.winerror != 5:
raise
else:
from errno import ESRCH
if not isinstance(e, ProcessLookupError) or e.errno != ESRCH:
raise
# make sure the process is not running anymore in Windows
if sys.platform == 'win32':
subprocess.call(['taskkill', '/F', '/T', '/PID', str(process_pid)])
# wait for the process to terminate
self._process.wait()
self._process = None
# 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 a Jupyter Notebook URL in the notification area
"""
display_url = ""
if self._process is not None:
notebook_txt = os.path.join(self._extension_path, "data", "launchers", "notebook.txt")
if os.path.exists(notebook_txt):
with open(notebook_txt, "r") as f:
display_url = f.read()
if display_url:
notification = "Jupyter Notebook is running at:\n\n - " + display_url.replace(" or ", " - ")
status=omni.kit.notification_manager.NotificationStatus.INFO
else:
notification = "Unable to identify Jupyter Notebook URL"
status=omni.kit.notification_manager.NotificationStatus.WARNING
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_socket(self) -> None:
"""Create a socket server to listen for incoming connections from the IPython kernel
"""
socket_txt = os.path.join(self._extension_path, "data", "launchers", "socket.txt")
# delete socket.txt file
if os.path.exists(socket_txt):
os.remove(socket_txt)
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')
carb.log_info('Connection from {}'.format(peername))
self.transport = transport
def data_received(self, data):
code = data.decode()
# completion
if code[:3] == "%!c":
code = code[3:]
asyncio.run_coroutine_threadsafe(self._parent._complete_code_async(code, self.transport), _get_event_loop())
# introspection
elif code[:3] == "%!i":
code = code[3:]
pos = code.find('%')
line, column = [int(i) for i in code[:pos].split(':')]
code = code[pos + 1:]
asyncio.run_coroutine_threadsafe(self._parent._introspect_code_async(code, line, column, self.transport), _get_event_loop())
# execution
else:
asyncio.run_coroutine_threadsafe(self._parent._exec_code_async(code, self.transport), _get_event_loop())
async def server_task():
self._server = await _get_event_loop().create_server(protocol_factory=lambda: ServerProtocol(self),
host="127.0.0.1",
port=self._socket_port,
family=socket.AF_INET,
reuse_port=None if sys.platform == 'win32' else True)
await self._server.start_serving()
task = _get_event_loop().create_task(server_task())
# write the socket port to socket.txt file
carb.log_info("Internal socket server is running at port {}".format(self._socket_port))
with open(socket_txt, "w") as f:
f.write(str(self._socket_port))
async def _complete_code_async(self, statement: str, transport: asyncio.Transport) -> None:
"""Complete objects under the cursor and send the result to the IPython kernel
:param statement: statement to complete
:type statement: str
:param transport: transport to send the result to the IPython kernel
:type transport: asyncio.Transport
:return: reply dictionary
:rtype: dict
"""
# generate completions
script = jedi.Script(statement, project=self._jedi_project)
completions = script.complete()
delta = completions[0].get_completion_prefix_length() if completions else 0
reply = {"matches": [c.name for c in completions], "delta": delta}
# send the reply to the IPython kernel
reply = json.dumps(reply)
transport.write(reply.encode())
# close the connection
transport.close()
async def _introspect_code_async(self, statement: str, line: int, column: int, transport: asyncio.Transport) -> None:
"""Introspect code under the cursor and send the result to the IPython kernel
:param statement: statement to introspect
:type statement: str
:param line: the line where the definition occurs
:type line: int
:param column: the column where the definition occurs
:type column: int
:param transport: transport to send the result to the IPython kernel
:type transport: asyncio.Transport
:return: reply dictionary
:rtype: dict
"""
# generate introspection
script = jedi.Script(statement, project=self._jedi_project)
definitions = script.infer(line=line, column=column)
reply = {"found": False, "data": "TODO"}
if len(definitions):
reply["found"] = True
reply["data"] = definitions[0].docstring()
# send the reply to the IPython kernel
reply = json.dumps(reply)
transport.write(reply.encode())
# close the connection
transport.close()
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 IPython kernel
:param statement: statement to execute
:type statement: str
:param transport: transport to send the result to the IPython kernel
:type transport: asyncio.Transport
:return: reply dictionary
: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()
# send the reply to the IPython kernel
reply = json.dumps(reply)
transport.write(reply.encode())
# close the connection
transport.close()
# launch Jupyter Notebook methods
def _launch_jupyter_process(self) -> None:
"""Launch the Jupyter notebook in a separate process
"""
# get packages path
paths = [p for p in sys.path if "pip3-envs" in p]
packages_txt = os.path.join(self._extension_path, "data", "launchers", "packages.txt")
with open(packages_txt, "w") as f:
f.write("\n".join(paths))
if sys.platform == 'win32':
executable_path = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "python.exe"))
else:
executable_path = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "..", "bin", "python3"))
cmd = [executable_path,
os.path.join(self._extension_path, "data", "launchers", "jupyter_launcher.py"),
self._notebook_ip,
str(self._notebook_port),
self._token,
str(self._classic_notebook_interface),
self._notebook_dir,
self._command_line_options]
carb.log_info("Starting Jupyter server in separate process")
carb.log_info(" |-- command: " + " ".join(cmd))
try:
self._process = subprocess.Popen(cmd, cwd=os.path.join(self._extension_path, "data", "launchers"))
except Exception as e:
carb.log_error("Error starting Jupyter server: {}".format(e))
self._process = None
| 18,476 | Python | 40.521348 | 144 | 0.546872 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "0.1.1"
category = "Utility"
feature = false
app = false
title = "Embedded Jupyter Notebook"
description = "Jupyter Notebook version of Omniverse's script editor"
authors = ["Toni-SM"]
repository = "https://github.com/Toni-SM/semu.misc.jupyter_notebook"
keywords = ["jupyter", "notebook", "ipython", "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.jupyter_notebook"
[python.pipapi]
requirements = ["jupyterlab", "notebook", "jedi"]
use_online_index = true
[settings]
# extension settings
exts."semu.misc.jupyter_notebook".socket_port = 8224
exts."semu.misc.jupyter_notebook".classic_notebook_interface = false
exts."semu.misc.jupyter_notebook".kill_processes_with_port_in_use = true
# jupyter notebook settings
exts."semu.misc.jupyter_notebook".notebook_ip = "0.0.0.0"
exts."semu.misc.jupyter_notebook".notebook_port = 8225
exts."semu.misc.jupyter_notebook".token = ""
exts."semu.misc.jupyter_notebook".notebook_dir = ""
# jupyter notebook's command line options other than: '--ip', '--port', '--token', '--notebook-dir'
exts."semu.misc.jupyter_notebook".command_line_options = "--allow-root --no-browser --JupyterApp.answer_yes=True"
| 1,494 | TOML | 29.510203 | 113 | 0.715529 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.1.1] - 2023-08-08
### Added
- Code autocompletion (<kbd>Tab</kbd>)
- Code introspection (<kbd>Ctrl</kbd> + <kbd>i</kbd>)
### Changed
- Implement embedded kernel on `ipykernel.kernelbase.Kernel`
- Update links in resource notebooks
### Removed
- Threaded kernel implementation
## [0.1.0] - 2023-08-07
The release was yanked
## [0.0.3-beta] - 2022-12-31
### Added
- Add `kill_processes_with_port_in_use` to extension settings
- Add Omniverse documentation and developer resource to notebooks
### Fixed
- Fix port in use when starting up and shutting down
## [0.0.2-beta] - 2022-08-14
### Added
- Jupyter Lab
- Launch Jupyter in separate (sub)process
- Embedded kernel using socket
## [0.0.1-beta] - 2022-08-08
### Added
- Jupyter Notebook
| 845 | Markdown | 21.864864 | 80 | 0.698225 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/docs/README.md | # semu.misc.jupyter_notebook
This extension can be described as the Jupyter notebook version of Omniverse's script editor. It allows to open a Jupyter Notebook embedded in the current NVIDIA Omniverse application scope
Visit https://github.com/Toni-SM/semu.misc.jupyter_notebook to read more about its use
| 309 | Markdown | 43.285708 | 189 | 0.812298 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/launchers/jupyter_launcher.py | from typing import List
import os
import sys
PACKAGES_PATH = []
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# add packages to sys.path
with open(os.path.join(SCRIPT_DIR, "packages.txt"), "r") as f:
for p in f.readlines():
p = p.strip()
if p:
PACKAGES_PATH.append(p)
if p not in sys.path:
print("Adding package to sys.path: {}".format(p))
sys.path.append(p)
# add provisioners to sys.path
sys.path.append(os.path.abspath(os.path.join(SCRIPT_DIR, "..", "provisioners")))
from jupyter_client.kernelspec import KernelSpecManager as _KernelSpecManager
class KernelSpecManager(_KernelSpecManager):
def __init__(self, *args, **kwargs):
"""Custom kernel spec manager to allow for loading of custom kernels
"""
super().__init__(*args, **kwargs)
kernel_dir = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "kernels"))
if kernel_dir not in self.kernel_dirs:
self.kernel_dirs.append(kernel_dir)
def main(ip: str = "0.0.0.0", port: int = 8225, argv: List[str] = [], classic_notebook_interface: bool = False) -> None:
"""Entry point for launching Juptyter Notebook/Lab
:param ip: Notebook server IP address (default: "0.0.0.0")
:type code: str, optional
:param port: Notebook server port number (default: 8225)
:type code: int, optional
:param argv: Command line arguments to pass to Jupyter Notebook/Lab (default: [])
:type code: List of strings, optional
:param classic_notebook_interface: Whether to use the classic notebook interface (default: False)
If false, the Juptyter Lab interface will be used
:type code: bool, optional
"""
# jupyter notebook
if classic_notebook_interface:
from notebook.notebookapp import NotebookApp
app = NotebookApp(ip=ip,
port=port,
kernel_spec_manager_class=KernelSpecManager)
app.initialize(argv=argv)
# jupyter lab
else:
from jupyterlab.labapp import LabApp
from jupyter_server.serverapp import ServerApp
jpserver_extensions = {LabApp.get_extension_package(): True}
find_extensions = LabApp.load_other_extensions
if "jpserver_extensions" in LabApp.serverapp_config:
jpserver_extensions.update(LabApp.serverapp_config["jpserver_extensions"])
LabApp.serverapp_config["jpserver_extensions"] = jpserver_extensions
find_extensions = False
app = ServerApp.instance(ip=ip,
port=port,
kernel_spec_manager_class=KernelSpecManager,
jpserver_extensions=jpserver_extensions)
app.aliases.update(LabApp.aliases)
app.initialize(argv=argv,
starter_extension=LabApp.name,
find_extensions=find_extensions)
# write url to file in script directory
with open(os.path.join(SCRIPT_DIR, "notebook.txt"), "w") as f:
f.write(app.display_url)
app.start()
if __name__ == "__main__":
argv = sys.argv[1:]
# testing the launcher
if not len(argv):
print("Testing the launcher")
argv = ['0.0.0.0', # ip
'8888', # port
'', # token
'False', # classic_notebook_interface
'', # notebook_dir
'--allow-root --no-browser'] # extra arguments
# get function arguments
ip = argv[0]
port = int(argv[1])
token = argv[2]
classic_notebook_interface = argv[3] == "True"
# buld notebook_dir
if not argv[4]:
notebook_dir = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "notebooks"))
notebook_dir = "--notebook-dir={}".format(notebook_dir)
# build token
if classic_notebook_interface:
token = "--NotebookApp.token={}".format(token)
else:
token = "--ServerApp.token={}".format(token)
# assets path
app_dir = []
if not classic_notebook_interface:
for p in PACKAGES_PATH:
print("Checking package to app_dir: {}".format(p))
if os.path.exists(os.path.join(p, "share", "jupyter", "lab")):
app_dir = ["--app-dir={}".format(os.path.join(p, "share", "jupyter", "lab"))]
if os.path.exists(os.path.join(p, "jupyterlab", "static")):
app_dir = ["--app-dir={}".format(os.path.join(p, "jupyterlab"))]
if app_dir:
break
print("app_dir: {}".format(app_dir))
# clean up the argv
argv = app_dir + [token] + [notebook_dir] + argv[5].split(" ")
# run the launcher
print("Starting Jupyter {} at {}:{}".format("Notebook" if classic_notebook_interface else "Lab", ip, port))
print(" with argv: {}".format(" ".join(argv)))
main(ip=ip, port=port, argv=argv, classic_notebook_interface=classic_notebook_interface)
# delete notebook.txt
try:
os.remove(os.path.join(SCRIPT_DIR, "notebook.txt"))
except:
pass
| 5,168 | Python | 33.925675 | 120 | 0.585526 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/launchers/ipykernel_launcher.py | import os
import sys
import json
import socket
import asyncio
SOCKET_HOST = "127.0.0.1"
SOCKET_PORT = 8224
PACKAGES_PATH = []
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# add packages to sys.path
with open(os.path.join(SCRIPT_DIR, "packages.txt"), "r") as f:
for p in f.readlines():
p = p.strip()
if p:
PACKAGES_PATH.append(p)
if p not in sys.path:
print("Adding package to sys.path: {}".format(p))
sys.path.append(p)
from ipykernel.kernelbase import Kernel
from ipykernel.kernelapp import IPKernelApp
async def _send_and_recv(message):
reader, writer = await asyncio.open_connection(host=SOCKET_HOST,
port=SOCKET_PORT,
family=socket.AF_INET)
writer.write(message.encode())
await writer.drain()
data = await reader.read()
writer.close()
await writer.wait_closed()
return data.decode()
def _get_line_column(code, cursor_pos):
line = code.count('\n', 0, cursor_pos) + 1
last_newline_pos = code.rfind('\n', 0, cursor_pos)
column = cursor_pos - last_newline_pos - 1
return line, column
class EmbeddedKernel(Kernel):
"""Omniverse Kit Python wrapper kernels
It re-use the IPython's kernel machinery
https://jupyter-client.readthedocs.io/en/latest/wrapperkernels.html
"""
# kernel info: https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info
implementation = "Omniverse Kit (Python 3)"
implementation_version = "0.1.0"
language_info = {
"name": "python",
"version": "3.7", # TODO: get from Omniverse Kit
"mimetype": "text/x-python",
"file_extension": ".py",
}
banner = "Embedded Omniverse (Python 3)"
help_links = [{"text": "semu.misc.jupyter_notebook", "url": "https://github.com/Toni-SM/semu.misc.jupyter_notebook"}]
async def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False):
"""Execute user code
"""
# https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute
execute_reply = {"status": "ok",
"execution_count": self.execution_count,
"payload": [],
"user_expressions": {}}
# no code
if not code.strip():
return execute_reply
# magic commands
if code.startswith('%'):
# TODO: process magic commands
pass
# python code
try:
data = await _send_and_recv(code)
reply_content = json.loads(data)
except Exception as e:
# show network error in client
print("\x1b[0;31m==================================================\x1b[0m")
print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT))
print(e)
print("\x1b[0;31m==================================================\x1b[0m")
reply_content = {"status": "error", "output": "", "traceback": [], "ename": str(type(e).__name__), "evalue": str(e)}
# code execution stdout: {"status": str, "output": str}
if not silent:
if reply_content["output"]:
stream_content = {"name": "stdout", "text": reply_content["output"]}
self.send_response(self.iopub_socket, "stream", stream_content)
reply_content.pop("output", None)
# code execution error: {"status": str("error"), "output": str, "traceback": list(str), "ename": str, "evalue": str}
if reply_content["status"] == "error":
self.send_response(self.iopub_socket, "error", reply_content)
# update reply
execute_reply["status"] = reply_content["status"]
execute_reply["execution_count"] = self.execution_count, # the base class increments the execution count
return execute_reply
def do_debug_request(self, msg):
return {}
async def do_complete(self, code, cursor_pos):
"""Code completation
"""
# https://jupyter-client.readthedocs.io/en/latest/messaging.html#msging-completion
complete_reply = {"status": "ok",
"matches": [],
"cursor_start": 0,
"cursor_end": cursor_pos,
"metadata": {}}
# parse code
code = code[:cursor_pos]
if not code or code[-1] in [' ', '=', ':', '(', ')']:
return complete_reply
# generate completions
try:
data = await _send_and_recv("%!c" + code)
reply_content = json.loads(data)
except Exception as e:
# show network error in client
print("\x1b[0;31m==================================================\x1b[0m")
print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT))
print(e)
print("\x1b[0;31m==================================================\x1b[0m")
reply_content = {"matches": [], "delta": cursor_pos}
# update replay: {"matches": list(str), "delta": int}
complete_reply["matches"] = reply_content["matches"]
complete_reply["cursor_start"] = cursor_pos - reply_content["delta"]
return complete_reply
async def do_inspect(self, code, cursor_pos, detail_level=0, omit_sections=()):
"""Object introspection
"""
# https://jupyter-client.readthedocs.io/en/latest/messaging.html#msging-inspection
inspect_reply = {"status": "ok",
"found": False,
"data": {},
"metadata": {}}
line, column = _get_line_column(code, cursor_pos)
# generate introspection
try:
data = await _send_and_recv(f"%!i{line}:{column}%" + code)
reply_content = json.loads(data)
except Exception as e:
# show network error in client
print("\x1b[0;31m==================================================\x1b[0m")
print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT))
print(e)
print("\x1b[0;31m==================================================\x1b[0m")
reply_content = {"found": False, "data": cursor_pos}
# update replay: {"found": bool, "data": str}
if reply_content["found"]:
inspect_reply["found"] = reply_content["found"]
inspect_reply["data"] = {"text/plain": reply_content["data"]}
return inspect_reply
if __name__ == "__main__":
if sys.path[0] == "":
del sys.path[0]
# read socket port from file
if os.path.exists(os.path.join(SCRIPT_DIR, "socket.txt")):
with open(os.path.join(SCRIPT_DIR, "socket.txt"), "r") as f:
SOCKET_PORT = int(f.read())
IPKernelApp.launch_instance(kernel_class=EmbeddedKernel)
| 7,057 | Python | 36.743315 | 128 | 0.530679 |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/provisioners/embedded_omniverse_python3/provisioner_socket.py | from typing import Any, List
import os
import sys
from jupyter_client.provisioning import LocalProvisioner
from jupyter_client.connect import KernelConnectionInfo
from jupyter_client.launcher import launch_kernel
class Provisioner(LocalProvisioner):
async def launch_kernel(self, cmd: List[str], **kwargs: Any) -> KernelConnectionInfo:
# set paths
if sys.platform == 'win32':
cmd[0] = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "python.exe"))
else:
cmd[0] = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "..", "bin", "python3"))
cmd[1] = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "launchers", "ipykernel_launcher.py"))
self.log.info("Launching kernel: %s", " ".join(cmd))
scrubbed_kwargs = LocalProvisioner._scrub_kwargs(kwargs)
self.process = launch_kernel(cmd, **scrubbed_kwargs)
pgid = None
if hasattr(os, "getpgid"):
try:
pgid = os.getpgid(self.process.pid)
except OSError:
pass
self.pid = self.process.pid
self.pgid = pgid
return self.connection_info
| 1,210 | Python | 34.617646 | 123 | 0.61405 |
Toni-SM/semu.data.visualizer/README.md | ## Data visualizer for NVIDIA Omniverse apps
This extension allows to switch [Matplotlib](https://matplotlib.org/) and [OpenCV](https://docs.opencv.org/) backend to display graphics and images inside NVIDIA Omniverse apps without modifying the code logic
<br>
**Target applications:** Any NVIDIA Omniverse app
**Supported OS:** Windows and Linux
**Changelog:** [CHANGELOG.md](src/semu.data.visualizer/docs/CHANGELOG.md)
**Table of Contents:**
- [Extension setup](#setup)
- [Extension usage](#usage)
<br>

<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.data.visualizer.git?branch=main&dir=exts
```
To install the source code version use the following url
```
git+https://github.com/Toni-SM/semu.data.visualizer.git?branch=main&dir=src
```
* Compressed (.zip) file for import
[semu.data.visualizer.zip](https://github.com/Toni-SM/semu.data.visualizer/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** switches the Matplotlib and OpenCV backends **to display graphics and images in the Omniverse app**
Disabling the extension reverts the changes: graphics and images will be displayed in their respective windows by default, outside the Omniverse app
> **Note:** The current implementation does not support interaction with the displayed graphics or images
| 2,185 | Markdown | 37.350877 | 305 | 0.743707 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/BUILD.md | ## Building form source
### Linux
```bash
cd src/semu.data.visualizer
bash compile_extension.bash
```
### Windows (Microsoft Visual C++ (MSVC))
We don't do that here!
### Windows (MinGW64)
#### Build extension
```batch
cd src\semu.data.visualizer
compile_extension.bat
```
#### Troubleshooting
* **Cannot find -lvcruntime140: No such file or directory**
```
cannot find -lvcruntime140: No such file or directory
```
Find and copy `vcruntime140.dll` to `...mingw64\lib\`
* **Error: enumerator value for '__pyx_check_sizeof_voidp' is not an integer constant**
```
error: enumerator value for '__pyx_check_sizeof_voidp' is not an integer constant
```
Add -DMS_WIN64 to the build command (Cython issue [#2670](https://github.com/cython/cython/issues/2670#issuecomment-432212671))
* **ValueError: Unknown MS Compiler version XXXX**
```
ValueError: Unknown MS Compiler version XXXX
```
Apply this [path](https://bugs.python.org/file40608/patch.diff) or just return `return ['vcruntime140']` in `...distutils\cygwinccompiler.py`
## Removing old compiled files
Get a fresh clone of the repository and follow the next steps
```bash
# remove compiled files _visualizer.cpython-37m-x86_64-linux-gnu.so
git filter-repo --invert-paths --path exts/semu.data.visualizer/semu/data/visualizer/_visualizer.cpython-37m-x86_64-linux-gnu.so
git filter-repo --invert-paths --path exts/semu.data.visualizer/semu/data/visualizer/_visualizer.cp37-win_amd64.pyd
# add origin
git remote add origin [email protected]:Toni-SM/semu.data.visualizer.git
# push changes
git push origin --force --all
git push origin --force --tags
```
## Packaging the extension
```bash
cd src/semu.data.visualizer
bash package_extension.bash
``` | 1,769 | Markdown | 23.929577 | 145 | 0.714528 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/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("_visualizer",
[os.path.join("semu", "data", "visualizer", "visualizer.py")],
library_dirs=[python_library_dir]),
]
setup(
name = 'semu.data.visualizer',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
| 825 | Python | 28.499999 | 91 | 0.682424 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/visualizer.py | import os
import sys
import carb
import omni
import omni.ui as ui
try:
import numpy as np
except ImportError:
print("numpy not found. Attempting to install...")
omni.kit.pipapi.install("numpy")
import numpy as np
try:
import matplotlib
except ImportError:
print("matplotlib not found. Attempting to install...")
omni.kit.pipapi.install("matplotlib")
import matplotlib
try:
import cv2
except ImportError:
print("opencv-python not found. Attempting to install...")
omni.kit.pipapi.install("opencv-python")
import cv2
from matplotlib.figure import Figure
from matplotlib.backend_bases import FigureManagerBase
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib._pylab_helpers import Gcf
def acquire_visualizer_interface(ext_id: str = "") -> dict:
"""Acquire the visualizer interface
:param ext_id: The extension id
:type ext_id: str
:returns: The interface
:rtype: dict
"""
global _opencv_windows
# add current path to sys.path to import the backend
path = os.path.dirname(__file__)
if path not in sys.path:
sys.path.append(path)
# get matplotlib backend
matplotlib_backend = matplotlib.get_backend()
if type(matplotlib_backend) is str:
if matplotlib_backend.lower() == "agg":
matplotlib_backend = carb.settings.get_settings().get("/exts/semu.data.visualizer/default_matplotlib_backend_if_agg")
else:
matplotlib_backend = carb.settings.get_settings().get("/exts/semu.data.visualizer/default_matplotlib_backend_if_agg")
interface = {"matplotlib_backend": matplotlib_backend,
"opencv_imshow": cv2.imshow,
"opencv_waitKey": cv2.waitKey}
# set custom matplotlib backend
if os.path.basename(__file__).startswith("_visualizer"):
matplotlib.use("module://_visualizer")
else:
print(">>>> [DEVELOPMENT] module://visualizer")
matplotlib.use("module://visualizer")
# set custom opencv methods
_opencv_windows = {}
cv2.imshow = _imshow
cv2.waitKey = _waitKey
return interface
def release_visualizer_interface(interface: dict) -> None:
"""Release the visualizer interface
:param interface: The interface to release
:type interface: dict
"""
# restore default matplotlib backend
try:
matplotlib.use(interface.get("matplotlib_backend", \
carb.settings.get_settings().get("/exts/semu.data.visualizer/default_matplotlib_backend_if_agg")))
except Exception as e:
matplotlib.use("Agg")
matplotlib.rcdefaults()
# restore default opencv imshow
try:
cv2.imshow = interface.get("opencv_imshow", None)
cv2.waitKey = interface.get("opencv_waitKey", None)
except Exception as e:
pass
# destroy all opencv windows
for window in _opencv_windows.values():
window.destroy()
_opencv_windows.clear()
# remove current path from sys.path
path = os.path.dirname(__file__)
if path in sys.path:
sys.path.remove(path)
# opencv backend
_opencv_windows = {}
def _imshow(winname: str, mat: np.ndarray) -> None:
"""Show the image
:param winname: The window name
:type winname: str
:param mat: The image
:type mat: np.ndarray
"""
if winname not in _opencv_windows:
_opencv_windows[winname] = FigureManager(None, winname)
_opencv_windows[winname].render_image(mat)
def _waitKey(delay: int = 0) -> int:
"""Wait for a key press on the canvas
:param delay: The delay in milliseconds
:type delay: int
:returns: The key code
:rtype: int
"""
return -1
# matplotlib backend
def draw_if_interactive():
"""
For image backends - is not required.
For GUI backends - this should be overridden if drawing should be done in
interactive python mode.
"""
pass
def show(*, block: bool = None) -> None:
"""Show all figures and enter the main loop
For image backends - is not required.
For GUI backends - show() is usually the last line of a pyplot script and
tells the backend that it is time to draw. In interactive mode, this should do nothing
:param block: If not None, the call will block until the figure is closed
:type block: bool
"""
for manager in Gcf.get_all_fig_managers():
manager.show(block=block)
def new_figure_manager(num: int, *args, FigureClass: type = Figure, **kwargs) -> 'FigureManagerOmniUi':
"""Create a new figure manager instance
:param num: The figure number
:type num: int
:param args: The arguments to be passed to the Figure constructor
:type args: tuple
:param FigureClass: The class to use for creating the figure
:type FigureClass: type
:param kwargs: The keyword arguments to be passed to the Figure constructor
:type kwargs: dict
:returns: The figure manager instance
:rtype: FigureManagerOmniUi
"""
return new_figure_manager_given_figure(num, FigureClass(*args, **kwargs))
def new_figure_manager_given_figure(num: int, figure: 'Figure') -> 'FigureManagerOmniUi':
"""Create a new figure manager instance for the given figure.
:param num: The figure number
:type num: int
:param figure: The figure
:type figure: Figure
:returns: The figure manager instance
:rtype: FigureManagerOmniUi
"""
canvas = FigureCanvasAgg(figure)
manager = FigureManagerOmniUi(canvas, num)
return manager
class FigureManagerOmniUi(FigureManagerBase):
def __init__(self, canvas: 'FigureCanvasBase', num: int) -> None:
"""Figure manager for the Omni UI backend
:param canvas: The canvas
:type canvas: FigureCanvasBase
:param num: The figure number
:type num: int
"""
if canvas is not None:
super().__init__(canvas, num)
self._window_title = "Figure {}".format(num) if type(num) is int else num
self._byte_provider = None
self._window = None
def destroy(self) -> None:
"""Destroy the figure window"""
try:
self._byte_provider = None
self._window = None
except:
pass
def set_window_title(self, title: str) -> None:
"""Set the window title
:param title: The title
:type title: str
"""
self._window_title = title
try:
self._window.title = title
except:
pass
def get_window_title(self) -> str:
"""Get the window title
:returns: The window title
:rtype: str
"""
return self._window_title
def resize(self, w: int, h: int) -> None:
"""Resize the window
:param w: The width
:type w: int
:param h: The height
:type h: int
"""
print("[WARNING] resize() is not implemented")
def show(self, *, block: bool = None) -> None:
"""Show the figure window
:param block: If not None, the call will block until the figure is closed
:type block: bool
"""
# draw canvas and get figure
self.canvas.draw()
image = np.asarray(self.canvas.buffer_rgba())
# show figure
self.render_image(image=image,
figsize=(self.canvas.figure.get_figwidth(), self.canvas.figure.get_figheight()),
dpi=self.canvas.figure.get_dpi())
def render_image(self, image: np.ndarray, figsize: tuple = (6.4, 4.8), dpi: int = 100) -> None:
"""Set and display the image in the window (inner function)
:param image: The image
:type image: np.ndarray
:param figsize: The figure size
:type figsize: tuple
:param dpi: The dpi
:type dpi: int
"""
height, width = image.shape[:2]
# convert image to 4-channel RGBA
if image.ndim == 2:
image = np.dstack((image, image, image, np.full((height, width, 1), 255, dtype=np.uint8)))
elif image.ndim == 3:
if image.shape[2] == 3:
image = np.dstack((image, np.full((height, width, 1), 255, dtype=np.uint8)))
# enable the window visibility
if self._window is not None and not self._window.visible:
self._window.visible = True
# create the byte provider
if self._byte_provider is None:
self._byte_provider = ui.ByteImageProvider()
self._byte_provider.set_bytes_data(image.flatten().data, [width, height])
# update the byte provider
else:
self._byte_provider.set_bytes_data(image.flatten().data, [width, height])
# create the window
if self._window is None:
self._window = ui.Window(self._window_title,
width=int(figsize[0] * dpi),
height=int(figsize[1] * dpi),
visible=True)
with self._window.frame:
with ui.VStack():
ui.ImageWithProvider(self._byte_provider)
# provide the standard names that backend.__init__ is expecting
FigureCanvas = FigureCanvasAgg
FigureManager = FigureManagerOmniUi
| 9,315 | Python | 29.544262 | 129 | 0.619431 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/scripts/extension.py | import omni.ext
try:
from .. import _visualizer
except:
print(">>>> [DEVELOPMENT] import visualizer")
from .. import visualizer as _visualizer
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
self._interface = _visualizer.acquire_visualizer_interface(ext_id)
def on_shutdown(self):
_visualizer.release_visualizer_interface(self._interface)
| 393 | Python | 23.624999 | 74 | 0.692112 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/tests/test_visualizer.py | import omni.kit.test
class TestExtension(omni.kit.test.AsyncTestCaseFailOnLogError):
async def setUp(self) -> None:
pass
async def tearDown(self) -> None:
pass
async def test_extension(self):
pass | 235 | Python | 20.454544 | 63 | 0.659574 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/tests/__init__.py | from .test_visualizer import *
| 31 | Python | 14.999993 | 30 | 0.774194 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "0.2.0"
category = "Other"
feature = false
app = false
title = "Data Visualizer (Plots and Images)"
description = "Switch Matplotlib and OpenCV backend to display graphics and images inside NVIDIA Omniverse apps"
authors = ["Toni-SM"]
repository = "https://github.com/Toni-SM/semu.data.visualizer"
keywords = ["data", "image", "plot"]
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.ui" = {}
"omni.kit.uiapp" = {}
"omni.kit.pipapi" = {}
[python.pipapi]
requirements = ["numpy", "matplotlib", "opencv-python"]
[[python.module]]
name = "semu.data.visualizer"
[[python.module]]
name = "semu.data.visualizer.tests"
[settings]
exts."semu.data.visualizer".default_matplotlib_backend_if_agg = "Agg"
| 932 | TOML | 21.756097 | 112 | 0.694206 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.2.0] - 2022-05-21
### Changed
- Rename the extension to `semu.data.visualizer`
## [0.1.0] - 2022-03-28
### Added
- Source code (src folder)
- Availability for Windows operating system
### Changed
- Rewrite the extension to implement a mechanism to change the Matplotlib
and OpenCV backend to display graphics and images inside NVIDIA Omniverse apps
- Improve the display process performance
### Removed
- Omniverse native plots
## [0.0.1] - 2021-06-18
### Added
- Update extension to Isaac Sim 2021.1.0 extension format
| 629 | Markdown | 23.230768 | 80 | 0.72337 |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/docs/README.md | # semu.data.visualizer
This extension allows to switch Matplotlib and OpenCV backend to display graphics and images inside NVIDIA Omniverse apps without modifying the code logic
Visit https://github.com/Toni-SM/semu.data.visualizer to read more about its use
| 262 | Markdown | 36.571423 | 154 | 0.816794 |
Toni-SM/omni.add_on.ros_control_bridge/README.md | ## ROS Control Bridge (add-on) for NVIDIA Omniverse Isaac Sim
<br>
<hr>
<br>
:warning: :warning: :warning:
**This repository has been integrated into `semu.robotics.ros_bridge`, in which its source code has been released.**
**Visit [semu.robotics.ros_bridge](https://github.com/Toni-SM/semu.robotics.ros_bridge)**
:warning: :warning: :warning:
<br>
<hr>
<br>
> This extension enables the **ROS action interfaces used for controlling robots**. Particularly those used by [MoveIt](https://moveit.ros.org/) to talk with the controllers on the robot (**FollowJointTrajectory** and **GripperCommand**)
<br>
### Table of Contents
- [Prerequisites](#prerequisites)
- [Add the extension to an NVIDIA Omniverse app and enable it](#extension)
- [Control your robot using MoveIt](#control)
- [Configure a FollowJointTrajectory action](#follow_joint_trajectory)
- [Configure a GripperCommand action](#gripper_command)
<br>
<a name="prerequisites"></a>
### Prerequisites
All prerequisites described in [ROS & ROS2 Bridge](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_ros_bridge.html) must be fulfilled before running this extension. In addition, this extension requires the following extensions to be present in Isaac Sim:
- [omni.usd.schema.add_on](https://github.com/Toni-SM/omni.usd.schema.add_on): USD add-on schemas
- [omni.add_on.ros_bridge_ui](https://github.com/Toni-SM/omni.add_on.ros_bridge_ui): Menu and commands
<br>
<a name="extension"></a>
### Add the extension to an NVIDIA Omniverse app and enable it
1. Add the the extension by following the steps described in [Extension Search Paths](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-search-paths) or simply download and unzip the latest [release](https://github.com/Toni-SM/omni.add_on.ros_control_bridge/releases) in one of the extension folders such as ```PATH_TO_OMNIVERSE_APP/exts```
Git url (git+https) as extension search path:
```
git+https://github.com/Toni-SM/omni.add_on.ros_control_bridge.git?branch=main&dir=exts
```
2. Enable the extension by following the steps described in [Extension Enabling/Disabling](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-enabling-disabling)
<br>
<a name="control"></a>
### Control your robot using MoveIt
#### Concepts
MoveIt's *move_group* talks to the robot through ROS topics and actions. Three interfaces are required to control the robot. Go to the [MoveIt](https://moveit.ros.org/) website to read more about the [concepts](https://moveit.ros.org/documentation/concepts/) behind it
- **Joint State information:** the ```/joint_states``` topic (publisher) is used to determining the current state information
- **Transform information:** the ROS TF library is used to monitor the transform information
- **Controller Interface:** *move_group* talks to the controllers on the robot using the *FollowJointTrajectory* action interface. However, it is possible to use other controller interfaces to control the robot
#### Configuration
**Isaac Sim side**
1. Import your robot from an URDF file using the [URDF Importer](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html) extension. Go to [ROS Wiki: Using Xacro](http://wiki.ros.org/urdf/Tutorials/Using%20Xacro%20to%20Clean%20Up%20a%20URDF%20File#Using_Xacro) to convert your robot description form ```.xacro``` to ```.urdf```
2. Add a *Joint State* topic using the menu (*Create > Isaac > ROS > Joint State*) according to the [ROS Bridge](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_ros_bridge.html) extension
3. Add a *TF topic* using the menu (*Create > Isaac > ROS > Pose Tree*) according to the [ROS Bridge](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_ros_bridge.html) extension
4. Add the corresponding ROS control actions implemented by this extension (**see the sections below**) according to your robotic application's requirements
**Note:** At that point, it is recommendable to setup the MoveIt YAML configuration file first to know the controllers' names and the action namespaces
5. Play the editor to activate the respective topics and actions. Remember the editor must be playing before launching the *move_group*
**MoveIt side**
1. Launch the [MoveIt Setup Assistant](http://docs.ros.org/en/melodic/api/moveit_tutorials/html/doc/setup_assistant/setup_assistant_tutorial.html) and generate a new configuration package loading the same ```.xacro``` or ```.urdf``` used in Isaac Sim. Also, select the same ROS controller interfaces inside the step *ROS Control*
```bash
roslaunch moveit_setup_assistant setup_assistant.launch
```
2. Launch the *move_group* using the configured controllers
For example, you can use the next launch file (sample.launch) which is configured to support the *FollowJointTrajectory* and *GripperCommand* controllers (panda_gripper_controllers.yaml) by replacing the ```panda_moveit_config``` with the generated folder's name and ```/panda/joint_state``` with the Isaac Sim joint state topic name
```bash
roslaunch moveit_config sample.launch
```
panda_gripper_controllers.yaml
```yaml
controller_list:
- name: panda_arm_controller
action_ns: follow_joint_trajectory
type: FollowJointTrajectory
default: true
joints:
- panda_joint1
- panda_joint2
- panda_joint3
- panda_joint4
- panda_joint5
- panda_joint6
- panda_joint7
- name: panda_gripper
action_ns: gripper_command
type: GripperCommand
default: true
joints:
- panda_finger_joint1
- panda_finger_joint2
```
sample.launch
```xml
<launch>
<!-- Load the URDF, SRDF and other .yaml configuration files on the param server -->
<include file="$(find panda_moveit_config)/launch/planning_context.launch">
<arg name="load_robot_description" value="true"/>
</include>
<!-- Publish joint states -->
<node name="joint_state_publisher" pkg="joint_state_publisher" type="joint_state_publisher">
<rosparam param="/source_list">["/panda/joint_state"]</rosparam>
</node>
<node name="joint_state_desired_publisher" pkg="topic_tools" type="relay" args="joint_states joint_states_desired"/>
<!-- Given the published joint states, publish tf for the robot links -->
<node name="robot_state_publisher" pkg="robot_state_publisher" type="robot_state_publisher" respawn="true" output="screen" />
<!-- Run the main MoveIt executable -->
<include file="$(find panda_moveit_config)/launch/move_group.launch">
<arg name="allow_trajectory_execution" value="true"/>
<arg name="info" value="true"/>
<arg name="debug" value="false"/>
</include>
<!-- Run Rviz (optional) -->
<include file="$(find panda_moveit_config)/launch/moveit_rviz.launch">
<arg name="debug" value="false"/>
</include>
</launch>
```
Also, you can modify the ```demo.launch``` file and disable the fake controller execution inside the main MoveIt executable
```xml
<arg name="fake_execution" value="false"/>
```
3. Use the Move Group [C++](http://docs.ros.org/en/melodic/api/moveit_tutorials/html/doc/move_group_interface/move_group_interface_tutorial.html) or [Python](http://docs.ros.org/en/melodic/api/moveit_tutorials/html/doc/move_group_python_interface/move_group_python_interface_tutorial.html) interfaces to control the robot
<br>
<a name="follow_joint_trajectory"></a>
### Configure a FollowJointTrajectory action
To add a ```FollowJointTrajectory``` action go to menu *Create > Isaac > ROS Control* and select *Follow Joint Trajectory*
To connect the schema with the robot of your choice, select the root of the articulation tree by pressing the *Add Target(s)* button under the ```articulationPrim``` field. Press the play button in the editor, and the topics related to this action will be activated for use
The communication shall take place in the namespace defined by the following fields:
```python
rosNodePrefix + controllerName + actionNamespace
```
<br>
The following figure shows a *FollowJointTrajectory* schema configured to match the ```panda_gripper_controllers.yaml``` described above

<br>
<a name="gripper_command"></a>
### Configure a GripperCommand action
To add a ```GripperCommand``` action go to menu *Create > Isaac > ROS Control* and select *Gripper Command*
To connect the schematic to the end-effector of your choice, first select the root of the articulation tree and then select each of the end-effector's articulations to control following this strict order. This can be done by pressing the *Add Target(s)* button repeatedly under the ```articulationPrim``` field. Press the play button in the editor, and the topics related to this action will be activated for use
The communication shall take place in the namespace defined by the following fields:
```python
rosNodePrefix + controllerName + actionNamespace
```
The ```GripperCommand``` action definition doesn't specify which joints will be controlled. The value manage by this action will affect all the specified joints equally
<br>
The following figure shows a *GripperCommand* schema configured to match the ```panda_gripper_controllers.yaml``` described above

| 9,798 | Markdown | 45.661905 | 412 | 0.726067 |
Toni-SM/semu.robotics.ros_bridge/README.md | ## ROS Bridge (external extension) for NVIDIA Omniverse Isaac Sim
> This extension enables the ROS action server interfaces for controlling robots (particularly those used by MoveIt to talk to robot controllers: [FollowJointTrajectory](http://docs.ros.org/en/api/control_msgs/html/action/FollowJointTrajectory.html) and [GripperCommand](http://docs.ros.org/en/api/control_msgs/html/action/GripperCommand.html)) and enables services for agile prototyping of robotic applications in [ROS](https://www.ros.org/)
<br>
**Target applications:** NVIDIA Omniverse Isaac Sim
**Supported OS:** Linux
**Changelog:** [CHANGELOG.md](exts/semu.robotics.ros_bridge/docs/CHANGELOG.md)
**Table of Contents:**
- [Prerequisites](#prerequisites)
- [Extension setup](#setup)
- [Extension usage](#usage)
- [Supported components](#components)
- [Attribute](#ros-attribute)
- [FollowJointTrajectory](#ros-follow-joint-trajectory)
- [GripperCommand](#ros-gripper-command)
<br>

<hr>
<a name="prerequisites"></a>
### Prerequisites
All prerequisites described in [ROS & ROS2 Bridge](https://docs.omniverse.nvidia.com/isaacsim/latest/features/external_communication/ext_omni_isaac_ros_bridge.html) must be fulfilled before running this extension
<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.robotics.ros_bridge.git?branch=main&dir=exts
```
* Compressed (.zip) file for import
[semu.robotics.ros_bridge.zip](https://github.com/Toni-SM/semu.robotics.ros_bridge/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 initializes a ROS node named `/SemuRosBridge` (configurable in the `extension.toml` file). This node will enable, when the simulation starts, the ROS topics, services and actions protocols according to the ROS prims (and their configurations) existing in the current stage
Disabling the extension shutdowns the ROS node and its respective active communication protocols
> **Note:** The current implementation only implements position control (velocity or effort control is not yet supported) for the FollowJointTrajectory and GripperCommand actions
<hr>
<a name="components"></a>
### Supported components

<br>
The following components are supported:
<a name="ros-attribute"></a>
* **Attribute (ROS service):** enables the services for getting and setting the attributes of a prim according to the service definitions described bellow
To add an Attribute service action search for ActionGraph nodes and select ***ROS1 Attribute Service***
The ROS package [add_on_msgs](https://github.com/Toni-SM/semu.robotics.ros_bridge/releases) contains the definition of the messages (download and add it to a ROS workspace). A sample code of a [python client application](https://github.com/Toni-SM/semu.robotics.ros_bridge/releases) is also provided
Prim attributes are retrieved and modified as JSON (applied directly to the data, without keys). Arrays, vectors, matrixes and other numeric classes (```pxr.Gf.Vec3f```, ```pxr.Gf.Matrix4d```, ```pxr.Gf.Quatf```, ```pxr.Vt.Vec2fArray```, etc.) are interpreted as a list of numbers (row first)
* **add_on_msgs.srv.GetPrims**: Get all prim path under the specified path
```yaml
string path # get prims at path
---
string[] paths # list of prim paths
string[] types # prim type names
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
* **add_on_msgs.srv.GetPrimAttributes**: Get prim attribute names and their types
```yaml
string path # prim path
---
string[] names # list of attribute base names (name used to Get or Set an attribute)
string[] displays # list of attribute display names (name displayed in Property tab)
string[] types # list of attribute data types
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
* **add_on_msgs.srv.GetPrimAttribute**: Get prim attribute
```yaml
string path # prim path
string attribute # attribute name
---
string value # attribute value (as JSON)
string type # attribute type
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
* **add_on_msgs.srv.SetPrimAttribute**: Set prim attribute
```yaml
string path # prim path
string attribute # attribute name
string value # attribute value (as JSON)
---
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
```
<a name="ros-follow-joint-trajectory"></a>
* **FollowJointTrajectory (ROS action):** enables the actions for a robot to follow a given trajectory
To add a FollowJointTrajectory action search for ActionGraph nodes and select ***ROS1 FollowJointTrajectory Action***
Select, by clicking the **Add Target(s)** button under the `inputs:targetPrims` field, the root of the robot's articulation tree to control and edit the fields that define the namespace of the communication. The communication will take place in the namespace defined by the following fields:
```
controllerName + actionNamespace
```
<a name="ros-gripper-command"></a>
* **GripperCommand (ROS action):** enables the actions to control a gripper
To add a GripperCommand action search for ActionGraph nodes and select ***ROS1 GripperCommand Action***
Select, by clicking the **Add Target(s)** button under the `inputs:targetPrims` field, the root of the robot's articulation tree to which the end-effector belongs and add the joints (of the gripper) to control using the `inputs:targetGripperJoints` field
Also, edit the fields that define the namespace of the communication. The communication will take place in the namespace defined by the following fields:
```
controllerName + actionNamespace
```
> **Note:** The GripperCommand action definition doesn't specify which joints will be controlled. The value manage by this action will affect all the specified joints equally
| 7,615 | Markdown | 47.509554 | 442 | 0.70151 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/ros_bridge.py | import omni
import carb
import rospy
import rosgraph
_ROS_NODE_RUNNING = False
def acquire_ros_bridge_interface(ext_id: str = "") -> 'RosBridge':
"""Acquire the RosBridge interface
:param ext_id: The extension id
:type ext_id: str
:returns: The RosBridge interface
:rtype: RosBridge
"""
return RosBridge()
def release_ros_bridge_interface(bridge: 'RosBridge') -> None:
"""Release the RosBridge interface
:param bridge: The RosBridge interface
:type bridge: RosBridge
"""
bridge.shutdown()
def is_ros_master_running() -> bool:
"""Check if the ROS master is running
:returns: True if the ROS master is running, False otherwise
:rtype: bool
"""
# check ROS master
try:
rosgraph.Master("/rostopic").getPid()
except:
return False
return True
def is_ros_node_running() -> bool:
"""Check if the ROS node is running
:returns: True if the ROS node is running, False otherwise
:rtype: bool
"""
return _ROS_NODE_RUNNING
class RosBridge:
def __init__(self) -> None:
"""Initialize the RosBridge interface
"""
self._node_name = carb.settings.get_settings().get("/exts/semu.robotics.ros_bridge/nodeName")
# omni objects and interfaces
self._timeline = omni.timeline.get_timeline_interface()
# events
self._timeline_event = self._timeline.get_timeline_event_stream().create_subscription_to_pop(self._on_timeline_event)
# ROS node
if is_ros_master_running():
self._init_ros_node()
def shutdown(self) -> None:
"""Shutdown the RosBridge interface
"""
self._timeline_event = None
rospy.signal_shutdown("semu.robotics.ros_bridge shutdown")
def _init_ros_node(self) -> None:
global _ROS_NODE_RUNNING
"""Initialize the ROS node
"""
try:
rospy.init_node(self._node_name, disable_signals=False)
_ROS_NODE_RUNNING = True
print("[Info][semu.robotics.ros_bridge] {} node started".format(self._node_name))
except rospy.ROSException as e:
print("[Error][semu.robotics.ros_bridge] {}: {}".format(self._node_name, e))
def _on_timeline_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the timeline event
:param event: Event
:type event: carb.events._events.IEvent
"""
if event.type == int(omni.timeline.TimelineEventType.PLAY):
if is_ros_master_running():
self._init_ros_node()
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
pass
elif event.type == int(omni.timeline.TimelineEventType.STOP):
pass
| 2,777 | Python | 27.639175 | 125 | 0.613972 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/ogn/nodes/OgnROS1ActionGripperCommand.py | import omni
from pxr import PhysxSchema
from omni.isaac.dynamic_control import _dynamic_control
from omni.isaac.core.utils.stage import get_stage_units
import rospy
import actionlib
import control_msgs.msg
try:
from ... import _ros_bridge
except:
from ... import ros_bridge as _ros_bridge
class InternalState:
def __init__(self):
"""Internal state for the ROS1 GripperCommand node
"""
self.initialized = False
self.dci = None
self.usd_context = None
self.timeline_event = None
self.action_server = None
self.articulation_path = ""
self.gripper_joints_paths = []
self._articulation = _dynamic_control.INVALID_HANDLE
self._joints = {}
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
# TODO: add to schema?
self._action_timeout = 10.0
self._action_position_threshold = 0.001
self._action_previous_position_sum = float("inf")
# feedback / result
self._action_result_message = control_msgs.msg.GripperCommandResult()
self._action_feedback_message = control_msgs.msg.GripperCommandFeedback()
def on_timeline_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the timeline event
:param event: Event
:type event: carb.events._events.IEvent
"""
if event.type == int(omni.timeline.TimelineEventType.PLAY):
pass
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
pass
elif event.type == int(omni.timeline.TimelineEventType.STOP):
self.initialized = False
self.shutdown_action_server()
self._articulation = _dynamic_control.INVALID_HANDLE
self._joints = {}
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
def shutdown_action_server(self) -> None:
"""Shutdown the action server
"""
# omni.isaac.ros_bridge/noetic/lib/python3/dist-packages/actionlib/action_server.py
print("[Info][semu.robotics.ros_bridge] ROS1 GripperCommand: destroying action server")
if self.action_server:
if self.action_server.started:
self.action_server.started = False
self.action_server.status_pub.unregister()
self.action_server.result_pub.unregister()
self.action_server.feedback_pub.unregister()
self.action_server.goal_sub.unregister()
self.action_server.cancel_sub.unregister()
del self.action_server
self.action_server = None
def _init_articulation(self) -> None:
"""Initialize the articulation and register joints
"""
# get articulation
path = self.articulation_path
self._articulation = self.dci.get_articulation(path)
if self._articulation == _dynamic_control.INVALID_HANDLE:
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: {} is not an articulation".format(path))
return
dof_props = self.dci.get_articulation_dof_properties(self._articulation)
if dof_props is None:
return
upper_limits = dof_props["upper"]
lower_limits = dof_props["lower"]
has_limits = dof_props["hasLimits"]
# get joints
for i in range(self.dci.get_articulation_dof_count(self._articulation)):
dof_ptr = self.dci.get_articulation_dof(self._articulation, i)
if dof_ptr != _dynamic_control.DofType.DOF_NONE:
# add only required joints
if self.dci.get_dof_path(dof_ptr) in self.gripper_joints_paths:
dof_name = self.dci.get_dof_name(dof_ptr)
if dof_name not in self._joints:
_joint = self.dci.find_articulation_joint(self._articulation, dof_name)
self._joints[dof_name] = {"joint": _joint,
"type": self.dci.get_joint_type(_joint),
"dof": self.dci.find_articulation_dof(self._articulation, dof_name),
"lower": lower_limits[i],
"upper": upper_limits[i],
"has_limits": has_limits[i]}
if not self._joints:
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: no joints found in {}".format(path))
self.initialized = False
def _set_joint_position(self, name: str, target_position: float) -> None:
"""Set the target position of a joint in the articulation
:param name: The joint name
:type name: str
:param target_position: The target position
:type target_position: float
"""
# clip target position
if self._joints[name]["has_limits"]:
target_position = min(max(target_position, self._joints[name]["lower"]), self._joints[name]["upper"])
# scale target position for prismatic joints
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
target_position /= get_stage_units()
# set target position
self.dci.set_dof_position_target(self._joints[name]["dof"], target_position)
def _get_joint_position(self, name: str) -> float:
"""Get the current position of a joint in the articulation
:param name: The joint name
:type name: str
:return: The current position of the joint
:rtype: float
"""
position = self.dci.get_dof_state(self._joints[name]["dof"], _dynamic_control.STATE_POS).pos
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
return position * get_stage_units()
return position
def on_goal(self, goal_handle: 'actionlib.ServerGoalHandle') -> None:
"""Callback function for handling new goal requests
:param goal_handle: The goal handle
:type goal_handle: actionlib.ServerGoalHandle
"""
goal = goal_handle.get_goal()
# reject if there is an active goal
if self._action_goal is not None:
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: multiple goals not supported")
goal_handle.set_rejected()
return
# store goal data
self._action_goal = goal
self._action_goal_handle = goal_handle
self._action_start_time = rospy.get_time()
self._action_previous_position_sum = float("inf")
goal_handle.set_accepted()
def on_cancel(self, goal_handle: 'actionlib.ServerGoalHandle') -> None:
"""Callback function for handling cancel requests
:param goal_handle: The goal handle
:type goal_handle: actionlib.ServerGoalHandle
"""
if self._action_goal is None:
goal_handle.set_rejected()
return
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_previous_position_sum = float("inf")
goal_handle.set_canceled()
def step(self, dt: float) -> None:
"""Update step
:param dt: Delta time
:type dt: float
"""
if not self.initialized:
return
# init articulation
if not self._joints:
self._init_articulation()
return
# update articulation
if self._action_goal is not None and self._action_goal_handle is not None:
target_position = self._action_goal.command.position
# set target
self.dci.wake_up_articulation(self._articulation)
for name in self._joints:
self._set_joint_position(name, target_position)
# end (position reached)
position = 0
current_position_sum = 0
position_reached = True
for name in self._joints:
position = self._get_joint_position(name)
current_position_sum += position
if abs(position - target_position) > self._action_position_threshold:
position_reached = False
break
if position_reached:
self._action_goal = None
self._action_result_message.position = position
self._action_result_message.stalled = False
self._action_result_message.reached_goal = True
if self._action_goal_handle is not None:
self._action_goal_handle.set_succeeded(self._action_result_message)
self._action_goal_handle = None
return
# end (stalled)
if abs(current_position_sum - self._action_previous_position_sum) < 1e-6:
self._action_goal = None
self._action_result_message.position = position
self._action_result_message.stalled = True
self._action_result_message.reached_goal = False
if self._action_goal_handle is not None:
self._action_goal_handle.set_succeeded(self._action_result_message)
self._action_goal_handle = None
return
self._action_previous_position_sum = current_position_sum
# end (timeout)
time_passed = rospy.get_time() - self._action_start_time
if time_passed >= self._action_timeout:
self._action_goal = None
if self._action_goal_handle is not None:
self._action_goal_handle.set_aborted()
self._action_goal_handle = None
# TODO: send feedback
# self._action_goal_handle.publish_feedback(self._action_feedback_message)
class OgnROS1ActionGripperCommand:
"""This node provides the services to list, read and write prim's attributes
"""
@staticmethod
def initialize(graph_context, node):
pass
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db) -> bool:
if not _ros_bridge.is_ros_node_running():
return False
if db.internal_state.initialized:
db.internal_state.step(0)
else:
try:
db.internal_state.usd_context = omni.usd.get_context()
db.internal_state.dci = _dynamic_control.acquire_dynamic_control_interface()
if db.internal_state.timeline_event is None:
timeline = omni.timeline.get_timeline_interface()
db.internal_state.timeline_event = timeline.get_timeline_event_stream() \
.create_subscription_to_pop(db.internal_state.on_timeline_event)
def get_action_name(namespace, controller_name, action_namespace):
controller_name = controller_name if controller_name.startswith("/") else "/" + controller_name
action_namespace = action_namespace if action_namespace.startswith("/") else "/" + action_namespace
return namespace if namespace else "" + controller_name + action_namespace
def get_relationships(node, usd_context, attribute):
stage = usd_context.get_stage()
prim = stage.GetPrimAtPath(node.get_prim_path())
return prim.GetRelationship(attribute).GetTargets()
# check for articulation
path = db.inputs.targetPrim.path
if not len(path):
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: targetPrim not set")
return
# check for articulation API
stage = db.internal_state.usd_context.get_stage()
if not stage.GetPrimAtPath(path).HasAPI(PhysxSchema.PhysxArticulationAPI):
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: {} doesn't have PhysxArticulationAPI".format(path))
return
db.internal_state.articulation_path = path
# check for gripper joints
relationships = get_relationships(db.node, db.internal_state.usd_context, "inputs:targetGripperJoints")
paths = [relationship.GetPrimPath().pathString for relationship in relationships]
if not paths:
print("[Warning][semu.robotics.ros_bridge] ROS1 GripperCommand: targetGripperJoints not set")
return
db.internal_state.gripper_joints_paths = paths
# create action server
db.internal_state.shutdown_action_server()
action_name = get_action_name(db.inputs.nodeNamespace, db.inputs.controllerName, db.inputs.actionNamespace)
db.internal_state.action_server = actionlib.ActionServer(action_name,
control_msgs.msg.GripperCommandAction,
goal_cb=db.internal_state.on_goal,
cancel_cb=db.internal_state.on_cancel,
auto_start=False)
db.internal_state.action_server.start()
print("[Info][semu.robotics.ros_bridge] ROS1 GripperCommand: register action {}".format(action_name))
except ConnectionRefusedError as error:
print("[Error][semu.robotics.ros_bridge] ROS1 GripperCommand: action server {} not started".format(action_name))
db.log_error(str(error))
db.internal_state.initialized = False
return False
except Exception as error:
print("[Error][semu.robotics.ros_bridge] ROS1 GripperCommand: error: {}".format(error))
db.log_error(str(error))
db.internal_state.initialized = False
return False
db.internal_state.initialized = True
return True
| 14,448 | Python | 41.875371 | 135 | 0.576412 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/ogn/nodes/OgnROS1ServiceAttribute.py | from typing import Any
import json
import asyncio
import threading
import omni
import carb
from pxr import Usd, Gf
from omni.isaac.dynamic_control import _dynamic_control
import rospy
try:
from ... import _ros_bridge
except:
from ... import ros_bridge as _ros_bridge
class InternalState:
def __init__(self):
"""Internal state for the ROS1 Attribute node
"""
self.initialized = False
self.dci = None
self.usd_context = None
self.timeline_event = None
self.GetPrims = None
self.GetPrimAttributes = None
self.GetPrimAttribute = None
self.SetPrimAttribute = None
self.srv_prims = None
self.srv_attributes = None
self.srv_getter = None
self.srv_setter = None
self._event = threading.Event()
self._event.set()
self.__event_timeout = carb.settings.get_settings().get("/exts/semu.robotics.ros_bridge/eventTimeout")
self.__set_attribute_using_asyncio = \
carb.settings.get_settings().get("/exts/semu.robotics.ros_bridge/setAttributeUsingAsyncio")
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: asyncio: {}".format(self.__set_attribute_using_asyncio))
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: event timeout: {}".format(self.__event_timeout))
def on_timeline_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the timeline event
:param event: Event
:type event: carb.events._events.IEvent
"""
if event.type == int(omni.timeline.TimelineEventType.PLAY):
pass
elif event.type == int(omni.timeline.TimelineEventType.PAUSE):
pass
elif event.type == int(omni.timeline.TimelineEventType.STOP):
self.initialized = False
self.shutdown_services()
def shutdown_services(self) -> None:
"""Shutdown the services
"""
if self.srv_prims is not None:
print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_prims.resolved_name))
self.srv_prims.shutdown()
self.srv_prims = None
if self.srv_getter is not None:
print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_getter.resolved_name))
self.srv_getter.shutdown()
self.srv_getter = None
if self.srv_attributes is not None:
print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_attributes.resolved_name))
self.srv_attributes.shutdown()
self.srv_attributes = None
if self.srv_setter is not None:
print("[Info][semu.robotics.ros_bridge] RosAttribute: unregister srv: {}".format(self.srv_setter.resolved_name))
self.srv_setter.shutdown()
self.srv_setter = None
async def _set_attribute(self, attribute: 'pxr.Usd.Attribute', attribute_value: Any) -> None:
"""Set the attribute value using asyncio
:param attribute: The prim's attribute to set
:type attribute: pxr.Usd.Attribute
:param attribute_value: The attribute value
:type attribute_value: Any
"""
ret = attribute.Set(attribute_value)
def process_setter_request(self, request: 'SetPrimAttribute.SetPrimAttributeRequest') -> 'SetPrimAttribute.SetPrimAttributeResponse':
"""Process the setter request
:param request: The service request
:type request: SetPrimAttribute.SetPrimAttributeRequest
:return: The service response
:rtype: SetPrimAttribute.SetPrimAttributeResponse
"""
response = self.SetPrimAttribute.SetPrimAttributeResponse()
response.success = False
stage = self.usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
if request.attribute and prim.HasAttribute(request.attribute):
# attribute
attribute = prim.GetAttribute(request.attribute)
attribute_type = type(attribute.Get()).__name__
# value
try:
value = json.loads(request.value)
attribute_value = None
except json.JSONDecodeError:
print("[Error][semu.robotics.ros_bridge] ROS1 Attribute: invalid value: {}".format(request.value))
response.success = False
response.message = "Invalid value '{}'".format(request.value)
return response
# parse data
try:
if attribute_type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Quatd', 'Quatf', 'Quath']:
attribute_value = type(attribute.Get())(*value)
elif attribute_type in ['Matrix4d', 'Matrix4f']:
attribute_value = type(attribute.Get())(value)
elif attribute_type.startswith('Vec') and attribute_type.endswith('Array'):
attribute_value = type(attribute.Get())(value)
elif attribute_type.startswith('Matrix') and attribute_type.endswith('Array'):
if attribute_type.endswith("dArray"):
attribute_value = type(attribute.Get())([Gf.Matrix2d(v) for v in value])
elif attribute_type.endswith("fArray"):
attribute_value = type(attribute.Get())([Gf.Matrix2f(v) for v in value])
elif attribute_type.startswith('Quat') and attribute_type.endswith('Array'):
if attribute_type.endswith("dArray"):
attribute_value = type(attribute.Get())([Gf.Quatd(*v) for v in value])
elif attribute_type.endswith("fArray"):
attribute_value = type(attribute.Get())([Gf.Quatf(*v) for v in value])
elif attribute_type.endswith("hArray"):
attribute_value = type(attribute.Get())([Gf.Quath(*v) for v in value])
elif attribute_type.endswith('Array'):
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['AssetPath']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['NoneType']:
pass
else:
attribute_value = type(attribute.Get())(value)
# set attribute
if attribute_value is not None:
# set attribute usign asyncio
if self.__set_attribute_using_asyncio:
try:
loop = asyncio.get_event_loop()
except:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
future = asyncio.ensure_future(self._set_attribute(attribute, attribute_value))
loop.run_until_complete(future)
response.success = True
# set attribute in the physics event
else:
self._attribute = attribute
self._value = attribute_value
self._event.clear()
response.success = self._event.wait(self.__event_timeout)
if not response.success:
response.message = "The timeout ({} s) for setting the attribute value has been reached" \
.format(self.__event_timeout)
except Exception as e:
print("[Error][semu.robotics.ros_bridge] ROS1 Attribute: srv {} request for {} ({}: {}): {}" \
.format(self.srv_setter.resolved_name, request.path, request.attribute, value, e))
response.success = False
response.message = str(e)
else:
response.message = "Prim has not attribute {}".format(request.attribute)
else:
response.message = "Invalid prim ({})".format(request.path)
return response
def process_getter_request(self, request: 'GetPrimAttribute.GetPrimAttributeRequest') -> 'GetPrimAttribute.GetPrimAttributeResponse':
"""Process the getter request
:param request: The service request
:type request: GetPrimAttribute.GetPrimAttributeRequest
:return: The service response
:rtype: GetPrimAttribute.GetPrimAttributeResponse
"""
response = self.GetPrimAttribute.GetPrimAttributeResponse()
response.success = False
stage = self.usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
if request.attribute and prim.HasAttribute(request.attribute):
attribute = prim.GetAttribute(request.attribute)
response.type = type(attribute.Get()).__name__
# parse data
response.success = True
if response.type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(2)])
elif response.type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(3)])
elif response.type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(4)])
elif response.type in ['Quatd', 'Quatf', 'Quath']:
data = attribute.Get()
response.value = json.dumps([data.real, data.imaginary[0], data.imaginary[1], data.imaginary[2]])
elif response.type in ['Matrix4d', 'Matrix4f']:
data = attribute.Get()
response.value = json.dumps([[data.GetRow(i)[j] for j in range(data.dimension[1])] \
for i in range(data.dimension[0])])
elif response.type.startswith('Vec') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[d[i] for i in range(len(d))] for d in data])
elif response.type.startswith('Matrix') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[[d.GetRow(i)[j] for j in range(d.dimension[1])] \
for i in range(d.dimension[0])] for d in data])
elif response.type.startswith('Quat') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[d.real, d.imaginary[0], d.imaginary[1], d.imaginary[2]] for d in data])
elif response.type.endswith('Array'):
try:
response.value = json.dumps(list(attribute.Get()))
except Exception as e:
print("[Warning][semu.robotics.ros_bridge] ROS1 Attribute: Unknow attribute type {}" \
.format(type(attribute.Get())))
print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros_bridge/issues)")
response.success = False
response.message = "Unknow type {}".format(type(attribute.Get()))
elif response.type in ['AssetPath']:
response.value = json.dumps(str(attribute.Get().path))
else:
try:
response.value = json.dumps(attribute.Get())
except Exception as e:
print("[Warning][semu.robotics.ros_bridge] ROS1 Attribute: Unknow {}: {}" \
.format(type(attribute.Get()), attribute.Get()))
print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros_bridge/issues)")
response.success = False
response.message = "Unknow type {}".format(type(attribute.Get()))
else:
response.message = "Prim has not attribute {}".format(request.attribute)
else:
response.message = "Invalid prim ({})".format(request.path)
return response
def process_attributes_request(self, request: 'GetPrimAttributes.GetPrimAttributesRequest') -> 'GetPrimAttributes.GetPrimAttributesResponse':
"""Process the 'get all attributes' request
:param request: The service request
:type request: GetPrimAttributes.GetPrimAttributesRequest
:return: The service response
:rtype: GetPrimAttributes.GetPrimAttributesResponse
"""
response = self.GetPrimAttributes.GetPrimAttributesResponse()
response.success = False
stage = self.usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
for attribute in prim.GetAttributes():
if attribute.GetNamespace():
response.names.append("{}:{}".format(attribute.GetNamespace(), attribute.GetBaseName()))
else:
response.names.append(attribute.GetBaseName())
response.displays.append(attribute.GetDisplayName())
response.types.append(type(attribute.Get()).__name__)
response.success = True
else:
response.message = "Invalid prim ({})".format(request.path)
return response
def process_prims_request(self, request: 'GetPrims.GetPrimsRequest') -> 'GetPrims.GetPrimsResponse':
"""Process the 'get all prims' request
:param request: The service request
:type request: GetPrims.GetPrimsRequest
:return: The service response
:rtype: GetPrims.GetPrimsResponse
"""
response = self.GetPrims.GetPrimsResponse()
response.success = False
stage = self.usd_context.get_stage()
# get prims
if not request.path or stage.GetPrimAtPath(request.path).IsValid():
path = request.path if request.path else "/"
for prim in Usd.PrimRange.AllPrims(stage.GetPrimAtPath(path)):
response.paths.append(str(prim.GetPath()))
response.types.append(prim.GetTypeName())
response.success = True
else:
response.message = "Invalid search path ({})".format(request.path)
return response
def step(self, dt: float) -> None:
"""Update step
:param dt: Delta time
:type dt: float
"""
if not self.initialized:
return
if self.__set_attribute_using_asyncio:
return
if self.dci.is_simulating():
if not self._event.is_set():
if self._attribute is not None:
ret = self._attribute.Set(self._value)
self._event.set()
class OgnROS1ServiceAttribute:
"""This node provides the services to list, read and write prim's attributes
"""
@staticmethod
def initialize(graph_context, node):
pass
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db) -> bool:
if not _ros_bridge.is_ros_node_running():
return False
if db.internal_state.initialized:
db.internal_state.step(0)
else:
try:
db.internal_state.usd_context = omni.usd.get_context()
db.internal_state.dci = _dynamic_control.acquire_dynamic_control_interface()
if db.internal_state.timeline_event is None:
timeline = omni.timeline.get_timeline_interface()
db.internal_state.timeline_event = timeline.get_timeline_event_stream() \
.create_subscription_to_pop(db.internal_state.on_timeline_event)
def get_service_name(namespace, name):
service_namespace = namespace if namespace.startswith("/") else "/" + namespace
service_name = name if name.startswith("/") else "/" + name
return service_namespace if namespace else "" + service_name
# load service definitions
from add_on_msgs.srv import _GetPrims
from add_on_msgs.srv import _GetPrimAttributes
from add_on_msgs.srv import _GetPrimAttribute
from add_on_msgs.srv import _SetPrimAttribute
db.internal_state.GetPrims = _GetPrims
db.internal_state.GetPrimAttributes = _GetPrimAttributes
db.internal_state.GetPrimAttribute = _GetPrimAttribute
db.internal_state.SetPrimAttribute = _SetPrimAttribute
# create services
db.internal_state.shutdown_services()
service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.primsServiceName)
db.internal_state.srv_prims = rospy.Service(service_name,
db.internal_state.GetPrims.GetPrims,
db.internal_state.process_prims_request)
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_prims.resolved_name))
service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.getAttributesServiceName)
db.internal_state.srv_attributes = rospy.Service(service_name,
db.internal_state.GetPrimAttributes.GetPrimAttributes,
db.internal_state.process_attributes_request)
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_attributes.resolved_name))
service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.getAttributeServiceName)
db.internal_state.srv_getter = rospy.Service(service_name,
db.internal_state.GetPrimAttribute.GetPrimAttribute,
db.internal_state.process_getter_request)
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_getter.resolved_name))
service_name = get_service_name(db.inputs.nodeNamespace, db.inputs.setAttributeServiceName)
db.internal_state.srv_setter = rospy.Service(service_name,
db.internal_state.SetPrimAttribute.SetPrimAttribute,
db.internal_state.process_setter_request)
print("[Info][semu.robotics.ros_bridge] ROS1 Attribute: register srv: {}".format(db.internal_state.srv_setter.resolved_name))
except Exception as error:
print("[Error][semu.robotics.ros_bridge] ROS1 Attribute: error: {}".format(error))
db.log_error(str(error))
db.internal_state.initialized = False
return False
db.internal_state.initialized = True
return True
| 20,602 | Python | 49.497549 | 145 | 0.557713 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/scripts/extension.py | import os
import sys
import carb
import omni.ext
import omni.graph.core as og
try:
from .. import _ros_bridge
except:
from .. import ros_bridge as _ros_bridge
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
self._rosbridge = None
self._extension_path = None
ext_manager = omni.kit.app.get_app().get_extension_manager()
if ext_manager.is_extension_enabled("omni.isaac.ros2_bridge"):
carb.log_error("ROS Bridge external extension cannot be enabled if ROS 2 Bridge is enabled")
ext_manager.set_extension_enabled("semu.robotics.ros_bridge", False)
return
self._extension_path = ext_manager.get_extension_path(ext_id)
sys.path.append(os.path.join(self._extension_path, "semu", "robotics", "ros_bridge", "packages"))
self._rosbridge = _ros_bridge.acquire_ros_bridge_interface(ext_id)
og.register_ogn_nodes(__file__, "semu.robotics.ros_bridge")
def on_shutdown(self):
if self._extension_path is not None:
sys.path.remove(os.path.join(self._extension_path, "semu", "robotics", "ros_bridge", "packages"))
self._extension_path = None
if self._rosbridge is not None:
_ros_bridge.release_ros_bridge_interface(self._rosbridge)
self._rosbridge = None
| 1,345 | Python | 36.388888 | 109 | 0.646097 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/_SetPrimAttribute.py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/SetPrimAttributeRequest.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class SetPrimAttributeRequest(genpy.Message):
_md5sum = "c72cd1009a2d47b7e1ab3f88d1ff98e3"
_type = "add_on_msgs/SetPrimAttributeRequest"
_has_header = False # flag to mark the presence of a Header object
_full_text = """string path # prim path
string attribute # attribute name
string value # attribute value (as JSON)
"""
__slots__ = ['path','attribute','value']
_slot_types = ['string','string','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
path,attribute,value
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(SetPrimAttributeRequest, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.path is None:
self.path = ''
if self.attribute is None:
self.attribute = ''
if self.value is None:
self.value = ''
else:
self.path = ''
self.attribute = ''
self.value = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.attribute
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.value
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.attribute = str[start:end].decode('utf-8', 'rosmsg')
else:
self.attribute = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.value = str[start:end].decode('utf-8', 'rosmsg')
else:
self.value = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.attribute
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
_x = self.value
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.attribute = str[start:end].decode('utf-8', 'rosmsg')
else:
self.attribute = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.value = str[start:end].decode('utf-8', 'rosmsg')
else:
self.value = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/SetPrimAttributeResponse.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class SetPrimAttributeResponse(genpy.Message):
_md5sum = "937c9679a518e3a18d831e57125ea522"
_type = "add_on_msgs/SetPrimAttributeResponse"
_has_header = False # flag to mark the presence of a Header object
_full_text = """bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
"""
__slots__ = ['success','message']
_slot_types = ['bool','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
success,message
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(SetPrimAttributeResponse, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.success is None:
self.success = False
if self.message is None:
self.message = ''
else:
self.success = False
self.message = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_B = None
def _get_struct_B():
global _struct_B
if _struct_B is None:
_struct_B = struct.Struct("<B")
return _struct_B
class SetPrimAttribute(object):
_type = 'add_on_msgs/SetPrimAttribute'
_md5sum = 'd15a408481ab068b790f599b3a64ee47'
_request_class = SetPrimAttributeRequest
_response_class = SetPrimAttributeResponse
| 11,604 | Python | 32.157143 | 145 | 0.606429 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/_GetPrimAttributes.py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/GetPrimAttributesRequest.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetPrimAttributesRequest(genpy.Message):
_md5sum = "1d00cd540af97efeb6b1589112fab63e"
_type = "add_on_msgs/GetPrimAttributesRequest"
_has_header = False # flag to mark the presence of a Header object
_full_text = """string path # prim path
"""
__slots__ = ['path']
_slot_types = ['string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
path
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(GetPrimAttributesRequest, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.path is None:
self.path = ''
else:
self.path = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self.path
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.path = str[start:end].decode('utf-8', 'rosmsg')
else:
self.path = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from add_on_msgs/GetPrimAttributesResponse.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetPrimAttributesResponse(genpy.Message):
_md5sum = "0c128a464ca5b41e4dd660a9d06a2cfb"
_type = "add_on_msgs/GetPrimAttributesResponse"
_has_header = False # flag to mark the presence of a Header object
_full_text = """string[] names # list of attribute base names (name used to Get or Set an attribute)
string[] displays # list of attribute display names (name displayed in Property tab)
string[] types # list of attribute data types
bool success # indicate a successful execution of the service
string message # informational, e.g. for error messages
"""
__slots__ = ['names','displays','types','success','message']
_slot_types = ['string[]','string[]','string[]','bool','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
names,displays,types,success,message
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(GetPrimAttributesResponse, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.names is None:
self.names = []
if self.displays is None:
self.displays = []
if self.types is None:
self.types = []
if self.success is None:
self.success = False
if self.message is None:
self.message = ''
else:
self.names = []
self.displays = []
self.types = []
self.success = False
self.message = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
length = len(self.names)
buff.write(_struct_I.pack(length))
for val1 in self.names:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
length = len(self.displays)
buff.write(_struct_I.pack(length))
for val1 in self.displays:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
length = len(self.types)
buff.write(_struct_I.pack(length))
for val1 in self.types:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.names = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.names.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.displays = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.displays.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.types = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.types.append(val1)
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
length = len(self.names)
buff.write(_struct_I.pack(length))
for val1 in self.names:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
length = len(self.displays)
buff.write(_struct_I.pack(length))
for val1 in self.displays:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
length = len(self.types)
buff.write(_struct_I.pack(length))
for val1 in self.types:
length = len(val1)
if python3 or type(val1) == unicode:
val1 = val1.encode('utf-8')
length = len(val1)
buff.write(struct.Struct('<I%ss'%length).pack(length, val1))
_x = self.success
buff.write(_get_struct_B().pack(_x))
_x = self.message
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.Struct('<I%ss'%length).pack(length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
if python3:
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.names = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.names.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.displays = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.displays.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.types = []
for i in range(0, length):
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1 = str[start:end].decode('utf-8', 'rosmsg')
else:
val1 = str[start:end]
self.types.append(val1)
start = end
end += 1
(self.success,) = _get_struct_B().unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.message = str[start:end].decode('utf-8', 'rosmsg')
else:
self.message = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_B = None
def _get_struct_B():
global _struct_B
if _struct_B is None:
_struct_B = struct.Struct("<B")
return _struct_B
class GetPrimAttributes(object):
_type = 'add_on_msgs/GetPrimAttributes'
_md5sum = 'c58d65c0fb14e3af9f2c6842bf315d01'
_request_class = GetPrimAttributesRequest
_response_class = GetPrimAttributesResponse
| 14,453 | Python | 32.381062 | 145 | 0.592126 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/packages/add_on_msgs/srv/__init__.py | from ._GetPrimAttribute import *
from ._GetPrimAttributes import *
from ._GetPrims import *
from ._SetPrimAttribute import *
| 125 | Python | 24.199995 | 33 | 0.776 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/tests/__init__.py | from .test_ros_bridge import *
| 31 | Python | 14.999993 | 30 | 0.741935 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/semu/robotics/ros_bridge/tests/test_ros_bridge.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import semu.robotics.ros_bridge
# 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 TestROSBridge(omni.kit.test.AsyncTestCaseFailOnLogError):
# 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_ros_bridge(self):
print("test_ros_bridge - TODO")
pass
| 919 | Python | 38.999998 | 142 | 0.724701 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "1.0.0"
category = "Simulation"
feature = false
app = false
title = "ROS Bridge (semu namespace)"
description = "ROS interfaces (semu namespace)"
authors = ["Toni-SM"]
repository = "https://github.com/Toni-SM/semu.robotics.ros_bridge"
keywords = ["ROS", "control"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[package.target]
config = ["release"]
platform = ["linux-*"]
python = ["*"]
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.test" = {}
"omni.graph" = {}
"omni.isaac.dynamic_control" = {}
[[python.module]]
name = "semu.robotics.ros_bridge"
[[python.module]]
name = "semu.robotics.ros_bridge.tests"
[fswatcher.patterns]
include = ["*.ogn", "*.py"]
exclude = ["Ogn*Database.py"]
[settings]
exts."semu.robotics.ros_bridge".nodeName = "SemuRosBridge"
exts."semu.robotics.ros_bridge".eventTimeout = 5.0
exts."semu.robotics.ros_bridge".setAttributeUsingAsyncio = false
| 1,004 | TOML | 21.333333 | 66 | 0.692231 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2022-06-15
### Changed
- Switch to OmniGraph
## [0.1.1] - 2022-05-28
### Changed
- Rename the extension to `semu.robotics.ros_bridge`
## [0.1.0] - 2022-04-14
### Added
- Source code (src folder)
- `control_msgs/FollowJointTrajectory` action server
- `control_msgs/GripperCommand` action server
### Changed
- Improve the extension implementation
### Removed
- `sensor_msgs/CompressedImage` topic
## [0.0.2] - 2021-10-29
### Added
- `add_on_msgs/RosAttribute` services
## [0.0.1] - 2021-06-22
### Added
- Update extension to Isaac Sim 2021.1.0 extension format
| 673 | Markdown | 20.062499 | 80 | 0.686478 |
Toni-SM/semu.robotics.ros_bridge/exts/semu.robotics.ros_bridge/docs/README.md | # semu.robotics.ros_bridge
This extension enables the ROS 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 ROS
Visit https://github.com/Toni-SM/semu.robotics.ros_bridge to read more about its use
| 375 | Markdown | 52.714278 | 259 | 0.826667 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/BUILD.md | ## Building form source
### Linux
```bash
cd src/semu.robotics.ros2_bridge
bash compile_extension.bash
```
## Removing old compiled files
Get a fresh clone of the repository and follow the next steps
```bash
# remove compiled files _ros2_bridge.cpython-37m-x86_64-linux-gnu.so
git filter-repo --invert-paths --path exts/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/_ros2_bridge.cpython-37m-x86_64-linux-gnu.so
# add origin
git remote add origin [email protected]:Toni-SM/semu.robotics.ros2_bridge.git
# push changes
git push origin --force --all
git push origin --force --tags
```
## Packaging the extension
```bash
cd src/semu.robotics.ros2_bridge
bash package_extension.bash
``` | 694 | Markdown | 21.419354 | 139 | 0.75072 |
Toni-SM/semu.robotics.ros2_bridge/src/semu.robotics.ros2_bridge/semu/robotics/ros2_bridge/ros2_bridge.py | from typing import List, Any
import time
import json
import asyncio
import threading
import omni
import carb
import omni.kit
from pxr import Usd, Gf, PhysxSchema
from omni.isaac.dynamic_control import _dynamic_control
from omni.isaac.core.utils.stage import get_stage_units
import rclpy
from rclpy.node import Node
from rclpy.duration import Duration
from rclpy.action import ActionServer, CancelResponse, GoalResponse
from trajectory_msgs.msg import JointTrajectoryPoint
import semu.usd.schemas.RosBridgeSchema as ROSSchema
import semu.usd.schemas.RosControlBridgeSchema as ROSControlSchema
# message types
GetPrims = None
GetPrimAttributes = None
GetPrimAttribute = None
SetPrimAttribute = None
FollowJointTrajectory = None
GripperCommand = None
def acquire_ros2_bridge_interface(ext_id: str = "") -> 'Ros2Bridge':
"""
Acquire the Ros2Bridge interface
:param ext_id: The extension id
:type ext_id: str
:returns: The Ros2Bridge interface
:rtype: Ros2Bridge
"""
global GetPrims, GetPrimAttributes, GetPrimAttribute, SetPrimAttribute, FollowJointTrajectory, GripperCommand
from add_on_msgs.srv import GetPrims as get_prims_srv
from add_on_msgs.srv import GetPrimAttributes as get_prim_attributes_srv
from add_on_msgs.srv import GetPrimAttribute as get_prim_attribute_srv
from add_on_msgs.srv import SetPrimAttribute as set_prim_attribute_srv
from control_msgs.action import FollowJointTrajectory as follow_joint_trajectory_action
from control_msgs.action import GripperCommand as gripper_command_action
GetPrims = get_prims_srv
GetPrimAttributes = get_prim_attributes_srv
GetPrimAttribute = get_prim_attribute_srv
SetPrimAttribute = set_prim_attribute_srv
FollowJointTrajectory = follow_joint_trajectory_action
GripperCommand = gripper_command_action
rclpy.init()
bridge = Ros2Bridge()
executor = rclpy.executors.MultiThreadedExecutor()
executor.add_node(bridge)
threading.Thread(target=executor.spin).start()
return bridge
def release_ros2_bridge_interface(bridge: 'Ros2Bridge') -> None:
"""
Release the Ros2Bridge interface
:param bridge: The Ros2Bridge interface
:type bridge: Ros2Bridge
"""
bridge.shutdown()
class Ros2Bridge(Node):
def __init__(self) -> None:
"""Initialize the Ros2Bridge interface
"""
self._components = []
self._node_name = carb.settings.get_settings().get("/exts/semu.robotics.ros2_bridge/nodeName")
super().__init__(self._node_name)
# omni objects and interfaces
self._usd_context = omni.usd.get_context()
self._timeline = omni.timeline.get_timeline_interface()
self._physx_interface = omni.physx.acquire_physx_interface()
self._dci = _dynamic_control.acquire_dynamic_control_interface()
# events
self._update_event = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update_event)
self._timeline_event = self._timeline.get_timeline_event_stream().create_subscription_to_pop(self._on_timeline_event)
self._stage_event = self._usd_context.get_stage_event_stream().create_subscription_to_pop(self._on_stage_event)
self._physx_event = self._physx_interface.subscribe_physics_step_events(self._on_physics_event)
def shutdown(self) -> None:
"""Shutdown the Ros2Bridge interface
"""
self._update_event = None
self._timeline_event = None
self._stage_event = None
self._stop_components()
self.destroy_node()
rclpy.shutdown()
def _get_ros_bridge_schemas(self) -> List['ROSSchema.RosBridgeComponent']:
"""Get the ROS bridge schemas in the current stage
:returns: The ROS bridge schemas
:rtype: list of RosBridgeComponent
"""
schemas = []
stage = self._usd_context.get_stage()
for prim in Usd.PrimRange.AllPrims(stage.GetPrimAtPath("/")):
if prim.GetTypeName() == "RosAttribute":
schemas.append(ROSSchema.RosAttribute(prim))
elif prim.GetTypeName() == "RosControlFollowJointTrajectory":
schemas.append(ROSControlSchema.RosControlFollowJointTrajectory(prim))
elif prim.GetTypeName() == "RosControlGripperCommand":
schemas.append(ROSControlSchema.RosControlGripperCommand(prim))
return schemas
def _stop_components(self) -> None:
"""Stop all components
"""
for component in self._components:
component.stop()
def _reload_components(self) -> None:
"""Reload all components
"""
# stop components
self._stop_components()
# load components
self._components = []
self._skip_update_step = True
for schema in self._get_ros_bridge_schemas():
if schema.__class__.__name__ == "RosAttribute":
self._components.append(RosAttribute(self, self._usd_context, schema, self._dci))
elif schema.__class__.__name__ == "RosControlFollowJointTrajectory":
self._components.append(RosControlFollowJointTrajectory(self, self._usd_context, schema, self._dci))
elif schema.__class__.__name__ == "RosControlGripperCommand":
self._components.append(RosControllerGripperCommand(self, self._usd_context, schema, self._dci))
def _on_update_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the kit update event
:param event: Event
:type event: carb.events._events.IEvent
"""
if self._timeline.is_playing():
for component in self._components:
if self._skip_update_step:
self._skip_update_step = False
return
# start components
if not component.started:
component.start()
return
# step
component.update_step(event.payload["dt"])
def _on_timeline_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the timeline event
:param event: Event
:type event: carb.events._events.IEvent
"""
# reload components
if event.type == int(omni.timeline.TimelineEventType.PLAY):
self._reload_components()
print("[Info][semu.robotics.ros2_bridge] RosControlBridge: components reloaded")
# stop components
elif event.type == int(omni.timeline.TimelineEventType.STOP) or event.type == int(omni.timeline.TimelineEventType.PAUSE):
self._stop_components()
print("[Info][semu.robotics.ros2_bridge] RosControlBridge: components stopped")
def _on_stage_event(self, event: 'carb.events._events.IEvent') -> None:
"""Handle the stage event
:param event: The stage event
:type event: carb.events._events.IEvent
"""
pass
def _on_physics_event(self, step: float) -> None:
"""Handle the physics event
:param step: The physics step
:type step: float
"""
for component in self._components:
component.physics_step(step)
class RosController:
def __init__(self, node: Node, usd_context: 'omni.usd._usd.UsdContext', schema: 'ROSSchema.RosBridgeComponent') -> None:
"""Base class for RosController
:param node: ROS2 node
:type node: Node
:param usd_context: USD context
:type usd_context: omni.usd._usd.UsdContext
:param schema: The ROS bridge schema
:type schema: ROSSchema.RosBridgeComponent
"""
self._node = node
self._usd_context = usd_context
self._schema = schema
self.started = False
def start(self) -> None:
"""Start the component
"""
raise NotImplementedError
def stop(self) -> None:
"""Stop the component
"""
print("[Info][semu.robotics.ros2_bridge] RosController: stopping {}".format(self._schema.__class__.__name__))
self.started = False
def update_step(self, dt: float) -> None:
"""Kit update step
:param dt: The delta time
:type dt: float
"""
raise NotImplementedError
def physics_step(self, dt: float) -> None:
"""Physics update step
:param dt: The physics delta time
:type dt: float
"""
raise NotImplementedError
class RosAttribute(RosController):
def __init__(self,
node: Node,
usd_context: 'omni.usd._usd.UsdContext',
schema: 'ROSSchema.RosBridgeComponent',
dci: 'omni.isaac.dynamic_control.DynamicControl') -> None:
"""RosAttribute interface
:param node: The ROS node
:type node: rclpy.node.Node
:param usd_context: USD context
:type usd_context: omni.usd._usd.UsdContext
:param schema: The ROS bridge schema
:type schema: ROSSchema.RosAttribute
:param dci: The dynamic control interface
:type dci: omni.isaac.dynamic_control.DynamicControl
"""
super().__init__(node, usd_context, schema)
self._dci = dci
self._srv_prims = None
self._srv_attributes = None
self._srv_getter = None
self._srv_setter = None
self._value = None
self._attribute = None
self._event = threading.Event()
self._event.set()
self.__event_timeout = carb.settings.get_settings().get("/exts/semu.robotics.ros2_bridge/eventTimeout")
self.__set_attribute_using_asyncio = \
carb.settings.get_settings().get("/exts/semu.robotics.ros2_bridge/setAttributeUsingAsyncio")
print("[Info][semu.robotics.ros2_bridge] RosAttribute: asyncio: {}".format(self.__set_attribute_using_asyncio))
print("[Info][semu.robotics.ros2_bridge] RosAttribute: event timeout: {}".format(self.__event_timeout))
async def _set_attribute(self, attribute: 'pxr.Usd.Attribute', attribute_value: Any) -> None:
"""Set the attribute value using asyncio
:param attribute: The prim's attribute to set
:type attribute: pxr.Usd.Attribute
:param attribute_value: The attribute value
:type attribute_value: Any
"""
ret = attribute.Set(attribute_value)
def _process_setter_request(self,
request: 'SetPrimAttribute.Request',
response: 'SetPrimAttribute.Response') -> 'SetPrimAttribute.Response':
"""Process the setter request
:param request: The service request
:type request: SetPrimAttribute.Request
:param response: The service response
:type response: SetPrimAttribute.Response
:return: The service response
:rtype: SetPrimAttribute.Response
"""
response.success = False
if self._schema.GetEnabledAttr().Get():
stage = self._usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
if request.attribute and prim.HasAttribute(request.attribute):
# attribute
attribute = prim.GetAttribute(request.attribute)
attribute_type = type(attribute.Get()).__name__
# value
try:
value = json.loads(request.value)
attribute_value = None
except json.JSONDecodeError:
print("[Error][semu.robotics.ros2_bridge] RosAttribute: invalid value: {}".format(request.value))
response.success = False
response.message = "Invalid value '{}'".format(request.value)
return response
# parse data
try:
if attribute_type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['Quatd', 'Quatf', 'Quath']:
attribute_value = type(attribute.Get())(*value)
elif attribute_type in ['Matrix4d', 'Matrix4f']:
attribute_value = type(attribute.Get())(value)
elif attribute_type.startswith('Vec') and attribute_type.endswith('Array'):
attribute_value = type(attribute.Get())(value)
elif attribute_type.startswith('Matrix') and attribute_type.endswith('Array'):
if attribute_type.endswith("dArray"):
attribute_value = type(attribute.Get())([Gf.Matrix2d(v) for v in value])
elif attribute_type.endswith("fArray"):
attribute_value = type(attribute.Get())([Gf.Matrix2f(v) for v in value])
elif attribute_type.startswith('Quat') and attribute_type.endswith('Array'):
if attribute_type.endswith("dArray"):
attribute_value = type(attribute.Get())([Gf.Quatd(*v) for v in value])
elif attribute_type.endswith("fArray"):
attribute_value = type(attribute.Get())([Gf.Quatf(*v) for v in value])
elif attribute_type.endswith("hArray"):
attribute_value = type(attribute.Get())([Gf.Quath(*v) for v in value])
elif attribute_type.endswith('Array'):
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['AssetPath']:
attribute_value = type(attribute.Get())(value)
elif attribute_type in ['NoneType']:
pass
else:
attribute_value = type(attribute.Get())(value)
# set attribute
if attribute_value is not None:
# set attribute usign asyncio
if self.__set_attribute_using_asyncio:
try:
loop = asyncio.get_event_loop()
except:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
future = asyncio.ensure_future(self._set_attribute(attribute, attribute_value))
loop.run_until_complete(future)
response.success = True
# set attribute in the physics event
else:
self._attribute = attribute
self._value = attribute_value
self._event.clear()
response.success = self._event.wait(self.__event_timeout)
if not response.success:
response.message = "The timeout ({} s) for setting the attribute value has been reached" \
.format(self.__event_timeout)
except Exception as e:
print("[Error][semu.robotics.ros2_bridge] RosAttribute: srv {} request for {} ({}: {}): {}" \
.format(self._srv_setter.resolved_name, request.path, request.attribute, value, e))
response.success = False
response.message = str(e)
else:
response.message = "Prim has not attribute {}".format(request.attribute)
else:
response.message = "Invalid prim ({})".format(request.path)
else:
response.message = "RosAttribute prim is not enabled"
return response
def _process_getter_request(self,
request: 'GetPrimAttribute.Request',
response: 'GetPrimAttribute.Response') -> 'GetPrimAttribute.Response':
"""Process the getter request
:param request: The service request
:type request: GetPrimAttribute.Request
:param response: The service response
:type response: GetPrimAttribute.Response
:return: The service response
:rtype: GetPrimAttribute.Response
"""
response.success = False
if self._schema.GetEnabledAttr().Get():
stage = self._usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
if request.attribute and prim.HasAttribute(request.attribute):
attribute = prim.GetAttribute(request.attribute)
response.type = type(attribute.Get()).__name__
# parse data
response.success = True
if response.type in ['Vec2d', 'Vec2f', 'Vec2h', 'Vec2i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(2)])
elif response.type in ['Vec3d', 'Vec3f', 'Vec3h', 'Vec3i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(3)])
elif response.type in ['Vec4d', 'Vec4f', 'Vec4h', 'Vec4i']:
data = attribute.Get()
response.value = json.dumps([data[i] for i in range(4)])
elif response.type in ['Quatd', 'Quatf', 'Quath']:
data = attribute.Get()
response.value = json.dumps([data.real, data.imaginary[0], data.imaginary[1], data.imaginary[2]])
elif response.type in ['Matrix4d', 'Matrix4f']:
data = attribute.Get()
response.value = json.dumps([[data.GetRow(i)[j] for j in range(data.dimension[1])] \
for i in range(data.dimension[0])])
elif response.type.startswith('Vec') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[d[i] for i in range(len(d))] for d in data])
elif response.type.startswith('Matrix') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[[d.GetRow(i)[j] for j in range(d.dimension[1])] \
for i in range(d.dimension[0])] for d in data])
elif response.type.startswith('Quat') and response.type.endswith('Array'):
data = attribute.Get()
response.value = json.dumps([[d.real, d.imaginary[0], d.imaginary[1], d.imaginary[2]] for d in data])
elif response.type.endswith('Array'):
try:
response.value = json.dumps(list(attribute.Get()))
except Exception as e:
print("[Warning][semu.robotics.ros2_bridge] RosAttribute: Unknow attribute type {}" \
.format(type(attribute.Get())))
print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros2_bridge/issues)")
response.success = False
response.message = "Unknow type {}".format(type(attribute.Get()))
elif response.type in ['AssetPath']:
response.value = json.dumps(str(attribute.Get().path))
else:
try:
response.value = json.dumps(attribute.Get())
except Exception as e:
print("[Warning][semu.robotics.ros2_bridge] RosAttribute: Unknow {}: {}" \
.format(type(attribute.Get()), attribute.Get()))
print(" |-- Please, report a new issue (https://github.com/Toni-SM/semu.robotics.ros2_bridge/issues)")
response.success = False
response.message = "Unknow type {}".format(type(attribute.Get()))
else:
response.message = "Prim has not attribute {}".format(request.attribute)
else:
response.message = "Invalid prim ({})".format(request.path)
else:
response.message = "RosAttribute prim is not enabled"
return response
def _process_attributes_request(self,
request: 'GetPrimAttributes.Request',
response: 'GetPrimAttributes.Response') -> 'GetPrimAttributes.Response':
"""Process the 'get all attributes' request
:param request: The service request
:type request: GetPrimAttributes.Request
:param response: The service response
:type response: GetPrimAttributes.Response
:return: The service response
:rtype: GetPrimAttributes.Response
"""
response.success = False
if self._schema.GetEnabledAttr().Get():
stage = self._usd_context.get_stage()
# get prim
if stage.GetPrimAtPath(request.path).IsValid():
prim = stage.GetPrimAtPath(request.path)
for attribute in prim.GetAttributes():
if attribute.GetNamespace():
response.names.append("{}:{}".format(attribute.GetNamespace(), attribute.GetBaseName()))
else:
response.names.append(attribute.GetBaseName())
response.displays.append(attribute.GetDisplayName())
response.types.append(type(attribute.Get()).__name__)
response.success = True
else:
response.message = "Invalid prim ({})".format(request.path)
else:
response.message = "RosAttribute prim is not enabled"
return response
def _process_prims_request(self, request: 'GetPrims.Request', response: 'GetPrims.Response') -> 'GetPrims.Response':
"""Process the 'get all prims' request
:param request: The service request
:type request: GetPrims.Request
:param response: The service response
:type response: GetPrims.Response
:return: The service response
:rtype: GetPrims.Response
"""
response.success = False
if self._schema.GetEnabledAttr().Get():
stage = self._usd_context.get_stage()
# get prims
if not request.path or stage.GetPrimAtPath(request.path).IsValid():
path = request.path if request.path else "/"
for prim in Usd.PrimRange.AllPrims(stage.GetPrimAtPath(path)):
response.paths.append(str(prim.GetPath()))
response.types.append(prim.GetTypeName())
response.success = True
else:
response.message = "Invalid search path ({})".format(request.path)
else:
response.message = "RosAttribute prim is not enabled"
return response
def start(self) -> None:
"""Start the services
"""
print("[Info][semu.robotics.ros2_bridge] RosAttribute: starting {}".format(self._schema.__class__.__name__))
service_name = self._schema.GetPrimsSrvTopicAttr().Get()
self._srv_prims = self._node.create_service(GetPrims, service_name, self._process_prims_request)
print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_prims.srv_name))
service_name = self._schema.GetGetAttrSrvTopicAttr().Get()
self._srv_getter = self._node.create_service(GetPrimAttribute, service_name, self._process_getter_request)
print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_getter.srv_name))
service_name = self._schema.GetAttributesSrvTopicAttr().Get()
self._srv_attributes = self._node.create_service(GetPrimAttributes, service_name, self._process_attributes_request)
print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_attributes.srv_name))
service_name = self._schema.GetSetAttrSrvTopicAttr().Get()
self._srv_setter = self._node.create_service(SetPrimAttribute, service_name, self._process_setter_request)
print("[Info][semu.robotics.ros2_bridge] RosAttribute: register srv: {}".format(self._srv_setter.srv_name))
self.started = True
def stop(self) -> None:
"""Stop the services
"""
if self._srv_prims is not None:
print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_prims.srv_name))
self._node.destroy_service(self._srv_prims)
self._srv_prims = None
if self._srv_getter is not None:
print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_getter.srv_name))
self._node.destroy_service(self._srv_getter)
self._srv_getter = None
if self._srv_attributes is not None:
print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_attributes.srv_name))
self._node.destroy_service(self._srv_attributes)
self._srv_attributes = None
if self._srv_setter is not None:
print("[Info][semu.robotics.ros2_bridge] RosAttribute: unregister srv: {}".format(self._srv_setter.srv_name))
self._node.destroy_service(self._srv_setter)
self._srv_setter = None
super().stop()
def update_step(self, dt: float) -> None:
"""Kit update step
:param dt: The delta time
:type dt: float
"""
pass
def physics_step(self, dt: float) -> None:
"""Physics update step
:param dt: The physics delta time
:type dt: float
"""
if not self.started:
return
if self.__set_attribute_using_asyncio:
return
if self._dci.is_simulating():
if not self._event.is_set():
if self._attribute is not None:
ret = self._attribute.Set(self._value)
self._event.set()
class RosControlFollowJointTrajectory(RosController):
def __init__(self,
node: Node,
usd_context: 'omni.usd._usd.UsdContext',
schema: 'ROSSchema.RosBridgeComponent',
dci: 'omni.isaac.dynamic_control.DynamicControl') -> None:
"""FollowJointTrajectory interface
:param node: The ROS node
:type node: rclpy.node.Node
:param usd_context: The USD context
:type usd_context: omni.usd._usd.UsdContext
:param schema: The schema
:type schema: ROSSchema.RosBridgeComponent
:param dci: The dynamic control interface
:type dci: omni.isaac.dynamic_control.DynamicControl
"""
super().__init__(node, usd_context, schema)
self._dci = dci
self._articulation = _dynamic_control.INVALID_HANDLE
self._joints = {}
self._action_server = None
self._action_dt = 0.05
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_point_index = 1
# feedback / result
self._action_result_message = None
self._action_feedback_message = FollowJointTrajectory.Feedback()
def start(self) -> None:
"""Start the action server
"""
print("[Info][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: starting {}" \
.format(self._schema.__class__.__name__))
# get attributes and relationships
action_namespace = self._schema.GetActionNamespaceAttr().Get()
controller_name = self._schema.GetControllerNameAttr().Get()
relationships = self._schema.GetArticulationPrimRel().GetTargets()
if not len(relationships):
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: empty relationships")
return
# check for articulation API
stage = self._usd_context.get_stage()
path = relationships[0].GetPrimPath().pathString
if not stage.GetPrimAtPath(path).HasAPI(PhysxSchema.PhysxArticulationAPI):
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: {} doesn't have PhysxArticulationAPI".format(path))
return
# start action server
self._action_server = ActionServer(self._node,
FollowJointTrajectory,
controller_name + action_namespace,
execute_callback=self._on_execute,
goal_callback=self._on_goal,
cancel_callback=self._on_cancel,
handle_accepted_callback=self._on_handle_accepted)
print("[Info][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: register action {}" \
.format(controller_name + action_namespace))
self.started = True
def stop(self) -> None:
"""Stop the action server
"""
super().stop()
self._articulation = _dynamic_control.INVALID_HANDLE
# destroy action server
if self._action_server is not None:
print("[Info][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: destroy action server: {}" \
.format(self._schema.GetPrim().GetPath()))
# self._action_server.destroy()
self._action_server = None
self._action_goal_handle = None
self._action_goal = None
def _duration_to_seconds(self, duration: Duration) -> float:
"""Convert a ROS2 Duration to seconds
:param duration: The ROS2 Duration
:type duration: Duration
:return: The duration in seconds
:rtype: float
"""
return Duration.from_msg(duration).nanoseconds / 1e9
def _init_articulation(self) -> None:
"""Initialize the articulation and register joints
"""
# get articulation
relationships = self._schema.GetArticulationPrimRel().GetTargets()
path = relationships[0].GetPrimPath().pathString
self._articulation = self._dci.get_articulation(path)
if self._articulation == _dynamic_control.INVALID_HANDLE:
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: {} is not an articulation".format(path))
return
dof_props = self._dci.get_articulation_dof_properties(self._articulation)
if dof_props is None:
return
upper_limits = dof_props["upper"]
lower_limits = dof_props["lower"]
has_limits = dof_props["hasLimits"]
# get joints
for i in range(self._dci.get_articulation_dof_count(self._articulation)):
dof_ptr = self._dci.get_articulation_dof(self._articulation, i)
if dof_ptr != _dynamic_control.DofType.DOF_NONE:
dof_name = self._dci.get_dof_name(dof_ptr)
if dof_name not in self._joints:
_joint = self._dci.find_articulation_joint(self._articulation, dof_name)
self._joints[dof_name] = {"joint": _joint,
"type": self._dci.get_joint_type(_joint),
"dof": self._dci.find_articulation_dof(self._articulation, dof_name),
"lower": lower_limits[i],
"upper": upper_limits[i],
"has_limits": has_limits[i]}
if not self._joints:
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: no joints found in {}".format(path))
self.started = False
def _set_joint_position(self, name: str, target_position: float) -> None:
"""Set the target position of a joint in the articulation
:param name: The joint name
:type name: str
:param target_position: The target position
:type target_position: float
"""
# clip target position
if self._joints[name]["has_limits"]:
target_position = min(max(target_position, self._joints[name]["lower"]), self._joints[name]["upper"])
# scale target position for prismatic joints
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
target_position /= get_stage_units()
# set target position
self._dci.set_dof_position_target(self._joints[name]["dof"], target_position)
def _get_joint_position(self, name: str) -> float:
"""Get the current position of a joint in the articulation
:param name: The joint name
:type name: str
:return: The current position of the joint
:rtype: float
"""
position = self._dci.get_dof_state(self._joints[name]["dof"], _dynamic_control.STATE_POS).pos
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
return position * get_stage_units()
return position
def _on_handle_accepted(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> None:
"""Callback function for handling newly accepted goals
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
"""
goal_handle.execute()
def _on_goal(self, goal: 'FollowJointTrajectory.Goal') -> 'rclpy.action.server.GoalResponse':
"""Callback function for handling new goal requests
:param goal: The goal
:type goal: FollowJointTrajectory.Goal
:return: Whether the goal was accepted
:rtype: rclpy.action.server.GoalResponse
"""
# reject if joints don't match
for name in goal.trajectory.joint_names:
if name not in self._joints:
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: joints don't match ({} not in {})" \
.format(name, list(self._joints.keys())))
return GoalResponse.REJECT
# reject if there is an active goal
if self._action_goal is not None:
print("[Warning][semu.robotics.ros2_bridge] RosControlFollowJointTrajectory: multiple goals not supported")
return GoalResponse.REJECT
# check initial position
if goal.trajectory.points[0].time_from_start:
initial_point = JointTrajectoryPoint(positions=[self._get_joint_position(name) for name in goal.trajectory.joint_names],
time_from_start=Duration().to_msg())
goal.trajectory.points.insert(0, initial_point)
# reset internal data
self._action_goal_handle = None
self._action_start_time = None
self._action_result_message = None
# store goal data
self._action_goal = goal
return GoalResponse.ACCEPT
def _on_cancel(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'rclpy.action.server.CancelResponse':
"""Callback function for handling cancel requests
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
:return: Whether the goal was canceled
:rtype: rclpy.action.server.CancelResponse
"""
if self._action_goal is None:
return CancelResponse.REJECT
# reset internal data
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_result_message = None
goal_handle.destroy()
return CancelResponse.ACCEPT
def _on_execute(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'FollowJointTrajectory.Result':
"""Callback function for processing accepted goals
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
:return: The result of the goal execution
:rtype: FollowJointTrajectory.Result
"""
# reset internal data
self._action_start_time = self._node.get_clock().now().nanoseconds / 1e9
self._action_result_message = None
# set goal
self._action_goal_handle = goal_handle
# wait for the goal to be executed
while self._action_result_message is None:
if self._action_goal is None:
result = FollowJointTrajectory.Result()
result.error_code = result.INVALID_GOAL
return result
time.sleep(self._action_dt)
self._action_goal = None
self._action_goal_handle = None
return self._action_result_message
def update_step(self, dt: float) -> None:
"""Kit update step
:param dt: The delta time
:type dt: float
"""
pass
def physics_step(self, dt: float) -> None:
"""Physics update step
:param dt: The physics delta time
:type dt: float
"""
if not self.started:
return
# init articulation
if not self._joints:
self._init_articulation()
return
# update articulation
if self._action_goal is not None and self._action_goal_handle is not None:
self._action_dt = dt
# end of trajectory
if self._action_point_index >= len(self._action_goal.trajectory.points):
self._action_goal = None
self._action_result_message = FollowJointTrajectory.Result()
self._action_result_message.error_code = self._action_result_message.SUCCESSFUL
if self._action_goal_handle is not None:
self._action_goal_handle.succeed()
self._action_goal_handle = None
return
previous_point = self._action_goal.trajectory.points[self._action_point_index - 1]
current_point = self._action_goal.trajectory.points[self._action_point_index]
time_passed = self._node.get_clock().now().nanoseconds / 1e9 - self._action_start_time
# set target using linear interpolation
if time_passed <= self._duration_to_seconds(current_point.time_from_start):
ratio = (time_passed - self._duration_to_seconds(previous_point.time_from_start)) \
/ (self._duration_to_seconds(current_point.time_from_start) \
- self._duration_to_seconds(previous_point.time_from_start))
self._dci.wake_up_articulation(self._articulation)
for i, name in enumerate(self._action_goal.trajectory.joint_names):
side = -1 if current_point.positions[i] < previous_point.positions[i] else 1
target_position = previous_point.positions[i] \
+ side * ratio * abs(current_point.positions[i] - previous_point.positions[i])
self._set_joint_position(name, target_position)
# send feedback
else:
self._action_point_index += 1
self._action_feedback_message.joint_names = list(self._action_goal.trajectory.joint_names)
self._action_feedback_message.actual.positions = [self._get_joint_position(name) \
for name in self._action_goal.trajectory.joint_names]
self._action_feedback_message.actual.time_from_start = Duration(seconds=time_passed).to_msg()
if self._action_goal_handle is not None:
self._action_goal_handle.publish_feedback(self._action_feedback_message)
class RosControllerGripperCommand(RosController):
def __init__(self,
node: Node,
usd_context: 'omni.usd._usd.UsdContext',
schema: 'ROSSchema.RosBridgeComponent',
dci: 'omni.isaac.dynamic_control.DynamicControl') -> None:
"""GripperCommand interface
:param node: The ROS node
:type node: rclpy.node.Node
:param usd_context: The USD context
:type usd_context: omni.usd._usd.UsdContext
:param schema: The ROS bridge schema
:type schema: ROSSchema.RosBridgeComponent
:param dci: The dynamic control interface
:type dci: omni.isaac.dynamic_control.DynamicControl
"""
super().__init__(node, usd_context, schema)
self._dci = dci
self._articulation = _dynamic_control.INVALID_HANDLE
self._joints = {}
self._action_server = None
self._action_dt = 0.05
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
# TODO: add to schema?
self._action_timeout = 10.0
self._action_position_threshold = 0.001
self._action_previous_position_sum = float("inf")
# feedback / result
self._action_result_message = None
self._action_feedback_message = GripperCommand.Feedback()
def start(self) -> None:
"""Start the action server
"""
print("[Info][semu.robotics.ros2_bridge] RosControllerGripperCommand: starting {}" \
.format(self._schema.__class__.__name__))
# get attributes and relationships
action_namespace = self._schema.GetActionNamespaceAttr().Get()
controller_name = self._schema.GetControllerNameAttr().Get()
relationships = self._schema.GetArticulationPrimRel().GetTargets()
if not len(relationships):
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: empty relationships")
return
elif len(relationships) == 1:
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: relationship is not a group")
return
# check for articulation API
stage = self._usd_context.get_stage()
path = relationships[0].GetPrimPath().pathString
if not stage.GetPrimAtPath(path).HasAPI(PhysxSchema.PhysxArticulationAPI):
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: {} doesn't have PhysxArticulationAPI".format(path))
return
# start action server
self._action_server = ActionServer(self._node,
GripperCommand,
controller_name + action_namespace,
execute_callback=self._on_execute,
goal_callback=self._on_goal,
cancel_callback=self._on_cancel,
handle_accepted_callback=self._on_handle_accepted)
print("[Info][semu.robotics.ros2_bridge] RosControllerGripperCommand: register action {}" \
.format(controller_name + action_namespace))
self.started = True
def stop(self) -> None:
"""Stop the action server
"""
super().stop()
self._articulation = _dynamic_control.INVALID_HANDLE
# destroy action server
if self._action_server is not None:
print("[Info][semu.robotics.ros2_bridge] RosControllerGripperCommand: destroy action server: {}" \
.format(self._schema.GetPrim().GetPath()))
# self._action_server.destroy()
self._action_server = None
self._action_goal_handle = None
self._action_goal = None
def _duration_to_seconds(self, duration: Duration) -> float:
"""Convert a ROS2 Duration to seconds
:param duration: The ROS2 Duration
:type duration: Duration
:return: The duration in seconds
:rtype: float
"""
return Duration.from_msg(duration).nanoseconds / 1e9
def _init_articulation(self) -> None:
"""Initialize the articulation and register joints
"""
# get articulation
relationships = self._schema.GetArticulationPrimRel().GetTargets()
path = relationships[0].GetPrimPath().pathString
self._articulation = self._dci.get_articulation(path)
if self._articulation == _dynamic_control.INVALID_HANDLE:
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: {} is not an articulation".format(path))
return
dof_props = self._dci.get_articulation_dof_properties(self._articulation)
if dof_props is None:
return
upper_limits = dof_props["upper"]
lower_limits = dof_props["lower"]
has_limits = dof_props["hasLimits"]
# get joints
# TODO: move to another relationship in the schema
paths = [relationship.GetPrimPath().pathString for relationship in relationships[1:]]
for i in range(self._dci.get_articulation_dof_count(self._articulation)):
dof_ptr = self._dci.get_articulation_dof(self._articulation, i)
if dof_ptr != _dynamic_control.DofType.DOF_NONE:
# add only required joints
if self._dci.get_dof_path(dof_ptr) in paths:
dof_name = self._dci.get_dof_name(dof_ptr)
if dof_name not in self._joints:
_joint = self._dci.find_articulation_joint(self._articulation, dof_name)
self._joints[dof_name] = {"joint": _joint,
"type": self._dci.get_joint_type(_joint),
"dof": self._dci.find_articulation_dof(self._articulation, dof_name),
"lower": lower_limits[i],
"upper": upper_limits[i],
"has_limits": has_limits[i]}
if not self._joints:
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: no joints found in {}".format(path))
self.started = False
def _set_joint_position(self, name: str, target_position: float) -> None:
"""Set the target position of a joint in the articulation
:param name: The joint name
:type name: str
:param target_position: The target position
:type target_position: float
"""
# clip target position
if self._joints[name]["has_limits"]:
target_position = min(max(target_position, self._joints[name]["lower"]), self._joints[name]["upper"])
# scale target position for prismatic joints
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
target_position /= get_stage_units()
# set target position
self._dci.set_dof_position_target(self._joints[name]["dof"], target_position)
def _get_joint_position(self, name: str) -> float:
"""Get the current position of a joint in the articulation
:param name: The joint name
:type name: str
:return: The current position of the joint
:rtype: float
"""
position = self._dci.get_dof_state(self._joints[name]["dof"], _dynamic_control.STATE_POS).pos
if self._joints[name]["type"] == _dynamic_control.JOINT_PRISMATIC:
return position * get_stage_units()
return position
def _on_handle_accepted(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> None:
"""Callback function for handling newly accepted goals
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
"""
goal_handle.execute()
def _on_goal(self, goal: 'GripperCommand.Goal') -> 'rclpy.action.server.GoalResponse':
"""Callback function for handling new goal requests
:param goal: The goal
:type goal: GripperCommand.Goal
:return: Whether the goal was accepted
:rtype: rclpy.action.server.GoalResponse
"""
# reject if there is an active goal
if self._action_goal is not None:
print("[Warning][semu.robotics.ros2_bridge] RosControllerGripperCommand: multiple goals not supported")
return GoalResponse.REJECT
# reset internal data
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_result_message = None
self._action_previous_position_sum = float("inf")
return GoalResponse.ACCEPT
def _on_cancel(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'rclpy.action.server.CancelResponse':
"""Callback function for handling cancel requests
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
:return: Whether the goal was canceled
:rtype: rclpy.action.server.CancelResponse
"""
if self._action_goal is None:
return CancelResponse.REJECT
# reset internal data
self._action_goal = None
self._action_goal_handle = None
self._action_start_time = None
self._action_result_message = None
self._action_previous_position_sum = float("inf")
goal_handle.destroy()
return CancelResponse.ACCEPT
def _on_execute(self, goal_handle: 'rclpy.action.server.ServerGoalHandle') -> 'GripperCommand.Result':
"""Callback function for processing accepted goals
:param goal_handle: The goal handle
:type goal_handle: rclpy.action.server.ServerGoalHandle
:return: The result of the goal execution
:rtype: GripperCommand.Result
"""
# reset internal data
self._action_start_time = self._node.get_clock().now().nanoseconds / 1e9
self._action_result_message = None
self._action_previous_position_sum = float("inf")
# set goal
self._action_goal_handle = goal_handle
self._action_goal = goal_handle.request
# wait for the goal to be executed
while self._action_result_message is None:
if self._action_goal is None:
return GripperCommand.Result()
time.sleep(self._action_dt)
self._action_goal = None
self._action_goal_handle = None
return self._action_result_message
def update_step(self, dt: float) -> None:
"""Kit update step
:param dt: The delta time
:type dt: float
"""
pass
def physics_step(self, dt: float) -> None:
"""Physics update step
:param dt: The physics delta time
:type dt: float
"""
if not self.started:
return
# init articulation
if not self._joints:
self._init_articulation()
return
# update articulation
if self._action_goal is not None and self._action_goal_handle is not None:
self._action_dt = dt
target_position = self._action_goal.command.position
# set target
self._dci.wake_up_articulation(self._articulation)
for name in self._joints:
self._set_joint_position(name, target_position)
# end (position reached)
position = 0
current_position_sum = 0
position_reached = True
for name in self._joints:
position = self._get_joint_position(name)
current_position_sum += position
if abs(position - target_position) > self._action_position_threshold:
position_reached = False
break
if position_reached:
self._action_result_message = GripperCommand.Result()
self._action_result_message.position = position
self._action_result_message.stalled = False
self._action_result_message.reached_goal = True
if self._action_goal_handle is not None:
self._action_goal_handle.succeed()
self._action_goal_handle = None
return
# end (stalled)
if abs(current_position_sum - self._action_previous_position_sum) < 1e-6:
self._action_result_message = GripperCommand.Result()
self._action_result_message.position = position
self._action_result_message.stalled = True
self._action_result_message.reached_goal = False
if self._action_goal_handle is not None:
self._action_goal_handle.succeed()
self._action_goal_handle = None
return
self._action_previous_position_sum = current_position_sum
# end (timeout)
time_passed = self._node.get_clock().now().nanoseconds / 1e9 - self._action_start_time
if time_passed >= self._action_timeout:
self._action_result_message = GripperCommand.Result()
if self._action_goal_handle is not None:
self._action_goal_handle.abort()
self._action_goal_handle = None
# TODO: send feedback
# self._action_goal_handle.publish_feedback(self._action_feedback_message)
| 55,059 | Python | 43.619125 | 141 | 0.576945 |
Toni-SM/semu.robotics.ros2_bridge/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/src/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/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/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.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>

<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>

<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>

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>

<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/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>

## Overview
<br>

## VS Code interface
<br>

## 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>

<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))

<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> ®ister_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 ? ®ister_local_exception_translator
: ®ister_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> ®ister_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> ®ister_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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.