tools/gen_sdf.sh 现在生成使用相对网格路径的 URDF 和 SDF 1.11,GPU雷达
This commit is contained in:
1 parent
c710b955b1
commit
56f4b3adb0
24 files changed
+405
-208
No files matched your search
@@ -0,0 +1,112 @@
|
||||
"""Build relocatable model files and the runtime ROS robot description."""
|
||||
|
||||
import argparse
|
||||
from contextlib import ExitStack
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PureWindowsPath
|
||||
import subprocess
|
||||
import tempfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def expand_urdf(share, mesh_prefix):
|
||||
source = share / 'urdf' / 'sentry.urdf.xacro'
|
||||
# Passing the source name keeps the xacro provenance comment relocatable too.
|
||||
return subprocess.run(
|
||||
['xacro', source.name, f'mesh_prefix:={mesh_prefix}'],
|
||||
cwd=source.parent, check=True, stdout=subprocess.PIPE, text=True,
|
||||
).stdout
|
||||
|
||||
|
||||
def runtime_description(share):
|
||||
# resource_retriever's local-file plugin opens the URI path directly.
|
||||
# Retain spaces instead of applying URL percent encoding.
|
||||
meshes = (share / 'meshes').resolve()
|
||||
return expand_urdf(share, f'file://{meshes.as_posix()}')
|
||||
|
||||
|
||||
def mesh_target(reference, parent):
|
||||
path = Path(reference)
|
||||
if path.is_absolute() or PureWindowsPath(reference).anchor or ':' in reference:
|
||||
raise ValueError(f'expected a relative mesh reference, got {reference!r}')
|
||||
target = Path(os.path.normpath(parent / path))
|
||||
if not target.is_file():
|
||||
raise ValueError(f'mesh reference {reference!r} does not exist relative to {parent}')
|
||||
return target
|
||||
|
||||
|
||||
def relative_path(target, parent):
|
||||
return Path(os.path.relpath(target, parent)).as_posix()
|
||||
|
||||
|
||||
def generate(workspace, gz):
|
||||
share = workspace / 'src' / 'sentry_sim'
|
||||
urdf = workspace / 'generated' / 'sentry.urdf'
|
||||
sdf = share / 'models' / 'sentry' / 'model.sdf'
|
||||
urdf.parent.mkdir(parents=True, exist_ok=True)
|
||||
source = expand_urdf(share, relative_path(share / 'meshes', urdf.parent))
|
||||
robot = ET.fromstring(source)
|
||||
if robot.tag != 'robot':
|
||||
raise ValueError('xacro did not produce a URDF robot')
|
||||
urdf_meshes = [mesh_target(node.attrib['filename'], urdf.parent) for node in robot.iter('mesh')]
|
||||
if not urdf_meshes:
|
||||
raise ValueError('URDF contains no meshes')
|
||||
env = os.environ.copy()
|
||||
env.pop('LD_LIBRARY_PATH', None)
|
||||
|
||||
with ExitStack() as cleanup:
|
||||
staged = []
|
||||
for output in (urdf, sdf):
|
||||
with tempfile.NamedTemporaryFile(dir=output.parent, suffix=output.suffix, delete=False) as stream:
|
||||
stage = Path(stream.name)
|
||||
cleanup.callback(stage.unlink, missing_ok=True)
|
||||
staged.append(stage)
|
||||
urdf_stage, sdf_stage = staged
|
||||
urdf_stage.write_text(source, encoding='utf-8')
|
||||
converted = subprocess.run([str(gz), 'sdf', '-p', str(urdf_stage)], env=env, check=True,
|
||||
stdout=subprocess.PIPE, text=True, timeout=30).stdout
|
||||
model = ET.fromstring(converted)
|
||||
if model.tag != 'sdf' or model.get('version') not in ('1.11', '1.12'):
|
||||
raise ValueError(f'unsupported SDFormat conversion output: {model.tag} {model.get("version")}')
|
||||
model.set('version', '1.11')
|
||||
sdf_meshes = []
|
||||
for uri in model.findall('.//mesh/uri'):
|
||||
target = mesh_target(uri.text or '', urdf.parent)
|
||||
sdf_meshes.append(target)
|
||||
uri.text = relative_path(target, sdf.parent)
|
||||
if sorted(urdf_meshes) != sorted(sdf_meshes):
|
||||
raise ValueError('SDF conversion changed the mesh inventory')
|
||||
ET.indent(model)
|
||||
sdf_stage.write_text(ET.tostring(model, encoding='unicode') + '\n', encoding='utf-8')
|
||||
subprocess.run([str(gz), 'sdf', '-k', str(sdf_stage)], env=env, check=True, timeout=30)
|
||||
for stage, output in zip(staged, (urdf, sdf)):
|
||||
stage.chmod(0o644)
|
||||
stage.replace(output)
|
||||
print(output.relative_to(workspace))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
generator = commands.add_parser('generate')
|
||||
generator.add_argument('workspace', type=Path)
|
||||
generator.add_argument('gz', type=Path)
|
||||
runtime = commands.add_parser('runtime-params')
|
||||
runtime.add_argument('share', type=Path)
|
||||
runtime.add_argument('output', type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.command == 'generate':
|
||||
generate(args.workspace.resolve(), args.gz)
|
||||
else:
|
||||
description = runtime_description(args.share)
|
||||
parameters = {'robot_description': description, 'use_sim_time': True}
|
||||
args.output.write_text(json.dumps({'robot_state_publisher': {'ros__parameters': parameters}}),
|
||||
encoding='utf-8')
|
||||
except (ValueError, OSError, subprocess.SubprocessError, ET.ParseError) as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user